[关闭]
@huangyichun 2018-04-04T11:54:20.000000Z 字数 39473 阅读 1177

剑指Offer试题

算法


1.题目描述:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

  1. //建议画个图理解下
  2. public class Solution {
  3. public boolean Find(int target, int [][] array) {
  4. if(array==null || array.length == 0){
  5. return false;
  6. }
  7. int row = 0;
  8. int col = array[0].length-1; //数组最后一列的下标
  9. while(row <=array.length-1 && col >=0){
  10. if(array[row][col] > target){//当该列最小的一个值都大于target
  11. col --; //向左移一列
  12. }else if(array[row][col] < target){//当该最小的一个小于target
  13. row ++; //向下移一行
  14. }else{ //如果该值等于target,返回true
  15. return true;
  16. }
  17. }
  18. return false;
  19. }
  20. }

2.题目描述:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy

  1. public class Solution {
  2. public String replaceSpace(StringBuffer str) {
  3. if(str == null || str.length() <= 0){
  4. return "";
  5. }
  6. int spaceCount = 0;
  7. for(int i=0; i<str.length(); i++){//计算空格个数
  8. if(str.charAt(i)==' '){
  9. spaceCount++;
  10. }
  11. }
  12. //设置初始下标
  13. int index = str.length()-1;
  14. int length = str.length()+spaceCount * 2;//设置新的StringBuilder大小
  15. //新StringBuilder最后一个字符下标
  16. int newIndex = length - 1;
  17. str.setLength(length);
  18. while(index >=0){
  19. //当前下标的字符
  20. char c = str.charAt(index);
  21. if(c != ' '){
  22. str.setCharAt(newIndex--, c);
  23. }else{
  24. str.setCharAt(newIndex--,'0');
  25. str.setCharAt(newIndex--,'2');
  26. str.setCharAt(newIndex--,'%');
  27. }
  28. index --;
  29. }
  30. return str.toString();
  31. }
  32. }

3.题目描述:输入一个链表,从尾到头打印链表每个节点的值

  1. import java.util.ArrayList;
  2. public class Solution {
  3. private ArrayList<Integer> list = new ArrayList<>();
  4. public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
  5. if(listNode != null){
  6. printListFromTailToHead(listNode.next);//递归
  7. list.add(listNode.val);
  8. }
  9. return list;
  10. }
  11. }

4.题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回

  1. import java.util.*;
  2. public class Solution {
  3. private Map<Integer,Integer> map = new HashMap<>();
  4. public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
  5. for(int i=0; i<pre.length; i++){
  6. map.put(in[i],i);//存放中序中值对应的下标
  7. }
  8. return rebuild(pre,0, pre.length-1, 0, pre.length-1);
  9. }
  10. public TreeNode rebuild(int[] pre, int pi, int pj, int ni, int nj){
  11. if(pi>pj)
  12. return null;
  13. int index = map.get(pre[pi]);//前序该值该中序中的位置
  14. TreeNode root = new TreeNode(pre[pi]);//创建根节点
  15. root.left = rebuild(pre, pi+1, pi+ index-ni, ni, index-1);//建立根节点的左子树
  16. root.right = rebuild(pre,pi+index-ni+1,pj, index+1, nj);//建立根节点右子树
  17. return root;//返回根节点
  18. }
  19. }

5.题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

  1. import java.util.Stack;
  2. import java.util.*;
  3. public class Solution {
  4. Stack<Integer> stack1 = new Stack<Integer>();//保存插入
  5. Stack<Integer> stack2 = new Stack<Integer>();//处理删除
  6. public void push(int node) {
  7. stack1.push(node);
  8. }
  9. //如果stack2不为空,直接从stack2删除
  10. //如果stack2为空,将stack1的内容,删除放入stack2中
  11. public int pop() {
  12. if(stack2.size() == 0 && stack1.size() == 0){
  13. throw new EmptyStackException();
  14. }
  15. if(stack2.size() == 0){
  16. while(!stack1.isEmpty()){
  17. stack2.push(stack1.pop());
  18. }
  19. }
  20. return stack2.pop();
  21. }
  22. }

6. 题目描述:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

  1. import java.util.ArrayList;
  2. public class Solution_1 {
  3. public static void main(String[] args) {
  4. int[] array = {4,1,1, 2, 3};
  5. int i = minNumberInRotateArray(array);
  6. System.out.println(i);
  7. }
  8. //本题考查二分查找
  9. public static int minNumberInRotateArray(int [] array) {
  10. if(array == null || array.length == 0){
  11. return 0;
  12. }
  13. if(array.length == 1){
  14. return array[0];
  15. }
  16. int index1 = 0;
  17. int index2 = array.length-1;
  18. int mid = index1;
  19. while(array[index1] >= array[index2]){
  20. mid = (index2-index1) / 2;
  21. if(index2-index1 == 1){ //当两个相邻时
  22. mid = index2;
  23. break;
  24. }
  25. if(array[index1] <= array[mid] && array[mid] > array[index2]){// 3 3 3 0 2情况
  26. index1 = mid;
  27. }else if(array[index2] >= array[mid] && array[index1] > array[mid]){// 3 0 0 0 2情况
  28. index2 = mid;
  29. }else{// 3 3 3 0 3, 3 0 0 0 3两种情况无法判断哪个属于旋转部分
  30. mid = getMin(array,index1, index2);//采用顺序查找
  31. break;
  32. }
  33. }
  34. return array[mid];
  35. }
  36. public static int getMin(int[] array, int index1, int index2){
  37. int min = index1;
  38. for(int i=index1+1; i<= index2; i++){
  39. if(array[min] > array[i]){
  40. min = i;
  41. }
  42. }
  43. return min;
  44. }
  45. }

7.题目描述:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39

  1. public class Solution {
  2. public int Fibonacci(int n) {
  3. if(n < 2){
  4. return n;
  5. }
  6. int f1 = 0;
  7. int f2 = 1;
  8. int f = f2;
  9. for(int i=2; i<= n; i++){
  10. f = f1 + f2;
  11. f1 = f2;
  12. f2 = f;
  13. }
  14. return f2;
  15. }
  16. }

8.题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法

  1. public class Solution {
  2. public int JumpFloor(int target) {
  3. if(target <= 2){
  4. return target;
  5. }
  6. int f1 = 1;
  7. int f2 = 2;
  8. int f = f2;
  9. for(int i=3; i<=target; i++){
  10. f = f1 +f2;
  11. f1 = f2;
  12. f2 = f;
  13. }
  14. return f2;
  15. }
  16. }

9.题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

  1. import java.util.*;
  2. public class Solution {
  3. public int JumpFloorII(int target) {
  4. //f(n) = f(n-1) + f(n-2) + ... + f(1); f(n) = 2 * f(n-1);
  5. //f(1) = 1 f(2) = 2 , f(n-1) = 2 xy(n-1)
  6. return (int)Math.pow(2,target-1);
  7. }
  8. }

10.题目描述我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

  1. public class Solution {
  2. public int RectCover(int target) {
  3. if(target <=2){
  4. return target;
  5. }
  6. int f1 = 1;
  7. int f2 = 2;
  8. int sum = 0;
  9. for(int i=3; i<= target; i++){
  10. sum = f1 + f2;
  11. f1 = f2;
  12. f2 = sum;
  13. }
  14. return sum;
  15. }
  16. }

