剑指offer

1
public class Solution {
    public boolean Find(int target, int [][] array) {
        boolean find = false;
         if(array!=null){
             int rows = array.length;
             int cols = array[0].length;
             int row = 0;
             int col = cols-1;
             while(row<rows && col>=0){
                 if(array[row][col] == target){
                     find = true;
                     break;
                 }else if(array[row][col] > target){
                     col -- ;
                 }else{
                     row++;
                 }
             }
             
         }
        return find;
    }
}
2
public class Solution {
    public String replaceSpace(StringBuffer str) {
        if(str == null){
            return str.toString();
        }
        StringBuffer res = new StringBuffer();
        int length = str.length();
        for(int i=0;i<length;i++){
            if(str.charAt(i) == ' '){
                res.append("%20");
            }else{
                res.append(str.charAt(i));
            }
        }
        return res.toString();
    }
}
3
import java.util.ArrayList;
import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        if(listNode == null){
            return list;
        }
        Stack<ListNode> stack = new Stack<>();
        while(listNode!=null){
            stack.push(listNode);
            listNode = listNode.next;
        }
        while(!stack.isEmpty()){
            list.add(stack.pop().val);
        }
        return list;
    }
}


4
public class Solution {
      public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre.length == 0 || in.length == 0){
            return null;
        }
        return reConstructBinaryTreeCore(pre,0,pre.length-1,in,0,in.length-1);
    }

    private TreeNode reConstructBinaryTreeCore(int[] pre, int preSt, int preEnd, int[] in, int inSt, int inEnd) {
        if(preSt > preEnd) return null;
        int rootValue = pre[preSt];
        TreeNode root = new TreeNode(rootValue);

        int index = inSt;
        while(index<inEnd && in[index]!=rootValue){
            index++;
        }

        root.left = reConstructBinaryTreeCore(pre,preSt+1,preSt+index-inSt,in,inSt,index-1);
        root.right = reConstructBinaryTreeCore(pre,preSt+index-inSt+1,preEnd,in,index+1,inEnd);

        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) {
        stack1.push(node);
    }
    
    public int pop() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

6
import java.util.ArrayList;
public class Solution {
    public int minNumberInRotateArray(int [] array) {
        if(array.length == 0) return 0;
        if(array.length == 1) return array[0];
        int low = 0;
        int high = array.length - 1;
        int mid = 0;
        while(low < high) {
            mid = low + (high - low)/2;
            if(array[high] < array[mid]) {
                low = mid+1;
            }
            else if(array[high] == array[mid]) {
                high = high-1;
            }
            else {
                high = mid;
            }
        }
        return array[low];
    }
}
7
public class Solution {
    public int Fibonacci(int n) {
        if(n == 0){
            return 0;
        }
        if(n==1||n==2){
            return 1;
        }
        
        return Fibonacci(n-1)+Fibonacci(n-2);
    }
}

public class Solution {
    public int Fibonacci(int n) {
        if(n == 0){
            return 0;
        }
        if(n == 1 || n ==2){
            return 1;
        }
        int one = 1;
        int two = 0;
        int target = 0;
        for(int i=2;i<=n;i++){
            target = one + two;
            two = one;
            one = target;
        }
        return one;
    }
}

8
public class Solution {
    public int JumpFloor(int target) {
        if(target == 1){
            return 1;
        }
        if(target == 2){
            return 2;
        }
        
        return JumpFloor(target-1)+JumpFloor(target-2);
    }
}

9

public class Solution {
    public int JumpFloorII(int target) {
        if(target == 1){
            return 1;
        }
        return 2*JumpFloorII(target -1);
    }
}

10
public class Solution {
    public int RectCover(int target) {
        if(target <1){
            return 0;
        }
        if(target == 1){
            return 1;
        }else if(target == 2){
            return 2;
        }
        return RectCover(target -1)+RectCover(target-2);
    }
}

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

12

public class Solution {
    public double Power(double base, int exponent) {
        int n = Math.abs(exponent);
        if(n == 0){
            return 1;
        }else if(n == 1){
            return base;
        }
        /**
         * 思路:如3 的 5 次方
         * 可以先求得3的平方 再求 3的平方的平方
         * 因为是奇数
         * 因此还要再乘一个基数
         * (注:位运算比算数运算快得多)
         * */
        double result = Power(base,n>>1);
        result *= result;
        if((n&1) == 1){
            result *= base;
        }
        return exponent<0? 1.0/result : result;
    }
}

