剑指Offer编程题汇总(Java版)

整理了牛客网剑指Offer的编程题,提供个人思路的Java代码,部分题目包含高效解法。
摘要由CSDN通过智能技术生成

将牛客网上剑指offer的编程题代码汇总一下,绝大部分是按自己思路写的代码,一部分题目还贴出了大牛们的快捷解法。祝好运!

/*
剑指Offer编程题汇总
*/
//1.
//在一个二维数组中(每个一维数组的长度相同),
//每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
public class Solution {
    public boolean Find(int target, int [][] array) {
        int rows =array.length;
        int cols=array[0].length;
        if(rows==0 || cols==0){
            return false;
        }
        int row=rows-1;
        int col=0;
        while(row>=0 && col<cols ){
            if(target>array[row][col]){
                col++;
            }
            else if(target<array[row][col]){
                row--;
            }else{
                return true;
            }
        }
        return false;
    }
}

//2.
//请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
public class Solution {
    public String replaceSpace(StringBuffer str) {
        return str.toString().replace(" ","%20");
    }
}

//3.
//输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
import java.util.ArrayDeque;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayDeque<Integer> mid = new ArrayDeque<Integer>();
        ArrayList<Integer> result = new ArrayList<>();
        if(listNode==null) {
            return result;
        }
        mid.push(listNode.val);
        while (listNode.next!= null) {
            listNode=listNode.next;
            mid.push(listNode.val);
        }
 
        while (!mid.isEmpty()) {
            result.add(mid.pop());
        }
 
        return result;
}
}

//4.
//输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
//假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.Arrays;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if (pre.length == 0 || in.length == 0) {
            return null;
        }
 
        TreeNode root = new TreeNode(pre[0]);
        for (int i = 0; i < in.length; i++) {
            if (in[i] == pre[0]) {
                root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i));
                root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length),Arrays.copyOfRange(in, i + 1, in.length));
                break;
            }
        }
        return root;
    }
}
//5.
//用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
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.size()<=0){
            while(stack1.size()!=0){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}
//6.
//把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
//输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
//例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
//NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
    public int minNumberInRotateArray(int [] array) {
        if(array.length==0){
            return 0;
        }
        Arrays.sort(array);
        return array[0];
    }
}

//7.
//大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39
public class Solution {
    public int Fibonacci(int n) {
        if (n == 0) {
            return 0;
        } else if (n == 1 || n == 2) {
            return 1;
        } else {
            return Fibonacci(n - 1) + Fibonacci(n - 2);
        }
         
    }
}