11.题目描述:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

  1. ## 位运算 ##
  2. /**负数是用补码表示的,补码求法位原码取反加一(原码是数的绝对值的二进制)
  3. 补码转换成原码为:取反加一(符号位不变)
  4. 例如: -16 二进制8位的 (原码)0001 0000 反码:1110 1111 补码:1111 0000
  5. 然后-16 / 2 = -8 相当于补码右移一位: 1111 1000 反码:1000 0111 原码: 1000 1000 = -8
  6. 移位运算:右移时,如果是负数,左边补1
  7. */
  8. public class Solution {
  9. public int NumberOf1(int n) {
  10. //思路: 一个数减去1,然后与上这个数,这样这个数从右到左的第一个1变为0
  11. int count = 0;
  12. while(n != 0){
  13. ++ count;
  14. n = (n-1) & n;
  15. }
  16. return count;
  17. }
  18. }

12.题目描述:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

  1. public class Solution {
  2. public double Power(double base, int exponent) {
  3. if(equal(base,0.0)){
  4. throw new IllegalArgumentException("底数不能为0");
  5. }
  6. int absExponent = exponent;
  7. if(exponent < 0){//将指数先转换成正的
  8. absExponent = -exponent;
  9. }
  10. double result = PowerWithUnsignedExponent(base, absExponent);
  11. if(exponent < 0){//如果指数为负
  12. result = 1.0 / result;
  13. }
  14. return result;
  15. }
  16. //非递归下的求法
  17. public static double PowerWithUnsignedExponent(double base, int exponent){
  18. double result = 1;
  19. double temp = base;
  20. while(exponent != 0){
  21. if((exponent & 0x1) == 1){
  22. result =result * temp;
  23. }
  24. exponent >>= 1;
  25. temp *= temp;
  26. }
  27. return result;
  28. }
  29. public boolean equal(double num1, double num2){
  30. if(num1-num2 > -0.0000001 && num1-num2 < 0.0000001){
  31. return true;
  32. }else{
  33. return false;
  34. }
  35. }
  36. }

13题目描述:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

  1. public class Solution {
  2. public void reOrderArray(int [] array) {
  3. if(array == null || array.length == 0){
  4. return ;
  5. }
  6. int begin = 0;
  7. int end = begin+1;
  8. while(end < array.length){
  9. while(begin < array.length-1 && (array[begin] & 0x1) != 0){//找到偶数
  10. begin ++;
  11. }
  12. end = begin +1;
  13. while(end <= array.length-1 && (array[end] & 0x1) == 0){//找到奇数
  14. end ++;
  15. }
  16. if(end == array.length)
  17. break;
  18. int temp = array[end];
  19. for(int i=end; i > begin; i--){//偶数后移
  20. array[i] = array[i-1];
  21. }
  22. array[begin] = temp;
  23. begin ++;
  24. }
  25. }
  26. }

14.题目描述:输入一个链表,输出该链表中倒数第k个结点

  1. public class Solution {
  2. public ListNode FindKthToTail(ListNode head,int k) {
  3. if(head == null || k <= 0){
  4. return null;
  5. }
  6. ListNode pHead = head;
  7. ListNode pBehind = null;
  8. for(int i=0; i<k-1; i++){//先走k-1个节点
  9. if(pHead.next != null){
  10. pHead = pHead.next;
  11. }else{
  12. return null;
  13. }
  14. }
  15. pBehind = head;
  16. while(pHead.next != null){
  17. pHead = pHead.next;
  18. pBehind = pBehind.next;
  19. }
  20. return pBehind;
  21. }
  22. }

15.题目描述:输入一个链表,反转链表后,输出链表的所有元素

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5. ListNode(int val) {
  6. this.val = val;
  7. }
  8. }*/
  9. public class Solution {
  10. public ListNode ReverseList(ListNode head) {
  11. if(head == null){
  12. return null;
  13. }
  14. //手动画个链表,操作下就能理解了
  15. ListNode preNode = null;
  16. ListNode nextNode = null;
  17. while(head != null){
  18. nextNode = head.next;
  19. head.next = preNode;
  20. preNode = head;
  21. head = nextNode;
  22. }
  23. return preNode;
  24. }
  25. }

16.题目描述:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则

  1. public class Solution {
  2. public ListNode Merge(ListNode list1,ListNode list2) {
  3. if(list1 == null)
  4. return list2;
  5. else if(list2 == null)
  6. return list1;
  7. ListNode head = null;
  8. //递归思想实现
  9. if(list1.val < list2.val){
  10. head = list1;
  11. head.next = Merge(list1.next, list2);
  12. }else{
  13. head = list2;
  14. head.next = Merge(list1, list2.next);
  15. }
  16. return head;
  17. }
  18. }

17.题目描述:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

  1. public class Solution {
  2. public boolean HasSubtree(TreeNode root1,TreeNode root2) {
  3. //使用先序遍历找到root1 == root2
  4. //当root1 = root2时,采用先序遍历判断两个子树是否相同
  5. boolean isChild = false;
  6. if(root1 == null || root2 == null){
  7. return false;
  8. }
  9. if(root1.val == root2.val){
  10. isChild = isTheSame(root1, root2);
  11. }
  12. if(!isChild){
  13. isChild = HasSubtree(root1.left,root2);
  14. }
  15. if(!isChild){
  16. isChild = HasSubtree(root1.right,root2);
  17. }
  18. return isChild;
  19. }
  20. public boolean isTheSame(TreeNode root1, TreeNode root2){
  21. if(root2 == null) //递归结束条件
  22. return true;
  23. if(root1 == null)
  24. return false;
  25. if(root1.val != root2.val)
  26. return false;
  27. return isTheSame(root1.left,root2.left) && isTheSame(root1.right,root2.right);
  28. }
  29. }

18.题目描述:操作给定的二叉树,将其变换为源二叉树的镜像。

  1. public class Solution {
  2. public void Mirror(TreeNode root) {
  3. if(root == null){//递归退出条件
  4. return;
  5. }
  6. if(root.left == null && root.right == null)//递归退出条件
  7. return;
  8. //交换左右子树
  9. TreeNode tmp = root.left;
  10. root.left = root.right;
  11. root.right = tmp;
  12. if(root.left != null){
  13. Mirror(root.left);
  14. }
  15. if(root.right != null){
  16. Mirror(root.right);
  17. }
  18. }
  19. }

19.题目描述:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.

  1. //这题没有按照剑指Offer来
  2. // 1 2 3 4
  3. // 5 6 7 8
  4. // 9 10 11 12
  5. // 13 14 15 16
  6. // 每先从上右下左各取3个数,刚好取完外圈
  7. //当到达最后一圈时可能有如下几种情况:
  8. // a b c 剩下一个长大于宽的矩形
  9. //-----------------------------------
  10. // a 剩下一个宽大于长的矩形
  11. // b
  12. // c
  13. // ---------------------------------
  14. // a 剩下一个值
  15. import java.util.ArrayList;
  16. public class Solution {
  17. public ArrayList<Integer> printMatrix(int [][] matrix) {
  18. ArrayList<Integer> list = new ArrayList<>();
  19. if(matrix == null || (matrix.length <=0 && matrix[0].length == 0))
  20. return list;
  21. int columns = matrix[0].length;
  22. int rows = matrix.length;
  23. int rowStart = 0; //第一行
  24. int rowEnd = rows-1; //最后一行
  25. int colStart = 0; //第一列
  26. int colEnd = columns - 1; //最后一列
  27. while(rowStart <= rowEnd && colStart <= colEnd){
  28. if(rowStart < rowEnd && colStart < colEnd){
  29. for(int i= colStart; i<= colEnd-1; i++){//左到右第一行
  30. list.add(matrix[rowStart][i]);
  31. }
  32. for(int i= rowStart; i<= rowEnd-1; i++){//上到下第一列
  33. list.add(matrix[i][colEnd]);
  34. }
  35. for(int i=colEnd; i >= colStart + 1; i--){//右到左第一行
  36. list.add(matrix[rowEnd][i]);
  37. }
  38. for(int i=rowEnd; i >= rowStart + 1; i--){//下到上第一列
  39. list.add(matrix[i][colStart]);
  40. }
  41. }else if(colStart < colEnd && rowStart == rowEnd){//剩下一个长大于宽的矩形
  42. for(int i= colStart; i<= colEnd; i++){
  43. list.add(matrix[rowStart][i]);
  44. }
  45. }else if(rowStart < rowEnd && colStart == colEnd){//剩下一个宽大于长的矩形
  46. for(int i = rowStart; i<= rowEnd; i++){
  47. list.add(matrix[i][colStart]);
  48. }
  49. }else{// 剩下一个值
  50. list.add(matrix[rowStart][colStart]);
  51. }
  52. rowStart ++;
  53. colStart ++;
  54. rowEnd --;
  55. colEnd --;
  56. }
  57. return list;
  58. }
  59. }

