剑指Offer之Java实现

最讨厌面试的时候,让在纸上手写代码了。又没什么卵用,工作中我就没见过,谁先在纸上写出算法,然后电脑上再敲一遍。。。

第1题——二维数组中的查找

public class Solution {

    public boolean Find(int target, int[][] array) {
        if(array == null) return false ;

        for(int i=0 ; i<array.length; i++) {
            if(binarySearch(array[i], target)) { return true ; }
        }

        return false ;
    }

    public boolean binarySearch(int[] array, int key) {
        int low = 0 ;
        int high = array.length-1 ;

        while(low <= high) {
            int mid = (low+high)/2 ;

            if(array[mid] == key) {
                return true ;
            }else if(array[mid] > key) {
                high = mid - 1 ;
            }else {
                low = mid + 1 ;
            }
        }

        return false ;
    }

}

第2题——替换空格

public class Solution {

    public String replaceSpace(StringBuffer str) {
        if(str == null) { return "" ; }
        return str.toString().replaceAll(" ", "%20") ;
    }

}

第3题——从尾到头打印链表

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;

public class Solution {

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> result = new ArrayList<Integer>() ;

        Stack<Integer> stack = new Stack<Integer>() ;
        while(listNode != null) {
            stack.push(listNode.val) ;
            listNode = listNode.next ;
        }

        while(!stack.isEmpty()) {
            result.add(stack.pop()) ;
        }

        return result ;
    }

}

第4题——重建二叉树

import java.util.*;

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

    public TreeNode reConstructBinaryTree(int[] pre,int[] in) {
        if(pre == null || in == null) { return null ; }
        if(pre.length == 0 || in.length == 0) { return null ; }

        TreeNode root = new TreeNode(pre[0]) ;

        int j = -1 ;
        for(int i=0; i<in.length; i++) {
            if(in[i] == pre[0]) {
                j = i ;
                break ;
            }
        }

        int[] preLeft = new int[j] ;
        int[] inLeft = new int[j] ;
        if(j > 0) {
            System.arraycopy(pre, 1, preLeft, 0, preLeft.length);
            System.arraycopy(in, 0, inLeft, 0, inLeft.length);
        }

        int[] preRight = new int[in.length-1-j] ;
        int[] inRight = new int[in.length-1-j] ;
        if( preRight.length !=0 && inRight.length !=0 ) {
            System.arraycopy(pre, j+1, preRight, 0, preRight.length);
            System.arraycopy(in, j+1, inRight, 0, inRight.length);
        }

        root.left = reConstructBinaryTree(preLeft, inLeft) ;
        root.right = reConstructBinaryTree(preRight, inRight) ;

        return root ;
    }

}

第5题——用两个栈实现队列

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        stack2.push(node) ;
    }

    public int pop() {
        if(!stack1.isEmpty()) {
            return stack1.pop() ;
        } else {
            while (!stack2.isEmpty()) {
                stack1.push(stack2.pop()) ;
            }

            return stack1.pop() ;
        }
    }
}

第6题——旋转数组的最小数字

import java.util.ArrayList;

public class Solution {

    public int minNumberInRotateArray(int[] array) {
        if(array == null || array.length == 0) { return 0 ; }   //呵呵
        if(array.length == 1) { return array[0] ; }

        int min = array[array.length-1] ;

        for(int i=array.length-2 ; i>=0; i--) {
            if(array[i] <= min) {
                min = array[i] ;
            }else {
                break ;
            }
        }

        return min ;
    }

}

第7题——斐波那契数列

public class Solution {
    public int Fibonacci(int n) {
        if(n == 0) return 0 ;
        if(n == 1) return 1 ;
        //return Fibonacci(n-1) + Fibonacci(n-2) ;
        double sqrt5 = Math.sqrt(5) ;
        return (int) ((Math.pow((1+sqrt5)/2, n) - Math.pow((1-sqrt5)/2, n))/sqrt5) ;
    }
}

或者

public class Solution {
    public int Fibonacci(int n) {
        if(n == 0) return 0 ;
        if(n == 1) return 1 ;

        int i = 0 ;
        int j = 1 ;
        int k = 0 ;
        for(int m=2 ; m<=n ; m++) {
            k = i + j ;
            i = j ;
            j = k ;
        }

        return k ;
    }
}

第8题——跳台阶

public class Solution {

    public int JumpFloor(int target) {
        if(target==1)   return 1 ;
        if(target==2)   return 2 ;

        double sqrt5 = Math.sqrt(5) ;
        return (int) ((Math.pow((1+sqrt5)/2, target+1) - Math.pow((1-sqrt5)/2, target+1))/sqrt5) ;
    }

}

第9题——变态跳台阶

public class Solution {
    public int JumpFloorII(int target) {
        return (int) Math.pow(2, target-1) ;
    }
}

第10题——矩形覆盖

public class Solution {
    public int RectCover(int target) {
        if(target == 0)   return 0 ;
        if(target == 1)   return 1 ;
        if(target == 2)   return 2 ;
        double sqrt5 = Math.sqrt(5) ;
        return (int) ((Math.pow((1+sqrt5)/2, target+1) - Math.pow((1-sqrt5)/2, target+1))/sqrt5) ;
    }
}

第11题——二进制中1的个数

public class Solution {

    public int NumberOf1(int n) {
        int count = 0;
        while (n != 0) {
            ++count ;
            n = (n - 1) & n ;
        }
        return count ;
    }

}

第12题——数值的整数次方

public class Solution {
    public double Power(double base, int exponent) {
        return Math.pow(base, exponent) ;
    }
}