//8.
//一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
public class Solution {
    public int JumpFloor(int target) {
        if(target==0){return 0;}
        else if(target==1){return 1;}
        else if(target==2){return 2;}
        else{
            return JumpFloor(target-1)+JumpFloor(target-2);
        }
    }
}
//9.
//一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
public class Solution {
    public int JumpFloorII(int target) {
        if(target==0){
            return 0;
        }
        else if(target==1){
            return 1;
        }
        else if(target==2){
            return 2;
    }
        else{
            return 2*JumpFloorII(target-1);
        }
}
}
//10.
//我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
public class Solution {
    public int RectCover(int target) {
        if(target==0){
            return 0;
        }
       else if(target==1){
            return 1;
    }else if(target==2){
            return 2;
        }else{
            return RectCover(target-1)+RectCover(target-2);
        }
}
//特殊的target=0时输出0,其他时候还是斐波那契递归。
//一个2*n的矩形,可以分为两种方式填充
//1、2*(n-1)  + 2*1 ,此时只要把RectCover(n-1)的那种,再拼接一个竖的2*1的就可以了,方法数目为RectCover(n-1)
//2、2*(n-2) + 2*2,此时2*2可以看成横着放两个1*2,或者竖着放两个2*1,但是其中竖的的正好是方法1的方式,故只算上横的即可,方法数目为RectCover(n-2)
 
}
//11.
//输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
public class Solution {
    public int NumberOf1(int n) {
            int count=0;
    while(n!=0){
        count++;
        n=n&(n-1);
    }
    return count;
    }
}
//12.
//给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。保证base和exponent不同时为0
public class Solution {
    public double Power(double base, int exponent) {
        if (base == 0.0){
            return 0.0;
        }
        // 前置结果设为1.0,即当exponent=0 的时候,就是这个结果
        double result = 1.0d;
        // 获取指数的绝对值
        int e = exponent > 0 ? exponent : -exponent;
        // 根据指数大小,循环累乘
        for(int i = 1 ; i <= e; i ++){
            result *= base;
        }
        // 根据指数正负,返回结果
        return exponent > 0 ? result : 1 / result;
  }
}
//13.
//输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,
//并保证奇数和奇数,偶数和偶数之间的相对位置不变
import java.util.Arrays;
public class Solution {
    public void reOrderArray(int [] array) {
       int[] temp =Arrays.copyOf(array, array.length);
        int count = 0;
        int m=0;
        for (int i : array) {
            if (i % 2 != 0) {
                array[count++] = i;
            }
            else {
                temp[m++]=i;
            }
        }
        int i=count;
        int j=0;
        for(;i<array.length && j<m;i++,j++) {
            array[i]=temp[j];
        }
    }
}
//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 tmp=head.next;
        int length=0;
        if(tmp==null){
            return head;
        }
        while(tmp!=null){
            length++;
            tmp=tmp.next;
        }
        length++;
        if(length==0 || k>length){
            return null;
        }else if(k==length){
            return head;
        }
         
        int index=length-k;
        tmp=head;
        while(index>0){
            if(tmp!=null){
                tmp=tmp.next;
                index--;
            }
        }
        return tmp;
    }
}
//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;
        }else if(head.next==null){
            return head;
        }
        ListNode reverseTmp=new ListNode(0);
        ListNode tmp=head;
        ListNode next=null;
        while(tmp!=null){
            next=tmp.next;
            tmp.next=reverseTmp.next;
            reverseTmp.next=tmp;
            tmp=next;
        }
         
        head=reverseTmp.next;
        return head;
    }
}
//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) {
            return list2;
        } else if (list2 == null) {
            return list1;
        }
 
        ListNode tmp1 = list1;
        ListNode tmp2 = list2;
        ListNode result = null;
        if(tmp1.val<=tmp2.val) {
            result=tmp1;
            tmp1=tmp1.next;
        }else {
            result=tmp2;
            tmp2=tmp2.next;
        }
        ListNode tmp3 = null;
        tmp3=result;
        while (tmp1 != null && tmp2 != null) {
            if(tmp1.val<=tmp2.val) {
                tmp3.next=tmp1;
                tmp1=tmp1.next;
                tmp3=tmp3.next;
            }else {
                tmp3.next=tmp2;
                tmp2=tmp2.next;
                tmp3=tmp3.next;
            }
        }
 
        while (tmp1 != null) {
            tmp3.next = tmp1;
            tmp3 = tmp3.next;
            tmp1 = tmp1.next;
        }
        while (tmp2 != null) {
            tmp3.next = tmp2;
            tmp3 = tmp3.next;
            tmp2 = tmp2.next;
        }
        return result;
}
}
//17.
//输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
/**
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(root2==null)return false;
        if(root1==null && root2!=null) return false;
        boolean flag=false;
        if(root1.val==root2.val){
            flag=issubtree(root1,root2);
        }
        if(!flag){
            flag=HasSubtree(root1.left,root2);
            if(!flag){
                flag=HasSubtree(root1.right,root2);
            }
        }
        return flag;
    }
    private boolean issubtree(TreeNode root1,TreeNode root2){
        if(root2==null)return true;
        if(root1==null && root2!=null) return false;
        if(root1.val==root2.val){
            return issubtree(root1.left,root2.left) && issubtree(root1.right,root2.right);
        }
        else{
            return false;
        }
    }
}

//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) {
            if (root.left != null && root.right != null) {
                TreeNode tmp = root.left;
                root.left = root.right;
                root.right = tmp;
                Mirror(root.left);
                Mirror(root.right);
            } else if (root.left == null && root.right != null) {
                root.left = root.right;
                root.right = null;
                Mirror(root.left);
            } else if (root.right == null && root.left != null) {
                root.right = root.left;
                root.left = null;
                Mirror(root.right);
            } else {
                return;
            }
        } else {
            return;
        }
 
    }
}
//19.
//输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
//例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        int rlength = matrix.length;
        int clength = matrix[0].length;
        int size = rlength * clength;
        ArrayList<Integer> result = new ArrayList<Integer>();
        int r = 0;
        int c = 0;
        int index = 0;
        while (size > 0) {
            while (c < clength) {
                result.add(matrix[r][c++]);
                size--;
            }
            if(size<=0) {break;}
            r++;
            c--;
            while (r < rlength) {
                result.add(matrix[r++][c]);
                size--;
            }
            if(size<=0) {break;}
            c--;
            r--;
            while (c >=index) {
                result.add(matrix[r][c--]);
                size--;
            }
            if(size<=0) {break;}
            r--;
            c++;
            while (r > index) {
                result.add(matrix[r--][c]);
                size--;
            }
            if(size<=0) {break;}
            c++;
            r++;
             
            rlength = rlength - 1;
            clength = clength - 1;
            index = index + 1;
        }
        return result;
}
}

定义四个变量代表范围,up、down、left、right
向右走存入整行的值,当存入后,该行再也不会被遍历,代表上边界的 up 加一,同时判断是否和代表下边界的 down 交错
向下走存入整列的值,当存入后,该列再也不会被遍历,代表右边界的 right 减一,同时判断是否和代表左边界的 left 交错
向左走存入整行的值,当存入后,该行再也不会被遍历,代表下边界的 down 减一,同时判断是否和代表上边界的 up 交错
向上走存入整列的值,当存入后,该列再也不会被遍历,代表左边界的 left 加一,同时判断是否和代表右边界的 right 交错


import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> list = new ArrayList<>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return list;
        }
        int up = 0;
        int down = matrix.length-1;
        int left = 0;
        int right = matrix[0].length-1;
        while(true){
            // 最上面一行
            for(int col=left;col<=right;col++){
                list.add(matrix[up][col]);
            }
            // 向下逼近
            up++;
            // 判断是否越界
            if(up > down){
                break;
            }
            // 最右边一行
            for(int row=up;row<=down;row++){
                list.add(matrix[row][right]);
            }
            // 向左逼近
            right--;
            // 判断是否越界
            if(left > right){
                break;
            }
            // 最下面一行
            for(int col=right;col>=left;col--){
                list.add(matrix[down][col]);
            }
            // 向上逼近
            down--;
            // 判断是否越界
            if(up > down){
                break;
            }
            // 最左边一行
            for(int row=down;row>=up;row--){
                list.add(matrix[row][left]);
            }
            // 向右逼近
            left++;
            // 判断是否越界
            if(left > right){
                break;
            }
        }
        return list;
    }
}
//20.
//定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
//注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
import java.util.Stack;
 
public class Solution {
 
    public Stack<Integer> stack=new Stack<>();
    public void push(int node) {
        stack.push(node);
    }
     
    public void pop() {
        stack.pop();
    }
     
    public int top() {
        return stack.peek();
    }
     
    public int min() {
        int minItem = 0;
        Stack<Integer> tmp = new Stack<>();
        if (stack != null) {
            minItem = stack.peek();
        }
        while (!stack.isEmpty()) {
             
            if (stack.peek() <= minItem) {
                minItem = stack.peek();
            }
            tmp.push(stack.pop());
        }
        while (!tmp.isEmpty()) {
            stack.push(tmp.pop());
        }
        return minItem;
    }
}
//21.
//输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。
//例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
//(注意:这两个序列的长度是相等的)
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        if (popA.length != pushA.length) {
            return false;
        } else {
            Stack<Integer> tmp = new Stack<>();
            int i = 0;
            int j = 0;
            while (i < pushA.length) {
                tmp.push(pushA[i]);
 
                if (pushA[i] == popA[j]) {
                    tmp.pop();
                    j++;
                }
                i++;
            }
            while (j < popA.length) {
                if (popA[j] == tmp.peek()) {
                    tmp.pop();
                }
                j++;
            }
            if (tmp.isEmpty()) {
                return true;
            } else {
                return false;
            }
        }
    }
}
//22.
//从上往下打印出二叉树的每个节点,同层节点从左至右打印。
import java.util.ArrayList;
import java.util.ArrayDeque;
/**
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<>();
        if(root==null){
            return result;
        }else{
		ArrayDeque<TreeNode> tmp = new ArrayDeque<TreeNode>();
		tmp.add(root);
		while (!tmp.isEmpty()) {
			root = tmp.pollFirst();
			if (root.left != null) {
				tmp.offer(root.left);
			}
			if (root.right != null) {
				tmp.offer(root.right);
			}
			result.add(root.val);
		}
		return result;
        }
	}
    
}
//23.
//输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
import java.util.Stack;
public class Solution {
    public static boolean VerifySquenceOfBST(int[] sequence) {
        if(sequence.length==0){
            return false;
        }
        Stack<Integer> tmp = new Stack<>();
        for (int i = 0; i < sequence.length; i++) {
            tmp.push(sequence[i]);
        }
        int top = tmp.pop();
 
        return pd(tmp, top);
    }
 
    private static boolean pd(Stack<Integer> tmp, int top) {
        if (tmp.isEmpty()) {
            return true;
        }
        if (tmp.peek() < top) {
            while (!tmp.isEmpty()) {
                if (tmp.peek() > top) {
                    return false;
                }
                tmp.pop();
            }
            return true;
        } else {
            if (!tmp.isEmpty()) {
                tmp.pop();
                return pd(tmp, top);
            } else {
                return true;
            }
        }
    }
}
//24.
//输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
//路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
import java.util.ArrayList;
/**
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) {
        if (root == null) {
            ArrayList<ArrayList<Integer>> tmp=new ArrayList<ArrayList<Integer>>();
            return tmp;
        }
 
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> path = new ArrayList<>();
        getAllPath(root, result, path);
        ArrayList<ArrayList<Integer>> finalresult = new ArrayList<ArrayList<Integer>>();
        for (ArrayList<Integer> a : result) {
            int sum = 0;
            for (int t : a) {
                sum += t;
            }
            if (sum == target) {
                finalresult.add(a);
            }
        }
        for (int i = 0; i < finalresult.size() - 1; i++) {
            for (int j = 0; j < finalresult.size() - 1 - i; j++) {
                ArrayList<Integer> tmp = new ArrayList<Integer>();
                if (finalresult.get(j + 1).size() >= finalresult.get(j).size()) {
                    tmp = finalresult.get(j);
                    finalresult.set(j, finalresult.get(j + 1));
                    finalresult.set(j + 1, tmp);
                }
            }
        }
 
        return finalresult;
 
    }
        private static void getAllPath(TreeNode root, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> path) {
        if (root != null) {
            path.add(root.val);
        }
        if (root.left != null) {
            getAllPath(root.left, result, path);
        }
        if (root.right != null) {
            getAllPath(root.right, result, path);
        }
        if (root.left == null && root.right == null) {
//          System.out.println(path);
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            for (int a : path) {
                tmp.add(a);
            }
            result.add(tmp);
            path.remove(path.size() - 1);
            return;
        }
        path.remove(path.size() - 1);
    }
}

public class Solution {
    private ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    private ArrayList<Integer> list = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root == null)return result;
        list.add(root.val);
        target -= root.val;
        if(target == 0 && root.left == null && root.right == null)
            result.add(new ArrayList<Integer>(list));
//因为在每一次的递归中,我们使用的是相同的result引用,所以其实左右子树递归得到的结果我们不需要关心,
//可以简写为FindPath(root.left, target);FindPath(root.right, target);
//但是为了大家能够看清楚递归的真相,此处我还是把递归的形式给大家展现了出来。
        ArrayList<ArrayList<Integer>> result1 = FindPath(root.left, target);
        ArrayList<ArrayList<Integer>> result2 = FindPath(root.right, target);
        list.remove(list.size()-1);
        return result;
    }
}
//25.
//输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),
//返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;
 
    RandomListNode(int label) {
        this.label = label;
    }
}
*/
import java.util.HashMap;
public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        if (pHead == null) {
            return pHead;
        }
        RandomListNode h1 = pHead;
        RandomListNode h2 = new RandomListNode(pHead.label);
 
        HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
 
        map.put(h1, h2);
        while (h1.next != null) {
            if (map.get(h1.next) == null) {
                h2.next = new RandomListNode(h1.next.label);
            } else {
                h2.next = map.get(h1.next);
            }
 
            if (h1.random != null) {
                if (map.get(h1.random) == null) {
                    h2.random = new RandomListNode(h1.random.label);
                } else {
                    h2.random = map.get(h1.random);
                }
            }
            h1 = h1.next;
            h2 = h2.next;
            map.put(h1, h2);
        }
        return map.get(pHead);
    }
}
//26.
//输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
import java.util.ArrayList;
public class Solution {
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return pRootOfTree;
        }
        ArrayList<TreeNode> result = new ArrayList<>();
        prefixOrder(pRootOfTree, result);
 
        for (int i = 0; i < result.size() - 1; i++) {
            result.get(i).right = result.get(i + 1);
            result.get(i + 1).left = result.get(i);
        }
 
        return result.get(0);       
    }
    private static void prefixOrder(TreeNode pRootOfTree, ArrayList<TreeNode> result) {
        if (pRootOfTree.left != null) {
            prefixOrder(pRootOfTree.left, result);
        }
        result.add(pRootOfTree);
        if (pRootOfTree.right != null) {
            prefixOrder(pRootOfTree.right, result);
        }
    }   
}
//27.
//输入一个字符串,按字典序打印出该字符串中字符的所有排列。
//例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
//输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
import java.util.ArrayList;
public class Solution {
    public ArrayList<String> Permutation(String str) {
        ArrayList<String> result = new ArrayList<String>();
        result = permutationHelp(str);
        return result;
    }
    private static ArrayList<String> permutationHelp(String str) {
        ArrayList<String> result = new ArrayList<>();
        if (str.length() == 0 ) {
            return result;
        }
        if(str.length()==1){
            result.add(str);
            return result;
        }
        char[] strArr = str.toCharArray();
 
        for (int i = 0; i < strArr.length; i++) {
            if (i == 0 || strArr[i] != strArr[0]) {
                // 将每个字符提到第一位去
                char firstOne = strArr[i];
                strArr[i] = strArr[0];
                strArr[0] = firstOne;
                // 截取除了第一位的剩余字符作为新的操作字符串
                String lowString = "";
                for (char ch : strArr) {
                    lowString = lowString + ch;
                }
                ArrayList<String> lowresult = permutationHelp(lowString.substring(1));
 
                for (String a : lowresult) {
                    result.add(firstOne + "" + a);
                }
            }
        }
        return result;
    }
}
//28.
//数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
//例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
import java.util.HashMap;
import java.util.Map.Entry;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        int length = array.length;
        if (length == 0) {
            return 0;
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < length; i++) {
            if (map.get(array[i]) !=null) {
                int oldValue = map.get(array[i]);
                map.replace(array[i], oldValue, ++oldValue);
            } else {
                map.put(array[i], 1);
            }
 
        }
 
        for (Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() >length / 2) {
                return entry.getKey();
            }
             
        }
        return 0;
    }
}
//29.
//输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> result = new ArrayList<>();
        if (k == 0 || k > input.length || input.length == 0) {
            return result;
        }
 
        int[] tmp = input;
        quickSort(tmp, 0, tmp.length - 1);
        int lastNum = tmp[0];
        result.add(tmp[0]);
        k--;
        for (int i = 1; i < tmp.length && k > 0; i++) {
            if (tmp[i] != lastNum) {
                result.add(tmp[i]);
                lastNum = tmp[i];
                k--;
            }
 
        }
        return result;
    }
    private static void quickSort(int[] arr, int left, int right) {
        int l = left; // 左下标
        int r = right; // 右下标
 
        int pivot = arr[(left + right) / 2];
        int temp = 0;
 
        while (l < r) {
 
            while (arr[l] < pivot) {
                l += 1;
            }
 
            while (arr[r] > pivot) {
                r -= 1;
            }
 
            if (l >= r) {
                break;
            }
 
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
 
            if (arr[l] == pivot) {
                r -= 1;
            }
 
            if (arr[r] == pivot) {
                l += 1;
            }
        }
 
        if (l == r) {
            l += 1;
            r -= 1;
        }
 
        if (left < r) {
            quickSort(arr, left, r);
        }
 
        if (right > l) {
            quickSort(arr, l, right);
        }
    }
}
链接:https://www.nowcoder.com/questionTerminal/6a296eb82cf844ca8539b57c23e6e9bf?answerType=1&f=discussion
来源:牛客网