20.题目描述:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

  1. import java.util.Stack;
  2. public class Solution {
  3. private Stack<Integer> minStack = new Stack();//存放最小的
  4. private Stack<Integer> stack = new Stack();//存放添加的
  5. public void push(int node) {
  6. if(minStack.isEmpty() || node < minStack.peek())
  7. minStack.push(node);
  8. stack.push(node);
  9. }
  10. public void pop() {
  11. if(stack.isEmpty())
  12. return;
  13. if(!minStack.isEmpty() && minStack.peek() == stack.peek()){
  14. minStack.pop();
  15. }
  16. stack.pop();
  17. }
  18. public int top() {
  19. return stack.peek();
  20. }
  21. public int min() {
  22. return minStack.peek();
  23. }
  24. }

21.题目描述:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

  1. import java.util.ArrayList;
  2. import java.util.Stack;
  3. public class Solution {
  4. public boolean IsPopOrder(int [] pushA,int [] popA) {
  5. Stack<Integer> stack = new Stack();
  6. int index = 0;
  7. for(int i=0; i<popA.length; i++){
  8. int num = popA[i];
  9. if(stack.isEmpty()){//栈为空时添加节点
  10. stack.push(pushA[index++]);
  11. }
  12. while(stack.peek()!= num && index < pushA.length){
  13. stack.push(pushA[index++]);
  14. }
  15. if(stack.peek()!=num && index >= pushA.length)//当栈顶元素不等于num且pushA元素已经都入栈
  16. return false;
  17. stack.pop();
  18. }
  19. return true;
  20. }
  21. }

22.题目描述:从上往下打印出二叉树的每个节点,同层节点从左至右打印。

  1. /**
  2. public class TreeNode {
  3. int val = 0;
  4. TreeNode left = null;
  5. TreeNode right = null;
  6. public TreeNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. */
  11. public class Solution {
  12. public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
  13. ArrayList<Integer> list = new ArrayList();
  14. LinkedList<TreeNode> queue = new LinkedList();
  15. if(root == null)
  16. return list;
  17. queue.offer(root);
  18. while(!queue.isEmpty()){
  19. TreeNode node = queue.poll();
  20. list.add(node.val);
  21. if(node.left != null){
  22. queue.offer(node.left);
  23. }
  24. if(node.right != null){
  25. queue.offer(node.right);
  26. }
  27. }
  28. return list;
  29. }
  30. }

23.题目描述:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

  1. public class Solution {
  2. public boolean VerifySquenceOfBST(int [] sequence) {
  3. if(sequence == null || sequence.length <=0)
  4. return false;
  5. return isPostBST(sequence, 0, sequence.length-1);
  6. }
  7. public boolean isPostBST(int[] array, int start, int end){
  8. //根节点的值
  9. int root = array[end];
  10. //找到左子树是否满足后序遍历
  11. int i=start;
  12. for(; i<end; i++){
  13. if(array[i] > root){
  14. break;
  15. }
  16. }
  17. int j=i;
  18. for(; j<end; j++){
  19. if(array[j] < root)
  20. return false;
  21. }
  22. boolean left = true;
  23. //判断左子树是不是二叉搜索树
  24. if(i > start){
  25. left = isPostBST(array,start, start + i -1);
  26. }
  27. boolean right = true;
  28. if(j < end){
  29. right = isPostBST(array, start+i, end-1);
  30. }
  31. return left && right;
  32. }
  33. }

24.题目描述:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

  1. import java.util.ArrayList;
  2. /**
  3. public class TreeNode {
  4. int val = 0;
  5. TreeNode left = null;
  6. TreeNode right = null;
  7. public TreeNode(int val) {
  8. this.val = val;
  9. }
  10. }
  11. */
  12. public class Solution {
  13. private ArrayList<ArrayList<Integer>> roads = new ArrayList();//存储所有路径
  14. private ArrayList<Integer> road = new ArrayList();//存放当前路径
  15. public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
  16. if(root == null)
  17. return roads;
  18. road.add(root.val);
  19. if(root.left == null && root.right == null){//当到达叶节点时
  20. if(target == root.val)
  21. roads.add(new ArrayList<>(road));
  22. }
  23. if(root.left != null){//当左子树不为空
  24. FindPath(root.left, target-root.val);
  25. }
  26. if(root.right != null){//当右子树不为空
  27. FindPath(root.right, target-root.val);
  28. }
  29. road.remove(road.size()-1);
  30. return roads;
  31. }
  32. }

25.题目描述:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

  1. /*
  2. public class RandomListNode {
  3. int label;
  4. RandomListNode next = null;
  5. RandomListNode random = null;
  6. RandomListNode(int label) {
  7. this.label = label;
  8. }
  9. }
  10. */
  11. public class Solution {
  12. //分成三步1.复制每个节点放置在该节点的后面
  13. //2.修改节点的random指针
  14. //3.修改节点的next指针
  15. public static RandomListNode Clone(RandomListNode pHead)
  16. {
  17. if(pHead == null)
  18. return null;
  19. copy(pHead);
  20. changeRandom(pHead);
  21. return changeNext(pHead);
  22. }
  23. public static RandomListNode changeNext(RandomListNode pHead){//修改next指针
  24. RandomListNode root = pHead;
  25. RandomListNode head = pHead.next;
  26. while(root != null){
  27. RandomListNode copy = root.next;
  28. root.next = copy.next;
  29. root = copy.next;
  30. if(root != null)
  31. copy.next = root.next;
  32. else
  33. copy.next = null;
  34. }
  35. return head;
  36. }
  37. public static void changeRandom(RandomListNode pHead){//修改随机指针
  38. RandomListNode root = pHead;
  39. while(root != null){
  40. if(root.random != null){
  41. root.next.random = root.random.next;
  42. }
  43. root = root.next.next;
  44. }
  45. }
  46. public static void copy(RandomListNode pHead){//复制节点
  47. RandomListNode root = pHead;
  48. while(root != null){
  49. RandomListNode node = new RandomListNode(root.label);//复制节点
  50. node.next = root.next;
  51. node.random = root.random;
  52. root.next = node;//修改原节点吓一跳指针
  53. root = node.next;//root指向下一个节点
  54. }
  55. }
  56. }