public class Solution {
    public double Power(double base, int exponent) {
        if(exponent == 0){
            return 1;
        }
        if(exponent == 1){
            return base;
        }
        int num = Math.abs(exponent);
        double result = 1;
        for(int i=0;i<num;i++){
            result *=base;
        }
        return exponent>0? result:1.0/result;
  }
}

13

public class Solution {
    public void reOrderArray(int [] array) {
        //冒泡排序
        for(int i=0;i<array.length-1;i++){
            for(int j=0;j<array.length-1-i;j++){
                if(array[j]%2 == 0 && array[j+1]%2 == 1){
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }
        }
    }
}

14

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null){
            return null;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = dummy;
        ListNode slow = dummy;
        while(k>0){
            fast = fast.next;
            k--;
        }
        if(fast == null){
            return null;
        }
        while(fast!=null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

15

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode pre = null;
        ListNode cur = head;
        while(cur!=null){
            ListNode nextNode = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nextNode;
        }
        return pre;
    }
}

16
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null && list2 == null){
            return null;
        }
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }
        ListNode dummy =new ListNode(-1);
        ListNode cur = dummy;
        while(list1!=null && list2!=null){
            if(list1.val <list2.val){
                cur.next = list1;
                list1 = list1.next;
                cur = cur.next;
            }else{
                cur.next = list2;
                list2 = list2.next;
                cur = cur.next;
            }
        }
        if(list1!=null){
            cur.next = list1;
        }
        if(list2!=null){
            cur.next = list2;
        }
        
        return dummy.next;
    }
}

17

public class Solution {
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        if(root1==null || root2 == null){
            return false;
        }
        boolean result = false;
        if(root1.val == root2.val){
            result = isSubTree(root1,root2);
        }
        if(!result){
            result = isSubTree(root1.left,root2);
        }
        if(!result){
            result = isSubTree(root1.right,root2);
        }
        return result;
    }
    private boolean isSubTree(TreeNode root1,TreeNode root2){
        if(root1 == null && root2 !=null){
            return false;
        }
        if(root2 == null){
            return true;
        }
        if(root1.val == root2.val){
            return isSubTree( root1.left, root2.left) && isSubTree( root1.right, root2.right);
        }
        
        return false;
    }
}

18

public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null){
            return ;
        }
        if(root.left == null && root.right == null){
            return ;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        if(root.left!=null){
            Mirror(root.left);
        }
        if(root.right!=null){
            Mirror(root.right);
        }
    }
}

public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null){
            return ;
        }
        Mirror(root.left);
        Mirror(root.right);
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
}

19
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
       ArrayList<Integer> res = new ArrayList<>();
        if(matrix == null){
            return res;
        }
        int rows = matrix.length - 1;
        int cols = matrix[0].length - 1;
        printMatrixCore(matrix,0,rows,0,cols,res);
        return res;
    }
    
    private void printMatrixCore(int [][] matrix,int rowSt,int rowEnd,
                                int colSt,int colEnd,ArrayList<Integer> res
                                ){
        if(rowSt<rowEnd && colSt < colEnd){
            for(int j = colSt;j<=colEnd;j++){
                res.add(matrix[rowSt][j]);
            }
            for(int i = rowSt+1;i<=rowEnd;i++){
                res.add(matrix[i][colEnd]);
            }
            for(int j = colEnd-1;j>=colSt;j--){
                res.add(matrix[rowEnd][j]);
            }
            for(int i = rowEnd-1;i>rowSt;i--){
                res.add(matrix[i][colSt]);
            }
            printMatrixCore(matrix,rowSt+1,rowEnd-1,colSt+1,colEnd-1,res);
        }
         if(rowSt == rowEnd && colSt < colEnd){
            for(int j=colSt;j<=colEnd;j++){
                res.add(matrix[rowSt][j]);
            }
        }
         if(rowSt < rowEnd && colSt == colEnd){
            for(int i=rowSt;i<=rowEnd;i++){
                res.add(matrix[i][colSt]);
            }
        }
         if(rowSt == rowEnd && colSt == colEnd){
            res.add(matrix[rowSt][colSt]);
        }
        
    }
}