//题目的思路还是非常简单的:维持一个K长度的最小值集合,然后利用插入排序的思想进行对前K个元素的不断更新。
//但是非常让人气愤的是居然if(k<= 0 || k > input.length)return result的判断占据了用例的大部分。

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
 
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(k<= 0 || k > input.length)return result;
        //初次排序,完成k个元素的排序
        for(int i = 1; i< k; i++){
            int j = i-1;
            int unFindElement = input[i];
            while(j >= 0 && input[j] > unFindElement){
                input[j+1] = input[j];
                j--;
            }
 
            input[j+1] = unFindElement;
        }
        //遍历后面的元素 进行k个元素的更新和替换
        for(int i = k; i < input.length; i++){
            if(input[i] < input[k-1]){
                int newK = input[i];
                int j = k-1;
                while(j >= 0 && input[j] > newK){
                    input[j+1] = input[j];
                    j--;
                }
                input[j+1] = newK;
            }
        }
        //把前k个元素返回
        for(int i=0; i < k; i++)
            result.add(input[i]);
        return result;
    }
}

//30.
//HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。
//但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},
//连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        if (array.length == 0) {
            return 0;
        }
        ArrayList<int[]> result = new ArrayList<int[]>();
        for (int i = 0; i < array.length; i++) {
            int[] arr = Arrays.copyOfRange(array, i, array.length);
            int[] sum = getSum(arr);
            result.add(sum);
        }
        int max = getMax(result.get(0));
        for (int[] a : result) {
            if (getMax(a) >= max) {
                max = getMax(a);
            }
        }
        return max;
    }
    private static int getMax(int[] arr) {
        if (arr.length == 1) {
            return arr[0];
        }
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= max) {
                max = arr[i];
            }
        }
        return max;
    }
 
    private static int[] getSum(int[] array) {
        int[] sum = new int[array.length];
        int total = 0;
        for (int i = 0; i < array.length; i++) {
            sum[i] = array[i] + total;
            total += array[i];
        }
        return sum;
 
    }
}
//31.
//求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。
//ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        if (n <= 0) {
            return 0;
        }
        int index = 0;
        for (int i = 1; i <=n; i++) {
            String str = i + "";
            char[] ch = str.toCharArray();
            for (int j = 0; j < ch.length; j++) {
                if ('1' == ch[j]) {
                    index++;
                }
            }
        }
        return index;
    }
}

//32.
//输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
//例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
import java.util.ArrayList;
 
public class Solution {
    public String PrintMinNumber(int [] numbers) {
        if (numbers.length == 0) {
            return "";
        }
        if (numbers.length == 1) {
            return numbers[0] + "";
        }
 
        for (int i = 0; i < numbers.length; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                int num1 = Integer.valueOf(numbers[i] + "" + numbers[j]);
                int num2 = Integer.valueOf(numbers[j] + "" + numbers[i]);
                if (num1 > num2) {
                    int temp = numbers[j];
                    numbers[j] = numbers[i];
                    numbers[i] = temp;
                }
            }
 
        }
        String str = new String("");
        for (int i = 0; i < numbers.length; i++)
            str = str + numbers[i];
        return str;
    }
}