26.题目描述:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

  1. /**
  2. public class TreeNode {
  3. int val = 0;
  4. TreeNode left = null;
  5. TreeNode right = null;
  6. public TreeNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. */
  11. public class Solution {
  12. private TreeNode head = null;//记录链表起始节点
  13. public TreeNode Convert(TreeNode pRootOfTree) {
  14. if(pRootOfTree == null){
  15. return null;
  16. }
  17. if(pRootOfTree.left == null && pRootOfTree.right == null)
  18. return pRootOfTree;
  19. if(head == null){//找到初始节点
  20. head = pRootOfTree;
  21. while(head.left != null){
  22. head = head.left;
  23. }
  24. }
  25. Convert(pRootOfTree.left);//左子树构成一个双向链表
  26. Convert(pRootOfTree.right);//右子树构成一个双向链表
  27. TreeNode leftLast = null;
  28. if(pRootOfTree.left != null){//找到左子树最右边一个就节点
  29. leftLast = pRootOfTree.left;
  30. while(leftLast.right != null){
  31. leftLast = leftLast.right;
  32. }
  33. }
  34. TreeNode rightFirst = null;
  35. if(pRootOfTree.right != null){//找到右子树最左边的一个点
  36. rightFirst = pRootOfTree.right;
  37. while(rightFirst.left != null){
  38. rightFirst = rightFirst.left;
  39. }
  40. }
  41. if(leftLast != null){//左子树最大的点不为空
  42. leftLast.right = pRootOfTree;
  43. pRootOfTree.left = leftLast;
  44. }
  45. if(rightFirst != null){//右子树最小的点不为空
  46. rightFirst.left = pRootOfTree;
  47. pRootOfTree.right = rightFirst;
  48. }
  49. return head;
  50. }
  51. }

27.题目描述:输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

  1. import java.util.*;
  2. public class Solution {
  3. public static ArrayList<String> Permutation(String str) {
  4. if(str == null)
  5. return null;
  6. ArrayList<String> list = new ArrayList<>();
  7. char[] chars = str.toCharArray();
  8. list = allSort(chars, 0, list);
  9. Collections.sort(list);
  10. return list;
  11. }
  12. public static ArrayList<String> allSort(char[] chars, int index, ArrayList<String> list){
  13. if(index == chars.length-1){
  14. list.add(String.valueOf(chars));
  15. return list;
  16. }
  17. for(int i=index; i< chars.length; i++){
  18. if(i != index && chars[i] == chars[index])//当要交换的值相同时
  19. continue;
  20. exChangeChars(index, i, chars); //修改第一个与后面的位置
  21. allSort(chars,index+1,list);
  22. exChangeChars(index, i, chars);//修改成原来的数组
  23. }
  24. return list;
  25. }
  26. /**
  27. * 交换两个字符数组的位置
  28. * @param index1
  29. * @param index2
  30. * @param chars
  31. */
  32. public static void exChangeChars(int index1, int index2, char[] chars){
  33. char tmp =chars[index1];
  34. chars[index1] = chars[index2];
  35. chars[index2] = tmp;
  36. }
  37. }

28.题目描述:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

  1. public class Solution {
  2. public int MoreThanHalfNum_Solution(int [] array) {
  3. if(array == null || array.length == 0)
  4. return 0;
  5. int num = 0;
  6. int count = 0;
  7. for(int i=0; i<array.length; i++){
  8. if(count == 0){
  9. num = array[i];
  10. count = 1;
  11. }else if(num == array[i]){
  12. count++;
  13. }else{
  14. count--;
  15. }
  16. }
  17. count = 0;
  18. for(int i=0; i<array.length; i++){
  19. if(array[i] == num)
  20. count++;
  21. }
  22. if((count << 1) <= array.length){
  23. return 0;
  24. }
  25. return num;
  26. }
  27. }

29.题目描述:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,

  1. import java.util.*;
  2. public class Solution {
  3. public static ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
  4. ArrayList<Integer> list = new ArrayList<>();
  5. if(input == null || k <=0 || input.length < k)
  6. return list;
  7. int start = 0;
  8. int end = input.length -1;
  9. int index = partition(input, start, end);
  10. while(index != k-1){
  11. if(index > k-1){
  12. end = index-1;
  13. index = partition(input,start,end);
  14. }else{
  15. start = index + 1;
  16. index = partition(input,start,end);
  17. }
  18. }
  19. for(int i=0; i<k; i++)
  20. list.add(input[i]);
  21. return list;
  22. }
  23. public static int partition(int[] array, int start, int end){
  24. if(array == null || array.length <= 0 || start< 0 || end >= array.length)
  25. throw new RuntimeException("输入不正确");
  26. int index = (int)(Math.random() *(end-start +1)) + start;//获取随机数
  27. swap(array,index,start);
  28. while(start < end){
  29. while(array[end] > array[start])
  30. end --;
  31. if(start < end){
  32. swap(array, start, end);
  33. start ++;
  34. }
  35. while(array[start] < array[end])
  36. start ++;
  37. if(start < end){
  38. swap(array,start, end);
  39. end--;
  40. }
  41. }
  42. return start;
  43. }
  44. public static void swap(int[] array, int index, int start){//交换数组位置
  45. int tmp = array[index];
  46. array[index] = array[start];
  47. array[start] = tmp;
  48. }
  49. }

30.题目描述:HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。你会不会被他忽悠住?(子向量的长度至少是1)

  1. public class Solution {
  2. public int FindGreatestSumOfSubArray(int[] array) {
  3. if(array== null || array.length <=0)
  4. throw new RuntimeException("数组长度不正确");
  5. int max = Integer.MIN_VALUE;
  6. int curSum = Integer.MIN_VALUE;
  7. for(int i=0; i<array.length; i++){
  8. if(curSum < 0)
  9. curSum = array[i];
  10. else
  11. curSum = array[i] + curSum;
  12. if(curSum > max)
  13. max = curSum;
  14. }
  15. return max;
  16. }
  17. }

31.题目描述:求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数。

  1. import java.util.*;
  2. public class Solution {
  3. public int NumberOf1Between1AndN_Solution(int n) {
  4. if(n <= 0)
  5. return 0;
  6. int high, low, cur, i = 1;
  7. high = n;
  8. int count = 0;
  9. while(high != 0){
  10. high = n / (int)Math.pow(10, i);
  11. int tmp = n % (int)Math.pow(10,i);
  12. cur = tmp / (int)Math.pow(10,i-1);
  13. low = tmp % (int)Math.pow(10,i-1);
  14. if(cur > 1){
  15. count += (high+1) * (int)Math.pow(10, i-1);
  16. }else if(cur == 1){
  17. count += high * (int)Math.pow(10,i-1) + low +1;
  18. }else{
  19. count+= high * (int)Math.pow(10,i-1);
  20. }
  21. i++;
  22. }
  23. return count;
  24. }
  25. }

32.题目描述:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

  1. import java.util.ArrayList;
  2. import java.util.*;
  3. public class Solution {
  4. public String PrintMinNumber(int [] numbers) {
  5. ArrayList<String> list = new ArrayList<>();
  6. for(int i=0; i<numbers.length; i++){
  7. list.add(Integer.toString(numbers[i]));
  8. }
  9. Collections.sort(list,new Comparator<String>(){
  10. public int compare(String o1, String o2){
  11. String s1 = o1 + o2;
  12. String s2 = o2 + o1;
  13. return s1.compareTo(s2);
  14. }
  15. }
  16. );
  17. StringBuilder sb = new StringBuilder();
  18. for(String s : list){
  19. sb.append(s);
  20. }
  21. return sb.toString();
  22. }
  23. }

33.题目描述:把只包含素因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

  1. import java.util.*;
  2. public class Solution {
  3. public int GetUglyNumber_Solution(int index) {
  4. if(index <= 0){
  5. return 0;
  6. }
  7. List<Integer> list = new ArrayList();
  8. list.add(1);
  9. int num1, num2, num3;
  10. int index1=0,index2=0,index3=0;
  11. while(list.size() < index){
  12. num1 = list.get(index1) * 2;
  13. num2 = list.get(index2) * 3;
  14. num3 = list.get(index3) * 5;
  15. int min = Math.min(num1, Math.min(num2,num3));
  16. list.add(min);
  17. if(min == num1)
  18. index1 ++;
  19. if(min == num2)
  20. index2 ++;
  21. if(min == num3)
  22. index3 ++;
  23. }
  24. return list.get(index-1);
  25. }
  26. }