第13题——调整数组顺序使奇数位于偶数前面

import java.util.*;

public class Solution {

    public void reOrderArray(int[] array) {
        if(array == null || array.length == 0) { return ; }

        ArrayList<Integer> odd = new ArrayList<Integer>() ;
        ArrayList<Integer> even = new ArrayList<Integer>() ;
        for(int i=0; i<array.length; i++) {
            if(array[i]%2==1) {
                odd.add(array[i]) ;
            }else {
                even.add(array[i]) ;
            }
        }

        for(int i=0; i<odd.size(); i++) {
            array[i] = odd.get(i) ;
        }

        for(int j=0; j<even.size(); j++) {
            array[odd.size()+j] = even.get(j) ;
        }

        odd.clear() ;
        even.clear() ;
    }

}

第14题——链表中倒数第k个结点

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {

    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null || k<=0) return null ;

        ListNode pre = head ;
        ListNode last = head ;
        for(int i=1; i<k; i++) {
            if(pre.next != null) {
                pre = pre.next ;
            }else {
                return null ;
            }
        }

        while(pre.next != null) {
            pre = pre.next ;
            last = last.next ;
        }

        return last ;
    }

}

第15题——反转链表

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {

    public ListNode ReverseList(ListNode head) {
        if(head == null) { return null ; }
        if(head.next == null) { return head ; }

        ListNode p1 = head.next ;
        ListNode p2 = p1 ;

        head.next = null ;

        while(p2 != null) {
            p1 = p2 ;
            p2 = p2.next ;
            p1.next = head ;
            head = p1 ;
        }

        return p1 ;
    }

}

第16题——合并两个排序的链表

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {

    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null && list2 == null) return null ;
        if(list1 != null && list2 == null) return list1 ;
        if(list1 == null && list2 != null) return list2 ;

        ListNode head = new ListNode(Integer.MIN_VALUE) ;
        ListNode temp = head ;

        while(list1 != null && list2 != null) {
            if(list1.val <= list2.val) {
                temp.next = list1 ;
                list1 = list1.next ;
                temp = temp.next ;
            }else {
                temp.next = list2 ;
                list2 = list2.next ;
                temp = temp.next ;
            }
        }


        if(list1 == null) { temp.next = list2 ; }
        if(list2 == null) { temp.next = list1 ; }

        return head.next ;
    }

}

第17题——树的子结构

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {

    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        if(root1 == null || root2 == null) return false;

        return likeSameTree(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2) ;
    }

    public boolean likeSameTree(TreeNode root1,TreeNode root2) {
        if(root1 == null && root2 != null ) { return false ; }
        if(root2 == null) { return true ; }

        if(root1.val != root2.val) { return false ; }

        return likeSameTree(root1.left, root2.left) && likeSameTree(root1.right, root2.right) ;
    }

}

第18题——二叉树的镜像

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {

    public void Mirror(TreeNode root) {

        if(root == null) {
            return ;
        }else {
            TreeNode temp = root.left ;
            root.left = root.right ;
            root.right = temp ;
        }

        Mirror(root.left) ;
        Mirror(root.right) ;

    }

}

第19题——顺时针打印矩阵

import java.util.*;

public class Solution {

    public ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<Integer>() ;
        if(matrix==null || matrix.length==0) { return result ; }

        printMatrixClockWisely(matrix, 0, 0, matrix.length - 1, matrix[0].length - 1, result);

        return result ;
    }

    public void printMatrixClockWisely(int[][] matrix, int startRow, int startCol, int endRow, int endCol, ArrayList<Integer> result) {
        if(startRow<endRow && startCol<endCol) {
            for(int j=startCol; j<=endCol; j++) { result.add(matrix[startRow][j]) ; }   //Right
            for(int i=startRow+1; i<=endRow-1; i++) { result.add(matrix[i][endCol]) ; }     //Down
            for(int j=endCol; j>=startCol; j--) { result.add(matrix[endRow][j]) ; }     //Left
            for(int i=endRow-1; i>=startRow+1; i--) { result.add(matrix[i][startCol]) ; }   //Up
            printMatrixClockWisely(matrix, startRow + 1, startCol + 1, endRow - 1, endCol - 1, result) ;
        }else if(startRow==endRow && startCol<endCol) {
            for(int j=startCol; j<=endCol; j++) { result.add(matrix[startRow][j]) ; }
        }else if(startRow<endRow && startCol==endCol) {
            for(int i=startRow; i<=endRow; i++) { result.add(matrix[i][endCol]) ; }
        }else if(startRow==endRow && startCol==endCol) {
            result.add(matrix[startRow][startCol]) ;
        }else {
            return ;
        }
    }

}

第20题——包含min函数的栈

import java.util.Stack;

public class Solution {

    Stack<Integer> st = new Stack<Integer>() ;

    public void push(int node) {
        st.push(new Integer(node)) ;
    }
    public void pop() {
        st.pop() ;
    }

    public int top() {
        return st.peek() ;
    }

    public int min() {
        int min = Integer.MAX_VALUE ;
        for(Integer temp : st) {
            if(temp < min)
                min = temp ;
        }
        return min ;
    }
}

第21题——栈的压入、弹出序列

import java.util.Stack;

public class Solution {
    public boolean IsPopOrder(int[] pushA,int[] popA) {
        int pushALength = pushA.length ;
        int popALength = popA.length ;

        if(pushALength != popALength) { return false ; }
        if(pushALength==0 || popALength==0) { return false ; }

        Stack<Integer> stack = new Stack<Integer>() ;
        for(int j=0,i=0 ; i<popALength ; i++) {
            stack.push(pushA[i]) ;
            while (j<popALength && stack.peek()==popA[j]) {
                stack.pop() ;
                j++ ;
            }
        }

        return stack.isEmpty() ;
    }
}