//33.
//把只包含质因子2、3和5的数称作丑数(Ugly Number)。
//例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
import java.util.ArrayDeque;
public class Solution {
    public int GetUglyNumber_Solution(int index) {
        if (index == 0) {
            return 0;
        }
        if (index == 1) {
            return 1;
        }
        int[] uglynumber = new int[index];
        uglynumber[0] = 1;
        // 丑数可以理解为丑数本身乘以(2,3,5)得到的
        ArrayDeque<Integer> Pnum2 = new ArrayDeque<>();
        ArrayDeque<Integer> Pnum3 = new ArrayDeque<>();
        ArrayDeque<Integer> Pnum5 = new ArrayDeque<>();
        int m;
        for (int i = 1; i < index; i++) {
            Pnum2.offer(uglynumber[i - 1] * 2);
            Pnum3.offer(uglynumber[i - 1] * 3);
            Pnum5.offer(uglynumber[i - 1] * 5);
            m = Math.min(Math.min(Pnum2.getFirst(), Pnum3.getFirst()), Pnum5.getFirst());
            uglynumber[i] = m;
            if (Pnum2.contains(m)) {
                Pnum2.poll();
            }
            if (Pnum3.contains(m)) {
                Pnum3.poll();
            }
            if (Pnum5.contains(m)) {
                Pnum5.poll();
            }
        }
 
        return uglynumber[index - 1];
    }
}
//34.
//在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
import java.util.ArrayList;
import java.util.LinkedHashSet;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if(str.length()==0){
            return -1;
        }
        LinkedHashSet<Character> set = new LinkedHashSet<>();
        ArrayList<Character> list = new ArrayList<>();
        char[] strchar = str.toCharArray();
        for (int i = 0; i < strchar.length; i++) {
            if (!set.contains(strchar[i])) {
                set.add(strchar[i]);
            }
            list.add(strchar[i]);
        }
        for (char a : set) {
            int index = list.indexOf(a);
            int num = 1;
            for (int i = index + 1; i < strchar.length; i++) {
                if (strchar[i] == a) {
                    num++;
                }
            }
            if (num == 1) {
                return index;
            }
        }
 
        return 0;
    }
}
刚开始还以为有什么特殊的解法,没想到当年也是按照hash的思想来做的,先统计出现的次数,然后在返回相应的index
链接:https://www.nowcoder.com/questionTerminal/1c82e8cf713b4bbeb2a5b31cf5b0417c?answerType=1&f=discussion
来源:牛客网

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if(str==null || str.length() == 0)return -1;
        int[] count = new int[256];
        //用一个类似hash的东西来存储字符出现的次数,很方便
        for(int i=0; i < str.length();i++)
            count[str.charAt(i)]++;
        //其实这个第二步应该也是ka我的地方,没有在第一时间想到只要在遍历一遍数组并访问hash记录就可以了
        for(int i=0; i < str.length();i++)
            if(count[str.charAt(i)]==1)
                return i;
        return -1;
    }
}
//35.
//在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。
//输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
public class Solution {
    private int count = 0;
 
    public void MergeSort(int[] array, int start, int end) {
        if (start >= end) {
            return;
        }
        int mid = (start + end) / 2;
        MergeSort(array, start, mid);
        MergeSort(array, mid + 1, end);
        Merge(array, start, mid, end);
    }
 
    public void Merge(int[] array, int start, int mid, int end) {
        int[] temp = new int[end - start + 1];
        int l = start;
        int r = mid + 1;
        int index = 0;
 
        while (l <=mid && r <=end) {
            if (array[l] <= array[r]) {
                temp[index++] = array[l++];
            } else {
                temp[index++] = array[r++];
                count = (count + (mid + 1 - l)) % 1000000007;
            }
        }
 
        while (l <=mid) {
            temp[index++] = array[l++];
        }
        while (r <=end) {
            temp[index++] = array[r++];
        }
 
        for (int i = 0; i < index; i++) {
            array[start + i] = temp[i];
        }
    }
    public int InversePairs(int [] array) {
        MergeSort(array, 0, array.length - 1);
        return count;
    }
}
//36.
//输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
/*
public class ListNode {
    int val;
    ListNode next = null;
 
    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode tmp1 = pHead1;
        while (tmp1!= null) {
            ListNode tmp2 = pHead2;
            while (tmp2!= null) {
                if (tmp1 == tmp2) {
                    return tmp1;
                }
                tmp2 = tmp2.next;
            }
            tmp1 = tmp1.next;
        }
        return null;
    }
}
//37.
//统计一个数字在排序数组中出现的次数。
public class Solution {
    public int GetNumberOfK(int [] array , int k) {
        if (array.length == 0) {
            return 0;
        }
        int index = 0;
        for (int i = 0; i < array.length; i++) {
            if (k == array[i]) {
                index++;
            }
        }
        return index;
    }
 
}
链接:https://www.nowcoder.com/questionTerminal/70610bf967994b22bb1c26f9ae901fa2?answerType=1&f=discussion
来源:牛客网

import java.util.Arrays;
public class Solution {
 
    public int GetNumberOfK(int [] array , int k) {
        int index = Arrays.binarySearch(array, k);
        if(index<0)return 0;
        int cnt = 1;
        for(int i=index+1; i < array.length && array[i]==k;i++)
            cnt++;
        for(int i=index-1; i >= 0 && array[i]==k;i--)
            cnt++;
        return cnt;
 
    }
}
//38.
//输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
import java.util.ArrayList;
public class Solution {
    public int TreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
 
        return height(root);
    }
 
    public static int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(root.left == null ? 0 : height(root.left), root.right == null ? 0 : height(root.right)) + 1;
    }
}

//非递归:用队列,count是当前的节点,nextcount是当前深度总的节点。【总是要遍历到当前深度的最后一个节点,深度才加1】
链接:https://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b?answerType=1&f=discussion
来源:牛客网

import java.util.LinkedList;
import java.util.Queue;
 public int TreeDepth1(TreeNode root) {
    if(root==null) {
      return 0;
    }
    Queue<TreeNode> q=new LinkedList<TreeNode>();
    q.add(root);
    int d=0,count=0,nextcount=q.size();
    while(q.size()!=0) {
      TreeNode t=q.poll();
      count++;
      if(t.left!=null) {
           q.add(t.left);
      }
      if(t.right!=null) {
           q.add(t.right);
      }
      if(count==nextcount) {
           d++;
           count=0;
           nextcount=q.size();
      }
    }
    return d;
}

//39.
//输入一棵二叉树,判断该二叉树是否是平衡二叉树。
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (root.left == null && root.right == null) {
            return true;
        }
 
        if ((height(root.left) > height(root.right) + 1) || (height(root.left) + 1 < height(root.right))) {
            return false;
        }
        if (root.left != null)
            return IsBalanced_Solution(root.left);
        else if (root.right != null)
            return IsBalanced_Solution(root.right);
        else {
            return true;
        }
    }
    public static int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(root.left == null ? 0 : height(root.left), root.right == null ? 0 : height(root.right)) + 1;
    }
}
//40.
//一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
import java.util.ArrayList;
import java.util.HashSet;
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        if (array.length == 0) {
            return;
        }
 
        int index = 0;
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < array.length; i++) {
            if (!set.contains(array[i])) {
                set.add(array[i]);
            }
        }
        ArrayList<Integer> result = new ArrayList<>();
 
        for (int a : set) {
            for (int i = 0; i < array.length; i++) {
                if (array[i] == a) {
                    index++;
                }
            }
            if (index == 1) {
                result.add(a);
            }
            index = 0;
        }
 
        num1[0] = result.get(0);
        num2[0] = result.get(1);
    }
}
链接:https://www.nowcoder.com/questionTerminal/e02fdb54d7524710a7d664d082bb7811?answerType=1&f=discussion
来源:牛客网

//首先:位运算中异或的性质:两个相同数字异或=0,一个数和0异或还是它本身。
//当只有一个数出现一次时,我们把数组中所有的数,依次异或运算,最后剩下的就是落单的数,因为成对儿出现的都抵消了。

//依照这个思路,我们来看两个数(我们假设是AB)出现一次的数组。我们首先还是先异或,剩下的数字肯定是A、B异或的结果
//,这个结果的二进制中的1,表现的是A和B的不同的位。我们就取第一个1所在的位数,假设是第3位,接着把原数组分成两组,分组标准是第3位是否为1。
//如此,相同的数肯定在一个组,因为相同数字所有位都相同,而不同的数,肯定不在一组。然后把这两个组按照最开始的思路,依次异或,剩余的两个结果就是这两个只出现一次的数字。
链接:https://www.nowcoder.com/questionTerminal/e02fdb54d7524710a7d664d082bb7811?answerType=1&f=discussion
来源:牛客网

public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
 
        int xor1 = 0;
        for(int i=0; i < array.length; i++)
            xor1 = xor1^array[i];
        //在xor1中找到第一个不同的位对数据进行分类,分类为两个队列对数据进行异或求和找到我们想要的结果
        int index = 1;
        while((index & xor1)==0)
            index = index <<1;//因为可能有多个位为1所以需要求一下位置
        int result1 = 0;
        int result2 = 0;
        for(int i=0; i < array.length; i++){
            if((index & array[i]) == 0)
                result1 = result1^array[i];
            else
                result2 = result2^array[i];
        }
        num1[0] = result1;
        num2[0] = result2;
}

//41.
//小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。
//没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (sum == 0) {
            return result;
        }
        if(sum==1){
            return result;
        }
 
        int testNum = (sum / 2)+1;
        for (int i = 1; i <= testNum; i++) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int j = i; j <=testNum; j++) {
                list.add(j);
            }
            int total = getsum(list);
            while (total > sum) {
                list.remove(list.size() - 1);
                total = getsum(list);
            }
            if (total == sum) {
                result.add(list);
            }
        }
        return result;
    }
    public static int getsum(ArrayList<Integer> list) {
        int result = 0;
        for (int a : list) {
            result += a;
        }
        return result;
    }
}
链接:https://www.nowcoder.com/questionTerminal/c451a3fd84b64cb19485dad758a55ebe?answerType=1&f=discussion
来源:牛客网

import java.util.ArrayList;
 
/**
思路:
输入sum=20(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
1,定义两个指针,左指针从1开始,右指针从2开始
循环开始
2,求和(1+2 = 3
3,如果判断3小于20,右指针++,2变为3,求和3+3=6。循环一直到右指针=6,和为21。
4,else if 判断21大于20,左指针++,1变为2,和减去左指针值,和为21-1=20。
5,else 和与输入一样,存数。   【再把右指针++,求和,求剩余组合】
循环结束
*/
public class Solution {
    public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer>> resp = new ArrayList<>();
        if(sum <= 0){
            return resp;
        }
        int leftP = 1;
        int rightP = 2;
        int sumVal = leftP + rightP;
 