20

import java.util.Stack;

public class Solution {

    Stack<Integer> data = new Stack<>();
    Stack<Integer> min = new Stack<>();
    public void push(int node) {
        data.push(node);
        if(min.isEmpty() || min.peek()>node){
            min.push(node);
        }else{
            min.push(min.peek());
        }
    }
    
    public void pop() {
        if(!data.isEmpty() && !min.isEmpty()){
            data.pop();
            min.pop();
        }
    }
    
    public int top() {
        return data.peek();
    }
    
    public int min() {
        return min.peek();
    }
}

21

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
      if(pushA == null || popA == null){
          return false;
      }
      int j = 0;
      Stack<Integer> stack = new Stack<>(); 
      for(int i=0;i<pushA.length;i++){
          stack.push(pushA[i]);
          while(!stack.isEmpty() && stack.peek() == popA[j]){
              stack.pop();
              j++;
          }
      }
      return stack.isEmpty();
    }
}

22
import java.util.ArrayList;
import java.util.LinkedList;
/**
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> list = new ArrayList<>();
        if(root == null){
            return list;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
           
            TreeNode pop = queue.removeFirst();
            list.add(pop.val);
            if(pop.left!=null){
                queue.add(pop.left);
            }
            if(pop.right!=null){
                queue.add(pop.right);
            }
        }
        return list;
    }
}

23

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence == null || sequence.length == 0){
            return false;
        }
        
        return VerifySquenceOfBSTCore(sequence,0,sequence.length-1);
    }
    private boolean VerifySquenceOfBSTCore(int [] sequence,int start,int end){
        if(start>=end){
            return true;
        }
        int root = sequence[end];
        int i=start;
        while(sequence[i]<root){
            i++;
        }
        for(int j=i;j<end;j++){
            if(sequence[j]<root){
                return false;
            }
        }
        
        return VerifySquenceOfBSTCore(sequence,start,i-1)&&
            VerifySquenceOfBSTCore(sequence,i,end-1);
    }
}

24
public class Solution {
    ArrayList<ArrayList<Integer>> res = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root == null){
            return res;
        }
        FindPathCore(root,target,new ArrayList<>());
        return res;
    }
    private void FindPathCore(TreeNode root,int target, ArrayList<Integer> list){
        if(root == null){
             return ;
        }
           
        list.add(root.val);
        if(root.val == target && root.left == null && root.right == null){
            res.add(new ArrayList(list));
            return ;
        }
        if(root.left != null){
            FindPathCore(root.left,target-root.val,list);
            list.remove(list.size()-1);
        }
        if(root.right != null){
            FindPathCore(root.right,target-root.val,list);
            list.remove(list.size()-1);
        }
    }
}

25

public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead == null){
            return pHead;
        }
        RandomListNode cur = pHead;
        while(cur!=null){
            RandomListNode cpNode = new RandomListNode(cur.label);
            cpNode.next = cur.next;
            cur.next = cpNode;
            cur = cpNode.next;
        }
        cur = pHead;
        while(cur!=null){
            RandomListNode nextNode = cur.next;
            if(cur.random!=null){
                nextNode.random = cur.random.next;
            }
            cur = nextNode.next;
        }
        cur = pHead;
        RandomListNode res = cur.next;
        while(cur.next!=null){
            RandomListNode temp = cur.next;
            cur.next = temp.next;
            cur = temp;
        }
        return res;
    }
}

26

public class Solution {
    public TreeNode Convert(TreeNode root) {
        if(root==null)
            return null;
        if(root.left==null&&root.right==null)
            return root;
        // 1.将左子树构造成双链表,并返回链表头节点
        TreeNode left = Convert(root.left);
        TreeNode p = left;
        // 2.定位至左子树双链表最后一个节点
        while(p!=null&&p.right!=null){
            p = p.right;
        }
        // 3.如果左子树链表不为空的话,将当前root追加到左子树链表
        if(left!=null){
            p.right = root;
            root.left = p;
        }
        // 4.将右子树构造成双链表,并返回链表头节点
        TreeNode right = Convert(root.right);
        // 5.如果右子树链表不为空的话,将该链表追加到root节点之后
        if(right!=null){
            right.left = root;
            root.right = right;
        }
        return left!=null?left:root;
    }

27

import java.util.ArrayList;
public class Solution {
    public ArrayList<String> Permutation(String str) {
        ArrayList<String> res = new ArrayList<>();
       if(str == null || str.length() == 0){
           return res;
       }
       boolean[] visited = new boolean[str.length()];
       PermutationCore(str,0,"",res,visited);
       return res;
    }
    private void PermutationCore(String str,int index,String temp,
                                 ArrayList<String> res,boolean[] visited){
        if(index == str.length()){
            if(res.contains(temp))
                return;
            res.add(temp);
            return ;
        }
        for(int i=0;i<str.length();i++){
            char s = str.charAt(i);
            if(visited[i] == false){
                visited[i] = true;
                PermutationCore(str,index+1,temp+s,res,visited);
                visited[i] = false;
            }
            
        }
        return ;
    }
}

28
import java.util.HashMap;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        HashMap<Integer,Integer> map = new HashMap<>();
        if(array == null){
            return 0;
        }
        if(array.length == 1){
            return array[0];
        }
        for(int num : array){
            map.put(num,map.getOrDefault(num,0)+1);
        }
        int halfLen = array.length/2;
        for(int key : map.keySet()){
            if(map.get(key)>halfLen){
                return key;
            }
        }
        return 0;
    }
}

29

import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> res = new ArrayList<>();
        if(input == null || input.length == 0||k<=0 || k>input.length){
            return res;
        }
        Arrays.sort(input);
        for(int i=0;i<k;i++){
            res.add(input[i]);
        }
        
        return res;
    }
}

30

public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        if(array.length == 0){
            return 0;
        }
        int sum = 0;
        int max = array[0];
        for(int i=0;i<array.length;i++){
            sum = 0;
            for(int j=i;j<array.length;j++){
                sum += array[j];
                if(sum > max){
                    max = sum;
                }
            }
        }
        return max;
    }
}
递推公式是DP[i] = max{DP[i-1] + A[i],A[i]}
public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        int curSum = 0;
        int max = array[0];
        for(int i=0;i<array.length;i++){
            curSum += array[i];
            if(curSum > max){
                max = curSum;
            }
            /*如果累加和出现小于0的情况,  
           则和最大的子序列肯定不可能包含前面的元素,  
           这时将累加和置0,从下个元素重新开始累加  */
            if(curSum < 0){
                curSum = 0;
            }
        }
        return max;
    }
}