34.题目描述:在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置。如果字符串为空,返回-1

  1. import java.util.*;
  2. public class Solution {
  3. public int FirstNotRepeatingChar(String str) {
  4. char[] chars = str.toCharArray();//转换成字符数组
  5. LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
  6. for(int i=0; i<chars.length; i++){
  7. if(map.containsKey(chars[i])){
  8. int value = map.get(chars[i]);
  9. map.put(chars[i],value+1);
  10. }else{
  11. map.put(chars[i],1);
  12. }
  13. }
  14. for(int i=0; i<chars.length; i++){
  15. if(map.get(chars[i]) == 1)
  16. return i;
  17. }
  18. return -1;
  19. }
  20. }

35.题目描述:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

  1. public class Solution {
  2. private int count = 0;
  3. private int[] copy;
  4. public int InversePairs(int [] array) {
  5. if(array == null || array.length == 0)
  6. return 0;
  7. copy = new int[array.length];
  8. sort(array, 0, array.length-1);
  9. return count;
  10. }
  11. public void sort(int[] array, int start, int end){
  12. if(start >= end)
  13. return;
  14. int mid = (start + end) / 2;
  15. sort(array, start, mid);
  16. sort(array,mid+1, end);
  17. merger(array, start, mid, end);
  18. }
  19. public void merger(int[] array, int start, int mid, int end){
  20. int i = start, j = mid+1;
  21. for(int k=i; k <= end; k++){
  22. copy[k] = array[k]; //复制需要合并的数组
  23. }
  24. for(int k = start; k <= end; k++){
  25. if(i > mid) array[k] = copy[j++]; //最半边取尽
  26. else if(j > end) array[k] = copy[i++]; //右半边取尽
  27. else if(copy[i] <= copy[j]) array[k] = copy[i++]; //左边小于等于右边
  28. else {
  29. array[k] = copy[j++];
  30. count = (count + mid - i+1) % 1000000007;
  31. }
  32. }
  33. }
  34. }

36.题目描述:输入两个链表,找出它们的第一个公共结点。

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5. ListNode(int val) {
  6. this.val = val;
  7. }
  8. }*/
  9. public class Solution {
  10. public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
  11. if(pHead1 == null || pHead2 == null)
  12. return null;
  13. int length1 = getLength(pHead1);
  14. int length2 = getLength(pHead2);
  15. int lengthDif = length1 - length2;
  16. ListNode longNode = pHead1;
  17. ListNode shortNode = pHead2;
  18. if(length2 > length1){
  19. lengthDif = length2 - length1;
  20. longNode = pHead2;
  21. shortNode = pHead1;
  22. }
  23. for(int i=0; i<lengthDif; i++){//长链表后移lengthDif位
  24. longNode = longNode.next;
  25. }
  26. while(longNode != null && shortNode != null && longNode != shortNode){
  27. longNode = longNode.next;
  28. shortNode = shortNode.next;
  29. }
  30. return longNode;
  31. }
  32. public int getLength(ListNode head){//获取链表长度
  33. int length = 0;
  34. ListNode pNode = head;
  35. while(pNode != null){
  36. length ++;
  37. pNode = pNode.next;
  38. }
  39. return length;
  40. }
  41. }

37.题目描述:统计一个数字在排序数组中出现的次数。

  1. public class Solution {
  2. public int GetNumberOfK(int [] array , int k) {
  3. if(array == null || array.length == 0)
  4. return 0;
  5. int left = getLeftIndex(array,k);
  6. int right = getRightIndex(array, k);
  7. if(left == -1 || right == -1)
  8. return 0;
  9. return right - left +1;
  10. }
  11. public int getLeftIndex(int[] array, int k){//获取左边第一个k下标
  12. int low = 0, mid = 0, high = array.length-1;
  13. while(low <= high){
  14. mid = (low + high) / 2;
  15. if(array[mid] > k){
  16. high = mid - 1;
  17. }else if(array[mid] < k){
  18. low = mid +1;
  19. }else{
  20. if(mid > 0 && array[mid-1] == k){
  21. high = mid-1;
  22. }else{
  23. return mid;
  24. }
  25. }
  26. }
  27. return -1;
  28. }
  29. public int getRightIndex(int[] array, int k){//获取左边第一个k下标
  30. int low = 0, mid=0, high = array.length-1;
  31. while(low <= high){
  32. mid = (low+high) / 2;
  33. if(array[mid] > k){
  34. high = mid -1;
  35. }else if(array[mid] < k){
  36. low = mid +1;
  37. }else{
  38. if(mid < array.length-1 && array[mid+1] == k){
  39. low = mid+1;
  40. }else{
  41. return mid;
  42. }
  43. }
  44. }
  45. return -1;
  46. }
  47. }

38.题目描述:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

  1. /**
  2. public class TreeNode {
  3. int val = 0;
  4. TreeNode left = null;
  5. TreeNode right = null;
  6. public TreeNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. */
  11. public class Solution {
  12. public int TreeDepth(TreeNode root) {
  13. if(root == null)
  14. return 0;
  15. int left = TreeDepth(root.left);
  16. int right = TreeDepth(root.right);
  17. return left > right ? (left + 1) : (right + 1);
  18. }
  19. }

39.题目描述:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

  1. public class Solution {
  2. boolean isBalanced = true;
  3. public boolean IsBalanced_Solution(TreeNode root) {
  4. getDeep(root);
  5. return isBalanced;
  6. }
  7. public int getDeep(TreeNode root){
  8. if(root == null)
  9. return 0;
  10. int left = getDeep(root.left);
  11. int right = getDeep(root.right);
  12. if(left - right > 1 || left - right < -1){
  13. isBalanced = false;
  14. }
  15. return left > right ? left + 1 : right + 1;
  16. }
  17. }

40.题目描述:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

  1. //num1,num2分别为长度为1的数组。传出参数
  2. //将num1[0],num2[0]设置为返回结果
  3. public class Solution {
  4. public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
  5. if(array.length == 2){
  6. num1[0] = array[0];
  7. num2[1] = array[1];
  8. }
  9. int result = 0;
  10. for(int i=0; i<array.length; i++){
  11. result ^= array[i];
  12. }
  13. int index = findFirstBitIs1(result);
  14. num1[0] = 0;
  15. num2[0] = 0;
  16. for(int i=0; i<array.length; i++){
  17. if(isBit1(array[i], index)){
  18. num1[0] ^= array[i];
  19. }else{
  20. num2[0] ^= array[i];
  21. }
  22. }
  23. }
  24. public boolean isBit1(int num, int indexBit){
  25. num = num >> indexBit;
  26. return (num & 1) == 1;
  27. }
  28. public int findFirstBitIs1(int num){//求两个出现一次数字的下标
  29. int index = 0;
  30. while((num & 1) == 0){
  31. num = num >> 1;
  32. ++index;
  33. }
  34. return index;
  35. }
  36. }