        while(sum > rightP){
            if(sumVal < sum){
                rightP++;
                sumVal += rightP;
            } else if (sumVal > sum){
                sumVal -= leftP;
                leftP++;
            } else {
                ArrayList<Integer> list = new ArrayList<>();
                for (int i=leftP; i<=rightP; i++) {
                    list.add(i);
                }
                resp.add(list);
 
                rightP++;
                sumVal += rightP;
            }
        }
 
        return resp;
 
    }
}
//42.
//输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
        ArrayList<Integer> result = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (sum == array[i] + array[j]) {
                    result.add(array[i]);
                    result.add(array[j]);
                }
            }
        }
        if (result.size() == 0) {
            return result;
        }
        int min = result.get(0) * result.get(1);
        ArrayList<Integer> finalresult = new ArrayList<>();
        for (int i = 0; i < result.size(); i += 2) {
            if (result.get(i) * result.get(i + 1) <= min) {
                min = result.get(i) * result.get(i + 1);
                finalresult.add(result.get(i));
                finalresult.add(result.get(i + 1));
 
            }
        }
 
        return finalresult;
 
    }
}
链接:https://www.nowcoder.com/questionTerminal/390da4f7a00f44bea7c2f3d19491311b?answerType=1&f=discussion
来源:牛客网

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
        ArrayList<Integer> result=new ArrayList<Integer>();
        //边界条件
        if(array==null||array.length<=1){
            return result;
        }
        int smallIndex=0;
        int bigIndex=array.length-1;
        while(smallIndex<bigIndex){
            //如果相等就放进去
             if((array[smallIndex]+array[bigIndex])==sum){
                result.add(array[smallIndex]);
                result.add(array[bigIndex]);
                 //最外层的乘积最小,别被题目误导
                 break;
        }else if((array[smallIndex]+array[bigIndex])<sum){
                 smallIndex++;
             }else{
                 bigIndex--;
             }
        }
        return result;
}
}
//43.
//汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。
//对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
public class Solution {
    public String LeftRotateString(String str,int n) {
        if (n == 0) {
            return str;
        }
        char[] chrarray = str.toCharArray();
        int len = str.length();
        char[] tmp = new char[len];
        for (int i = 0; i < len; i++) {
            tmp[(i - n + len) % len] = chrarray[i];
        }
        String result = "";
        for (int i = 0; i < len; i++) {
            result = result + tmp[i];
        }
        return result;
 
    }
}
//44.
//牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。
//例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
public class Solution {
    public String ReverseSentence(String str) {
        if(str.length()<=0||str==null){
            return str;
        }
        String a=str;
        if(a.trim().length()==0){
            return str;
        }
        else{
        String[] test = str.split(" ");
        int len = test.length;
        String[] tmp = new String[len];
        for (int i = 0; i < len; i++) {
            tmp[len-i-1] = test[i];
        }
        String result = "";
        for (int i = 0; i < len; i++) {
            result = result + tmp[i]+" ";
        }
        return result.trim();
        }
    }
}
//剑指offer的思想,先翻转所有的字符,然后利用滑动窗口的思想,遇到' '就翻转,然后两者一起跳转到' '后重新滑动。
链接:https://www.nowcoder.com/questionTerminal/3194a4f4cf814f63919d0790578d51f3?answerType=1&f=discussion
来源:牛客网

/**
 * @author caoduanxi
 * @Date 2020/2/6 13:18
 */
public String ReverseSentence(String str) {
    if (str == null || str.trim().length() == 0) return str;
    char[] chars = str.toCharArray();
    reverseChars(chars, 0, str.length() - 1);
    // 利用滑动窗口
    // 遇到' '执行翻转
    int l = 0;
    int r = 0;
    while (l < str.length()) {
        if (chars[r] == ' ') {
            reverseChars(chars, l, r - 1);
            // 交换完之后,一起跳过' '
            r++;
            l = r;
        }
        if (r == str.length() - 1) {
            reverseChars(chars, l, r);
            // 到了最后交换玩就break,否则r会出现越界,可以在while中加对r的判断
            break;
        }
        r++;
    }
    return String.valueOf(chars);
}
private void reverseChars(char[] chars, int l, int r) {
    while (l < r) {
        char temp = chars[l];
        chars[l] = chars[r];
        chars[r] = temp;
        l++;
        r--;
    }
}
//45.
//LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...
//他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”
//不是顺子.....LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。
//LL决定去买体育彩票啦。 
//现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。
import java.util.TreeSet;
public class Solution {
    public boolean isContinuous(int [] numbers) {
        if(numbers.length < 5 || numbers.length > 5) {
            return false;
        }
        int num = 0;
        TreeSet<Integer> set = new TreeSet<> ();
        for (int i=0; i<numbers.length;i++) {
            if (numbers[i]==0) {
                num ++;
            } else {
                set.add(numbers[i]);
            }
        }
        if ((num + set.size()) != 5) {
            return false;
        }
        if ((set.last() - set.first()) < 5) {
            return true;
        }
        return false;
    }
}
//46.
//每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。
//其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。
//每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,
//可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
//如果没有小朋友,请返回-1
/*
经典的约瑟夫问题
*/
public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        BoyLinkedlist list = new BoyLinkedlist();
        list.addBoy(n);
        list.countBoy(0, m, n);
        if (list.first == null) {
            return -1;
        } else {
            return list.first.no-1;
        }
    }
}
class BoyLinkedlist {
    public Boy first = null;
 