31
https://www.nowcoder.com/profile/835689/codeBookDetail?submissionId=1522621
public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        int count = 0;
        for(int i=1;i<=n;i++){
            String s = String.valueOf(i);
            for(int j=0;j<s.length();j++){
                if(s.charAt(j) == '1'){
                    count++;
                }
            }
        }
        return count;
    }
}

32

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Solution {
    public String PrintMinNumber(int [] numbers) {
        int n = numbers.length;
        String s="";
        ArrayList<Integer> list = new ArrayList<>();
        for(int i=0;i<n;i++){
            list.add(numbers[i]);
        }
        Collections.sort(list,new Comparator<Integer>(){
            public int compare(Integer o1,Integer o2){
                String s1 = o1+""+o2;
                String s2 = o2+""+o1;
                return s1.compareTo(s2);
            }
        });
        for(Integer j:list){
            s+=j;
        }
        return s;
    }
}

递归+回溯
import java.util.*;

public class Solution {
    ArrayList<String> res = new ArrayList<>();
    public String PrintMinNumber(int [] numbers) {
        if(numbers == null || numbers.length == 0){
            return "";
        }
        boolean[] isVisited = new boolean[numbers.length];
        
        PrintMinNumberCore(numbers,0,"",isVisited);
        long [] array = new long[res.size()];
        for(int i=0;i<array.length;i++){
            array[i] = Long.valueOf(res.get(i));
        }
        Arrays.sort(array);

        return String.valueOf(array[0]);
    }

    private void PrintMinNumberCore(int [] numbers,int index,String temp,boolean[] isVisited){
        if(index == numbers.length){
            res.add(temp);
            return;
        }
        for(int i=0;i<numbers.length;i++){
            if(!isVisited[i]){
                isVisited[i] = true;
                PrintMinNumberCore(numbers,index+1,temp+numbers[i],isVisited);
                isVisited[i] = false;
            }

        }
        return ;
    }
}