第22题——从上往下打印二叉树

import java.util.*;


/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>() ;

        if(root == null) { return result ; }

        Deque<TreeNode> queue = new LinkedList<TreeNode>() ;
        queue.add(root) ;
        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.poll() ;
            if(treeNode.left != null) { queue.add(treeNode.left) ; }
            if(treeNode.right != null) { queue.add(treeNode.right) ; }
            result.add(treeNode.val) ;
        }

        return result ;
    }
}

第23题——二叉搜索树的后序遍历序列

public class Solution {

    public boolean VerifySquenceOfBST(int[] sequence) {
        if( sequence==null || sequence.length==0) { return false ; }
        if( sequence.length==1 ) { return true ; }

        int root = sequence[sequence.length-1] ;
        int j = 0 ;
        for(int i=0; i<sequence.length; i++) {
            if(sequence[i] >= root) {
                j = i ;
                break ;
            }
        }
        int[] leftRoot = new int[j] ;
        if(j > 0) {
            System.arraycopy(sequence, 0, leftRoot, 0, leftRoot.length) ;
        }

        int[] rightRoot = new int[sequence.length-1-j] ;
        if(rightRoot.length > 0) {
            System.arraycopy(sequence, j, rightRoot, 0, rightRoot.length) ;
            for(int i=0 ; i<rightRoot.length ; i++) {
                if(rightRoot[i] < root) { return false ; }
            }
        }

        if(leftRoot.length==0 || rightRoot.length==0) { return true ; }
        return VerifySquenceOfBST(leftRoot) &&  VerifySquenceOfBST(rightRoot) ;
    }

}

第24题——二叉树中和为某一值的路径

import java.util.*;

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/

public class Solution {

    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>() ;

        ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>() ;
        FindAllPath(root, temp);
        for(int i=0 ; i<temp.size(); i++) {
            int sum = 0 ;
            for(int j=0; j<temp.get(i).size(); j++) {
                sum += temp.get(i).get(j) ;
            }
            if(sum == target) {
                result.add(temp.get(i)) ;
            }
        }

        temp.clear() ;
        return result ;
    }


    public void FindAllPath(TreeNode root, ArrayList<ArrayList<Integer>> result) {
        ArrayList<Integer> temp = new ArrayList<Integer>() ;
        FindAllPath(root, result, temp);
        temp.clear() ;
    }

    public void FindAllPath(TreeNode root, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> temp) {
        if(root == null) return ;

        if(root.left != null || root.right != null) {  //非叶子节点
            temp.add(root.val) ;
            FindAllPath(root.left, result, temp) ;
            FindAllPath(root.right, result, temp) ;
            temp.remove(temp.size()-1) ;
        } else {
            temp.add(root.val) ;
            temp.trimToSize() ;
            result.add((ArrayList<Integer>) temp.clone()) ;
            temp.remove(temp.size()-1) ;
            return ;
        }
    }

}

第25题——复杂链表的复制

/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
public class Solution {

    public RandomListNode Clone(RandomListNode pHead) {
        if(pHead == null) { return null ; }

        RandomListNode head = new RandomListNode(pHead.label) ;
        RandomListNode temp = head ;

        while(pHead.next != null) {
            temp.next = new RandomListNode(pHead.next.label) ;
            if(pHead.random != null) {
                temp.random = new RandomListNode(pHead.random.label) ;
            }
            pHead = pHead.next ;
            temp = temp.next ;
        }

        return head ;
    }

}

第26题——二叉搜索树与双向链表

import java.util.*;

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/

public class Solution {

    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null) { return null ; }
        if(pRootOfTree.left == null && pRootOfTree.right == null) { return pRootOfTree ; }

        ArrayList<TreeNode> result = new ArrayList<TreeNode>() ;
        inOrderTreeNode(pRootOfTree, result) ;
        TreeNode head = result.get(0) ;
        TreeNode p1 = head ;
        TreeNode p2 = head ;

        for(int i=0 ; i<=result.size()-2 ; i++) {
            p1 = result.get(i) ;
            p2 = result.get(i+1) ;
            p1.right = p2 ;
            p2.left = p1 ;
        }

        return head ;
    }

    public void inOrderTreeNode(TreeNode root, ArrayList<TreeNode> result) {
        if(root == null) { return ; }

        inOrderTreeNode(root.left, result) ;
        result.add(root) ;
        inOrderTreeNode(root.right, result) ;
    }

}

第27题——字符串的排列

import java.util.*;

public class Solution {

    public ArrayList<String> Permutation(String str) {
        ArrayList<String> result = new ArrayList<String>() ;
        if(str==null || str.length()==0) { return result ; }

        char[] chars = str.toCharArray() ;
        TreeSet<String> temp = new TreeSet<>() ;
        Permutation(chars, 0, temp);
        result.addAll(temp) ;
        return result ;
    }

    public void Permutation(char[] chars, int begin, TreeSet<String> result) {
        if(chars==null || chars.length==0 || begin<0 || begin>chars.length-1) { return ; }

        if(begin == chars.length-1) {
            result.add(String.valueOf(chars)) ;
        }else {
            for(int i=begin ; i<=chars.length-1 ; i++) {
                swap(chars, begin, i) ;

                Permutation(chars, begin+1, result);

                swap(chars, begin, i) ;
            }
        }
    }