41.题目描述:小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

  1. import java.util.ArrayList;
  2. public class Solution {
  3. public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
  4. ArrayList<ArrayList<Integer>> list = new ArrayList<>();
  5. if(sum < 3)
  6. return list;
  7. int small = 1;
  8. int big = 2;
  9. int mid = (sum + 1) / 2;
  10. int curSum = big + small;
  11. while(small < mid){
  12. if(curSum == sum){
  13. list.add(countinueSequence(small, big));
  14. curSum -= small;
  15. ++ small;
  16. }else if(curSum < sum){
  17. ++big;
  18. curSum += big;
  19. }else{
  20. curSum -= small;
  21. ++small;
  22. }
  23. }
  24. return list;
  25. }
  26. public ArrayList<Integer> countinueSequence(int small, int big){
  27. ArrayList<Integer> list = new ArrayList<>();
  28. for(int i=small; i<= big; i++){
  29. list.add(i);
  30. }
  31. return list;
  32. }
  33. }

42.题目描述:输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。

  1. import java.util.ArrayList;
  2. public class Solution {
  3. public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
  4. int first = 0, last = array.length-1;
  5. int mulSum = Integer.MAX_VALUE;
  6. ArrayList<Integer> list = new ArrayList<>();
  7. while(first < last){
  8. int numFirst = array[first];
  9. int numLast = array[last];
  10. if(numFirst + numLast < sum)
  11. ++first;
  12. else if(numFirst + numLast > sum)
  13. --last;
  14. else{
  15. if(numFirst * numLast < mulSum){
  16. mulSum = numFirst * numLast;
  17. list.clear();
  18. list.add(numFirst);
  19. list.add(numLast);
  20. }
  21. ++first;
  22. }
  23. }
  24. return list;
  25. }
  26. }

43.题目描述:汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

  1. public class Solution {
  2. public String LeftRotateString(String str,int n) {
  3. if(str == null || str.length() == 0){
  4. return "";
  5. }
  6. char[] chars = str.toCharArray();
  7. int length = chars.length;
  8. reverse(chars, 0, length-1);
  9. n = n % length;
  10. reverse(chars, 0, length - n -1);
  11. reverse(chars, length -n, length-1);
  12. return new String(chars);
  13. }
  14. public void reverse(char[] chars, int start, int end){//翻转
  15. while(start < end){
  16. char tmp = chars[start];
  17. chars[start] = chars[end];
  18. chars[end] = tmp;
  19. ++ start;
  20. --end;
  21. }
  22. }
  23. }

44.题目描述:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

  1. public class Solution {
  2. public String ReverseSentence(String str) {
  3. if(str == null || str.length() == 1)
  4. return str;
  5. char[] chars = str.toCharArray();
  6. reverse(chars, 0, str.length()-1);
  7. int start = 0;
  8. for(int i=0; i<chars.length; ++i){
  9. if(chars[i] == ' '){
  10. reverse(chars, start, i-1);
  11. start = i + 1;
  12. }else if(i == chars.length-1){
  13. reverse(chars, start, i);
  14. }
  15. }
  16. return String.valueOf(chars);
  17. }
  18. public void reverse(char[] chars, int start, int end){//翻转
  19. while(start < end){
  20. char tmp = chars[start];
  21. chars[start] = chars[end];
  22. chars[end] = tmp;
  23. ++ start;
  24. --end;
  25. }
  26. }
  27. }

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的运气如何。为了方便起见,你可以认为大小王是0。

  1. import java.util.*;
  2. public class Solution {
  3. public boolean isContinuous(int [] numbers) {
  4. if(numbers == null || numbers.length < 1)
  5. return false;
  6. Arrays.sort(numbers);
  7. int numberZero = 0;
  8. int numberGap = 0;
  9. for(int i=0; i<numbers.length && numbers[i] == 0; i++){
  10. ++numberZero ;
  11. }
  12. int small = numberZero;
  13. int big = small + 1;
  14. while(big < numbers.length){
  15. if(numbers[small] == numbers[big])//对子
  16. return false;
  17. numberGap += numbers[big] - numbers[small] - 1;
  18. small = big;
  19. ++big;
  20. }
  21. if(numberGap <= numberZero)
  22. return true;
  23. return false;
  24. }
  25. }

46.题目描述:每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)

  1. public class Solution {
  2. public int LastRemaining_Solution(int n, int m) {
  3. if(n < 1 || m < 1)
  4. return -1;
  5. int last = 0;
  6. for(int i=2; i<=n; i++){
  7. last = (last + m) % i;
  8. }
  9. return last;
  10. }
  11. }

47.题目描述:求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

  1. public class Solution {
  2. public int Sum_Solution(int n) {
  3. int sum = n;
  4. boolean bool = (sum>0) && (sum += Sum_Solution(n-1))>0;
  5. return sum;
  6. }
  7. }

48.题目描述:写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。

  1. public class Solution {
  2. public int Add(int num1,int num2) {
  3. int sum = num1 ^ num2;
  4. int carry = (num1 & num2) << 1;
  5. sum += carry;
  6. return sum;
  7. }
  8. }

49.题目描述:将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

  1. public class Solution {
  2. public int StrToInt(String str) {
  3. if(str == null)
  4. return 0;
  5. boolean negative = false;//判断符号
  6. int result = 0;
  7. int i =0, len = str.length();
  8. if(len > 0){
  9. char firstChar = str.charAt(0);
  10. if(firstChar < '0'){
  11. if(firstChar == '-'){
  12. negative = true;
  13. }else if(firstChar != '+')
  14. return 0;
  15. if(len == 1)
  16. return 0;
  17. i++;
  18. }
  19. while(i < len){
  20. char c = str.charAt(i++);
  21. if(c < '0' || c > '9')
  22. return 0;
  23. if((negative && -result < Integer.MIN_VALUE) || (!negative && result > Integer.MAX_VALUE))
  24. return 0;
  25. result = result * 10 + (c - '0');
  26. }
  27. }else{
  28. return 0;
  29. }
  30. return negative ? -result : result;
  31. }
  32. }

50.题目描述:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。

  1. public class Solution {
  2. // Parameters:
  3. // numbers: an array of integers
  4. // length: the length of array numbers
  5. // duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
  6. // Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
  7. // 这里要特别注意~返回任意重复的一个,赋值duplication[0]
  8. // Return value: true if the input is valid, and there are some duplications in the array number
  9. // otherwise false
  10. public boolean duplicate(int numbers[],int length,int [] duplication) {
  11. if(numbers == null || numbers.length < 1)
  12. return false;
  13. for(int i=0; i<numbers.length; ++i){
  14. if(numbers[i] < 0 || numbers[i] > length-1)
  15. return false;
  16. }
  17. for(int i=0; i< length; ++i){
  18. while(numbers[i] != i){
  19. if(numbers[i] == numbers[numbers[i]]){
  20. duplication[0] = numbers[i];
  21. return true;
  22. }
  23. int temp = numbers[i];
  24. numbers[i] = numbers[temp];
  25. numbers[temp] = temp;
  26. }
  27. }
  28. return false;
  29. }
  30. }

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]。不能使用除法。

  1. import java.util.ArrayList;
  2. public class Solution {
  3. public int[] multiply(int[] A) {
  4. if(A == null || A.length < 1){
  5. return null;
  6. }
  7. int[] array1 = new int[A.length];//保存前半部分矩阵
  8. array1[0] = 1;
  9. for(int i=1; i< A.length; i++){
  10. array1[i] = array1[i-1] * A[i-1];
  11. }
  12. int[] array2 = new int[A.length];
  13. array2[A.length-1] = array1[A.length-1]; // 设置最后一个值
  14. int temp = 1;
  15. for(int i=A.length-2; i>=0; i--){
  16. temp *= A[i+1];
  17. array2[i] = temp * array1[i];
  18. }
  19. return array2;
  20. }
  21. }