33
public class Solution {
    public int GetUglyNumber_Solution(int index) {
        if(index < 7){
            return index;
        }
        int[] arr = new int[index];
        arr[0] = 1;
        int p2 = 0,p3 = 0, p5 = 0;
        for(int i=1;i<index;i++){
            //选出三个队列头最小的数
            arr[i] = min(arr[p2]*2,min(arr[p3]*3,arr[p5]*5));
            //这三个if有可能进入一个或者多个,进入多个是三个队列头最小的数有多个的情况
            if(arr[i] == arr[p2]*2) p2++;
            if(arr[i] == arr[p3]*3) p3++;
            if(arr[i] == arr[p5]*5) p5++;
        }
        return arr[index-1];
    }
    private int min(int a, int b) {
        return (a > b) ? b : a;
    }
}

34

import java.util.HashMap;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if(str == null || str.length()==0){
            return -1;
        }
        HashMap<Character,Integer> map = new HashMap<>();
        for(int i=0;i<str.length();i++){
            map.put(str.charAt(i),map.getOrDefault(str.charAt(i),0)+1);
        }
        
        for(int index = 0;index<str.length();index++){
            if(map.get(str.charAt(index)) == 1){
                return index;
            }
        }
        return -1;
    }
}

35.....

36
先走dis
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
         if(pHead1 == null || pHead2 == null){
             return null;
         }
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        int len1 = 0;
        int len2 = 0;
        while(p1!=null){
            p1 = p1.next;
            len1++;
        }
        while(p2!=null){
            p2 = p2.next;
            len2++;
        }
        int dis = 0;
        p1 = pHead1;
        p2 = pHead2;
        if(len1>len2){
            dis = len1-len2;
            for(int i=0;i<dis;i++){
                p1 = p1.next;
            }
        }else{
            for(int i=0;i<dis;i++){
                p2 = p2.next;
            }
        }
        while(p1!=p2){
            p1 = p1.next;
            p2 = p2.next;
            if(p1 == p2){
                break;
            }
        }
        return p1!=null? p1 : null;
    }
}

37
public class Solution {
    public int GetNumberOfK(int [] array , int k) {
       if(array == null || array.length == 0){
           return 0;
       }
        int count = 0;
        for(int i=0;i<array.length;i++){
            if(array[i] == k){
                count ++;
            }
        }
        return count;
    }
}

38
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int i = TreeDepth(root.left);
        int j = TreeDepth(root.right);
        
        return i>j? i+1:j+1;
    }
}

39

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null ){
            return true;
        }
        if(Math.abs(depth(root.left)-depth(root.right))>1){
            return false;
        }else{
            return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
        }
    }
    
    private int depth(TreeNode root){
        if(root == null){
            return 0;
        }
        int i = depth(root.left);
        int j = depth(root.right);
        
        return i>j? i+1:j+1;
    }
    
}

40
import java.util.HashMap;
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int num : array){
            map.put(num,map.getOrDefault(num,0)+1);
        }
        boolean flag = false;
        int[] keepNum = new int[2];
        int i = 0;
        for(Integer key : map.keySet()){
            if(map.get(key)%2 == 1){
                keepNum[i++] = key;
            }
        }
        num1[0] = keepNum[0];
        num2[0] = keepNum[1];
    }
}

41
滑动窗口
import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
       ArrayList<ArrayList<Integer> > res = new ArrayList<>();
        int l = 1;
        int r = 2;
        
        while(l<(sum+1)/2){
            int curSum = listSum(l,r);
            if(curSum == sum){
                ArrayList<Integer> list = new ArrayList<>();
                for(int i=l;i<=r;i++){
                    list.add(i);
                }
                res.add(list);
                l++;
            }
            if(curSum < sum){
                r++;
            }else{
                l++;
            }
        }
        
        return res;
    }
    
    private int listSum(int l,int r){
        int sum = 0;
        for(int i=l;i<=r;i++){
            sum +=i;
        }
        return sum;
    }
}