    public void swap(char[] x, int a, int b) {
        char t = x[a];
        x[a] = x[b];
        x[b] = t;
    }

}

第28题——数组中出现次数超过一半的数字

import java.util.HashMap;

public class Solution {

    public int MoreThanHalfNum_Solution(int[] array) {
        if(array == null || array.length == 0) { return 0 ; }
        if(array.length == 1) { return array[0] ; }

        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>() ;
        for(int i=0; i<=array.length-1; i++) {
            if(!hashMap.containsKey(array[i])) {
                hashMap.put(array[i], 1) ;
            } else {
                int value = hashMap.get(array[i]) ;
                hashMap.put(array[i], value+1) ;
                if(hashMap.get(array[i]) > array.length/2) { return array[i] ; }
            }
        }

        return 0 ;
    }

}

第29题——最小的K个数

import java.util.*;

public class Solution {

    public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
        ArrayList<Integer> result = new ArrayList<Integer>() ;
        if(input==null || k<=0 || k>input.length) return result ;

        for(int i=0 ; i<=k-1 ; i++) {
            for(int j=i+1 ; j<=input.length-1 ; j++) {
                if(input[i] > input[j]) {
                    int temp = input[i] ;
                    input[i] = input[j] ;
                    input[j] = temp ;
                }
            }
            result.add(input[i]) ;
        }

        return result ;
    }

}

第30题——连续子数组的最大和

public class Solution {

    public int FindGreatestSumOfSubArray(int[] array) {
        if(array==null || array.length==0) { return 0 ; }

        int max = Integer.MIN_VALUE ;
        int sum = 0 ;
        for(int i=0 ; i<=array.length-1 ; i++) {
            sum += array[i] ;
            if(sum > max) { max = sum ; }
            if(sum < 0) { sum = 0 ; }
        }
        return max ;
    }

}

第31题——整数中1出现的次数(从1到n整数中1出现的次数)

public class Solution {

    public int NumberOf1Between1AndN_Solution(int n) {
        int count = 0 ;
        for(int i=1; i<=n; i++) {
            int temp = i ;
            while(temp != 0) {
                if(temp % 10 == 1) { count++ ; }
                temp /= 10 ;
            }
        }

        return count ;
    }

}

第32题——把数组排成最小的数

import java.util.*;

public class Solution {

    public String PrintMinNumber(int [] numbers) {
        if(numbers == null || numbers.length == 0) { return "" ; }

        String[] str = new String[numbers.length];
        for(int i = 0; i <=numbers.length-1; i++){
            str[i] = String.valueOf(numbers[i]) ;
        }
        Arrays.sort(str,new Comparator<String>(){
            @Override
            public int compare(String s1, String s2) {
                String c1 = s1 + s2;
                String c2 = s2 + s1;
                return c1.compareTo(c2);
            }
        });
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i <=numbers.length-1 ; i++){
            sb.append(str[i]) ;
        }
        return sb.toString();
    }

}

第33题——丑数

public class Solution {

    public int GetUglyNumber_Solution(int index) {
        if(index <=0 ) { return 0 ; }

        int[] uglyNumbers = new int[index] ;
        uglyNumbers[0] = 1 ;
        int nextUglyIndex = 1 ;
        int p2 = 0 ;
        int p3 = 0 ;
        int p5 = 0 ;
        while(nextUglyIndex <= index-1) {
            uglyNumbers[nextUglyIndex] = min(uglyNumbers[p2]*2, uglyNumbers[p3]*3, uglyNumbers[p5]*5) ;
            while(uglyNumbers[p2]*2 <= uglyNumbers[nextUglyIndex]) { p2++ ; }
            while(uglyNumbers[p3]*3 <= uglyNumbers[nextUglyIndex]) { p3++ ; }
            while(uglyNumbers[p5]*5 <= uglyNumbers[nextUglyIndex]) { p5++ ; }
            nextUglyIndex++ ;
        }

        return uglyNumbers[index-1] ;
    }

    public int min(int a, int b, int c) {
        int temp = (a < b) ? a : b ;
        return temp < c ? temp : c ;
    }

}

第34题——第一个只出现一次的字符位置

import java.util.*;

public class Solution {

    public int FirstNotRepeatingChar(String str) {
        if(str == null || str.length() == 0) { return -1 ; }

        LinkedHashMap <Character, Integer> map = new LinkedHashMap<Character, Integer>();
        for(int i=0;i<str.length();i++){
            if(map.containsKey(str.charAt(i))){
                int time = map.get(str.charAt(i));
                map.put(str.charAt(i), ++time);
            }
            else {
                map.put(str.charAt(i), 1);
            }
        }
        int pos = -1; 
        for(int i=0; i<str.length(); i++){
            char c = str.charAt(i);
            if (map.get(c) == 1) {
                return i;
            }
        }
        return pos;

    }

}

第35题——数组中的逆序对

public class Solution {
    public int InversePairs(int [] array) {
        if(array==null||array.length==0) { return 0 ; }
        int[] copy = new int[array.length];
        for(int i=0;i<array.length;i++) { copy[i] = array[i] ; }
        int count = InversePairsCore(array,copy,0,array.length-1);//数值过大求余
        return count;

    }