    public void addBoy(int n) {
        if (n < 1) {
            return;
        }
        Boy curboy = null;
        for (int i = 1; i <= n; i++) {
            Boy boy = new Boy(i);
            if (i == 1) {
                first = boy;
                first.next = first;
                curboy = first;
            } else {
                curboy.next = boy;
                boy.next = first;
                curboy = boy;
            }
        }
    }
 
    public void countBoy(int startNo, int countNum, int nums) {
        if (first == null || startNo < 0 || startNo > nums) {
            return;
        }
        Boy helper = first;
        while (true) {
            if (helper.next == first) {
                break;
            }
            helper = helper.next;
        }
 
        for (int i = 0; i < startNo - 1; i++) {
            first = first.next;
            helper = helper.next;
        }
 
        while (true) {
            if (helper == first) {
                break;
            }
            for (int j = 0; j < countNum - 1; j++) {
                first = first.next;
                helper = helper.next;
            }
            first = first.next;
            helper.next = first;
        }
    }
 
    class Boy {
        public int no;
        public Boy next;
 
        public Boy(int no) {
            super();
            this.no = no;
        }
    }
 
}

//47.
//求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
public class Solution {
    public int Sum_Solution(int n) {
        int sum = n;
        // n=1时直接返回1
        boolean flag = (sum > 0) && ((sum += Sum_Solution(n - 1)) > 0);
        return sum;
    }
}
//48.
//写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
public class Solution {
    public int Add(int num1,int num2) {
        int sum, carray;
        do {
            sum = num1 ^ num2;
            carray = (num1 & num2) << 1;
            num1 = sum;
            num2 = carray;
        } while (num2 != 0);
        return num1;
    }
}

//49.
//将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
public class Solution {
    public int StrToInt(String str) {
         // \d代表[0-9] 但是要写成\\d才行。
        if(!str.matches("[1-9,+,-]\\d+")) return 0;
        int len = str.length();
        int i = len-1;
        long res = 0;  //long类型,避免溢出。不能用int
  
        while(i>=0&&str.charAt(i)>='0'&&str.charAt(i)<='9'){
            res += Math.pow(10,len-1-i)*(str.charAt(i)-'0');
            i--;
        }
        res = (str.charAt(0) == '-' ? -res : res);
        //溢出就返回0,用long类型的res来比较,
        //如果定义为int res,那再比较就没有意义了,int范围为[-2147483648,2147483647]
        if(res>Integer.MAX_VALUE|| res<Integer.MIN_VALUE)return 0;
        return (int)res;
    }
}
//50.
//在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。
//也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
import java.util.LinkedHashSet;
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 (length <= 1) {
			duplication[0] = -1;
			return false;
		}
		LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
		for (int i = 0; i < length; i++) {
			if (!set.contains(numbers[i])) {
				set.add(numbers[i]);
			}
		}

		for (int a : set) {
			int index = 0;
			for (int j = 0; j < length; j++) {
				if (a == numbers[j]) {
					index++;
				}
			}
			if (index > 1) {
				duplication[0] = a;
				return true;
			}
		}
		duplication[0] = -1;
		return false;
    }
}
链接:https://www.nowcoder.com/questionTerminal/623a5ac0ea5b4e5f95552655361ae0a8?answerType=1&f=discussion
来源:牛客网
//将输入数组排序,再判断相邻位置是否存在相同数字,如果存在,对 duplication 赋值返回,否则继续比较
import java.util.*;
public class Solution {
    public boolean duplicate(int numbers[],int length,int [] duplication) {
        if(numbers == null || length == 0){
            return false;
        }
        Arrays.sort(numbers);
        for(int i=0;i<length-1;i++){
            if(numbers[i] == numbers[i+1]){
                duplication[0] = numbers[i];
                return true;
            }
        }
        return false;
    }
}
//51.
//给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],
//其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
//(注意:规定B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2];)
import java.util.ArrayList;
public class Solution {
    public int[] multiply(int[] A) {
        if (A.length <= 1) {
            return A;
        }
        int[] result = new int[A.length];
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < A.length; i++) {
            list.add(A[i]);
        }
        for (int i = 0; i < result.length; i++) {
            int tmp = list.get(i);
            list.remove(i);
            int mul = 1;
            for (int k = 0; k < list.size(); k++) {
                mul *= list.get(k);
            }
            result[i] = mul;
            list.add(i, tmp);
        }
        return result;
    }
}

//52.
//请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 
//在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
public class Solution {
    public boolean match(char[] str, char[] pattern)
    {
        return matchStr(str, 0, pattern, 0);
    }
    public static boolean matchStr(char[] str, int i, char[] pattern, int j) {
 
        // 边界
        if (i == str.length && j == pattern.length) { // 字符串和模式串都为空
            return true;
        } else if (j == pattern.length) { // 模式串为空
            return false;
        }
 
        boolean flag = false;
        boolean next = (j + 1 < pattern.length && pattern[j + 1] == '*'); // 模式串下一个字符是'*'
        if (next) {
            if (i < str.length && (pattern[j] == '.' || str[i] == pattern[j])) { // 要保证i<str.length,否则越界
                return matchStr(str, i, pattern, j + 2) || matchStr(str, i + 1, pattern, j);
            } else {
                return matchStr(str, i, pattern, j + 2);
            }
        } else {
            if (i < str.length && (pattern[j] == '.' || str[i] == pattern[j])) {
                return matchStr(str, i + 1, pattern, j + 1);
            } else {
                return false;
            }
        }
    }
}
//53.
//请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
//例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
import java.util.regex.Pattern;
public class Solution {
    public boolean isNumeric(char[] str) {
        String pattern="^[-+]?\\d*(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?$";
        String s = new String(str);
        return Pattern.matches(pattern,s);
    }
}
//解释:https://www.nowcoder.com/questionTerminal/6f8c901d091949a5837e24bb82a731f2?answerType=1&f=discussion
//54.
//请实现一个函数用来找出字符流中第一个只出现一次的字符。
//例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
public class Solution {
    //Insert one char from stringstream
    public char hash[] = new char[256];
    String s = "";
    public void Insert(char ch)
    {
        s += ch;
        hash[ch]++;
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        char[] chrarray=s.toCharArray();
        for(char a: chrarray) {
            if(hash[a]==1) {
                return a;
            }
        }
        return '#';
    }
}
//55.
//给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
/*
 public class ListNode {
    int val;
    ListNode next = null;
 
    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public static int CodeNumsOfCircle = 0;
    public ListNode EntryNodeOfLoop(ListNode pHead)
    {
        if (pHead == null || pHead.next == null) {
            return null;
        }
        ListNode t1 = pHead;
        ListNode t2 = pHead.next;
        if (hasCircle(pHead, t1, t2)) {
            ListNode m1 = pHead;
            ListNode m2 = pHead;
            while (CodeNumsOfCircle > 0) {
                m2 = m2.next;
                CodeNumsOfCircle--;
            }
            while (m1 != m2) {
                m1 = m1.next;
                m2 = m2.next;
            }
 
            return m1;
 
        } else {
            return null;
        }
 
    }
private static boolean hasCircle(ListNode pHead, ListNode t1, ListNode t2) {
        while (t2 != null) {
            ListNode tmp = pHead;
            int m = 0;
            int n = 0;
            while (tmp != t2) {
                m++;
                tmp = tmp.next;
 
            }
            tmp = pHead;
            while (tmp != t1) {
                n++;
                tmp = tmp.next;
 
            }
            if (m <= n) {
                CodeNumsOfCircle = n - m + 1;
                return true;
            }
            t1 = t1.next;
            t2 = t2.next;
        }
        return false;
 
    }
}
//56.
//在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
/*
 public class ListNode {
    int val;
    ListNode next = null;
 
    ListNode(int val) {
        this.val = val;
    }
}
*/
import java.util.HashSet;
public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if (pHead == null || pHead.next == null) {
            return pHead;
        }
        HashSet<Integer> set1 = new HashSet<>();
        HashSet<Integer> set2 = new HashSet<>();
        ListNode tmp = pHead;
        ListNode helper = pHead;
        while (tmp != null) {
            if (!set1.contains(tmp.val)) {
                set1.add(tmp.val);
            } else {
                set2.add(tmp.val);
            }
            tmp = tmp.next;
        }
        tmp = pHead;
        helper = pHead.next;
        while (helper != null) {
            if (set2.contains(helper.val)) {
                helper = helper.next;
                tmp.next = helper;
            } else {
                tmp = tmp.next;
                helper = helper.next;
            }
        }
        if (set2.contains(pHead.val) && pHead.next == null) {
            return null;
        }
        if (set2.contains(pHead.val) && pHead.next != null) {
            return pHead.next;
        } else {
            return pHead;
        }
    }
}