52.题目描述:请实现一个函数用来匹配包括'.'和''的正则表达式。模式中的字符'.'表示任意一个字符,而''表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

  1. public class Solution {
  2. public boolean match(char[] str, char[] pattern) {
  3. if(str == null || pattern == null)
  4. return false;
  5. int strIndex = 0;
  6. int patternIndex = 0;
  7. return isMatchCode(str,pattern,strIndex, patternIndex);
  8. }
  9. /**
  10. 当模式中的第二个字符不是“*”时:
  11. 1、如果字符串第一个字符和模式中的第一个字符相匹配,那么字符串和模式都后移一个字符,然后匹配剩余的。
  12. 2、如果
  13. 字符串第一个字符和模式中的第一个字符相不匹配,直接返回false。
  14. 而当模式中的第二个字符是“*”时:
  15. 如果字符串第一个字符跟模式第一个字符不匹配,则模式后移2个字符,继续匹配。如果字符串第一个字符跟模式第一个字符匹配,可以有3种匹配方式:
  16. 1、模式后移2字符,相当于x*被忽略;
  17. 2、字符串后移1字符,模式后移2字符;
  18. 3、字符串后移1字符,模式不变,即继续匹配字符下一位,因为*可以匹配多位;
  19. */
  20. public boolean isMatchCode(char[] str, char[] pattern, int strIndex, int patIndex){
  21. if(strIndex == str.length && patIndex == pattern.length)
  22. return true;
  23. if(strIndex != str.length && patIndex == pattern.length)
  24. return false;
  25. if(patIndex+1<pattern.length && pattern[patIndex+1] == '*'){
  26. if(strIndex != str.length &&(pattern[patIndex] ==str[strIndex] || pattern[patIndex] == '.')){
  27. return isMatchCode(str,pattern,strIndex, patIndex+2) || isMatchCode(str,pattern,strIndex+1,patIndex+1)|| isMatchCode(str,pattern, strIndex+1, patIndex);
  28. }else {
  29. return isMatchCode(str, pattern, strIndex, patIndex+2);
  30. }
  31. }
  32. if(strIndex != str.length && (pattern[patIndex] == str[strIndex] || pattern[patIndex] == '.')){
  33. return isMatchCode(str,pattern, strIndex+1, patIndex+1);
  34. }
  35. return false;
  36. }
  37. }

53.题目描述:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。

  1. public class Solution {
  2. public boolean isNumeric(char[] str) {
  3. String s = String.valueOf(str);
  4. // * 匹配前一个字符0次或多次
  5. // ? 匹配前面的0次或者1次
  6. // . 配除换行符 \n 之外的任何单字符。要匹配 . ,请使用 \.
  7. // + 匹配前面字符1次或多次
  8. return s.matches("[\\+-]?[0-9]*(\\.[0-9]+)?([eE][\\+-]?[0-9]+)?");
  9. }
  10. }

54.题目描述:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

  1. import java.util.*;
  2. public class Solution {
  3. //Insert one char from stringstream
  4. private LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
  5. public void Insert(char ch)
  6. {
  7. if(map.containsKey(ch)){
  8. int value = map.get(ch);
  9. map.put(ch, value+1);
  10. }else{
  11. map.put(ch, 1);
  12. }
  13. }
  14. //return the first appearence once char in current stringstream
  15. public char FirstAppearingOnce()
  16. {
  17. for(Map.Entry<Character,Integer> entry : map.entrySet()){
  18. if(entry.getValue() == 1)
  19. return entry.getKey();
  20. }
  21. return '#';
  22. }
  23. }

55.题目描述:一个链表中包含环,请找出该链表的环的入口结点。

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5. ListNode(int val) {
  6. this.val = val;
  7. }
  8. }
  9. */
  10. public class Solution {
  11. public ListNode EntryNodeOfLoop(ListNode pHead)
  12. {
  13. if(pHead == null)
  14. return null;
  15. ListNode p1 = pHead;
  16. ListNode p2 = pHead;
  17. while(p1 != null && p2.next != null){
  18. p1 = p1.next;
  19. p2 = p2.next.next;
  20. if(p1 == p2){
  21. p1 = pHead;
  22. while(p1 != p2){
  23. p1 = p1.next;
  24. p2 = p2.next;
  25. }
  26. return p1;
  27. }
  28. }
  29. return null;
  30. }
  31. }

56.题目描述:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5. ListNode(int val) {
  6. this.val = val;
  7. }
  8. }
  9. */
  10. public class Solution {
  11. public static ListNode deleteDuplication(ListNode pHead) {
  12. if(pHead == null)
  13. return null;
  14. ListNode head = new ListNode(-1);
  15. head.next = pHead;
  16. ListNode preNode = head;
  17. ListNode pNode = head.next;
  18. while(pNode != null && pNode.next != null){
  19. if(pNode.val == pNode.next.val){
  20. int value = pNode.val;
  21. while(pNode != null && pNode.val == value)
  22. pNode = pNode.next;
  23. preNode.next = pNode;
  24. }else{
  25. preNode = pNode;
  26. pNode = pNode.next;
  27. }
  28. }
  29. return head.next;
  30. }
  31. }

57.题目描述:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

  1. /*
  2. public class TreeLinkNode {
  3. int val;
  4. TreeLinkNode left = null;
  5. TreeLinkNode right = null;
  6. TreeLinkNode next = null;
  7. TreeLinkNode(int val) {
  8. this.val = val;
  9. }
  10. }
  11. */
  12. public class Solution {
  13. public TreeLinkNode GetNext(TreeLinkNode pNode)
  14. {
  15. if(pNode == null)
  16. return null;
  17. if(pNode.right != null){
  18. pNode = pNode.right;
  19. while(pNode.left != null)
  20. pNode = pNode.left;
  21. return pNode;
  22. }else{
  23. TreeLinkNode node = pNode.next;
  24. while(node != null && node.right == pNode){
  25. pNode = node;
  26. node = node.next;
  27. }
  28. return node;
  29. }
  30. }
  31. }

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

  1. /*
  2. public class TreeNode {
  3. int val = 0;
  4. TreeNode left = null;
  5. TreeNode right = null;
  6. public TreeNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. */
  11. public class Solution {
  12. boolean isSymmetrical(TreeNode pRoot)
  13. {
  14. return isSymmetrical(pRoot, pRoot);
  15. }
  16. boolean isSymmetrical(TreeNode root1, TreeNode root2){
  17. if(root1 == null && root2 == null)
  18. return true;
  19. if(root1 == null || root2 == null)
  20. return false;
  21. if(root1.val != root2.val)
  22. return false;
  23. return isSymmetrical(root1.left,root2.right) && isSymmetrical(root1.right, root2.left);
  24. }
  25. }

59.题目描述:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

  1. import java.util.ArrayList;
  2. import java.util.*;
  3. /*
  4. public class TreeNode {
  5. int val = 0;
  6. TreeNode left = null;
  7. TreeNode right = null;
  8. public TreeNode(int val) {
  9. this.val = val;
  10. }
  11. }
  12. */
  13. public class Solution {
  14. public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
  15. ArrayList<ArrayList<Integer>> list = new ArrayList<>();
  16. if(pRoot == null)
  17. return list;
  18. LinkedList<TreeNode> stack1 = new LinkedList<>();
  19. LinkedList<TreeNode> stack2 = new LinkedList<>();
  20. stack1.push(pRoot);
  21. int index = 1;
  22. while(!stack1.isEmpty() || !stack2.isEmpty()){
  23. ArrayList<Integer> arrayList = new ArrayList<>();
  24. if(index == 1){
  25. while(!stack1.isEmpty()){
  26. TreeNode node = stack1.pop();
  27. if(node.left != null){
  28. stack2.push(node.left);
  29. }
  30. if(node.right != null){
  31. stack2.push(node.right);
  32. }
  33. arrayList.add(node.val);
  34. }
  35. index = 2;
  36. }else{
  37. while(!stack2.isEmpty()){
  38. TreeNode node = stack2.pop();
  39. if(node.right != null){
  40. stack1.push(node.right);
  41. }
  42. if(node.left != null){
  43. stack1.push(node.left);
  44. }
  45. arrayList.add(node.val);
  46. }
  47. index = 1;
  48. }
  49. if(arrayList.size()>0)
  50. list.add(arrayList);
  51. }
  52. return list;
  53. }
  54. }