    private int InversePairsCore(int[] array,int[] copy,int low,int high) {
        if(low==high) { return 0; }
        int mid = (low+high)>>1;
        int leftCount = InversePairsCore(array,copy,low,mid)%1000000007;
        int rightCount = InversePairsCore(array,copy,mid+1,high)%1000000007;
        int count = 0;
        int i=mid;
        int j=high;
        int locCopy = high;
        while(i>=low&&j>mid) {
            if(array[i]>array[j]) {
                count += j-mid;
                copy[locCopy--] = array[i--];
                if(count>=1000000007) { //数值过大求余
                    count%=1000000007;
                }
            }
            else {
                copy[locCopy--] = array[j--];
            }
        }
        for(;i>=low;i--) { copy[locCopy--]=array[i]; }
        for(;j>mid;j--) { copy[locCopy--]=array[j]; }
        for(int s=low;s<=high;s++) { array[s] = copy[s]; }
        return (leftCount+rightCount+count)%1000000007;
    }
}

第36题——两个链表的第一个公共结点

import java.util.* ;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {

    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1 == null || pHead2 == null) { return  null ; }

        HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>() ;
        while(pHead1 != null) {
            hashMap.put(pHead1, null) ;
            pHead1 = pHead1.next ;
        }

        while(pHead2 != null) {
            if(hashMap.containsKey(pHead2)) { return pHead2 ; }
            pHead2 = pHead2.next ;
        }

        return null ;
    }

}

第37题——数字在排序数组中出现的次数

public class Solution {

    public int GetNumberOfK(int[] array , int k) {
        if(array == null) return -1 ;

        int count = 0 ;
        for(int i=0 ; i<=array.length-1 ;i++) {
            if(k == array[i]) { count++ ; }
            if(k < array[i]) { break ; }
        }
        return count ;

    }

}

第38题——二叉树的深度

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
   public int TreeDepth(TreeNode root) {
        if(root == null) { return 0 ; }

        int depthLeft = TreeDepth(root.left) ;
        int depthRight = TreeDepth(root.right) ;

        return depthLeft > depthRight ? depthLeft+1 : depthRight+1 ;
   }
}

第39题——平衡二叉树平衡二叉树

public class Solution {

    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) { return true ; }

        if(Math.abs(TreeDepth(root.left) - TreeDepth(root.right)) > 1 ) { return false ; }

        return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right) ;
    }



    public int TreeDepth(TreeNode root) {
        if(root == null) { return 0 ; }

        return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1 ;
    }

}

第40题——数组中只出现一次的数字

import java.util.*;

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {

    public void FindNumsAppearOnce(int[] array,int num1[] , int num2[]) {
        if(array == null || array.length < 2) { return ; }

        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>() ;
        for(int i=0; i<=array.length-1; i++) {
            if(!hashMap.containsKey(array[i])) {
                hashMap.put(array[i], 1) ;
            }else {
                hashMap.remove(array[i]) ;
            }
        }

        int[] temp = new int[2] ;
        int count = 0 ;
        Iterator it = hashMap.keySet().iterator() ;
        while(it.hasNext()) {
            temp[count++] = (int) it.next() ;
        }

        num1[0] = temp[0] ;
        num2[0] = temp[1] ;
    }

}

第41题——和为S的连续正数序列

import java.util.ArrayList;

public class Solution {

    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        for (double k = Math.floor(Math.sqrt(2*sum)); k >= 2 ; k--) {
            double n = (2*sum+k*(1-k))/(2*k) ;
            if(n%1==0) {
                ArrayList<Integer> list = new ArrayList<>();
                for (int j = (int)(n);j<n+k;j++) {
                    list.add(j) ;
                }
                result.add(list) ;
            }
        }

        return result ;
    }

}

第42题——和为S的两个数字

import java.util.*;

public class Solution {

    public ArrayList<Integer> FindNumbersWithSum(int[] array,int sum) {
        ArrayList<Integer> result = new ArrayList<Integer>() ;
        if(array == null) { return result ; }

        int index = Arrays.binarySearch(array, sum/2) ;
        if(index < 0 ) { index = -index-1 ; }
        if(index >= array.length) { return result ; }

        for(int i=0; i<=index-1; i++){
            for(int j=array.length-1; j>=index; j--) {
                if(array[i] + array[j] == sum) {
                    result.add(array[i]) ;
                    result.add(array[j]) ;
                    return result ;
                }
            }
        }

        return result ;
    }

}

第43题——左旋转字符串

public class Solution {

    public String LeftRotateString(String str,int n) {
        if(str == null || str.length() == 0 || n <0) { return "" ; }
        if(n >= str.length()) { return str ; }

        String s1 = str.substring(0, n) ;
        String s2 = str.substring(n, str.length()) ;
        return s2+s1 ;
    }

}

第44题——翻转单词顺序列

public class Solution {

    public String ReverseSentence(String str) {
        if(str == null || str.length() == 0) { return "" ; }
        if(str.matches("\\s+")) { return str ; }

        StringBuilder sb = new StringBuilder() ;
        String[] strs = str.split("\\s+") ;
        for(int i=strs.length-1 ; i>=0 ; i--) {
            if(i != 0) {
                sb.append(strs[i]+" ") ;
            }else {
                sb.append(strs[i]) ;
            }
        }

        return sb.toString() ;
    }

}

第45题——扑克牌顺子

import java.util.*;

public class Solution {

    public boolean isContinuous(int[] numbers) {
        if(numbers==null || numbers.length!=5) { return false ; }
        int zeroCount = 0 ;
        int interval = 0 ;

        Arrays.sort(numbers) ;

        for(int i=0 ; i<=numbers.length-2 ; i++) {
            if(numbers[i] == 0) {
                zeroCount++ ;
                continue ;
            }
            if(numbers[i]==numbers[i+1]) { return false ; }
            if(numbers[i+1] - numbers[i] > 1) { interval += (numbers[i+1] - numbers[i]-1) ; }
        }

        return interval <= zeroCount ;
    }

}