//多次遍历,第一次遍历把重复的结点值存入 set 容器,第二次遍历,当结点值存储在 set 容器中,就删除该结点
链接:https://www.nowcoder.com/questionTerminal/fc533c45b73a41b0b44ccba763f866ef?answerType=1&f=discussion
来源:牛客网

import java.util.*;
public class Solution {
    public ListNode deleteDuplication(ListNode pHead){
        if(pHead == null){
            return  null;
        }
        // 先找出相同结点,存入 set
        HashSet<Integer> set = new HashSet<>();
        ListNode pre = pHead;
        ListNode cur = pHead.next;
        while(cur != null){
            if(cur.val == pre.val){
                set.add(cur.val);
            }
            pre = cur;
            cur = cur.next;
        }
        // 再根据相同节点删除
        // 先删头部
        while(pHead != null && set.contains(pHead.val)){
            pHead = pHead.next;
        }
        if(pHead == null){
            return null;
        }
        // 再删中间结点
        pre = pHead;
        cur = pHead.next;
        while(cur != null){
            if(set.contains(cur.val)){
                pre.next = cur.next;
                cur = cur.next;
            }else{
                pre = cur;
                cur = cur.next;
            }
        }
        return pHead;
    }
}
//57.
//给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
/*
public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;
 
    TreeLinkNode(int val) {
        this.val = val;
    }
}
*/
import java.util.*;
public class Solution {
    static ArrayList<TreeLinkNode> list = new ArrayList<>();
    public TreeLinkNode GetNext(TreeLinkNode pNode){
        TreeLinkNode par = pNode;
        while(par.next != null){
            par = par.next;
        }
        InOrder(par);
        for(int i=0;i<list.size();i++){
            if(pNode == list.get(i)){
                return i == list.size()-1?null:list.get(i+1);
            }
        }
        return null;
    }
    void InOrder(TreeLinkNode pNode){
        if(pNode!=null){
            InOrder(pNode.left);
            list.add(pNode);
            InOrder(pNode.right);
        }
    }
}

//58.
//请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

//做这种题也没太多诀窍啦技巧啦什么的,就是按题意先画一棵“大”一点的对称二叉树,然后按树的一层一层比较一下,看看怎么算是满足对称的二叉树,思路就有了。
//代码写出来竟然和书上的一模一样,惊呆了...
链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb?answerType=1&f=discussion
来源:牛客网

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

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
public class Solution {
    boolean isSymmetrical(TreeNode pRoot)
    {
        if (pRoot == null) {
            return true;
        }
 
        if (pRoot.left == null && pRoot.right == null) {
            return true;
        }
 
        TreeNode mRoot = new TreeNode(0);
        copyoftree(pRoot,mRoot);
        Mirror(mRoot);
        return isEqual(pRoot, mRoot);
    }
    public static boolean isEqual(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) {
            return true;
        }
        if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) {
            return false;
        }
        if (root1.val != root2.val) {// 判断每个节点的值是否相等,如果去除此判断,则判断两个二叉树是否结构相等
            return false;
        }
        return isEqual(root1.left, root2.left) && isEqual(root1.right, root2.right);
    }
 
    public static void Mirror(TreeNode root) {
        if (root != null) {
            if (root.left != null && root.right != null) {
                TreeNode tmp = root.left;
                root.left = root.right;
                root.right = tmp;
                Mirror(root.left);
                Mirror(root.right);
            } else if (root.left == null && root.right != null) {
                root.left = root.right;
                root.right = null;
                Mirror(root.left);
            } else if (root.right == null && root.left != null) {
                root.right = root.left;
                root.left = null;
                Mirror(root.right);
            } else {
                return;
            }
        } else {
            return;
        }
    }
    public static void copyoftree(TreeNode t1, TreeNode t2) {
        if (t1 == null) {
            return;
        } else {
            t2.val = t1.val;
            TreeNode left = new TreeNode(0);
            TreeNode right = new TreeNode(0);
            if (t1.left != null) {
                t2.left = left;
                copyoftree(t1.left, t2.left);
            }
            if (t1.right != null) {
                t2.right = right;
                copyoftree(t1.right, t2.right);
            }
        }
    }
}

//59.
//请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
import java.util.ArrayList;
import java.util.Stack;
 