60.题目描述:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

  1. import java.util.ArrayList;
  2. import java.util.*;
  3. /*
  4. public class TreeNode {
  5. int val = 0;
  6. TreeNode left = null;
  7. TreeNode right = null;
  8. public TreeNode(int val) {
  9. this.val = val;
  10. }
  11. }
  12. */
  13. public class Solution {
  14. ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
  15. ArrayList<ArrayList<Integer>> list = new ArrayList<>();
  16. if(pRoot == null)
  17. return list;
  18. LinkedList<TreeNode> queue = new LinkedList<>();
  19. queue.offer(pRoot);
  20. while(!queue.isEmpty()){
  21. int num = queue.size();
  22. ArrayList<Integer> array = new ArrayList<>();
  23. while(num > 0){
  24. TreeNode node = queue.poll();
  25. if(node.left != null)
  26. queue.offer(node.left);
  27. if(node.right != null)
  28. queue.offer(node.right);
  29. array.add(node.val);
  30. -- num;
  31. }
  32. if(array.size() > 0){
  33. list.add(array);
  34. }
  35. }
  36. return list;
  37. }
  38. }

61.题目描述:请实现两个函数,分别用来序列化和反序列化二叉树

  1. /*
  2. public class TreeNode {
  3. int val = 0;
  4. TreeNode left = null;
  5. TreeNode right = null;
  6. public TreeNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. */
  11. public class Solution {
  12. int index = 0;
  13. String Serialize(TreeNode root) {
  14. if(root == null)
  15. return "#,";
  16. String res = root.val +",";
  17. res += Serialize(root.left);
  18. res += Serialize(root.right);
  19. return res;
  20. }
  21. TreeNode Deserialize(String str) {
  22. String[] s = str.split(",");
  23. return Deserialize(s);
  24. }
  25. TreeNode Deserialize(String[] s){
  26. if(s[index].equals("#")){
  27. ++index;
  28. return null;
  29. }
  30. TreeNode root = new TreeNode(Integer.parseInt(s[index++]));
  31. root.left = Deserialize(s);
  32. root.right = Deserialize(s);
  33. return root;
  34. }
  35. }

62.题目描述:给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

  1. /*
  2. public class TreeNode {
  3. int val = 0;
  4. TreeNode left = null;
  5. TreeNode right = null;
  6. public TreeNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. */
  11. public class Solution {
  12. int index = 0;
  13. TreeNode KthNode(TreeNode pRoot, int k)
  14. {
  15. if(pRoot != null){
  16. TreeNode node = KthNode(pRoot.left,k);//找到中序第一个节点
  17. if(node != null)
  18. return node;
  19. ++index;
  20. if(index == k )
  21. return pRoot;
  22. node = KthNode(pRoot.right,k);
  23. if(node != null)
  24. return node;
  25. }
  26. return null;
  27. }
  28. }

63.题目描述:如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

  1. import java.util.*;
  2. public class Solution {
  3. int count = 0;
  4. private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
  5. private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(15,new Comparator<Integer>() {
  6. @Override
  7. public int compare(Integer o1, Integer o2) {
  8. return o2 - o1;
  9. }
  10. });
  11. public void Insert(Integer num) {
  12. if((count & 1) == 0){
  13. if(!maxHeap.isEmpty() && maxHeap.peek() > num) {
  14. maxHeap.offer(num);
  15. num = maxHeap.poll();
  16. }
  17. minHeap.offer(num);
  18. }else {
  19. if(!minHeap.isEmpty() && minHeap.peek() < num){
  20. minHeap.offer(num);
  21. num = minHeap.poll();
  22. }
  23. maxHeap.offer(num);
  24. }
  25. ++count;
  26. }
  27. public Double GetMedian() {
  28. if((count & 1) == 1)
  29. return Double.valueOf(minHeap.peek());
  30. else
  31. return Double.valueOf(minHeap.peek() + maxHeap.peek())/ 2;
  32. }
  33. }

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]}。

  1. import java.util.*;
  2. public class Solution {
  3. public static ArrayList<Integer> maxInWindows(int [] num, int size)
  4. {
  5. ArrayList<Integer> list = new ArrayList<>();
  6. if(num == null ||size == 0 || num.length < size)
  7. return list;
  8. LinkedList<Integer> queue = new LinkedList<>();
  9. for(int i=0; i<num.length; i++){
  10. while(!queue.isEmpty()&& num[i] > num[queue.getLast()])
  11. queue.pollLast();
  12. queue.offerLast(i);
  13. if(i - queue.getFirst() >= size)
  14. queue.pollFirst();
  15. if(i >= size-1)
  16. list.add(num[queue.peek()]);
  17. }
  18. return list;
  19. }
  20. }

65.题目描述:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如[a b c e s f c s a d e e]是3*4矩阵,其包含字符串"bcced"的路径,但是矩阵中不包含“abcb”路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

  1. public class Solution {
  2. public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
  3. {
  4. int[] flag = new int[matrix.length];
  5. for(int i=0; i<rows; i++){
  6. for(int j=0; j<cols; j++){
  7. if(help(matrix,i,j, rows,cols,str,flag,0))
  8. return true;
  9. }
  10. }
  11. return false;
  12. }
  13. public boolean help(char[] matrix, int i, int j, int rows, int cols, char[] str, int[] flag, int k){
  14. int index = i * cols + j;
  15. if(i<0 || i>=rows || j<0 || j >= cols || flag[index] == 1 || str[k] != matrix[index])
  16. return false;
  17. if(k == str.length-1)
  18. return true;
  19. flag[index] = 1;
  20. if(help(matrix,i-1,j,rows,cols,str,flag,k+1) || help(matrix,i+1,j,rows,cols,str,flag,k+1)
  21. || help(matrix,i,j-1,rows,cols,str,flag,k+1) ||help(matrix,i,j+1,rows,cols,str,flag,k+1))
  22. return true;
  23. flag[index] = 0;
  24. return false;
  25. }
  26. }

66.题目描述:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

  1. public class Solution {
  2. public int movingCount(int threshold, int rows, int cols)
  3. {
  4. int[][] move = new int[rows][cols];
  5. return moveing(threshold, 0, 0, rows, cols, move);
  6. }
  7. public int moveing(int threshold, int i, int j,int rows, int cols, int[][] move){
  8. if(i < 0 || j <0 || i>=rows || j >= cols || !isCanMove(i,j, threshold) || move[i][j] == 1)
  9. return 0;
  10. move[i][j] = 1;
  11. return moveing(threshold, i+1, j, rows, cols, move)
  12. +moveing(threshold, i-1, j, rows, cols, move)+
  13. moveing(threshold, i, j-1, rows, cols, move)+
  14. moveing(threshold, i, j+1, rows, cols, move)+1;
  15. }
  16. public boolean isCanMove(int rows, int cols, int threshold){
  17. int sum = 0;
  18. while(rows > 0){
  19. sum += rows % 10;
  20. rows = rows/ 10;
  21. }
  22. while(cols >0){
  23. sum += cols % 10;
  24. cols = cols /10;
  25. }
  26. if(sum <= threshold)
  27. return true;
  28. return false;
  29. }
  30. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注