classSolution{ publicintfindRepeatNumber(int[] nums){ for (int i=0; i<nums.length; i++) { if (nums[i]!=i) { if (nums[nums[i]]==nums[i]) return nums[i]; swap(nums, i, nums[i]); } } return -1; }
publicvoidswap(int[] nums, int i, int j){ int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } }
二维数组中的查找
思路:从左下角或者右上角开始遍历(左下角的数,为该行最小值和该列最大值;右上角相反)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution{ publicbooleanfindNumberIn2DArray(int[][] matrix, int target){ int n = matrix.length; if (n==0) returnfalse; int m = matrix[0].length; if (m==0) returnfalse; int i = 0, j = m-1; while (i<n && j>=0) { if (matrix[i][j]==target) returntrue; elseif (matrix[i][j]<target) i++; else j--; } returnfalse; } }
classSolution{ public String replaceSpace(StringBuffer str){ int p = str.length()-1; for (int i=0; i<=p; i++) { if (str.charAt(i) == ' ') str.append(" "); } int q = str.length()-1; while (p<q && p>=0) { char c = str.charAt(p--); if (c==' ') { str.setCharAt(q--, '0'); str.setCharAt(q--, '2'); str.setCharAt(q--, '%'); } else str.setCharAt(q--, c); } return str.toString(); } }
链表
从尾到头打印链表
思路:利用栈后进先出的性质。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution{ publicint[] reversePrint(ListNode head) { if (head==null) returnnewint[]{}; Stack<Integer> s = new Stack<>(); while (head!=null) { s.push(head.val); head = head.next; } int len = s.size(); int[] res = newint[len]; for (int i=0; i<len; i++) { res[i] = s.pop(); } return res; } }
classSolution{ public TreeNode buildTree(int[] preorder, int[] inorder){ if (preorder.length==0 || preorder.length!=inorder.length) returnnull; return reBuild(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1); }
public TreeNode reBuild(int[] pre, int[]in, int pl, int pr, int il, int ir){ if (pl>pr || il>ir) returnnull; TreeNode root = new TreeNode(pre[pl]); if (pl==pr) return root; int h = 0; while (in[il+h]!=root.val) { h++; } root.left = reBuild(pre, in, pl+1, pl+h, il, il+h-1); root.right = reBuild(pre, in, pl+h+1, pr, il+h+1, ir); return root; } }
publicint[][] matrix; publicint M; publicint N; publicint K;
publicintmovingCount(int m, int n, int k){ this.M = m; this.N = n; this.K = k; this.matrix = newint[m][n]; dfs(0, 0); int res = 0; for (int i=0; i<m; i++) { for (int j=0; j<n; j++) { if (matrix[i][j]==1) res++; } } return res; }
publicvoiddfs(int i, int j){ if (i<0 || j<0 || i>=M || j>=N) return;//边界判断 if (!check(i, j)) return;//不符合要求的格子 if (matrix[i][j]==1) return;//防止重复进入 matrix[i][j] = 1;//标记可以进入此格 dfs(i-1, j); dfs(i+1, j); dfs(i, j-1); dfs(i, j+1); }
publicbooleancheck(int i, int j){ int t=0; while (i>0) { t += i%10; i/=10; } while (j>0) { t += j%10; j/=10; } return t<=K; } }