第46题——孩子们的游戏(圆圈中最后剩下的数)

import java.util.*;

public class Solution {

    public int LastRemaining_Solution(int n, int m) {
        if(n < 1 || m < 1) { return -1 ; }

        LinkedList<Integer> list = new LinkedList<Integer>() ;
        for(int i=0; i<=n-1 ; i++) { list.add(i) ; }

        int out = 0 ;
        while(list.size() > 1) {
            if((out+m)%list.size() != 0) {
                out = (out+m)%list.size() - 1 ;
                list.remove(out) ;
            }else {
                list.removeLast() ;
                out = 0 ;
            }
        }

        return list.getFirst() ;
    }

}

第47题——求1+2+3+…+n

public class Solution {

    public int Sum_Solution(int n) {
        return sumSolution(n, 0) ;
    }

    public int sumSolution(int a, int b) {
        if(a==0) return b ;

        return sumSolution(a-1, b+a) ;
    }

}

第48题——不用加减乘除做加法

public class Solution {

     public int Add(int num1,int num2) {
        int tmp;
        while(num2!=0){
            tmp = num1&num2;
            num1 ^= num2;
            num2 = tmp<<1;
        }
        return num1;
    }

}

第49题——把字符串转换成整数

public class Solution {

    public int StrToInt(String str) {
        if(str == null || str.length()==0) { return 0 ; }
        char[] chars = str.toCharArray() ;
        int signal = chars[0] == '-' ? -1 : 0 ;
        long sum = 0 ;
        for(int i=0 ; i<=chars.length-1; i++) {
            if(chars[i] == '+' || chars[i] == '-') {
                continue ;
            }else if(chars[i]>'9' || chars[i]<'0') {
                return 0 ;
            }else {
                sum += (chars[i] - '0')*Math.pow(10, chars.length-1-i) ;
            }
        }
        return  signal==0 ? (int)sum : (int)sum*-1 ;
    }

}

第50题——数组中重复的数字

import java.util.HashMap;

public class Solution {
    // Parameters:
    //    numbers:     an array of integers
    //    length:      the length of array numbers
    //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
    //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
    //    这里要特别注意~返回任意重复的一个,赋值duplication[0]
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false   
    public boolean duplicate(int numbers[],int length,int[] duplication) {
        if(numbers==null || length<=0) { return false ; }

        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>() ;
        for(int i=0; i<=numbers.length-1; i++) {
            if(!hashMap.containsKey(numbers[i])) {
                hashMap.put(numbers[i], 1) ;
            } else {
                int value = hashMap.get(numbers[i]) ;
                hashMap.put(numbers[i], value+1) ;
                if(hashMap.get(numbers[i]) >= 2) {
                    duplication[0] = numbers[i] ;
                    return true ;
                }
            }
        }

        return false ;
    }

}

第51题——构建乘积数组

import java.util.ArrayList;

public class Solution {

    public int[] multiply(int[] A) {
        if (A == null || A.length <= 1) { return null; }

        int[] result = new int[A.length];
        // result[0]取1
        result[0] = 1;
        for (int i = 1; i < A.length; i++) {
            // 第一步每个result[i]都等于于data[0]*data[1]...data[i-1] 当i=n-1时,此时result[n-1]的结果已经计算出来了【A】
            result[i] = result[i -1] * A[i - 1];
        }
        // tmp保存data[n-1]*data[n-2]...data[i+1]的结果
        int tmp = 1;
        // 第二步求data[n-1]*data[n-2]...data[i+1] result[n-1]的结果已经计算出来,所以从data.length-2开始操作
        for (int i = A.length - 2; i >= 0; i--) {
            tmp *= A[i + 1];
            result[i] *= tmp;
        }
        return result;
    }

}

第52题——正则表达式匹配

public class Solution {

    public boolean match(char[] str, char[] pattern) {
        StringBuilder sb1 = new StringBuilder() ;
        for(int i=0 ; i<=str.length-1; i++) { sb1.append(str[i]) ; }

        StringBuilder sb2 = new StringBuilder() ;
        for(int i=0 ; i<=pattern.length-1; i++) { sb2.append(pattern[i]) ; }

        return sb1.toString().matches(sb2.toString()) ;
    }

}

第53题——表示数值的字符串

public class Solution {

    public boolean isNumeric(char[] str) {
        String string = String.valueOf(str) ;

        return string.matches("[\\+\\-]?[0-9]*(\\.[0-9]*)?([eE][\\+\\-]?[0-9]+)?");
    }

}

第54题——字符流中第一个不重复的字符

import java.util.*;

public class Solution {

    LinkedHashMap<Character, Integer> hashMap = new LinkedHashMap<Character, Integer>() ;
    //Insert one char from stringstream
    public void Insert(char ch) {
        if(! hashMap.containsKey(ch)) {
            hashMap.put(ch, 1) ;
        } else {
            int value = hashMap.get(ch) ;
            hashMap.put(ch, value+1) ;
        }
    }
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        Iterator it = hashMap.keySet().iterator() ;
        while(it.hasNext()) {
            char key = (char) it.next() ;
            if(hashMap.get(key) == 1) {
                return key ;
            }
        }

        return '#' ;
    }

}

第55题——链表中环的入口结点

import java.util.*;

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        HashSet<ListNode> set = new HashSet<ListNode>() ;
        while (pHead != null) {
            if (!set.add(pHead)) { return pHead ; }
            pHead = pHead.next ;
        }
        return null ;
    }

}

第56题——删除链表中重复的结点