/*
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<>();
 
        if (pRoot == null) {
            return result;
        }
        if (pRoot.left == null && pRoot.right == null) {
            ArrayList<Integer> list = new ArrayList<>();
            list.add(pRoot.val);
            result.add(list);
            return result;
        }
        Stack<TreeNode> stackl = new Stack<>();
        Stack<TreeNode> stackr = new Stack<>();
        int index = 1;
        stackl.add(pRoot);
        while (!stackl.isEmpty() || !stackr.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            if (index % 2 != 0) {
                while (!stackl.isEmpty()) {
                    pRoot = stackl.peek();
                    list.add(stackl.pop().val);
                    if (pRoot.left != null)
                        stackr.add(pRoot.left);
                    if (pRoot.right != null)
                        stackr.add(pRoot.right);
                }
                result.add(list);
                if (!stackr.isEmpty())
                    pRoot = stackr.peek();
                index++;
            }
 
            else {
                while (!stackr.isEmpty()) {
                    pRoot = stackr.peek();
                    list.add(stackr.pop().val);
                    if (pRoot.right != null) {
                        stackl.add(pRoot.right);
                    }
                    if (pRoot.left != null) {
                        stackl.add(pRoot.left);
                    }
                }
                result.add(list);
                if (!stackl.isEmpty())
                    pRoot = stackl.peek();
                index++;
            }
 
        }
        return result;
    }
 
}
链接:https://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0?answerType=1&f=discussion
来源:牛客网

主要的方法与BFS写法没什么区别
BFS里是每次只取一个,而我们这里先得到队列长度size,这个size就是这一层的节点个数,然后通过for循环去poll出这size个节点,这里和按行取值二叉树返回ArrayList<ArrayList<Integer>>这种题型的解法一样,之字形取值的核心思路就是通过两个方法:
list.add(T): 按照索引顺序从小到大依次添加
list.add(index, T): 将元素插入index位置,index索引后的元素依次后移,这就完成了每一行元素的倒序,或者使用Collection.reverse()方法倒序也可以
链接:https://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0?answerType=1&f=discussion
来源:牛客网

import java.util.LinkedList;
public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        LinkedList<TreeNode> q = new LinkedList<>();
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        boolean rev = true;
        q.add(pRoot);
        while(!q.isEmpty()){
            int size = q.size();
            ArrayList<Integer> list = new ArrayList<>();
            for(int i=0; i<size; i++){
                TreeNode node = q.poll();
                if(node == null){continue;}
                if(rev){
                    list.add(node.val);
                }else{
                    list.add(0, node.val);
                }
                q.offer(node.left);
                q.offer(node.right);
            }
            if(list.size()!=0){res.add(list);}
            rev=!rev;
        }
        return res;
    }
}

//60.
//从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
 
/*
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) {
        ArrayDeque<TreeNode> deque = new ArrayDeque<>();
        ArrayDeque<TreeNode> deque2 = new ArrayDeque<>();
        HashMap<TreeNode, Integer> map = new HashMap<>();
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        ArrayList<Integer> list = new ArrayList<>();
        if (pRoot == null) {
            return result;
        }
        deque.add(pRoot);
        int deep = 1;
        map.put(pRoot, 1);
        while (!deque.isEmpty()) {
            while (deque.size() > 0) {
                pRoot = deque.getFirst();
                deep = map.get(pRoot);
                list.add(deque.poll().val);
                deque2.add(pRoot);
                if (!deque.isEmpty()) {
                    if (map.get(deque2.getLast()) != map.get(deque.getFirst())) {
                        result.add(list);
 
                        list = new ArrayList<Integer>();
                    }
                } else {
                    result.add(list);
 
                    list = new ArrayList<Integer>();
                }
 
                if (pRoot.left != null) {
                    deque.add(pRoot.left);
                    map.put(pRoot.left, deep + 1);
                }
                if (pRoot.right != null) {
                    deque.add(pRoot.right);
                    map.put(pRoot.right, deep + 1);
                }
            }
        }
        return result;
}
}

链接:https://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288?answerType=1&f=discussion
来源:牛客网

层序遍历的模板是用一个队列,入队每次遇到的非空结点,出队当前最前结点,直到队列为空,遍历完成
现在为了保存层数信息,我们添加了map,每次入队新的结点,map 保存 <结点,层数> 的 <K,V> 对
关于相同层数如何入 lists,前面也讨论这就不赘述了
链接:https://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288?answerType=1&f=discussion
来源:牛客网

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 {
    ArrayList<ArrayList<Integer>> Print(TreeNode root) {
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
        HashMap<TreeNode, Integer> map = new HashMap<>();
        if (root == null) {
            return lists;
        }
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.addFirst(root);
        map.put(root, 0);
        while (!queue.isEmpty()) {
            root = queue.pollLast();
            int deep = map.get(root);
            if (root.left != null) {
                queue.addFirst(root.left);
                map.put(root.left, deep + 1);
            }
            if (root.right != null) {
                queue.addFirst(root.right);
                map.put(root.right, deep + 1);
            }
            if (lists.size() <= deep) {
                ArrayList<Integer> list = new ArrayList<>();
                list.add(root.val);
                lists.add(list);
            } else {
                ArrayList<Integer> list = lists.get(deep);
                list.add(root.val);
            }
        }
        return lists;
    }
 
}
//61.
//二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。
//序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。
//二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
public class Solution {
    int index = -1;
    String Serialize(TreeNode root) {
        if (root == null) {
            return "#";
        } else {
            return root.val + "," + Serialize(root.left) + "," + Serialize(root.right);
        }
  }
    TreeNode Deserialize(String str) {
        String[] s = str.split(",");// 将序列化之后的序列用,分隔符转化为数组
        index++;// 索引每次加一
        int len = s.length;
        if (index > len) {
            return null;
        }
        TreeNode treeNode = null;
        if (!s[index].equals("#")) {// 不是叶子节点 继续走 是叶子节点出递归
            treeNode = new TreeNode(Integer.parseInt(s[index]));
            treeNode.left = Deserialize(str);
            treeNode.right = Deserialize(str);
        }
        return treeNode;
    }
}
//62.
//给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
import java.util.ArrayList;
public class Solution {
    ArrayList<TreeNode> list = new ArrayList<>();
    TreeNode KthNode(TreeNode pRoot, int k) {
        inOrder(pRoot);
        if(k>=1 && list.size()>=k) {
            return list.get(k-1);
        }
        return null;
    }
 
    void inOrder(TreeNode pRoot) {
        if(pRoot!=null){
            inOrder(pRoot.left);
            list.add(pRoot);
            inOrder(pRoot.right);
        }
    }
}

//63.
//如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。
//如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
 
    PriorityQueue<Integer> left = new PriorityQueue<>(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    });
    PriorityQueue<Integer> right = new PriorityQueue<>();
    private int N;
 
    public void Insert(Integer num) {
 
        if (N % 2 == 0) {
            left.add(num);
            right.add(left.poll());
        } else {
            right.add(num);
            left.add(right.poll());
        }
        N++;
    }
 
    public Double GetMedian() {
 
        if (N % 2 == 0)
            return (left.peek() + right.peek()) / 2.0;
        else
            return (double) right.peek();
    }
 
 
}
//64.
//给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,
//那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个:
// {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> result = new ArrayList<>();
        if (size > num.length||size==0) {
            return result;
        }
        if (size == num.length) {
            for (int a : num) {
                result.add(a);
            }
            ArrayList<Integer> finalArrayList = new ArrayList<>();
            finalArrayList.add(getMax(result));
            return finalArrayList;
        }
        for (int i = 0; i + size <=num.length; i++) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int j = i; j <i + size; j++) {
                list.add(num[j]);
            }
            result.add(getMax(list));
 
        }
        return result;
    }
    public static int getMax(ArrayList<Integer> list) {
        int max = list.get(0);
        for (int a : list) {
            if (a >= max) {
                max = a;
            }
        }
        return max;
    }
}
//65.
//请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
//路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 
public class Solution {
boolean[] visited = null;
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        visited = new boolean[matrix.length];
        for(int i = 0; i < rows; i++)
            for(int j = 0; j < cols; j++)
                if(subHasPath(matrix,rows,cols,str,i,j,0))
                    return true;
        return false;
    }
  
    public boolean subHasPath(char[] matrix, int rows, int cols, char[] str, int row, int col, int len){
        if(matrix[row*cols+col] != str[len]|| visited[row*cols+col] == true) return false;
        if(len == str.length-1) return true;
        visited[row*cols+col] = true;
        if(row > 0 && subHasPath(matrix,rows,cols,str,row-1,col,len+1)) return true;
        if(row < rows-1 && subHasPath(matrix,rows,cols,str,row+1,col,len+1)) return true;
        if(col > 0 && subHasPath(matrix,rows,cols,str,row,col-1,len+1)) return true;
        if(col < cols-1 && subHasPath(matrix,rows,cols,str,row,col+1,len+1)) return true;
        visited[row*cols+col] = false;
        return false;
    }
}
//66.
//地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 
//例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
import java.util.LinkedList;
import java.util.Queue;
 
public class Solution {
 
    private final int dx[] = { -1, 1, 0, 0 };
    private final int dy[] = { 0, 0, -1, 1 };
 
    public int movingCount(int threshold, int rows, int cols) {
        if (threshold <= 0 || rows <= 0 || cols <= 0) {
            return 0;
        }
 
        int ans = 0;
        boolean[][] vis = new boolean[rows + 1][cols + 1];
 
        Queue<Path> queue = new LinkedList<>();
 
        queue.add(new Path(0, 0));
        vis[0][0] = true;
        while (!queue.isEmpty()) {
            Path p = queue.poll();
            int x = p.getX();
            int y = p.getY();
 
            for (int i = 0; i < 4; i++) {
                int xx = x + dx[i];
                int yy = y + dy[i];
                if (xx >= 0 && xx < rows && yy >= 0 && yy < cols && !vis[xx][yy] && (sum(xx) + sum(yy) <= threshold)) {
                    ans++;
                    vis[xx][yy] = true;
                    queue.add(new Path(xx, yy));
                }
            }
        }
        return ans + 1;
 
    }
 
    public int sum(int x) {
        int ans = 0;
        while (x != 0) {
            ans += (x % 10);
            x /= 10;
        }
        return ans;
    }
}
 
class Path {
    private int x;
    private int y;
 
    public Path(int x, int y) {
        this.x = x;
        this.y = y;
    }
 
    public int getX() {
        return x;
    }
 
    public void setX(int x) {
        this.x = x;
    }
 
    public int getY() {
        return y;
    }
 
    public void setY(int y) {
        this.y = y;
    }
}

//67.
//给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1),
//每段绳子的长度记为k[0],k[1],...,k[m]。请问k[0]xk[1]x...xk[m]可能的最大乘积是多少?
//例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
public class Solution {
 
    public int cutRope(int target) {
        return cutRope(target, 0);
    }
 
    public int cutRope(int target, int max) {
        int maxValue = max;
        for (int i = 1; i < target; ++i) {
            maxValue = Math.max(maxValue, i * cutRope(target - i, target - i));
        }
        return maxValue;
    }
 
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值