42

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
        ArrayList<Integer> res = new ArrayList<>();
        int left = 0;
        int right = array.length-1;
        int len = array.length;
        while(left < (len+1)/2){
            int curSum = array[left] + array[right];
            if(curSum == sum){
                res.add(array[left]);
                res.add(array[right]);
                break;
            }else if(curSum < sum){
                left ++;
            }else{
                right --;
            }
        }
        return res;
    }
}

43

public class Solution {
    public String LeftRotateString(String str,int n) {
        if(str == null || str.length() == 0 || n<=0){
            return str;
        }
        int len = str.length();
        int k = n%len;
        
        String sub1 = str.substring(0,k);
        String sub2 = str.substring(k,len);
        
        return sub2+sub1;
    }
}

44

public class Solution {
    public String ReverseSentence(String str) {
        if(str == "" || str.length() == 1 || str == null||str.length() == 0){
            return str;
        }
        if(str.trim().equals("")){
            return str;
        }
        String[] strs = str.split(" ");
        String s = "";
        for(int i=strs.length-1;i>=0;i--){
            if(i == strs.length-1)
                s = s+strs[i];
            else
                s = s+" "+strs[i];
        }
        return s;
    }
}

45
import java.util.Arrays;
public class Solution {
    public boolean isContinuous(int [] numbers) {
        if(numbers == null || numbers.length == 0){
            return false;
        }
        Arrays.sort(numbers);
        int zeroNum = 0;
        int gapSize = 0;
        int len = numbers.length;
        for(int i=0;i<len;i++){
            if(numbers[i] == 0){
                zeroNum ++;
            }
        }
        
        int small = zeroNum;
        int big = small+1;
        while(big<len){
            if(numbers[small] == numbers[big]){
                return false;
            }
            gapSize += numbers[big] - numbers[small] -1;
            small = big;
            big++;
        }
        
        return gapSize>zeroNum? false:true;
    }
}
46
约瑟夫环
public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        if(n==0 || m<0){
            return -1;
        }
        ListNode root = new ListNode(0);
        ListNode head = root;
        for(int i=1;i<n;i++){
            root.next = new ListNode(i);
            root = root.next;
        }
        root.next = head;
        while(root != root.next){
            for(int i=0;i<m-1;i++){
                root = root.next;
            }
            root.next = root.next.next;
        }
        return root.val;
    }
    
    class ListNode{
        private ListNode next;
        private int val;
        ListNode(int val){
            this.val = val;
        }
    }
}
47
public class Solution {
    public int Sum_Solution(int n) {
        int sum = n;
        boolean ans = (n>0) && (sum +=Sum_Solution(n-1))>0;
        return sum;
    }
}
48
public class Solution {
    public int Add(int num1,int num2) {
        while(num2!=0){
            int temp = num1^num2;
            num2 = (num1&num2)<<1;
            num1 = temp;
        }
        return num1;
    }
}
49
public class Solution {
    public int StrToInt(String str) {
        if(str == null ||str.length()==0){
            return 0;
        }
        int num = 0;
        boolean flag = false;
        try{
            int index = 0;
            if(str.charAt(0)=='+'){
                index ++;
            }
            if(str.charAt(0)=='-'){
                index++;
                flag = true;
            }
            for(int i=index;i<str.length();i++){
                if(str.charAt(i)>='0'&&str.charAt(i)<='9'){
                    num = num*10 + (str.charAt(i)-'0');
                }else{
                    return 0;
                }
            }
        }catch(Exception e){
            return 0;
        }
        return flag == false? num : -1*num;
    }
}

50
import java.util.HashSet;
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) {
        HashSet<Integer> set = new HashSet<>();
        for(int i=0;i<length;i++){
            if(!set.add(numbers[i])){
                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 == 0){
            return A;
        }
        int len = A.length;
        int[] B = new int[A.length];
        B[0] = 1;
        for(int i=1;i<len;i++){
            B[i] = B[i-1]*A[i-1];
        }
        int temp = 1;
        for(int i=len-2;i>=0;i--){
            temp *= A[i+1];
            B[i] *=temp;
        }
        return B;
    }
}

52...

53...