import java.util.*;

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode deleteDuplication(ListNode pHead) {
        if(pHead == null) { return null ; }
        if(pHead.next == null) { return pHead ; }

        LinkedHashMap<Integer, Integer> hashMap = new LinkedHashMap<Integer, Integer>() ;
        while(pHead != null) {
            if(! hashMap.containsKey(pHead.val)) {
                hashMap.put(pHead.val, 1) ;
            }else {
                int value = hashMap.get(pHead.val) ;
                hashMap.put(pHead.val, value+1) ;
            }
            pHead = pHead.next ;
        }

        ListNode head = new ListNode(Integer.MAX_VALUE) ;
        ListNode temp = head ;

        Iterator<Integer> it = hashMap.keySet().iterator() ;
        while(it.hasNext()) {
            int key = it.next() ;
            if(hashMap.get(key) == 1) {
                temp.next = new ListNode(key) ;
                temp = temp.next ;
            }
        }

        hashMap.clear() ;
        return head.next ;
    }

}

第57题——二叉树的下一个结点

/*
public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public TreeLinkNode GetNext(TreeLinkNode pNode) {
        if(pNode == null) { return null ; }

        TreeLinkNode parent = pNode.next ;

        if(parent == null) {
            return findLeftOfRtree(pNode) ;
        }else {
            if(parent.left == pNode) {
                if(pNode.right == null) {
                    return parent ;
                } else {
                    return findLeftOfRtree(pNode) ;
                }
            } else {
                if(pNode.right != null) {
                    return findLeftOfRtree(pNode) ;
                } else {
                    TreeLinkNode temp = parent ;
                    while(temp.next != null ) {
                        if(temp.next.left == temp) {
                            return temp.next ;
                        }
                        temp = temp.next ;
                    }
                    return null ;
                }
            }
        }
    }

    public TreeLinkNode findLeftOfRtree(TreeLinkNode pNode) {
        TreeLinkNode temp = pNode.right ;
        if(temp == null) return null ;
        while(temp.left != null) {
            temp = temp.left ;
        }
        return temp ;
    }

}

第58题——对称的二叉树

import java.util.*;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {

    public boolean isSymmetrical(TreeNode pRoot) {
        if(pRoot == null) { return true ; }

        return isSymmetrical(pRoot.left, pRoot.right) ;
    }

    public boolean isSymmetrical(TreeNode left, TreeNode right) {
        if(left == null && right == null) { return true ; }
        if(left == null || right == null) { return false ; }
        if(left.val != right.val) { return false ; }
        return isSymmetrical(left.left, right.right) && isSymmetrical(left.right, right.left) ;
    }

}

第59题——按之字形顺序打印二叉树

import java.util.*;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {

    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>() ;
        if(pRoot == null) { return result ; }

        LinkedList<TreeNode> list1 = new LinkedList<TreeNode>() ;
        LinkedList<TreeNode> list2 = new LinkedList<TreeNode>() ;
        list1.add(pRoot) ;

        while(!list1.isEmpty()) {
            ArrayList<Integer> temp1 = new ArrayList<Integer>() ;
            while(!list1.isEmpty()) {
                TreeNode root = list1.poll() ;
                temp1.add(root.val) ;

                if(root.left != null) { list2.add(root.left) ; }
                if(root.right != null) { list2.add(root.right) ; }
            }
            result.add(temp1) ;

            if(!list2.isEmpty()) {
                LinkedList<TreeNode> list2copy = (LinkedList<TreeNode>) list2.clone() ;
                Stack<TreeNode> stack = new Stack<TreeNode>() ;
                while(!list2copy.isEmpty()) {
                    stack.push(list2copy.poll()) ;
                }
                ArrayList<Integer> temp2 = new ArrayList<Integer>() ;
                while(!stack.isEmpty()) {
                    temp2.add(stack.pop().val) ;
                }
                result.add(temp2) ;

                while(!list2.isEmpty()) {
                    TreeNode root = list2.poll() ;
                    if(root.left != null) { list1.add(root.left) ; }
                    if(root.right != null) { list1.add(root.right) ; }
                }
            }

        }

        result.trimToSize() ;
        return result ;
    }

}

第60题——把二叉树打印成多行

import java.util.*;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {

        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>() ;
        if(pRoot == null) { return result ; }

        Deque<TreeNode> queue1 = new LinkedList<TreeNode>() ;
        Deque<TreeNode> queue2 = new LinkedList<TreeNode>() ;
        queue1.add(pRoot) ;

        while(!queue1.isEmpty()) {
            ArrayList<Integer> temp1 = new ArrayList<Integer>() ;
            while(!queue1.isEmpty()) {
                TreeNode root = queue1.poll() ;
                temp1.add(root.val) ;

                if(root.left != null) { queue2.add(root.left) ; }
                if(root.right != null) { queue2.add(root.right) ; }
            }
            result.add(temp1) ;

            if(!queue2.isEmpty()) {
                ArrayList<Integer> temp2 = new ArrayList<Integer>() ;
                while(!queue2.isEmpty()) {
                    TreeNode root = queue2.poll() ;
                    temp2.add(root.val) ;

                    if(root.left != null) { queue1.add(root.left) ; }
                    if(root.right != null) { queue1.add(root.right) ; }
                }
                result.add(temp2) ;
            }
        }

        result.trimToSize() ;
        return result ;
    }
}

第61题——序列化二叉树

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {

    public String Serialize(TreeNode root) {
        if(root == null) { return "" ; }
        StringBuilder sb = new StringBuilder() ;
        preOrderVal(root, sb) ;
        return sb.toString() ;
    }
    public void preOrderVal(TreeNode root, StringBuilder result) {
        if(root == null) {
            result.append("#,") ;
        }else {
            result.append(root.val+",") ;
            preOrderVal(root.left, result) ;
            preOrderVal(root.right, result) ;
        }
    }

    public int index = -1 ;
    public TreeNode Deserialize(String str) {
        if(str==null || str.length()==0) { return null ; }

        String[] strings = str.split(",") ;
        return createBinaryTree(strings) ;
    }
    public TreeNode createBinaryTree(String[] strings) {
        if(strings==null || strings.length==0 || index>strings.length-1) { return null ; }
        index++ ;
        TreeNode root = null ;
        if(!strings[index].equals("#")) {
            root = new TreeNode(Integer.valueOf(strings[index])) ;
            root.left = createBinaryTree(strings) ;
            root.right = createBinaryTree(strings) ;
        }

        return root ;
    }

}

第62题——二叉搜索树的第k个结点

import java.util.*;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {

   TreeNode KthNode(TreeNode pRoot, int k) {
        if(pRoot == null || k <= 0) return null ;
        ArrayList<TreeNode> result = new ArrayList<TreeNode>() ;
        inOrderTreeNode(pRoot, result) ;
        if(k > result.size()) {
            return null ;
        } else {
            return result.get(k-1) ;
        }
    }

    public void inOrderTreeNode(TreeNode root, ArrayList<TreeNode> result) {
        if(root == null) {
            return ;
        } else {
            inOrderTreeNode(root.left, result) ;
            result.add(root);
            inOrderTreeNode(root.right, result) ;
        }
    }

}

第63题——数据流中的中位数

import java.util.*;

public class Solution {

    ArrayList<Integer> al = new ArrayList<Integer>() ;
    public void Insert(Integer num) {
        al.add(num) ;
        Collections.sort(al);
    }

    public Double GetMedian() {
        int index = al.size() ;
        if(index % 2 == 1) {
            return (double) al.get(index/2) ;
        }else {
            return (double) (al.get((index-1)/2) + al.get((index-1)/2+1) )/2 ;
        }
    }

}

第64题——滑动窗口的最大值

import java.util.*;

public class Solution {

    public ArrayList<Integer> maxInWindows(int[] num, int size) {
        ArrayList<Integer> result = new ArrayList<Integer>() ;
        if(num==null || size>num.length || size<=0) { return result ; }

        for(int i=0 ; i<=num.length-size ; i++) {
            int max = Integer.MIN_VALUE ;
            for(int j=i; j<=i+size-1; j++) {
                if(num[j] > max) { max = num[j] ; }
            }
            result.add(max) ;
        }

        return result ;
    }

}

第65题——矩阵中的路径

import java.util.*;

public class Solution {

    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        if(matrix==null || matrix.length==0 || str==null || str.length==0 || matrix.length!=rows*cols || rows<=0 || cols<=0 || rows*cols < str.length) {
            return false ;
        }

        boolean[] visited = new boolean[rows*cols] ;
        int[] pathLength = {0} ;

        for(int i=0 ; i<=rows-1 ; i++) {
            for(int j=0 ; j<=cols-1 ; j++) {
                if(hasPathCore(matrix, rows, cols, str, i, j, visited, pathLength)) { return true ; }
            }
        }

        return false ;
    }

    public boolean hasPathCore(char[] matrix, int rows, int cols, char[] str, int row, int col, boolean[] visited, int[] pathLength) {
        boolean flag = false ;

        if(row>=0 && row<rows && col>=0 && col<cols && !visited[row*cols+col] && matrix[row*cols+col]==str[pathLength[0]]) {
            pathLength[0]++ ;
            visited[row*cols+col] = true ;
            if(pathLength[0]==str.length) { return true ; }
            flag = hasPathCore(matrix, rows, cols, str, row, col+1, visited, pathLength)  ||
                   hasPathCore(matrix, rows, cols, str, row+1, col, visited, pathLength)  ||
                   hasPathCore(matrix, rows, cols, str, row, col-1, visited, pathLength)  ||
                   hasPathCore(matrix, rows, cols, str, row-1, col, visited, pathLength) ;

            if(!flag) {
                pathLength[0]-- ;
                visited[row*cols+col] = false ;
            }
        }

        return flag ;
    }

}

第66题——机器人的运动范围

import java.util.*;

public class Solution {

    public int movingCount(int threshold, int rows, int cols) {
        if(threshold <0 || rows<=0 || cols<=0) { return 0 ; }

        boolean[] visited = new boolean[rows*cols] ;
        return movingCountCore(threshold, rows, cols, 0, 0, visited) ;
    }
    public int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
        int cellCount = 0 ;
        if(check(threshold, rows, cols, row, col, visited)) {
            visited[row*cols+col] = true ;
            cellCount = 1 + movingCountCore(threshold, rows, cols, row, col+1, visited)
                        + movingCountCore(threshold, rows, cols, row+1, col, visited)
                        + movingCountCore(threshold, rows, cols, row, col-1, visited)
                        + movingCountCore(threshold, rows, cols, row-1, col, visited);
        }

        return cellCount ;
    }
    public boolean check(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
        return row>=0 && row<=rows-1 && col>=0 && col<=cols-1 && digitalSum(row)+digitalSum(col)<=threshold && !visited[row*cols+col] ;
    }
    public int digitalSum(int x) {
        int count = 0 ;
        while(x != 0) {
            count += x%10 ;
            x = x / 10 ;
        }
        return count ;
    }

}

友情链接

猜你喜欢

转载自blog.csdn.net/yitengtongweishi/article/details/80680438