54
public class Solution {
    //Insert one char from stringstream
    int[] chars = new int[256];
    String sb = "";
    public void Insert(char ch)
    {
        sb += ch;
        chars[ch]++;
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
    for(int i=0;i<sb.length();i++){
        if(chars[sb.charAt(i)]==1){
            return sb.charAt(i);
        }
    }
        return '#';
    }
}

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

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

    public ListNode EntryNodeOfLoop(ListNode pHead)
    {
        if(pHead == null){
            return null;
        }
        
        ListNode pFast = pHead;
        ListNode pSlow = pHead;
        
        while(pFast!=null && pFast.next!=null){
            pFast = pFast.next.next;
            pSlow = pSlow.next;
            if(pFast == pSlow){
                pFast = pHead;
                while(pFast!=pSlow){
                    pFast = pFast.next;
                    pSlow = pSlow.next;
                }
                return pSlow;
            }
        }
        return null;
    }
}

56

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null || pHead.next == null){
            return pHead;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = pHead;
        ListNode curNode = dummy;
        while(curNode.next !=null){
            ListNode nextNode = curNode.next;
            if(nextNode.next!=null && nextNode.val == nextNode.next.val){
                while(nextNode.next!=null && nextNode.next.val == nextNode.val){
                   nextNode = nextNode.next;
                }
                curNode.next = nextNode.next;
            }else{
                curNode = curNode.next;
            }
        }
        return dummy.next;
    }
}

57

public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        if(pNode == null){
            return pNode;
        }
        if(pNode.right !=null){
            pNode = pNode.right;
            while(pNode.left!=null){
                pNode = pNode.left;
            }
            return pNode;
        }
        while(pNode.next!=null){
            if(pNode.next.left == pNode) return pNode.next;
            pNode = pNode.next;
        }
        return null;
    }
}

58
public class Solution {
    boolean isSymmetrical(TreeNode pRoot)
    {
        return Miorror(pRoot,pRoot);
    }
    
    private boolean Miorror(TreeNode node1,TreeNode node2){
        if(node1 == null && node2 == null){
            return true;
        }
        if(node1 == null ||node2 == null){
            return false;
        }
        return (node1.val == node2.val) && Miorror(node1.left,node2.right)&&
            Miorror(node1.right,node2.left);
    }
}

59
import java.util.ArrayList;
import java.util.LinkedList;
/*
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>> res = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        if(pRoot == null){
            return res;
        }
        queue.add(pRoot);
        int index = 0;
        while(!queue.isEmpty()){
            int count = queue.size();
            ArrayList<Integer> subList = new ArrayList<>();
            while(count>0){
                TreeNode pop = queue.poll();
                
                if(index%2 == 1){
                    subList.add(0,pop.val);
                }else{
                    subList.add(pop.val);
                }
                if(pop.left!=null) queue.add(pop.left);
                if(pop.right!=null) queue.add(pop.right);
                count--;
            }
            index++;
            res.add(subList);
        }
        return res;
    }
}
60

import java.util.ArrayList;
import java.util.LinkedList;

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

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

    }

}
*/
public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
         ArrayList<ArrayList<Integer>> res = new ArrayList<>();
         if(pRoot == null){
             return res;
         }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(pRoot);
        int level = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            ArrayList<Integer> subList = new ArrayList<>();
            while(size>0){
                TreeNode pop = queue.poll();
                subList.add(pop.val);
                if(pop.left!=null) queue.add(pop.left);
                if(pop.right!=null) queue.add(pop.right);
                size --;
            }
            res.add(subList);
        }
        return res;
    }
    
}

61

public class Solution {
    String Serialize(TreeNode root) {
        if(root == null){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Serialize1(root,sb);
        return sb.toString();
  }
    public void Serialize1(TreeNode root,StringBuilder sb){
        if(root == null){
            sb.append("#,");
            return;
        }
        sb.append(root.val);
        sb.append(",");
        Serialize1(root.left,sb);
        Serialize1(root.right,sb);
    }
    TreeNode Deserialize(String str) {
       if(str == ""){
           return null;
       }
        String[] strs = str.split(",");
       return Deserialize1(strs);
  }
    int index = -1;
    TreeNode Deserialize1(String[] strs){
        index++;
        if(!strs[index].equals("#") ){
            TreeNode root = new TreeNode(Integer.valueOf(strs[index]));
            root.left = Deserialize1(strs);
            root.right = Deserialize1(strs);
            return root; 
        }
        return null;
    }
}
62
public class Solution {
    int index = 0;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot == null || k<=0){
            return null;
        }
        TreeNode node = KthNode(pRoot.left,k);
        if(node!=null){
            return node;
        }
        index++;
        if(index==k){
            return pRoot;
        }
        node = KthNode(pRoot.right,k);
        if(node!=null){
            return node;
        }
        return null;
    }
}

63

import java.util.ArrayList;
public class Solution {

    ArrayList<Integer> list = new ArrayList<>();
    public void Insert(Integer num) {
        if(list.size() == 0){
            list.add(num);
        }else{
            boolean flag = false;
            for(int e:list){
                if(num < e){
                    int index = list.indexOf(e);
                    list.add(index,num);
                    flag = true;
                    break;
                }
            }
            if(!flag){
                list.add(num);
            }
        }
    }

    public Double GetMedian() {
        if(list.size() == 0){
            return 0.0;
        }
        int len = list.size();
        if(len%2 == 1){
            return (double)list.get((len-1)/2);
        }else{
            return ((double)list.get((len-1)/2)+(double)list.get((len-1)/2 +1))/2;
        }
    }
}

64

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> res = new ArrayList<>();
        if(num == null || size <=0){
            return res;
        }
        int len = num.length;
        if(size > len){
            return res;
        }
        int left = 0;
        while(left+size<= len){
            int max = findMax(num,left,size);
            res.add(max);
            left++;
        }
        return res;
    }
    
    public int findMax(int[] num,int left,int size){
        int max = num[left];
        for(int i=left+1;i<left+size;i++){
            if(num[i]>max){
                max = num[i];
            }
        }
        return max;
    }
}

65

public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        if(matrix == null || rows<=0 || cols<=0 || str == null){
            return false;
        }
        int length = 0;
        boolean[] isVisited = new boolean[rows*cols];
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                if(hasPathCore(matrix,i,rows,j,cols,str,isVisited,length)){
                    return true;
                }
            }
        }
        return false;
    }
    
    private boolean hasPathCore(char[] matrix, int row,int rows,
                                int col,int cols, char[] str,boolean[] isVisited,int length){
        if(length == str.length){
            return true;
        }
        boolean hasPath=false;
        if(row>=0&&row<rows&&
           col>=0&&col<cols&&
           isVisited[row*cols+col]==false&&
           str[length] == matrix[row*cols+col]
          ){
            length ++;
            isVisited[row*cols+col] = true;
            hasPath = hasPathCore(matrix,row+1,rows,col,cols,str,isVisited,length)||
                hasPathCore(matrix,row,rows,col+1,cols,str,isVisited,length)||
                hasPathCore(matrix,row-1,rows,col,cols,str,isVisited,length)||
                hasPathCore(matrix,row,rows,col-1,cols,str,isVisited,length);
            if(!hasPath){
                -- length;
                isVisited[row*cols+col] = false;
            }
        }
        return hasPath;
    }


}

66
public class Solution {
    public int movingCount(int threshold, int rows, int cols)
    {
        if(threshold <=0 || rows<=0 || cols <=0){
            return 0;
        }
        boolean[] isVisited = new boolean[rows*cols];
        
        int count = movingCountCore(threshold,0,rows,0,cols,isVisited);
        return count;
    }
    
    private int movingCountCore(int threshold, int row,int rows,
                                int col, int cols,boolean[] isVisited){
        int count = 0;
        if(check(threshold,row,rows,col,cols,isVisited)){
            isVisited[row*cols+col] = true;
            count = 1+movingCountCore(threshold,row+1,rows,col,cols,isVisited)+
                movingCountCore(threshold,row,rows,col+1,cols,isVisited)+
                movingCountCore(threshold,row-1,rows,col,cols,isVisited)+
                movingCountCore(threshold,row,rows,col-1,cols,isVisited);
        }
        return count;
    }
    
    private boolean check(int threshold, int row,int rows,
                          int col, int cols,boolean[] isVisited){
        if(row>=0&&row<rows&&
           col>=0&&col<cols&&
           isVisited[row*cols+col] == false&&
           getSum(row) + getSum(col) <= threshold
           ){
            return true;
        }
        return false;
    }
    private int getSum(int num){
        int sum = 0;
        while(num>0){
            sum += num%10;
            num /=10;
        }
        return sum;
    }
    
    
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值