├── src ├── Solution.java ├── Main47.java ├── Main38.java ├── Main48.java ├── Main53.java ├── Main9.java ├── Main18.java ├── Main12.java ├── Main43.java ├── Main55.java ├── Main34.java ├── Main5.java ├── Main10.java ├── Main42.java ├── Main58.java ├── Main51.java ├── Main32.java ├── Main45.java ├── Main62.java ├── Main7.java ├── Main33.java ├── Main50.java ├── Main39.java ├── Main54.java ├── Main67.java ├── Main22.java ├── Main21.java ├── Main20.java ├── Main8.java ├── Main63.java ├── Main31.java ├── Main6.java ├── Main60.java ├── Main2.java ├── Main40.java ├── Main11.java ├── Main14.java ├── Main30.java ├── Main13.java ├── Main26.java ├── Main46.java ├── Main35.java ├── Main57.java ├── Main65.java ├── Main15.java ├── Main56.java ├── Main64.java ├── Main27.java ├── Main16.java ├── Main44.java ├── Main28.java ├── Main19.java ├── Main3.java ├── Main24.java ├── Main37.java ├── Main23.java ├── Main36.java ├── Main1.java ├── Main29.java ├── Main59.java ├── Main17.java ├── Main41.java ├── Main66.java ├── Main25.java ├── Main49.java ├── Main52.java ├── Main61.java └── Main4.java └── README.md /src/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | } -------------------------------------------------------------------------------- /src/Main47.java: -------------------------------------------------------------------------------- 1 | public class Main47 { 2 | public int Sum_Solution(int n) { 3 | int sum = n; 4 | boolean flag = (n > 0) && (sum += Sum_Solution(n - 1)) > 0; 5 | return sum; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Main38.java: -------------------------------------------------------------------------------- 1 | public class Main38 { 2 | public int TreeDepth(TreeNode node) { 3 | if (node == null) { 4 | return 0; 5 | } 6 | return Math.max(TreeDepth(node.left), TreeDepth(node.right)) + 1; // + 1就是当前node对路径产生的影响 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Main48.java: -------------------------------------------------------------------------------- 1 | public class Main48 { 2 | public int Add(int num1,int num2) { 3 | int sum1, sum2; 4 | do{ 5 | sum1 = num1 ^ num2; 6 | sum2 = (num1 & num2) << 1; 7 | num1 = sum1; 8 | num2 = sum2; 9 | }while (num2 != 0); 10 | return num1; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Main53.java: -------------------------------------------------------------------------------- 1 | public class Main53 { 2 | public boolean isNumber(String s) { 3 | if (s.endsWith("f") || s.endsWith("d") || s.endsWith("F") || s.endsWith("D")) { 4 | return false; 5 | } 6 | try { 7 | Double.parseDouble(s); 8 | } catch (Exception e) { 9 | return false; 10 | } 11 | return true; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Main9.java: -------------------------------------------------------------------------------- 1 | public class Main9 { 2 | public int JumpFloorII(int target) { 3 | if (target == 1) { 4 | return 1; 5 | } 6 | int[] a = new int[target + 1]; 7 | int sum = 1; /// 设置一个sum变量去记录1到n-1阶的总的情况数 8 | for (int i = 2; i <= target; i++) { 9 | a[i] = sum + 1; /// 对于第i阶台阶他是等于从第1阶到第i-1阶台阶的情况数之和然后再加上1(从起点到i阶的情况) 10 | sum = sum + a[i]; /// 需要去更新1到i阶的情况数 11 | } 12 | return a[target]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Main18.java: -------------------------------------------------------------------------------- 1 | public class Main18 { 2 | public void Mirror(TreeNode node) { 3 | if (node != null) { 4 | if (node.left != null) { 5 | Mirror(node.left); 6 | } 7 | if (node.right != null) { 8 | Mirror(node.right); 9 | } 10 | /// 下面三行就是交换node节点的左右孩子 11 | TreeNode temp = node.left; 12 | node.left = node.right; 13 | node.right = temp; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Main12.java: -------------------------------------------------------------------------------- 1 | public class Main12 { 2 | public double Power(double base, int exponent) { 3 | double ans = 1.0; 4 | if (exponent >= 0) { 5 | for (int i = 1; i<= exponent; i++) { 6 | ans = ans * base; 7 | } 8 | } else { 9 | for (int i = 1; i<= -exponent; i++) { /// 注意一下exponent是一个负数 10 | ans = ans * base; 11 | } 12 | ans = 1 / ans; 13 | } 14 | return ans; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Main43.java: -------------------------------------------------------------------------------- 1 | public class Main43 { 2 | public String LeftRotateString(String str,int n) { 3 | if (str.length() == 0) { 4 | return ""; 5 | } 6 | StringBuilder flipStr = new StringBuilder(str).reverse(); // 第一次翻转 7 | String str1 = flipStr.substring(0, flipStr.length() - n); // 取出第一个子序列 8 | String str2 = flipStr.substring(flipStr.length() - n); // 取出第二个子序列 9 | return new StringBuilder(str1).reverse().append(new StringBuilder(str2).reverse()).toString(); // 第二次翻转 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Main55.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class Main55 { 5 | public ListNode EntryNodeOfLoop(ListNode pHead) 6 | { 7 | Map map = new HashMap<>(); 8 | ListNode node = pHead; 9 | while (node != null) { 10 | map.put(node, map.getOrDefault(node, 0) + 1); 11 | if (map.get(node) == 2) { 12 | return node; 13 | } 14 | node = node.next; 15 | } 16 | return null; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Main34.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class Main34 { 5 | public int FirstNotRepeatingChar(String str) { 6 | Map map = new HashMap<>(); 7 | for (int i = 0; i < str.length(); i++) { 8 | map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1); 9 | } 10 | for (int i = 0; i < str.length(); i++) { 11 | if (map.get(str.charAt(i)) == 1) { 12 | return i; 13 | } 14 | } 15 | return -1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Main5.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Main5 { 4 | Stack stack1 = new Stack(); 5 | Stack stack2 = new Stack(); 6 | 7 | public void push(int node) { 8 | while (!stack2.isEmpty()) { 9 | stack1.push(stack2.pop()); /// 将栈2中的元素放入到栈1中 10 | } 11 | stack1.push(node); 12 | } 13 | 14 | public int pop() { 15 | while (!stack1.isEmpty()) { 16 | stack2.push(stack1.pop()); /// 将栈1中的元素放入到栈2中 17 | } 18 | return stack2.pop(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Main10.java: -------------------------------------------------------------------------------- 1 | public class Main10 { 2 | public int RectCover(int target) { 3 | if (target == 0) { 4 | return 0; 5 | } 6 | if (target == 1) { 7 | return 1; 8 | } 9 | if (target == 2) { 10 | return 2; 11 | } 12 | int[] a = new int[target + 1]; 13 | a[1] = 1; 14 | a[2] = 2; 15 | for (int i = 3; i <= target; i++) { 16 | a[i] = a[i - 1] + a[i - 2]; /// 对于2*i的矩形,他的情况数就是等于2*(i-1)的基础上在右边放置一个竖着的2*1的小矩阵,然后再加上2*(i-2)的矩形的基础上在右边横着放置两个2*1的小矩阵。 17 | } 18 | return a[target]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Main42.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main42 { 4 | public ArrayList FindNumbersWithSum(int [] array, int sum) { 5 | ArrayList list = new ArrayList<>(); 6 | int l = 0; 7 | int r = array.length - 1; 8 | 9 | while (l <= r - 1) { 10 | if (array[l] + array[r] == sum) { 11 | list.add(array[l]); 12 | list.add(array[r]); 13 | break; 14 | } else if (array[l] + array[r] < sum) { 15 | l++; 16 | } else { 17 | r--; 18 | } 19 | } 20 | return list; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Main58.java: -------------------------------------------------------------------------------- 1 | public class Main58 { 2 | public boolean isSymmetrical(TreeNode pRoot) { 3 | if (pRoot == null) { 4 | return true; 5 | } 6 | return solve(pRoot.left, pRoot.right); 7 | } 8 | 9 | private boolean solve(TreeNode node1, TreeNode node2) { 10 | if (node1 == null && node2 == null) { 11 | return true; 12 | } 13 | if (node1 == null || node2 == null) { 14 | return false; 15 | } 16 | if (node1.val != node2.val) { 17 | return false; 18 | } 19 | return solve(node1.left, node2.right) && solve(node1.right, node2.left); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Main51.java: -------------------------------------------------------------------------------- 1 | public class Main51 { 2 | public static int[] multiply(int[] A) { 3 | int[] f1 = new int[A.length]; // 0到i-1的乘积 4 | int[] f2 = new int[A.length]; // i+1到n-1的乘积 5 | 6 | int ans1 = 1; // 0-(i-1)的乘积 7 | int ans2 = 1; // (i+1)-n-1的乘积 8 | for (int i = 0, j = A.length - 1; i < A.length; i++, j--) { 9 | f1[i] = ans1; 10 | ans1 *= A[i]; 11 | 12 | f2[j] = ans2; 13 | ans2 *= A[j]; 14 | } 15 | int[] B = new int[A.length]; 16 | for (int i = 0; i < A.length; i++) { 17 | B[i] = f1[i] * f2[i]; 18 | } 19 | return B; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Main32.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Comparator; 3 | 4 | public class Main32 { 5 | public String PrintMinNumber(int [] numbers) { 6 | ArrayList list = new ArrayList<>(); 7 | for (int x : numbers) { 8 | list.add(x + ""); 9 | } 10 | list.sort((o1, o2) -> { 11 | // 下面的排序规则是核心 12 | String a1 = o1 + o2; 13 | String a2 = o2 + o1; 14 | return a1.compareTo(a2); 15 | }); 16 | StringBuilder ans = new StringBuilder(); 17 | for (String x : list) { 18 | ans.append(x); 19 | } 20 | return ans.toString(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Main45.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Main45 { 4 | public boolean isContinuous(int [] numbers) { 5 | if (numbers.length == 0) { 6 | return false; 7 | } 8 | int sum = 0; 9 | for (int x : numbers) { 10 | if (x == 0) { 11 | sum++; 12 | } 13 | } 14 | Arrays.sort(numbers); 15 | for (int i = sum + 1; i < numbers.length; i++) { 16 | sum -= numbers[i] - numbers[i - 1] - 1; 17 | if (sum < 0 || numbers[i] == numbers[i - 1]) { 18 | return false; 19 | } 20 | } 21 | return true; 22 | } 23 | } 24 | // 0 0 1 1 5 -------------------------------------------------------------------------------- /src/Main62.java: -------------------------------------------------------------------------------- 1 | public class Main62 { 2 | private TreeNode ans; 3 | private int index; 4 | 5 | public TreeNode KthNode(TreeNode pRoot, int k) { 6 | index = 1; 7 | ans = null; 8 | if (k != 0 && pRoot != null) { 9 | solve(pRoot, k); 10 | } 11 | return ans; 12 | } 13 | 14 | private void solve(TreeNode node, int k) { 15 | if (ans == null) { 16 | if (node.left != null) { 17 | solve(node.left, k); 18 | } 19 | if (index == k) { 20 | ans = node; 21 | } 22 | index++; 23 | if (node.right != null) { 24 | solve(node.right, k); 25 | } 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/Main7.java: -------------------------------------------------------------------------------- 1 | public class Main7 { 2 | // public int Fibonacci(int n) { 3 | // if (n == 0) { 4 | // return 0; 5 | // } 6 | // int[] a = new int[n + 1]; 7 | // if (n == 1 || n == 2) { 8 | // return 1; 9 | // } 10 | // a[1] = 1; 11 | // a[2] = 1; 12 | // for (int i = 3; i <= n; i++) { 13 | // a[i] = a[i - 1] + a[i - 2]; 14 | // } 15 | // return a[n]; 16 | // } 17 | 18 | // a[n] = a[n - 1] + a[n - 2]; 19 | 20 | private static int Fibonacci(int n) { 21 | if (n == 0) { 22 | return 0; /// 终止递归的条件 23 | } 24 | if (n == 1 || n == 2) { 25 | return 1; /// 终止递归的条件 26 | } 27 | return Fibonacci(n - 1) + Fibonacci(n -2); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Main33.java: -------------------------------------------------------------------------------- 1 | public class Main33 { 2 | public int GetUglyNumber_Solution(int index) { 3 | int[] a = new int[index]; 4 | a[0] = 1; 5 | int index1 = 0; // 遍历丑数*2的队列 6 | int index2 = 0; // 遍历丑数*3的队列 7 | int index3 = 0; // 遍历丑数*5的队列 8 | 9 | for (int i = 1; i < index; i++) { 10 | a[i] = Math.min(Math.min(a[index1] * 2, a[index2] * 3) , a[index3] * 5); 11 | // 根据放在第i个位置上的数字更新遍历三个队列的下标 12 | if (a[i] == a[index1] * 2) { 13 | index1++; 14 | } 15 | if (a[i] == a[index2] * 3) { 16 | index2++; 17 | } 18 | if (a[i] == a[index3] * 5) { 19 | index3++; 20 | } 21 | } 22 | return a[index - 1]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Main50.java: -------------------------------------------------------------------------------- 1 | public class Main50 { 2 | public static int findRepeatNumber(int[] nums) { 3 | int ans = -1; 4 | for (int i = 0; i < nums.length; i++) { 5 | if (nums[i] == i) { 6 | continue; // 不需要去维护index和index对应的值相等的关系 7 | } 8 | if (nums[nums[i]] == nums[i]) { 9 | ans = nums[i]; 10 | break; 11 | } 12 | // 下面的三行是交换两个数字,目的是为了维护 nums[nums[i]] = nums[i] 13 | int temp = nums[i]; 14 | nums[i] = nums[nums[i]]; 15 | nums[temp] = temp; 16 | } 17 | return ans; 18 | } 19 | 20 | public static void main(String[] args) { 21 | int[] a = new int[]{2, 3, 1, 0, 2, 5, 3}; 22 | System.out.println(findRepeatNumber(a)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Main39.java: -------------------------------------------------------------------------------- 1 | public class Main39 { 2 | private boolean ans; 3 | public boolean IsBalanced_Solution(TreeNode root) { 4 | if (root == null) { 5 | return true; 6 | } 7 | ans = true; 8 | TreeDepth(root); 9 | return ans; 10 | } 11 | 12 | private int TreeDepth(TreeNode node) { 13 | if (node == null) { 14 | return 0; 15 | } 16 | if (ans) { // 剪枝操作 17 | int leftDepth = TreeDepth(node.left); // 求出当前节点的左子树的高度 18 | int rightDepth = TreeDepth(node.right); // 求出当前节点的右子树的高度 19 | if (Math.abs(leftDepth - rightDepth) > 1) { 20 | ans = false; 21 | } 22 | return Math.max(leftDepth, rightDepth) + 1; 23 | } 24 | return 0; // 这个地方返回什么已经不重要了,因为我们已经找一个节点不满足条件了 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Main54.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class Main54 { 5 | private Map map = new HashMap<>(); // 保存每个字符出现的次数 6 | private StringBuilder str = new StringBuilder(); // 保存字符流 7 | private int index = 0; // 用来保存字符只出现一次的第一个位置 8 | 9 | //Insert one char from stringstream 10 | public void Insert(char ch) 11 | { 12 | str.append(ch); 13 | map.put(ch, map.getOrDefault(ch, 0) + 1); 14 | } 15 | //return the first appearence once char in current stringstream 16 | public char FirstAppearingOnce() 17 | { 18 | while (index < str.length()) { 19 | if (map.get(str.charAt(index)) == 1) { 20 | return str.charAt(index); 21 | } 22 | index++; 23 | } 24 | return '#'; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Main67.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.math.BigInteger; 3 | 4 | public class Main67 { 5 | public static int cutRope(int n) { 6 | BigInteger[] dp = new BigInteger[n + 1]; 7 | if (n == 2) { 8 | return 1; 9 | } 10 | if (n == 3) { 11 | return 2; 12 | } 13 | dp[1] = BigInteger.ONE; 14 | dp[2] = BigInteger.valueOf(2); 15 | dp[3] = BigInteger.valueOf(3); // 1 + 2 16 | for (int k = 4; k <= n; k++) { 17 | dp[k] = BigInteger.ZERO; 18 | for (int i = 1; i <= k / 2; i++) { 19 | BigInteger temp = dp[i].multiply(dp[k - i]); 20 | if (dp[k].compareTo(temp) < 0) { 21 | dp[k] = temp; 22 | } 23 | } 24 | } 25 | return dp[n].mod(BigInteger.valueOf(1000000007)).intValue(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Main22.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | import java.util.Queue; 4 | 5 | public class Main22 { 6 | public ArrayList PrintFromTopToBottom(TreeNode root) { 7 | ArrayList ans = new ArrayList<>(); 8 | Queue queue = new LinkedList<>(); // 放入遍历二叉树的节点(本质上是维护宽搜) 9 | if (root != null) { 10 | queue.add(root); 11 | } 12 | // 迭代的过程->宽搜 13 | while (!queue.isEmpty()) { 14 | TreeNode node = queue.peek(); 15 | ans.add(node.val); // 将当前节点的val值放入ArrayList中 16 | // 同层节点从左至右打印 17 | if (node.left != null) { 18 | queue.add(node.left); 19 | } 20 | if (node.right != null) { 21 | queue.add(node.right); 22 | } 23 | queue.poll(); // 当前节点val值已经放入ans中,所以要删去 24 | } 25 | return ans; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Main21.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Main21 { 4 | public boolean IsPopOrder(int [] pushA,int [] popA) { 5 | Stack stack = new Stack<>(); 6 | int pushIndex = 0; // 入栈序列的下标 7 | int popIndex = 0; // 出栈序列的下标 8 | 9 | while (pushIndex < pushA.length) { 10 | if (!stack.isEmpty() && stack.peek() == popA[popIndex]) { 11 | stack.pop(); 12 | popIndex++; 13 | } else { 14 | stack.push(pushA[pushIndex]); 15 | pushIndex++; 16 | } 17 | } 18 | 19 | // 下面的这个while循环其实就是为了防止当所有入栈的元素都压入栈的时候,栈顶元素和出栈序列的下标所指的数字没有来得及比较。 20 | while (!stack.isEmpty()) { 21 | if (stack.peek() == popA[popIndex]) { 22 | stack.pop(); 23 | popIndex++; 24 | } else { 25 | return false; 26 | } 27 | } 28 | return true; 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Main20.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Main20 { 4 | private Stack dataStack = new Stack<>(); // 数据栈 5 | private Stack minStack = new Stack<>(); // 维护min函数的栈 6 | 7 | public void push(int node) { 8 | dataStack.push(node); 9 | 10 | if (minStack.isEmpty() || minStack.peek() > dataStack.peek()) { 11 | minStack.push(dataStack.peek()); // 当前minStack的栈顶元素大于数据栈的栈顶元素 12 | } else { 13 | minStack.push(minStack.peek()); // 当前minStack的栈顶元素小于数据栈的栈顶元素 14 | } 15 | } 16 | 17 | public void pop() { 18 | if (!dataStack.isEmpty()) { 19 | dataStack.pop(); 20 | } 21 | if (!minStack.isEmpty()) { 22 | minStack.pop(); 23 | } 24 | } 25 | 26 | public int top() { 27 | // 取出数据栈的栈顶元素 28 | return dataStack.peek(); 29 | } 30 | 31 | public int min() { 32 | // 取出维护min函数的栈的栈顶元素 33 | return minStack.peek(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Main8.java: -------------------------------------------------------------------------------- 1 | import java.net.JarURLConnection; 2 | 3 | public class Main8 { 4 | /* public int JumpFloor(int target) { 5 | if (target == 1) { 6 | return 1; /// 目前递归到第1阶台阶,就没有必要往下去递归了 7 | } 8 | if (target == 2) { 9 | return 1 + JumpFloor(target - 1); /// 如果target == 2,其实就是等于从起点位置直接跳2阶 + 递归到第一阶的情况的总的跳阶的次数 10 | // return 2; 11 | } 12 | return JumpFloor(target - 1) + JumpFloor(target - 2); /// 当前target台阶的次数等于往前跳1阶加上往前跳2阶 13 | }*/ 14 | 15 | public int JumpFloor(int target) { 16 | if (target == 1) { 17 | return 1; 18 | } 19 | if (target == 2) { 20 | return 2; 21 | } 22 | int[] a = new int[target + 1]; /// a[i] 代表从起点到第i阶的总的情况数 23 | a[1] = 1; /// 第一阶的总情况数是1 24 | a[2] = 2; /// 第二阶的总情况数是2 25 | for (int i = 3; i <= target; i++) { 26 | a[i] = a[i - 1] + a[i - 2]; /// 对于第i阶的总情况数就等于从起点到第i-1阶的情况数(从0 -> i-1 -> +1 = i)加上从起点到第i-2阶的情况数(0 -> i-2 -> +2 ->i) 27 | } 28 | return a[target]; 29 | } 30 | 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/Main63.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | public class Main63 { 4 | private PriorityQueue queue1 = new PriorityQueue<>(((o1, o2) -> (o2 - o1))); // 中位数的左区间 > 大顶堆 5 | private PriorityQueue queue2 = new PriorityQueue<>(); // 中位数的右区间 > 小顶堆 6 | private int sum = 0; // 数据流中个数 7 | 8 | public void Insert(Integer num) { 9 | if (sum % 2 == 0) { 10 | // 当两个堆的元素个数一样的时候,此时新增一个元素,放入大顶堆(左区间) 11 | queue1.add(num); 12 | } else { 13 | queue2.add(num); 14 | } 15 | if(!queue2.isEmpty() && queue1.peek() > queue2.peek()) { 16 | assert !queue1.isEmpty(); 17 | int temp1 = queue1.poll(); 18 | int temp2 = queue2.poll(); 19 | queue1.add(temp2); 20 | queue2.add(temp1); 21 | } 22 | sum++; 23 | } 24 | 25 | public Double GetMedian() { 26 | if (sum % 2 == 1) { 27 | return (double) queue1.peek(); 28 | } else { 29 | return (queue1.peek() + queue2.peek()) / 2.0; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Main31.java: -------------------------------------------------------------------------------- 1 | public class Main31 { 2 | /*public int NumberOf1Between1AndN_Solution(int n) { 3 | int sum = 0; 4 | for (int i = 1; i <= n; i++) { 5 | int x = i; 6 | while (x != 0) { 7 | if (x % 10 == 1) { 8 | sum++; 9 | } 10 | x = x / 10; 11 | } 12 | } 13 | return sum; 14 | }*/ 15 | 16 | public int NumberOf1Between1AndN_Solution(int n) { 17 | if (n == 0) { 18 | return 0; 19 | } 20 | String str = "" + n; 21 | int len = str.length(); 22 | if (len == 1) { 23 | return 1; 24 | } 25 | int res = (int) Math.pow(10, len - 1); // 是获取当前n的幂级 26 | // int firstNumber = str.charAt(0) - '0'; 27 | int firstNumber = n / res; 28 | int firstBit = firstNumber == 1 ? (n % res) + 1 : res; 29 | int otherBit = (len - 1) * firstNumber * res / 10; //(len - 1)的意思就是剩余位的个数(C(len-1, 1) -> 从剩余的len-1位中选取一位来作为1),res/10的意思就是剩余的len-2位可能出现的情况 30 | return firstBit + otherBit + NumberOf1Between1AndN_Solution(n % res); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Main6.java: -------------------------------------------------------------------------------- 1 | public class Main6 { 2 | // public int minNumberInRotateArray(int [] array) { 3 | // if (array.length == 0) { 4 | // return 0; 5 | // } 6 | // int ans = array[0]; 7 | // for (int i = 1; i < array.length; i++) { 8 | // ans = Math.min(ans, array[i]); 9 | // } 10 | // return ans; 11 | // } 12 | 13 | 14 | public static int minNumberInRotateArray(int[] array) { 15 | if (array.length == 0) { 16 | return 0; 17 | } 18 | int l = 0; 19 | int r = array.length - 1; 20 | while (l < r - 1) { 21 | int mid = (l + r) >> 1; 22 | if (array[mid] >= array[l]) { 23 | l = mid; /// 说明mid所在的位置是在第一个非递减子数组中 24 | } else if (array[mid] <= array[r]) { 25 | r = mid; /// 说明mid所在的位置是在第二个非递减子数组中 26 | } 27 | } 28 | return array[r]; 29 | } 30 | 31 | public static void main(String[] args) { 32 | int[] array = {3,4,5,1,2}; 33 | System.out.println(minNumberInRotateArray(array)); 34 | } 35 | 36 | } 37 | 38 | // 2,2,2,2,3 -> 3, 2, 2, 2, 2 -------------------------------------------------------------------------------- /src/Main60.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | import java.util.Queue; 4 | 5 | public class Main60 { 6 | ArrayList> Print(TreeNode root) { 7 | ArrayList> ans = new ArrayList<>(); 8 | 9 | Queue queue = new LinkedList<>(); 10 | queue.add(root); 11 | int sum = 1; // 用来保存每一层的节点的个数 12 | 13 | while (!queue.isEmpty() && root != null) { 14 | ArrayList list = new ArrayList<>(); 15 | int temp = 0; 16 | while (sum > 0) { 17 | TreeNode node = queue.poll(); 18 | assert node != null; 19 | list.add(node.val); 20 | if (node.left != null) { 21 | temp++; 22 | queue.add(node.left); 23 | } 24 | if (node.right != null) { 25 | temp++; 26 | queue.add(node.right); 27 | } 28 | sum--; 29 | } 30 | sum = temp; 31 | ans.add(list); 32 | } 33 | return ans; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Main2.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main2 { 4 | // private static String replaceSpace(StringBuffer str) { 5 | // int len = str.length(); 6 | // String res = "%20"; 7 | // StringBuffer ans = new StringBuffer(); 8 | // for (int i = 0; i < len; i++) { 9 | // if (str.charAt(i) == ' ') { 10 | // ans.append(res); 11 | // } else { 12 | // ans.append(str.charAt(i)); 13 | // } 14 | // } 15 | // return ans.toString(); 16 | // } 17 | 18 | private static String replaceSpace(StringBuffer str) { 19 | int len = str.length(); 20 | String res = "%20"; 21 | StringBuffer ans = new StringBuffer(); 22 | for (int i = 0; i < len; i++) { 23 | ans.append(str.charAt(i) == ' ' ? res : str.charAt(i)); /// 判断当前字符是否为空格 24 | } 25 | return ans.toString(); 26 | } 27 | 28 | public static void main(String[] args) { 29 | Scanner cin = new Scanner(System.in); 30 | StringBuffer str = new StringBuffer(); 31 | str.append(cin.nextLine()); 32 | System.out.println(replaceSpace(str)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Main40.java: -------------------------------------------------------------------------------- 1 | public class Main40 { 2 | public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { 3 | if (array.length != 0) { 4 | int ans = 0; 5 | // 通过第一个循环找到那两个出现过一次的数字的异或结果 6 | for (int x : array) { 7 | ans ^= x; 8 | } 9 | // 根据这个异或结果去找到分割出这两个数字的方式->从右往左找到第一个位置不为0的地方 10 | int lastNumberOfOne = find(ans); 11 | num1[0] = 0; 12 | num2[0] = 0; 13 | for (int x : array) { 14 | if (judge(x, lastNumberOfOne) == 0) { 15 | num1[0] ^= x; 16 | } else { 17 | num2[0] ^= x; 18 | } 19 | } 20 | } 21 | } 22 | 23 | // 判断x的从右往左看,第lastNumberOfOne位是否为1 24 | private int judge(int x, int lastNumberOfOne) { 25 | x >>= (lastNumberOfOne - 1); // 将x的第lastNumberOfOne位移到最右边 26 | return x & 1; 27 | } 28 | 29 | private int find(int ans) { 30 | int sum = 1; 31 | int res = 1; 32 | while ((ans & res) == 0) { 33 | sum++; 34 | res <<= 1; 35 | } 36 | return sum; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Main11.java: -------------------------------------------------------------------------------- 1 | public class Main11 { 2 | // public int NumberOf1(int n) { 3 | // int sum = 0; /// 记录1的个数 4 | // int temp = 1; /// 本质上是用temp变量去判断n的每一位数字是否为1 5 | // while (temp != 0) { /// 当temp为0的时候,说明已经移动了32次,然后就说明已经遍历完了n的每一位 6 | // sum = (n & temp) != 0 ? sum + 1 : sum; 7 | // temp = temp << 1; 8 | // } 9 | // return sum; 10 | // } 11 | 12 | public int NumberOf1(int n) { 13 | int sum = 0; /// 记录1的个数 14 | while (n != 0) { /// 说明当前n的二进制表示中肯定有1 15 | sum++; 16 | n = n & (n - 1); /// 本质上就是消除从右往左数的第一个位置的1。 17 | } 18 | return sum; 19 | } 20 | 21 | public static void main(String[] args) { 22 | // int i = -16; 23 | // while (i != 0) { 24 | // System.out.println(i); 25 | // i = i >> 1; 26 | // } 27 | } 28 | } 29 | 30 | /// 第二种方法 31 | // 5 -》 101 & 1 —》 10 & 1 -》 1 & 1 -》 0 & 1这种方法是有问题的。 32 | // 1 -> 0000000...01 -> (-1) -> 11....11111 -> 右移1位,数字-1的二进制的左边是补1的,也就是说,无论你右移多少次,结果都是-1. 33 | // 34 | // 改进:对n&运算的后面的那个数字进行操作: 35 | // 5-》 101 & 1 -》 101 & 10 -》 101 & 100 36 | 37 | 38 | /// 第三种方法 39 | // 5 -》 101 & 100(101 - 1) = 100 -》 100 & 011(100 - 1) = 000 -》 000 40 | 41 | -------------------------------------------------------------------------------- /src/Main14.java: -------------------------------------------------------------------------------- 1 | public class Main14 { 2 | /* public ListNode FindKthToTail(ListNode head,int k) { 3 | ListNode removeNode = head; 4 | while (k != 0) { 5 | if (removeNode == null) { /// k 大于链表的长度,直接返回null 6 | return null; 7 | } 8 | removeNode = removeNode.next; 9 | k--; 10 | } 11 | while (removeNode != null) { /// 这个循环其实就是同时移动head和removeNode两个节点。 12 | removeNode = removeNode.next; 13 | head = head.next; 14 | } 15 | return head; 16 | }*/ 17 | 18 | private ListNode ans; /// 最终返回的结果 19 | private int sum; /// 用来记录当前节点是倒数第几个节点 20 | 21 | private void dfs(ListNode node, int k) { 22 | if (node.next != null) { 23 | dfs(node.next, k); /// 继续递归到下一节点。 24 | } 25 | // 下面这部分其实就是判断当前层的节点是倒数第几个节点。 26 | sum++; 27 | if (sum == k) { 28 | ans = node; 29 | } 30 | } 31 | 32 | public ListNode FindKthToTail(ListNode head, int k) { 33 | ans = null; 34 | sum = 0; 35 | if (head == null) { /// 说明链表为null,就没有必要去递归的需要了 36 | return null; 37 | } 38 | dfs(head, k); /// 递归遍历链表 39 | return ans; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Main30.java: -------------------------------------------------------------------------------- 1 | public class Main30 { 2 | /* public int FindGreatestSumOfSubArray(int[] array) { 3 | int[] sum = new int[array.length]; // 用来去统计0-i位置的和 4 | sum[0] = array[0]; 5 | for (int i = 1; i < array.length; i++) { 6 | sum[i] = sum[i - 1] + array[i]; 7 | } 8 | int Max = sum[0]; // 默认第一个元素 9 | // i是终点,j是起点 10 | for (int i = 0; i < array.length; i++) { 11 | for (int j = 0; j <= i; j++) { 12 | if (j == 0) { 13 | Max = Math.max(Max, sum[i]); // 说明起点在0位置 14 | } else { 15 | Max = Math.max(Max, sum[i] - sum[j - 1]); // j-i的和它就等于从起点到i位置之和减去从起点到j-1的位置之和 16 | } 17 | } 18 | } 19 | return Max; 20 | }*/ 21 | public int FindGreatestSumOfSubArray(int[] array) { 22 | int sum = 0; 23 | int Max = array[0]; 24 | for (int i = 0; i < array.length; i++) { 25 | // 这几行代码的过程就是:通过sum变量去统计当前连续子序列的和,统计完之后,更新Max的值,最后判断是否更新sum的值 26 | sum += array[i]; 27 | Max = Math.max(Max, sum); 28 | if (sum < 0) { 29 | sum = 0; 30 | } 31 | } 32 | return Max; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Main13.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main13 { 4 | /* public void reOrderArray(int [] array) { 5 | int len = array.length; 6 | 7 | for (int i = 0; i < len; i++) { 8 | if (array[i] % 2 != 0) { 9 | for (int j = i - 1; j >= 0; j--) { 10 | if (array[j] % 2 == 0) { 11 | int temp = array[j]; 12 | array[j] = array[j + 1]; 13 | array[j + 1] = temp; 14 | } else { 15 | break; 16 | } 17 | } 18 | } 19 | } 20 | }*/ 21 | public void reOrderArray(int[] array) { 22 | int len = array.length; 23 | ArrayList list1 = new ArrayList<>(); /// 保存奇数 24 | ArrayList list2 = new ArrayList<>(); /// 保存偶数 25 | 26 | for (int i = 0; i < len; i++) { 27 | if (array[i] % 2 != 0) { 28 | list1.add(array[i]); 29 | } else { 30 | list2.add(array[i]); 31 | } 32 | } 33 | int index = 0; 34 | for (int x : list1) { 35 | array[index++] = x; 36 | } 37 | for (int x : list2) { 38 | array[index++] = x; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Main26.java: -------------------------------------------------------------------------------- 1 | public class Main26 { 2 | private TreeNode ans; // 最终返回得双向链表得头部 3 | private TreeNode removeNode; // 双向链表的尾部节点 4 | // flag -> 代表的是第n层节点到达第n+1层节点的方向,0->第n+1层节点是第n层节点得左孩子,1->第n+1层节点是第n层节点得右孩子 5 | private void dfs(TreeNode node, int flag) { 6 | if (node.left != null) { 7 | dfs(node.left, 0); 8 | } 9 | if (ans == null) { 10 | ans = node; 11 | removeNode = node; 12 | } else { 13 | // 做一般处理->添加边,修改边 14 | if(flag == 0) { 15 | removeNode.right = node; // 从尾部节点引出一条边指向当前节点,也就是说创建一条从小到大的边 16 | node.left = removeNode; // 这行代码对于非root节点是没有影响的,主要是为了修改root的左孩子的指向 17 | } else { 18 | removeNode.right = node; // 这行代码对于非root节点是没有影响的,主要是为了修改root的右孩子的指向 19 | node.left = removeNode; // 从当前节点引出一条边指向尾部节点,也就是说创建一条从大到小的边 20 | 21 | } 22 | removeNode = node; // 更新双向链表得尾部节点的值 23 | } 24 | if (node.right != null) { 25 | dfs(node.right, 1); 26 | } 27 | } 28 | public TreeNode Convert(TreeNode pRootOfTree) { 29 | if(pRootOfTree == null) { 30 | return null; 31 | } 32 | ans = null; 33 | removeNode = null; 34 | dfs(pRootOfTree, 0); 35 | return ans; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Main46.java: -------------------------------------------------------------------------------- 1 | public class Main46 { 2 | /* public static int LastRemaining_Solution(int n, int m) { 3 | if (n == 0 || m == 0) { 4 | return -1; 5 | } 6 | boolean[] vis = new boolean[n]; // vis[i] = true代表第i个小朋友移除圆桌 7 | int sum = 0; // 用来记录当前已经移除的人数总和 8 | int res = 0; // 用来记录某一次循环的过程中已经计数人数的个数 9 | int index = 0; 10 | while (sum < n - 1) { 11 | res = 0; 12 | // 在某一次循环中,让index处于没有被移除的学生位置 13 | while (vis[index]) { 14 | index = (index + 1) % n; 15 | } 16 | // 模拟找第m个位置的学生 17 | while (res < m) { 18 | if(!vis[index]) { 19 | res++; 20 | } 21 | index = (index + 1) % n; 22 | } 23 | vis[(index + n - 1) % n] = true; // 标记当前循环移除的学生位置的下标 24 | sum++; 25 | } 26 | // 在返回结果时,让index处于没有被移除的学生位置 27 | while (vis[index]) { 28 | index = (index + 1) % n; 29 | } 30 | return index; 31 | }*/ 32 | public int LastRemaining_Solution(int n, int m) { 33 | if (n == 0 || m == 0) { 34 | return -1; 35 | } 36 | int ans = 0; 37 | for (int i = 2; i <= n; i++) { 38 | ans = (ans + m) % i; 39 | } 40 | return ans; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Main35.java: -------------------------------------------------------------------------------- 1 | public class Main35 { 2 | private long sum; // 用来去统计逆序对的个数 3 | public int InversePairs(int [] array) { 4 | sum = 0; 5 | int l = 0; 6 | int r = array.length - 1; 7 | divide(l ,r, array); 8 | return (int) (sum % 1000000007); 9 | } 10 | 11 | private void divide(int l, int r, int[] array) { 12 | if (l != r) { 13 | int mid = (l + r) >> 1; 14 | divide(l, mid, array); 15 | divide(mid + 1, r, array); 16 | merge(l, r, mid, array); 17 | } 18 | } 19 | 20 | private void merge(int l, int r, int mid, int[] array) { 21 | int i = l; // 左区间的起点 22 | int j = mid + 1; // 右区间的起点 23 | int[] temp = new int[r - l + 1]; 24 | int index = 0; 25 | while (i <= mid && j <= r) { 26 | if (array[i] > array[j]) { 27 | temp[index++] = array[j++]; 28 | sum += mid - i + 1; // 这一行是核心,去统计逆序对个数,统计的基础是在归并排序的合并过程中,合并的两个子序列都是有序的 29 | } else { 30 | temp[index++] = array[i++]; 31 | } 32 | } 33 | while (i <= mid) { 34 | temp[index++] = array[i++]; 35 | } 36 | while (j <= r) { 37 | temp[index++] = array[j++]; 38 | } 39 | index = 0; 40 | for (int k = l; k <= r; k++) { 41 | array[k] = temp[index++]; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Main57.java: -------------------------------------------------------------------------------- 1 | public class Main57 { 2 | public TreeLinkNode GetNext(TreeLinkNode pNode) { 3 | if (pNode.right != null) { 4 | // 第一种情况,pNode节点的右孩子不为空 5 | pNode = pNode.right; 6 | while (pNode.left != null) { 7 | pNode = pNode.left; 8 | } 9 | return pNode; 10 | } else { 11 | TreeLinkNode tempNode = pNode.next; 12 | if (tempNode == null) { 13 | return null; 14 | } 15 | if (tempNode.left == pNode) { 16 | // 第二种情况,当前节点右孩子为空,并且当前节点是父亲节点的左孩子 17 | return tempNode; 18 | } else { 19 | // 第二种情况,当前节点右孩子为空,并且当前节点是父亲节点的右孩子 20 | boolean flag = false; 21 | while (tempNode.next != null) { 22 | if (tempNode.next.left == tempNode) { 23 | flag = true; 24 | break; 25 | } 26 | tempNode = tempNode.next; 27 | } 28 | return flag ? tempNode.next : null; // flag尾true时,说明pNode所指的节点不是二叉树中最右侧节点 29 | } 30 | } 31 | } 32 | } 33 | 34 | 35 | class TreeLinkNode { 36 | int val; 37 | TreeLinkNode left = null; 38 | TreeLinkNode right = null; 39 | TreeLinkNode next = null; 40 | 41 | TreeLinkNode(int val) { 42 | this.val = val; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Main65.java: -------------------------------------------------------------------------------- 1 | public class Main65 { 2 | public boolean exist(char[][] board, String word) { 3 | boolean[][] vis = new boolean[board.length][board[0].length]; 4 | for (int i = 0; i < board.length; i++) { 5 | for (int j = 0; j < board[i].length; j++) { 6 | if (solve(board, word, i, j, vis, 0)) { 7 | // 找到一种情况即可 8 | return true; 9 | } 10 | } 11 | } 12 | return false; 13 | } 14 | 15 | private boolean solve(char[][] board, String word, int x, int y, boolean[][] vis, int index) { 16 | // 越界处理以及每个方格只能访问一次 17 | if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || vis[x][y]) { 18 | return false; 19 | } 20 | // 匹配到某一位置不满足条件 21 | if (word.charAt(index) != board[x][y]) { 22 | return false; 23 | } 24 | // 匹配成功 25 | if (index == word.length() - 1) { 26 | return true; 27 | } 28 | 29 | vis[x][y] = true; // x,y位置的标记 30 | boolean flag = solve(board, word, x + 1, y, vis, index + 1) || 31 | solve(board, word, x - 1, y, vis, index + 1) || 32 | solve(board, word, x, y + 1, vis, index + 1) || 33 | solve(board, word, x, y - 1, vis, index + 1); 34 | vis[x][y] = false; // x,y位置的标记状态回溯 35 | return flag; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Main15.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Main15 { 4 | /* public ListNode ReverseList(ListNode head) { 5 | if (head == null) { 6 | return null; 7 | } 8 | 9 | ListNode frontNode = head; 10 | ListNode removeNode = head.next; 11 | 12 | while (removeNode != null) { 13 | ListNode tempNode = removeNode.next; /// 用来保存移动节点的下一个节点,不然的话,就会造成节点最终无法往右移动的情况。 14 | removeNode.next = frontNode; /// 实现链表的反置 15 | // 下面两行代码就是实现两个节点的向右平移操作。 16 | frontNode = removeNode; 17 | removeNode = tempNode; 18 | } 19 | head.next = null; 20 | return frontNode; 21 | }*/ 22 | public ListNode ReverseList(ListNode head) { 23 | if (head == null) { 24 | return null; 25 | } 26 | Stack stack = new Stack<>(); 27 | while (head != null) { 28 | stack.push(head); 29 | head = head.next; 30 | } 31 | 32 | ListNode removeNode = stack.pop(); /// 创建新的链表,需要创建一个新的引用 33 | ListNode ans = removeNode; 34 | removeNode.next = null; /// 初始化 35 | while (!stack.isEmpty()) { 36 | ListNode x = stack.pop(); /// 取出栈顶节点元素,然后初始化节点元素的next值 37 | x.next = null; 38 | /// 可以用链表的尾接法去理解 39 | removeNode.next = x; 40 | removeNode = x; 41 | } 42 | return ans; 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Main56.java: -------------------------------------------------------------------------------- 1 | public class Main56 { 2 | private ListNode change(ListNode x) { 3 | int temp = x.val; 4 | while (x != null && x.val == temp) { 5 | x = x.next; 6 | } 7 | return x; 8 | } 9 | public ListNode deleteDuplication(ListNode pHead) { 10 | ListNode ans = pHead; // 最终链表的头节点 11 | // 确定最终链表的头节点 12 | while (ans != null) { 13 | if (ans.next != null && ans.val == ans.next.val) { 14 | // 当前ans所指的节点是重复节点 15 | ans = change(ans); 16 | } else { 17 | // 当前ans所指的节点就是我们最终链表的头节点 18 | break; 19 | } 20 | } 21 | if (ans == null) { 22 | return null; 23 | } 24 | // 判断从ans到链表的尾部,判断每一个节点是否为重复节点。 25 | ListNode lastNode = ans; // 最终链表的尾部节点 26 | ListNode removeNode = lastNode.next; // 遍历剩余的节点的变量 27 | while (removeNode != null) { 28 | if (removeNode.next != null && removeNode.val == removeNode.next.val) { 29 | // 当前removeNode所指的节点是重复节点 30 | removeNode = change(removeNode); 31 | } else { 32 | lastNode.next = removeNode; 33 | lastNode = removeNode; 34 | removeNode = removeNode.next; 35 | } 36 | } 37 | lastNode.next = null; // 1 -> 2 -> 3 -> 4 -> 4 38 | return ans; 39 | } 40 | } 41 | 42 | // 1 -> 2 -> 3 -> 4 -> 4 43 | -------------------------------------------------------------------------------- /src/Main64.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | 4 | public class Main64 { 5 | 6 | public static ArrayList maxInWindows(int[] num, int size) { 7 | ArrayList ans = new ArrayList<>(); 8 | if (num.length == 0 || size == 0 || size > num.length) { 9 | return ans; 10 | } 11 | 12 | int Max = Integer.MIN_VALUE; 13 | int pos = -1; 14 | for (int i = 0; i < size; i++) { 15 | if (num[i] > Max) { 16 | Max = num[i]; 17 | pos = i; 18 | } 19 | } 20 | ans.add(Max); 21 | for (int i = size; i <= num.length - 1; i++) { // i - > 窗口的右区间 22 | if (i - size + 1 <= pos) { 23 | if (num[i] > Max) { 24 | Max = num[i]; 25 | pos = i; 26 | } 27 | } else { 28 | Max = Integer.MIN_VALUE; 29 | for (int j = i - size + 1; j <= i; j++) { 30 | if (num[j] > Max) { 31 | Max = num[j]; 32 | pos = j; 33 | } 34 | } 35 | } 36 | ans.add(Max); 37 | } 38 | return ans; 39 | } 40 | 41 | public static void main(String[] args) { 42 | int[] a = new int[]{2, 3, 4, 2, 6, 2, 5, 1}; 43 | System.out.println(Arrays.toString(maxInWindows(a, 3).toArray())); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Main27.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.HashSet; 4 | 5 | public class Main27 { 6 | private String change(char[] a) { 7 | StringBuilder res = new StringBuilder(); 8 | for (char value : a) { 9 | res.append(value); 10 | } 11 | return res.toString(); 12 | } 13 | private void solve(ArrayList ans, char[] a, int index, int length) { 14 | if (index == length - 1) { 15 | String res = change(a); 16 | ans.add(res); 17 | } else { 18 | // 就说明现在要去确定index位置的字符 19 | for (int i = index; i < length; i++) { 20 | char temp = a[i]; 21 | a[i] = a[index]; 22 | a[index] = temp; 23 | // 当前index位置的字符已经通过交换找到了,那么就递归去找下一个位置的字符 24 | solve(ans, a, index + 1, length); 25 | // 其实就是去为了消除当前层去递归的时候的进行交换字符的影响,如果不消除的话,那么就会造成原index位置的字符发生变化 26 | temp = a[i]; 27 | a[i] = a[index]; 28 | a[index] = temp; 29 | 30 | } 31 | } 32 | } 33 | public ArrayList Permutation(String str) { 34 | char[] a = str.toCharArray(); 35 | ArrayList ans = new ArrayList<>(); 36 | solve(ans, a, 0, str.length()); 37 | ans = new ArrayList(new HashSet(ans)); // 去重操作 38 | Collections.sort(ans); // 字典排序 -> ans.sort(null); 39 | return ans; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Main16.java: -------------------------------------------------------------------------------- 1 | public class Main16 { 2 | public ListNode Merge(ListNode list1,ListNode list2) { 3 | if (list1 == null) { 4 | return list2; 5 | } 6 | if (list2 == null) { 7 | return list1; 8 | } 9 | ListNode headNode; /// 最终合成链表得头节点。 10 | if (list1.val > list2.val) { 11 | headNode = list2; 12 | list2 = list2.next; 13 | } else { 14 | headNode = list1; 15 | list1 = list1.next; 16 | } 17 | ListNode removeNode = headNode; /// 其实在当前位置就是合成链表得长度为1,头节点和尾节点是一样的。 18 | 19 | while (list1 != null && list2 != null) { 20 | if (list1.val > list2.val) { 21 | removeNode.next = list2; /// 将合成链表的尾部节点添加链表2中当前所指向的节点 22 | removeNode = list2; /// 去更新合成链表的尾部节点 23 | list2 = list2.next; 24 | } else { 25 | removeNode.next = list1; /// 将合成链表的尾部节点添加链表2中当前所指向的节点 26 | removeNode = list1; /// 去更新合成链表的尾部节点 27 | list1 = list1.next; 28 | } 29 | } 30 | 31 | /// 其实就是将剩余的链表1中的节点放入到合成链表中 32 | while (list1 != null) { 33 | removeNode.next = list1; 34 | removeNode = list1; 35 | list1 = list1.next; 36 | } 37 | /// 其实就是将剩余的链表2中的节点放入到合成链表中 38 | while (list2 != null) { 39 | removeNode.next = list2; 40 | removeNode = list2; 41 | list2 = list2.next; 42 | } 43 | return headNode; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Main44.java: -------------------------------------------------------------------------------- 1 | class Main44 { 2 | /*public String ReverseSentence(String str) { 3 | String flipStr = new StringBuilder(str).reverse().toString(); // 第一次翻转 4 | StringBuilder res = new StringBuilder(); // 用来遍历每一个单词 5 | StringBuilder ans = new StringBuilder(); // 用来保存结果 6 | for (int i = 0; i < flipStr.length(); i++) { 7 | if (flipStr.charAt(i) == ' ') { 8 | ans.append(res.reverse().toString()).append(" "); // 第二次翻转 9 | res = new StringBuilder(); 10 | } else { 11 | res.append(flipStr.charAt(i)); 12 | } 13 | } 14 | ans.append(res.reverse().toString()); // 最后那个单词的翻转结果保存到ans当中 15 | return ans.toString(); 16 | }*/ 17 | 18 | public String ReverseSentence(String str) { 19 | String flipStr = new StringBuilder(str.trim()).reverse().toString(); // 第一次翻转 20 | StringBuilder res = new StringBuilder(); // 用来遍历每一个单词 21 | StringBuilder ans = new StringBuilder(); // 用来保存结果 22 | for (int i = 0; i < flipStr.length(); i++) { 23 | if (flipStr.charAt(i) == ' ') { 24 | if (res.length() > 0) { 25 | ans.append(ans.length() == 0 ? res.reverse() : " " + res.reverse()); 26 | res = new StringBuilder(); 27 | } 28 | } else { 29 | res.append(flipStr.charAt(i)); 30 | } 31 | } 32 | if (res.length() > 0) { 33 | ans.append(ans.length() == 0 ? res.reverse() : " " + res.reverse()); 34 | } 35 | return ans.toString(); 36 | } 37 | } -------------------------------------------------------------------------------- /src/Main28.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class Main28 { 5 | /*public int MoreThanHalfNum_Solution(int [] array) { 6 | Map map = new HashMap<>(); // 去存储每个数字出现的次数 7 | int target = 0; // 用来去存储出现次数最多的那个数字 8 | int sum = 0; // 用来去存储出现次数最多的那个数字出现的次数 9 | for (int x : array) { 10 | map.put(x, map.getOrDefault(x, 0) + 1); // 更新当前位置数字出现的次数 11 | if (sum < map.get(x)) { 12 | // 就是说明当前位置的数字出现的次数比之前统计的target数字出现的次数大 13 | sum = map.get(x); 14 | target = x; 15 | } 16 | } 17 | if(sum > array.length / 2) { 18 | return target; 19 | } 20 | return 0; 21 | }*/ 22 | private boolean check(int target, int[] array) { 23 | int sum = 0; 24 | for (int x : array) { 25 | if (x == target) { 26 | sum++; 27 | } 28 | } 29 | return sum > array.length / 2; 30 | } 31 | public int MoreThanHalfNum_Solution(int [] array) { 32 | if (array.length == 0) { 33 | return 0; 34 | } 35 | int target = array[0]; // 用来保存最终出现次数最多的数字 36 | int sum = 0; // 用来保存数组从第1个位置到第i个位置中,target出现的次数 - 不是target出现的次数 37 | 38 | for (int x : array) { 39 | if (x == target) { 40 | sum ++; 41 | } else { 42 | sum--; 43 | } 44 | if (sum == 0) { 45 | target = x; 46 | sum = 1; 47 | } 48 | } 49 | if (check(target, array)) { 50 | return target; 51 | } 52 | return 0; 53 | } 54 | } 55 | 56 | -------------------------------------------------------------------------------- /src/Main19.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main19 { 4 | public ArrayList printMatrix(int [][] matrix) { 5 | ArrayList ans = new ArrayList<>(); 6 | int flag = 1;// 1->right, 2->down, 3->left, 4->up 7 | int x = 0; 8 | int y = 0; 9 | boolean[][] vis = new boolean[matrix.length][matrix[0].length]; // 这个就是用来标记已经走过的点 10 | while (ans.size() < matrix.length * matrix[0].length) { 11 | if(x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || vis[x][y]) { 12 | // vis[x][y] -> 已经遍历过的位置也当作越界处理 13 | if(flag == 1) { 14 | flag = 2; // 往下走 15 | y--; // 消除越界的影响 16 | x++; // 本质上就是到达下一个位置的横坐标 17 | } else if(flag == 2) { 18 | flag = 3; // 往左走 19 | x--; // 消除越界的影响 20 | y--; // 本质上就是到达下一个位置的纵坐标 21 | } else if (flag == 3) { 22 | flag = 4; // 往上走 23 | y++; // 消除越界的影响 24 | x--; // 本质上就是到达下一个位置的横坐标 25 | } else { 26 | flag = 1;//往右走 27 | x++; // 消除越界的影响 28 | y++; // 本质上就是到达下一个位置的纵坐标 29 | } 30 | 31 | } else { 32 | ans.add(matrix[x][y]); 33 | vis[x][y] = true; // 去标记已经遍历过的位置 34 | // 根据flag的值更新遍历矩阵的下标x,y的值 35 | if(flag == 1) { 36 | y++; 37 | } else if (flag == 2) { 38 | x++; 39 | } else if (flag == 3) { 40 | y--; 41 | } else { 42 | x--; 43 | } 44 | } 45 | } 46 | return ans; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Main3.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main3 { 4 | 5 | // public ArrayList printListFromTailToHead(ListNode listNode) { 6 | // ArrayList list = new ArrayList<>(); 7 | // Stack stack = new Stack<>(); 8 | // while(listNode != null) { 9 | // stack.add(listNode.val); /// 取当前节点的值放入栈中 10 | // listNode = listNode.next; /// 更新当前节点为下一个节点 11 | // } 12 | // while (!stack.isEmpty()) { 13 | // list.add(stack.pop()); /// 取出当前栈顶元素然后放入list中 14 | // } 15 | // return list; 16 | // } 17 | 18 | private static ArrayList printListFromTailToHead(ListNode listNode) { 19 | ArrayList list = new ArrayList<>(); 20 | if (listNode == null) { 21 | return list; 22 | } 23 | return solve(list, listNode); 24 | } 25 | // 1->2->3->4 26 | private static ArrayList solve(ArrayList list, ListNode listNode) { 27 | if (listNode.next != null) { /// 当前节点的下一个节点不为空 28 | list = solve(list, listNode.next); /// 往下递归 29 | } 30 | list.add(listNode.val); /// 将当前节点的val值放入list列表中 31 | // System.out.println(list); 32 | return list; 33 | } 34 | 35 | public static void main(String[] args) { 36 | ListNode head = new ListNode(0); 37 | ListNode removeNode = head; 38 | 39 | for (int i = 1; i < 10; i++) { 40 | ListNode x = new ListNode(i); 41 | x.next = null; 42 | removeNode.next = x; 43 | removeNode = x; 44 | } 45 | System.out.println(printListFromTailToHead(head)); 46 | } 47 | } 48 | class ListNode { 49 | int val; 50 | ListNode next = null; 51 | 52 | ListNode(int val) { 53 | this.val = val; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Main24.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main24 { 4 | private ArrayList> ans; 5 | 6 | /** 7 | * 8 | * @param node 二叉树节点 9 | * @param target 目标权值和 10 | * @param sum 当前路径的权值和 11 | * @param list 保存当前路径 12 | */ 13 | private void solve(TreeNode node, int target, int sum, ArrayList list) { 14 | if (node != null) { 15 | sum += node.val; 16 | list.add(node.val); 17 | if (node.left == null && node.right == null) { 18 | if (sum == target) { 19 | ArrayList res = new ArrayList<>(list); // ArrayList是引用传递 20 | ans.add(res); 21 | } 22 | } else { 23 | solve(node.left, target, sum, list); // 递归左子树 24 | solve(node.right, target, sum, list); // 递归右子树 25 | } 26 | // 消除掉当前节点对查找路径的影响 --> 至关重要 27 | list.remove(list.size() - 1); 28 | } 29 | } 30 | private void change() { 31 | for (int i = 0; i < ans.size(); i++) { 32 | int index = i; 33 | for (int j = i + 1; j < ans.size(); j++) { 34 | if (ans.get(j).size() > ans.get(index).size()) { 35 | index = j; 36 | } 37 | } 38 | if (i != index) 39 | { 40 | ArrayList temp = ans.get(i); 41 | ans.set(i, ans.get(index)); 42 | ans.set(index, temp); 43 | } 44 | } 45 | } 46 | public ArrayList> FindPath(TreeNode root, int target) { 47 | ans = new ArrayList>(); 48 | ArrayList list = new ArrayList<>(); 49 | solve(root, target, 0, list); 50 | change(); 51 | return ans; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Main37.java: -------------------------------------------------------------------------------- 1 | public class Main37 { 2 | private int findFirstPosition(int[] array, int k) { 3 | int l = 0; 4 | int r = array.length - 1; 5 | while (l < r) { 6 | int mid = (l + r) >> 1; 7 | if (array[mid] == k) { 8 | if(mid - 1 >= 0 && array[mid - 1] == k) { 9 | // 说明mid当前的位置不是初始位置,k的初始位置是在l~mid-1区间 10 | r = mid - 1; 11 | } else { 12 | // 就可以说明mid位置的数字就是k的初始位置 13 | return mid; 14 | } 15 | } else if (array[mid] > k) { 16 | r = mid - 1; // k是属于l~mid-1区间 17 | } else { 18 | l = mid + 1; // k是属于mid+1~r区间 19 | } 20 | } 21 | return l; 22 | } 23 | 24 | private int findLastPosition(int[] array, int k) { 25 | int l = 0; 26 | int r = array.length - 1; 27 | while (l < r) { 28 | int mid = (l + r) >> 1; 29 | if (array[mid] == k) { 30 | if(mid + 1 < array.length && array[mid + 1] == k) { 31 | // 说明mid当前的位置不是终止位置,k的初始位置是在mid+1~r区间 32 | l = mid + 1; 33 | } else { 34 | // 就可以说明mid位置的数字就是k的终止位置 35 | return mid; 36 | } 37 | } else if (array[mid] > k) { 38 | r = mid - 1; // k是属于l~mid-1区间 39 | } else { 40 | l = mid + 1; // k是属于mid+1~r区间 41 | } 42 | } 43 | return l; 44 | } 45 | 46 | public int GetNumberOfK(int [] array , int k) { 47 | if (array.length == 0) { 48 | return 0; 49 | } 50 | int firstPosition = findFirstPosition(array, k); 51 | int lastPosition = findLastPosition(array, k); 52 | if (array[firstPosition] != k) { 53 | return 0; 54 | } 55 | return lastPosition - firstPosition + 1; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Main23.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main23 { 4 | private boolean solve(ArrayList list) { 5 | // 递归终止的条件 6 | if (list.size() == 0 || list.size() == 1) { 7 | return true; 8 | } 9 | ArrayList minList = new ArrayList<>(); // 用来保存小于endNumber数字的序列 10 | ArrayList maxList = new ArrayList<>(); // 用来保存大于endNumber数字的序列 11 | int endNumber = list.get(list.size() - 1); 12 | int minIndex = -1; // 用来记录minList中第一个数字的位置 13 | int maxIndex = -1; // 用来记录maxList中第一个数字的位置 14 | // 下面这个循环其实就是对当前list序列的一个分割(分割条件就是endNumber) 15 | for (int i = 0; i < list.size(); i++) { 16 | if (list.get(i) > endNumber) { 17 | if (maxIndex == -1) { 18 | maxIndex = i; 19 | } 20 | maxList.add(list.get(i)); 21 | } else if (list.get(i) < endNumber) { 22 | if (minIndex == -1) { 23 | minIndex = i; 24 | } 25 | minList.add(list.get(i)); 26 | } 27 | } 28 | if (minIndex != -1 && maxIndex != -1) { 29 | if (minIndex > maxIndex) { 30 | return false; // 本质上使右子树的序列在左子树的前面,不满足后序遍历 31 | } 32 | for (int i = maxIndex; i < list.size(); i++) { 33 | if (list.get(i) < endNumber) { 34 | return false; // 说明在大于endNumber的序列初始位置到末尾,不连续,中间有小于endNumber的数字分割开来 35 | } 36 | } 37 | } 38 | return solve(minList) && solve(maxList); // && -> 每一个子序列都是需要满足的 39 | } 40 | public boolean VerifySquenceOfBST(int [] sequence) { 41 | if (sequence.length == 0) { 42 | return false; 43 | } 44 | ArrayList list = new ArrayList<>(); 45 | for (int i = 0; i < sequence.length; i++) { 46 | list.add(sequence[i]); 47 | } 48 | return solve(list); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Main36.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Main36 { 4 | /* public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { 5 | Stack stack1 = new Stack<>(); 6 | Stack stack2 = new Stack<>(); 7 | 8 | while (pHead1 != null) { 9 | stack1.add(pHead1); 10 | pHead1 = pHead1.next; 11 | } 12 | while (pHead2 != null) { 13 | stack2.add(pHead2); 14 | pHead2 = pHead2.next; 15 | } 16 | ListNode ans = null; 17 | while (!stack1.isEmpty() && !stack2.isEmpty()) { 18 | if(stack1.peek().val == stack2.peek().val) { 19 | ans = stack1.peek(); 20 | stack1.pop(); 21 | stack2.pop(); 22 | } else { 23 | break; 24 | } 25 | } 26 | return ans; 27 | }*/ 28 | public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { 29 | int len1 = 0; 30 | int len2 = 0; 31 | ListNode removeNode1 = pHead1; 32 | ListNode removeNode2 = pHead2; 33 | while (removeNode1 != null) { 34 | len1++; 35 | removeNode1 = removeNode1.next; 36 | } 37 | while (removeNode2 != null) { 38 | len2++; 39 | removeNode2 = removeNode2.next; 40 | } 41 | 42 | // 下面的两个判断就是是的两个链表的length相同 43 | if (len1 > len2) { 44 | for (int i = 1; i <= len1 - len2; i++) { 45 | pHead1 = pHead1.next; 46 | } 47 | } else if (len2 > len1) { 48 | for (int i = 1; i <= len2 - len1; i++) { 49 | pHead2 = pHead2.next; 50 | } 51 | } 52 | ListNode ans = null; 53 | while (pHead1 != null) { 54 | if (pHead1.val ==pHead2.val) { 55 | ans = pHead1; 56 | break; 57 | } 58 | pHead1 = pHead1.next; 59 | pHead2 = pHead2.next; 60 | } 61 | return ans; 62 | 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/Main1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main1 { 4 | // public boolean Find(int target, int [][] array) { 5 | // for (int i = 0; i < array.length; i++) 6 | // { 7 | // for (int j = 0; j < array[0].length; j++) 8 | // { 9 | // if (array[i][j] == target) 10 | // return true; 11 | // } 12 | // } 13 | // return false; 14 | // } 15 | 16 | // private static boolean Find(int target, int[][] array) { 17 | // int i = array.length - 1; 18 | // int j = 0; 19 | // while(i >= 0 && i < array.length && j >= 0 && j < array[0].length) 20 | // { 21 | // // array[i][j] 22 | // if (array[i][j] == target) 23 | // return true; 24 | // else if (array[i][j] > target) 25 | // i--; 26 | // else 27 | // j++; 28 | // } 29 | // return false; 30 | // } 31 | 32 | private static boolean Find(int target, int[][] array) { 33 | int i = 0; 34 | int j = array[0].length - 1; 35 | while(i >= 0 && i < array.length && j >= 0 && j < array[0].length) 36 | { 37 | // array[i][j] 38 | if (array[i][j] == target) 39 | return true; 40 | else if (array[i][j] > target) 41 | j--; 42 | else 43 | i++; 44 | } 45 | return false; 46 | } 47 | 48 | public static void main(String[] args) { 49 | int n, m; 50 | Scanner cin = new Scanner(System.in); 51 | n = cin.nextInt(); 52 | m = cin.nextInt(); 53 | int[][] array = new int[n][m]; 54 | for (int i = 0; i < n; i++) 55 | for (int j = 0; j < m; j++) 56 | array[i][j] = cin.nextInt(); 57 | for (int i = 1; i <= n*m+1; i++) 58 | { 59 | int target = cin.nextInt(); 60 | System.out.println(Find(target, array)); 61 | } 62 | } 63 | } 64 | 65 | //i, j, target = 2 66 | //3 3 67 | //1 2 3 68 | //4 5 6 69 | //7 8 9 70 | -------------------------------------------------------------------------------- /src/Main29.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main29 { 4 | public ArrayList GetLeastNumbers_Solution(int [] input, int k) { 5 | if (k > input.length || k == 0) { 6 | return new ArrayList<>(); 7 | } 8 | 9 | int[] a = new int[k]; // 用数组去模拟k个节点的堆结构 10 | System.arraycopy(input, 0, a, 0, k); // 初始化堆中元素 11 | // 下面就开始维护堆使其成为大顶堆 - > 堆的初始化 12 | for (int i = k / 2 - 1; i >= 0; i--) { 13 | // i -> i其实就是我们所要去维护堆的节点下标 14 | initiate(i, a, k); 15 | } 16 | // 去遍历剩余的len - k个节点 17 | for (int i = k; i < input.length; i++) { 18 | if (input[i] < a[0]) { 19 | a[0] = input[i]; 20 | initiate(0, a, k); 21 | } 22 | } 23 | // 将大顶堆中的节点元素进行升序操作 24 | for (int i = a.length - 1; i > 0; i--) { 25 | // 分为两个过程, 第一步交换,第二步固定(固定的操作其实是通过控制堆的节点个数去实现的) 26 | int temp = a[i]; 27 | a[i] = a[0]; 28 | a[0] = temp; 29 | initiate(0, a, i); 30 | } 31 | // 返回 32 | ArrayList ans = new ArrayList<>(); 33 | for (int x : a) { 34 | ans.add(x); 35 | } 36 | return ans; 37 | } 38 | 39 | /** 40 | * 初始化堆的函数,其实就是维护每一个节点的位置的函数 41 | * @param index 维护当前堆的下标 42 | * @param a 数组->堆 43 | * @param length 堆的节点个数 44 | */ 45 | private void initiate(int index, int[] a, int length) { 46 | int temp = a[index]; // 先去保存当前位置的值 47 | for (int k = index * 2 + 1; k < length; k = k * 2 + 1) { 48 | if ((k + 1) < length && a[k + 1] > a[k]) { 49 | // 取出当前位置的左右孩子中节点值最大的节点 50 | k++; 51 | } 52 | if (a[k] > temp) { 53 | a[index] = a[k]; 54 | index = k; // 更新index的值,index -> 代表的是temp数字最终在堆中位置,当k = k * 2 + 1执行后,index和k的关系其实就是父亲节点和孩子节点的关系。 55 | } else { 56 | break; // 由于我们是从下往上去维护的,所以说我们就没有往下更新的必要了 57 | } 58 | } 59 | a[index] = temp; // index所在的位置进行更新就行了 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/Main59.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main59 { 4 | /*public int[] levelOrder(TreeNode root) { 5 | Queue queue = new LinkedList<>(); 6 | queue.add(root); 7 | ArrayList list = new ArrayList<>(); 8 | while (!queue.isEmpty() && root != null) { 9 | TreeNode node = queue.poll(); 10 | list.add(node.val); 11 | 12 | if (node.left != null) { 13 | queue.add(node.left); 14 | } 15 | if (node.right != null) { 16 | queue.add(node.right); 17 | } 18 | } 19 | int[] ans = new int[list.size()]; 20 | int index = 0; 21 | for (int x : list) { 22 | ans[index++] = x; 23 | } 24 | return ans; 25 | }*/ 26 | 27 | public List> levelOrder(TreeNode root) { 28 | List> ans = new LinkedList<>(); 29 | 30 | Queue queue = new LinkedList<>(); 31 | queue.add(root); 32 | int sum = 1; // 用来保存每一层的节点的个数 33 | int num = 1; 34 | 35 | while (!queue.isEmpty() && root != null) { 36 | List list = new LinkedList<>(); 37 | int temp = 0; 38 | while (sum > 0) { 39 | TreeNode node = queue.poll(); 40 | assert node != null; 41 | list.add(node.val); 42 | if(node.left != null) { 43 | temp++; 44 | queue.add(node.left); 45 | } 46 | if (node.right != null) { 47 | temp++; 48 | queue.add(node.right); 49 | } 50 | sum--; 51 | } 52 | sum = temp; 53 | if(num % 2 == 0) { 54 | for (int i = 0, j = list.size() - 1; i < j; i++, j--) { 55 | int res = list.get(i); 56 | list.set(i, list.get(j)); 57 | list.set(j, res); 58 | } 59 | } 60 | num++; 61 | ans.add(list); 62 | } 63 | return ans; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Main17.java: -------------------------------------------------------------------------------- 1 | public class Main17 { 2 | 3 | private boolean judge(TreeNode node1, TreeNode node2) { /// 第二部分,匹配 4 | if (node2 == null) { 5 | return true; /// 说明二叉树B的某一个方向的节点已经完全的匹配成功。 6 | } 7 | if (node1 == null) { 8 | return false; /// 说明在某一方向上,二叉树A中的节点不缺少的,相对于二叉树B 9 | } 10 | if (node1.val == node2.val) { 11 | boolean flag1 = true; /// 默认左子树是匹配的,假如说不匹配,它就会返回false 12 | boolean flag2 = true; /// 默认右子树是匹配的,假如说不匹配,它就会返回false 13 | if (node1.left != null || node2.left != null) { 14 | flag1 = judge(node1.left, node2.left); /// 比较子树A和二叉树B的左子树 15 | } 16 | if (flag1 && (node1.right != null || node2.right != null)) { /// flag1 -> 剪枝 17 | flag2 = judge(node1.right, node2.right); /// 比较子树A和二叉树B的右子树 18 | } 19 | return flag1 && flag2; /// && -> 不光某一个节点的左子树要完全匹配,右子树也是要完全匹配的 20 | } else { 21 | return false; 22 | } 23 | } 24 | 25 | /// 二叉树的先序遍历 26 | private boolean dfs(TreeNode node, TreeNode root2) { /// 第一部分,查找 27 | boolean flag = false; 28 | if (node.val == root2.val) { 29 | flag = judge(node, root2); /// 进入第二部分的匹配过程 30 | } 31 | if (flag) { 32 | return true; /// 通过当前节点已经找到二叉树B的完全匹配结果了,就没有必要再往下去遍历二叉树A了。也可以说是剪枝欸但一个过程 33 | } 34 | boolean flag1 = false; /// 用来记录当前节点的左子树中的查找结果(其实也是包含了匹配的过程),如果查找成功(包含了匹配过程)返回true 35 | boolean flag2 = false; /// 用来记录当前节点的右子树中的查找结果(其实也是包含了匹配的过程),如果查找成功(包含了匹配过程)返回true 36 | if (node.left != null) { 37 | flag1 = dfs(node.left, root2); /// 当前节点的val不等于二叉树B的root值,那么就去遍历当前节点的左子树,看否找到二叉树B 38 | } 39 | if ((!flag1) && node.right != null) { /// !flag1-》剪枝 40 | flag2 = dfs(node.right, root2); /// 当前节点的val不等于二叉树B的root值,那么就去遍历当前节点的右子树,看否找到二叉树B 41 | } 42 | return flag1 || flag2; /// || -》只需要找到节点的某一个方向的子树进行匹配成功就行了 43 | } 44 | 45 | public boolean HasSubtree(TreeNode root1,TreeNode root2) { 46 | if (root1 == null || root2 == null) { /// root1 == null -> 就是二叉树A就是一颗空树, root2 -> 约定空树不是任意一个树的子结构 47 | return false; 48 | } 49 | return dfs(root1, root2); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Main41.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main41 { 4 | /* public ArrayList > FindContinuousSequence(int sum) { 5 | ArrayList> ans = new ArrayList<>(); 6 | int l = 1; 7 | int r = 2; 8 | ArrayList list = new ArrayList<>(); 9 | list.add(1); 10 | list.add(2); 11 | while (l < (sum + 1) / 2) { 12 | int tempSum = cul(l, r); 13 | while (tempSum > sum) { 14 | tempSum -= l; 15 | l++; 16 | list.remove(0); 17 | } 18 | if (tempSum == sum) { 19 | ans.add(new ArrayList<>(list)); 20 | l++; 21 | list.remove(0); 22 | } 23 | r++; 24 | list.add(r); 25 | } 26 | return ans; 27 | } 28 | 29 | private int cul(int l, int r) { 30 | return (l + r) * (r - l + 1) / 2; 31 | }*/ 32 | public ArrayList > FindContinuousSequence(int sum) { 33 | ArrayList> ans = new ArrayList<>(); 34 | for (int i = 1; i <= sum; i++) { 35 | int x = 2 * i - 1; 36 | double temp = Math.sqrt(x * x + 8 * sum); 37 | if (judge(temp)) { 38 | int res = (int) temp; 39 | double n1 = (double) (-x + res) / 2; 40 | double n2 = (double) (-x - res) / 2; 41 | if (judge(n1) && n1 > 1) { 42 | ArrayList list = new ArrayList<>(); 43 | for (int j = i, k = 1; k <= n1; j++, k++) { 44 | list.add(j); 45 | } 46 | ans.add(list); 47 | } 48 | if (judge(n2) && n2 > 1) { 49 | ArrayList list = new ArrayList<>(); 50 | for (int j = i, k = 1; k <= n2; j++, k++) { 51 | list.add(j); 52 | } 53 | ans.add(list); 54 | } 55 | } 56 | } 57 | return ans; 58 | } 59 | 60 | private boolean judge(double x) { 61 | int res = (int) x; 62 | return x - res <= 0.00000001; 63 | } 64 | } -------------------------------------------------------------------------------- /src/Main66.java: -------------------------------------------------------------------------------- 1 | public class Main66 { 2 | private int test(int m, int n, int k) { 3 | int res = 1; 4 | boolean[][] vis = new boolean[m][n]; 5 | vis[0][0] = true; 6 | for (int i = 0; i < m; i++) { 7 | for (int j = 0; j < n; j++) { 8 | if (cul(i, j) <= k) { 9 | if (i - 1 >= 0 && vis[i - 1][j]) { 10 | // 下 11 | res++; 12 | vis[i][j] = true; 13 | } else if (i + 1 < m && vis[i + 1][j]) { 14 | // 上 15 | res++; 16 | vis[i][j] = true; 17 | } else if (j - 1 >= 0 && vis[i][j - 1]) { 18 | // 左 19 | res++; 20 | vis[i][j] = true; 21 | } else if (j + 1 < n && vis[i][j + 1]) { 22 | // 右 23 | res++; 24 | vis[i][j] = true; 25 | } 26 | } 27 | } 28 | } 29 | return res; 30 | } 31 | 32 | 33 | 34 | private int sum; 35 | public int movingCount(int threshold, int rows, int cols) { 36 | sum = 0; 37 | boolean[][] vis = new boolean[rows][cols]; 38 | solve(0, 0, rows, cols, vis, threshold); 39 | return sum; 40 | } 41 | private int cul(int x, int y) { 42 | int res = 0; 43 | while (x != 0) { 44 | res += x % 10; 45 | x /= 10; 46 | } 47 | while (y != 0) { 48 | res += y % 10; 49 | y /= 10; 50 | } 51 | return res; 52 | } 53 | 54 | private void solve(int x, int y, int rows, int cols, boolean[][] vis, int threshold) { 55 | if (x < 0 || y < 0 || x >= rows || y >= cols || vis[x][y] || (cul(x, y) > threshold)) { 56 | return; 57 | } 58 | 59 | // 当前位置(x,y)是可以走的,那么就从当前位置往四个方向移动即可 60 | vis[x][y] = true; 61 | sum++; 62 | solve(x + 1, y, rows, cols, vis, threshold); 63 | solve(x - 1, y, rows, cols, vis, threshold); 64 | solve(x, y + 1, rows, cols, vis, threshold); 65 | solve(x, y - 1, rows, cols, vis, threshold); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Main25.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | class RandomListNode { 4 | int label; 5 | RandomListNode next = null; 6 | RandomListNode random = null; 7 | 8 | RandomListNode(int label) { 9 | this.label = label; 10 | } 11 | } 12 | public class Main25 { 13 | /* public RandomListNode Clone(RandomListNode pHead) { 14 | Map map = new HashMap<>(); 15 | RandomListNode removeNode = pHead; 16 | // 去创建新链表中的节点元素和原链表节点元素与新链表节点元素之间的映射关系 17 | while (removeNode != null) { 18 | RandomListNode node = new RandomListNode(removeNode.label); 19 | map.put(removeNode, node); 20 | removeNode = removeNode.next; 21 | } 22 | removeNode = pHead; 23 | // 去创建新链表中每个节点的结构关系(根据原链表的节点的结构关系) 24 | while (removeNode != null) { 25 | RandomListNode node = map.get(removeNode); 26 | node.next = map.get(removeNode.next); 27 | node.random = map.get(removeNode.random); 28 | removeNode = removeNode.next; 29 | } 30 | return map.getOrDefault(pHead, null); 31 | }*/ 32 | public RandomListNode Clone(RandomListNode pHead) { 33 | if (pHead == null) { 34 | return null; 35 | } 36 | // 第一个过程->创建新链表节点插入到原链表中 37 | RandomListNode removeNode = pHead; 38 | while (removeNode != null) { 39 | RandomListNode temp = removeNode.next; 40 | RandomListNode node = new RandomListNode(removeNode.label); 41 | removeNode.next = node; // 原节点指向新节点 42 | node.next = temp; // 新节点指向当前节点的next 43 | removeNode = temp; 44 | } 45 | // 第二个过程->创建rangdom节点指向 46 | removeNode = pHead; 47 | while (removeNode != null) { 48 | removeNode.next.random = removeNode.random == null ? null : removeNode.random.next; 49 | removeNode = removeNode.next.next; // 用两个next是把新链表节点隔过去 50 | } 51 | 52 | // 第三个过程->链表的分割 53 | removeNode = pHead; 54 | RandomListNode cloneHead = pHead.next; 55 | while (removeNode != null) { 56 | RandomListNode node = removeNode.next; 57 | removeNode.next = node.next; // 原链表中节点的结构之间关系的维护 58 | node.next = node.next == null ? null : node.next.next;// 维护新链表中节点关系的维护 59 | removeNode = removeNode.next; 60 | } 61 | return cloneHead; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/Main49.java: -------------------------------------------------------------------------------- 1 | public class Main49 { 2 | 3 | public static int StrToInt(String str) { 4 | int len = str.length(); 5 | int index = 0; 6 | // 第一步,删除前面的空格 7 | while (index < len) { 8 | if (str.charAt(index) == ' ') { 9 | index++; 10 | } else { 11 | break; 12 | } 13 | } 14 | int flag = 0; 15 | long ans = 0; // 最终返回的结果 16 | boolean flag1 = false; 17 | while (index < len) { 18 | // "3-2" 19 | if (!flag1 && (str.charAt(index) == '-' || str.charAt(index) == '+')) { 20 | if (flag != 0) { 21 | return 0; // "-123-3", 第二个-号是非法字符, 返回0 22 | } 23 | flag = str.charAt(index) == '-' ? -1 : 1; 24 | } else if (str.charAt(index) >= '0' && str.charAt(index) <= '9') { 25 | flag1 =true; 26 | ans = ans * 10 + str.charAt(index ) -'0'; // "-123" 27 | if (judge(ans, flag)) { // 对ans是否溢出int类型做下判断 28 | return 0; 29 | } 30 | } else { 31 | return 0; // 既不是数字,也不是正负号,那就是其他字符了,返回0 32 | } 33 | index++; 34 | } 35 | return flag == -1 ? (int) ans * (-1) : (int) ans; 36 | } 37 | 38 | private static boolean judge(long ans, int flag) { 39 | if (flag == -1) { 40 | if (ans * (-1) < Integer.MIN_VALUE) { 41 | return true; 42 | } 43 | return false; 44 | } else { 45 | if (ans > Integer.MAX_VALUE) { 46 | return true; 47 | } 48 | return false; 49 | } 50 | } 51 | 52 | public static void main(String[] args) { 53 | // System.out.println(Integer.MAX_VALUE); 54 | // System.out.println(Integer.MIN_VALUE); 55 | String s1 = "+2147483647"; 56 | String s2 = "+2147483648"; 57 | String s3 = "-2147483648"; 58 | String s4 = "-2147483649"; 59 | String s5 = "-1234"; 60 | String s6 = "+1234"; 61 | String s7 = "-123+123"; 62 | String s8 = "-123a123"; 63 | String s9 = "3-2"; 64 | System.out.println(StrToInt(s1)); 65 | System.out.println(StrToInt(s2)); 66 | System.out.println(StrToInt(s3)); 67 | System.out.println(StrToInt(s4)); 68 | System.out.println(StrToInt(s5)); 69 | System.out.println(StrToInt(s6)); 70 | System.out.println(StrToInt(s7)); 71 | System.out.println(StrToInt(s8)); 72 | System.out.println(StrToInt(s9)); 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Main52.java: -------------------------------------------------------------------------------- 1 | public class Main52 { 2 | public static boolean isMatch(String s, String p) { 3 | return solve(s, p, 0, 0); 4 | } 5 | 6 | /** 7 | * 字符串匹配 8 | * @param s 字符串1 9 | * @param p 字符串2 10 | * @param index1 字符串1的下标 11 | * @param index2 字符串2的下标 12 | * @return 当前s和p的匹配结果 13 | */ 14 | private static boolean solve(String s, String p, int index1, int index2) { 15 | 16 | // 递归终止条件1 17 | if (index1 == s.length() && (index2 == p.length() || (index2 + 1 == p.length() - 1 && p.charAt(index2 + 1) == '*'))) { 18 | return true; 19 | } 20 | 21 | // 递归终止条件2 22 | if (index1 == s.length() || p.length() == index2) { 23 | if (index1 == s.length()) { 24 | return change(p, index2); 25 | } else { 26 | return false; 27 | } 28 | } 29 | 30 | // p当前字符的下一个位置的字符时* 31 | if(index2 + 1 < p.length() && p.charAt(index2 + 1) == '*') { 32 | if(judge(s.charAt(index1), p.charAt(index2))) { 33 | return solve(s, p, index1, index2 + 2) || solve(s, p, index1 + 1, index2); 34 | } else { 35 | return solve(s, p, index1, index2 + 2); 36 | } 37 | } 38 | 39 | // 当前两个下标所指的字符匹配 40 | if (judge(s.charAt(index1), p.charAt(index2))) { 41 | return solve(s, p, index1 + 1, index2 + 1); 42 | } 43 | 44 | return false; // 当前的index1所指的字符与index2所指的字符不一致 45 | } 46 | 47 | private static boolean change(String p, int index2) { 48 | while (index2 < p.length()) { 49 | if (index2 + 1 < p.length() && p.charAt(index2 + 1) == '*') { 50 | index2 += 2; 51 | } else { 52 | return false; 53 | } 54 | } 55 | return true; 56 | } 57 | 58 | /** 59 | * 60 | * @param s1 字符1 61 | * @param s2 字符2 62 | * @return 两个字符是否匹配的结果 63 | */ 64 | private static boolean judge(char s1, char s2) { 65 | if (s1 == s2 || s2 == '.') { 66 | return true; 67 | } 68 | return false; 69 | } 70 | 71 | public static boolean match(char[] str, char[] pattern) { 72 | StringBuilder s1 = new StringBuilder(); 73 | StringBuilder s2 = new StringBuilder(); 74 | 75 | for (char x : str) { 76 | s1.append(x); 77 | } 78 | for (char x : pattern) { 79 | s2.append(x); 80 | } 81 | return solve(s1.toString(), s2.toString(), 0, 0); 82 | } 83 | 84 | public static void main(String[] args) { 85 | char[] str = new char[]{'a', 'a', 'a'}; 86 | char[] patten = new char[]{'.', '*'}; 87 | System.out.println(match(str, patten)); 88 | /*System.out.println(isMatch("aaa", ".*"));*/ 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/Main61.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | 4 | public class Main61 { 5 | // Encodes a tree to a single string. 6 | public static String serialize(TreeNode root) { 7 | StringBuilder ans = new StringBuilder("["); 8 | Queue queue = new LinkedList<>(); 9 | queue.add(root); 10 | int sum = 1; // 用来记录当前节点及其后面非空节点的个数 11 | while (!queue.isEmpty() && root != null) { 12 | TreeNode node = queue.poll(); 13 | if (node == null) { 14 | ans.append("null"); 15 | } else { 16 | ans.append(node.val); 17 | sum--; 18 | if (node.left != null) { 19 | sum++; 20 | } 21 | if (node.right != null) { 22 | sum++; 23 | } 24 | queue.add(node.left); 25 | queue.add(node.right); 26 | } 27 | if (sum != 0) { 28 | ans.append(","); 29 | } else { 30 | break; 31 | } 32 | } 33 | ans.append("]"); 34 | return ans.toString(); 35 | } 36 | 37 | // Decodes your encoded data to tree. 38 | public static TreeNode deserialize(String data) { 39 | String s = data.substring(1, data.length() - 1); 40 | if ("".equals(s)) { 41 | return null; // data = "[]" 42 | } 43 | String[] a = s.split(","); 44 | int index = 0; 45 | Queue queue = new LinkedList<>(); 46 | TreeNode root = new TreeNode(change(a[index++])); 47 | queue.add(root); 48 | while (!queue.isEmpty() && index < a.length) { 49 | TreeNode node = queue.poll(); 50 | if (!"null".equals(a[index])) { 51 | node.left = new TreeNode(change(a[index++])); 52 | queue.add(node.left); 53 | } else { 54 | index++; 55 | } 56 | if (index < a.length && !"null".equals(a[index])) { 57 | node.right = new TreeNode(change(a[index++])); 58 | queue.add(node.right); 59 | } else { 60 | index++; 61 | } 62 | } 63 | return root; 64 | } 65 | 66 | private static int change(String s) { 67 | int res = 0; 68 | int i = 0; 69 | int flag = 1; 70 | if (s.charAt(0) == '-') { 71 | i++; 72 | flag = -1; 73 | } 74 | for (; i < s.length(); i++) { 75 | res = res * 10 + s.charAt(i) - '0'; 76 | } 77 | return res * flag; 78 | } 79 | 80 | public static void main(String[] args) { 81 | TreeNode root = new TreeNode(1); 82 | root.left = new TreeNode(2); 83 | root.right = new TreeNode(3); 84 | TreeNode temp = root.right; 85 | temp.left = new TreeNode(4); 86 | temp.right = new TreeNode(5); 87 | // System.out.println(serialize(root)); 88 | TreeNode newRoot = deserialize(serialize(root)); 89 | assert newRoot != null; 90 | dfs(newRoot); 91 | } 92 | 93 | private static void dfs(TreeNode node) { 94 | if (node.left != null) { 95 | dfs(node.left); 96 | } 97 | System.out.println(node.val); 98 | if (node.right != null) { 99 | dfs(node.right); 100 | } 101 | 102 | } 103 | } -------------------------------------------------------------------------------- /src/Main4.java: -------------------------------------------------------------------------------- 1 | import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; 2 | 3 | class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | 8 | TreeNode(int x) { 9 | val = x; 10 | } 11 | } 12 | 13 | public class Main4 { 14 | private static int index = 0; 15 | private static TreeNode solve(int[] pre, int[] tempIn) { 16 | int len1 = 0; /// 当前节点的左子树的节点的个数 17 | int len2 = 0; /// 当前节点的右子树的节点的个数 18 | for (int i = 0; i < tempIn.length; i++) { 19 | if (pre[index] == tempIn[i]) { 20 | break; 21 | } 22 | len1 ++; /// 左子树节点的个数++ 23 | } 24 | len2 = tempIn.length - len1 - 1; 25 | 26 | int index1 = 0; 27 | int index2 = 0; 28 | int[] temp1 = new int[len1]; /// 当前节点的左子树 29 | int[] temp2 = new int[len2]; /// 当前节点的右子树 30 | boolean flag = false; 31 | for (int i = 0; i < tempIn.length; i++) { 32 | if (pre[index] == tempIn[i]) { 33 | flag = true; 34 | } else if (!flag) { 35 | temp1[index1++] = tempIn[i]; 36 | } else { 37 | temp2[index2++] = tempIn[i]; 38 | } 39 | } 40 | TreeNode node = new TreeNode(pre[index]); 41 | node.right = null; 42 | node.left = null; 43 | // System.out.printf("%d左子树:", pre[index]); 44 | // for (int i = 0; i < temp1.length; i++) { 45 | // System.out.printf("%d ", temp1[i]); 46 | // } 47 | // System.out.printf(","); 48 | // System.out.printf("%d右子树:", pre[index]); 49 | // for (int i = 0; i < temp2.length; i++) { 50 | // System.out.printf("%d ", temp2[i]); 51 | // } 52 | // System.out.println(); 53 | if (index < pre.length && temp1.length > 0) { 54 | index++; /// 遍历前序序列的下标加1 55 | node.left = solve(pre, temp1); /// 创建当前节点的左子树 56 | } 57 | if (index < pre.length && temp2.length > 0) { 58 | index++; /// 遍历前序序列的下标加1 59 | node.right = solve(pre, temp2); /// 创建当前节点的右子树 60 | } 61 | return node; 62 | } 63 | private static TreeNode reConstructBinaryTree(int[] pre, int[] in) { 64 | index = 0; /// 遍历前序序列的下标 65 | return solve(pre, in); 66 | } 67 | 68 | public static void main(String[] args) { 69 | int[] pre = {1, 2, 4, 7, 3, 5, 6, 8}; /// 前序遍历 70 | int[] in = {4, 7, 2, 1, 5, 3, 8, 6}; /// 中序遍历 71 | TreeNode root = reConstructBinaryTree(pre, in); 72 | 73 | dfs1(root); 74 | System.out.println(); 75 | dfs2(root); 76 | System.out.println(); 77 | dfs3(root); 78 | System.out.println(); 79 | 80 | } 81 | private static void dfs1(TreeNode node) { 82 | System.out.printf("%d ", node.val); 83 | if (node.left != null) { 84 | dfs1(node.left); 85 | } 86 | if (node.right != null) { 87 | dfs1(node.right); 88 | } 89 | } 90 | private static void dfs3(TreeNode node) { 91 | if (node.left != null) { 92 | dfs3(node.left); 93 | } 94 | if (node.right != null) { 95 | dfs3(node.right); 96 | } 97 | System.out.printf("%d ", node.val); 98 | } 99 | 100 | private static void dfs2(TreeNode node) { 101 | if (node.left != null) { 102 | dfs2(node.left); 103 | } 104 | System.out.printf("%d ", node.val); 105 | if (node.right != null) { 106 | dfs2(node.right); 107 | } 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 二维数组中的查找 2 | ### 方法一: 3 | 通过遍历array数组,去查找array数组中有没有target的值。它的时间复杂度是(O(n * m)) 4 | ~~~ java 5 | public boolean Find(int target, int [][] array) { 6 | for (int i = 0; i < array.length; i++) 7 | { 8 | for (int j = 0; j < array[0].length; j++) 9 | { 10 | if (array[i][j] == target) 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | ~~~ 17 | 18 | ### 方法二(从矩阵的右上角开始找): 19 | 设置一个i,j表示所找当前位置,如果说array[i][j] > target大的话,接着就往左找,反之往下找,直到找到array[i][j] == target为止。它的时间复杂度是:O(n + m) 20 | ~~~ java 21 | public boolean Find(int target, int [][] array) { 22 | int i = 0; 23 | int j = array[0].length - 1; 24 | while(i >= 0 && i < array.length && j >= 0 && j < array[0].length) 25 | { 26 | // array[i][j] 27 | if (array[i][j] == target) 28 | return true; 29 | else if (array[i][j] > target) 30 | j--; 31 | else 32 | i++; 33 | } 34 | return false; 35 | } 36 | ~~~ 37 | ### 方法三(从矩阵的左下角开始找): 38 | 设置一个i,j表示所找当前位置,如果说array[i][j] > target大的话,接着就往上找,反之往右找,直到找到array[i][j] == target为止。它的时间复杂度是:O(n + m) 39 | ~~~ java 40 | public boolean Find(int target, int [][] array) { 41 | int i = array.length - 1; 42 | int j = 0; 43 | while(i >= 0 && i < array.length && j >= 0 && j < array[0].length) 44 | { 45 | // array[i][j] 46 | if (array[i][j] == target) 47 | return true; 48 | else if (array[i][j] > target) 49 | i--; 50 | else 51 | j++; 52 | } 53 | return false; 54 | } 55 | ~~~ 56 | 57 | ## 替换空格 58 | ### 方法一:去遍历字符串,然后判断当前位置的字符是否为空格,如果为空格的话,就追加"%20",如果不为空格的话,那么就追加当前位置的字符 59 | ~~~ java 60 | public String replaceSpace(StringBuffer str) { 61 | int len = str.length(); 62 | String res = "%20"; 63 | StringBuffer ans = new StringBuffer(); 64 | for (int i = 0; i < len; i++) { 65 | ans.append(str.charAt(i) == ' ' ? res : str.charAt(i)); 66 | } 67 | return ans.toString(); 68 | } 69 | ~~~ 70 | 71 | ## 从尾到头打印链表 72 | ### 方法一:通过Java中的Stack类去模拟栈的过程 73 | ~~~ java 74 | public ArrayList printListFromTailToHead(ListNode listNode) { 75 | ArrayList list = new ArrayList<>(); 76 | Stack stack = new Stack<>(); 77 | while(listNode != null) { 78 | stack.add(listNode.val); /// 取当前节点的值放入栈中 79 | listNode = listNode.next; /// 更新当前节点为下一个节点 80 | } 81 | while (!stack.isEmpty()) { 82 | list.add(stack.pop()); /// 取出当前栈顶元素然后放入list中 83 | } 84 | return list; 85 | } 86 | ~~~ 87 | ### 方法二:采用递归的方式去模拟链表反置的作用 88 | ~~~ java 89 | private static ArrayList printListFromTailToHead(ListNode listNode) { 90 | ArrayList list = new ArrayList<>(); 91 | if (listNode == null) { 92 | return list; 93 | } 94 | return solve(list, listNode); 95 | } 96 | // 1->2->3->4 97 | private static ArrayList solve(ArrayList list, ListNode listNode) { 98 | if (listNode.next != null) { /// 当前节点的下一个节点不为空 99 | list = solve(list, listNode.next); /// 往下递归 100 | } 101 | list.add(listNode.val); 102 | // System.out.println(list); 103 | return list; 104 | } 105 | ~~~ 106 | 107 | ## 重建二叉树 108 | ### 方法一:通过依次遍历前序序列,然后在中序序列中确定当前遍历的前序序列中的数字所在的位置,然后在去划分出当前节点的左右子树,最后在去传入递归程序即可。 109 | ~~~ java 110 | import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; 111 | 112 | class TreeNode { 113 | int val; 114 | TreeNode left; 115 | TreeNode right; 116 | 117 | TreeNode(int x) { 118 | val = x; 119 | } 120 | } 121 | 122 | public class Main4 { 123 | private static int index = 0; 124 | private static TreeNode solve(int[] pre, int[] tempIn) { 125 | int len1 = 0; /// 当前节点的左子树的节点的个数 126 | int len2 = 0; /// 当前节点的右子树的节点的个数 127 | for (int i = 0; i < tempIn.length; i++) { 128 | if (pre[index] == tempIn[i]) { 129 | break; 130 | } 131 | len1 ++; /// 左子树节点的个数++ 132 | } 133 | len2 = tempIn.length - len1 - 1; 134 | 135 | int index1 = 0; 136 | int index2 = 0; 137 | int[] temp1 = new int[len1]; /// 当前节点的左子树 138 | int[] temp2 = new int[len2]; /// 当前节点的右子树 139 | boolean flag = false; 140 | for (int i = 0; i < tempIn.length; i++) { 141 | if (pre[index] == tempIn[i]) { 142 | flag = true; 143 | } else if (!flag) { 144 | temp1[index1++] = tempIn[i]; 145 | } else { 146 | temp2[index2++] = tempIn[i]; 147 | } 148 | } 149 | TreeNode node = new TreeNode(pre[index]); 150 | node.right = null; 151 | node.left = null; 152 | // System.out.printf("%d左子树:", pre[index]); 153 | // for (int i = 0; i < temp1.length; i++) { 154 | // System.out.printf("%d ", temp1[i]); 155 | // } 156 | // System.out.printf(","); 157 | // System.out.printf("%d右子树:", pre[index]); 158 | // for (int i = 0; i < temp2.length; i++) { 159 | // System.out.printf("%d ", temp2[i]); 160 | // } 161 | // System.out.println(); 162 | if (index < pre.length && temp1.length > 0) { 163 | index++; /// 遍历前序序列的下标加1 164 | node.left = solve(pre, temp1); /// 创建当前节点的左子树 165 | } 166 | if (index < pre.length && temp2.length > 0) { 167 | index++; /// 遍历前序序列的下标加1 168 | node.right = solve(pre, temp2); /// 创建当前节点的右子树 169 | } 170 | return node; 171 | } 172 | private static TreeNode reConstructBinaryTree(int[] pre, int[] in) { 173 | index = 0; /// 遍历前序序列的下标 174 | return solve(pre, in); 175 | } 176 | 177 | public static void main(String[] args) { 178 | int[] pre = {1, 2, 4, 7, 3, 5, 6, 8}; /// 前序遍历 179 | int[] in = {4, 7, 2, 1, 5, 3, 8, 6}; /// 中序遍历 180 | TreeNode root = reConstructBinaryTree(pre, in); 181 | 182 | dfs1(root); 183 | System.out.println(); 184 | dfs2(root); 185 | System.out.println(); 186 | dfs3(root); 187 | System.out.println(); 188 | 189 | } 190 | private static void dfs1(TreeNode node) { 191 | System.out.printf("%d ", node.val); 192 | if (node.left != null) { 193 | dfs1(node.left); 194 | } 195 | if (node.right != null) { 196 | dfs1(node.right); 197 | } 198 | } 199 | private static void dfs3(TreeNode node) { 200 | if (node.left != null) { 201 | dfs3(node.left); 202 | } 203 | if (node.right != null) { 204 | dfs3(node.right); 205 | } 206 | System.out.printf("%d ", node.val); 207 | } 208 | 209 | private static void dfs2(TreeNode node) { 210 | if (node.left != null) { 211 | dfs2(node.left); 212 | } 213 | System.out.printf("%d ", node.val); 214 | if (node.right != null) { 215 | dfs2(node.right); 216 | } 217 | } 218 | 219 | } 220 | ~~~ 221 | ## 用两个栈去实现队列 222 | ### 方法一:通过两个栈中元素之间的的复制交换去实现了队列的功能。 223 | ~~~ java 224 | import java.util.Stack; 225 | 226 | public class Main5 { 227 | Stack stack1 = new Stack(); 228 | Stack stack2 = new Stack(); 229 | 230 | public void push(int node) { 231 | while (!stack2.isEmpty()) { 232 | stack1.push(stack2.pop()); /// 将栈2中的元素放入到栈1中 233 | } 234 | stack1.push(node); 235 | } 236 | 237 | public int pop() { 238 | while (!stack1.isEmpty()) { 239 | stack2.push(stack1.pop()); /// 将栈1中的元素放入到栈2中 240 | } 241 | return stack2.pop(); 242 | } 243 | } 244 | ~~~ 245 | 246 | ## 旋转数组的最小数字 247 | ### 方法一:遍历数组,不断去更新保存最小值的变量。时间复杂度是O(n) 248 | ~~~ java 249 | public int minNumberInRotateArray(int [] array) { 250 | if (array.length == 0) { 251 | return 0; 252 | } 253 | int ans = array[0]; 254 | for (int i = 1; i < array.length; i++) { 255 | ans = Math.min(ans, array[i]); 256 | } 257 | return ans; 258 | } 259 | ~~~ 260 | ### 方法二:通过二分的方法,不断去更新存在于两个子数组(两个非递减排序子数组)中的下标。时间复杂度是O(log(n)) 261 | ~~~ java 262 | public int minNumberInRotateArray(int[] array) { 263 | if (array.length == 0) { 264 | return 0; 265 | } 266 | int l = 0; 267 | int r = array.length - 1; 268 | while (l < r - 1) { 269 | int mid = (l + r) >> 1; 270 | if (array[mid] >= array[l]) { 271 | l = mid; /// 说明mid所在的位置是在第一个非递减子数组中 272 | } else if (array[mid] <= array[r]) { 273 | r = mid; /// 说明mid所在的位置是在第二个非递减子数组中 274 | } 275 | } 276 | return array[r]; 277 | } 278 | ~~~ 279 | 280 | ## 斐波那契额数列 281 | ### 方法一:采用递推的方式去求出a[n]的值 282 | ~~~ java 283 | public int Fibonacci(int n) { 284 | if (n == 0) { 285 | return 0; 286 | } 287 | int[] a = new int[n + 1]; 288 | if (n == 1 || n == 2) { 289 | return 1; 290 | } 291 | a[1] = 1; 292 | a[2] = 1; 293 | for (int i = 3; i <= n; i++) { 294 | a[i] = a[i - 1] + a[i - 2]; 295 | } 296 | return a[n]; 297 | } 298 | ~~~ 299 | 300 | ### 方法二:采用递归的方式去求出a[n]的值 301 | ~~~ java 302 | public int Fibonacci(int n) { 303 | if (n == 0) { 304 | return 0; /// 终止递归的条件 305 | } 306 | if (n == 1 || n == 2) { 307 | return 1; /// 终止递归的条件 308 | } 309 | return Fibonacci(n - 1) + Fibonacci(n -2); 310 | } 311 | ~~~ 312 | 313 | ## 跳台阶 314 | ### 方法一:采用递归的方式去模拟出每次跳台阶的时候所作出的选择:要么跳1阶,要么跳2阶。 315 | ~~~ java 316 | public int JumpFloor(int target) { 317 | if (target == 1) { 318 | return 1; /// 目前递归到第1阶台阶,就没有必要往下去递归了 319 | } 320 | if (target == 2) { 321 | return 1 + JumpFloor(target - 1); /// 如果target == 2,其实就是等于从起点位置直接跳2阶 + 递归到第一阶的情况的总的跳阶的次数 322 | // return 2; 323 | } 324 | return JumpFloor(target - 1) + JumpFloor(target - 2); /// 当前target台阶的次数等于往前跳1阶加上往前跳2阶 325 | } 326 | ~~~ 327 | 328 | ### 方法二:采用递推的方式去计算出从起点到第i阶的总的情况数与从起点到第i - 1阶的总的情况数和从起点到第i - 2阶的总的情况数之间的关系等式。 329 | ~~~ java 330 | public int JumpFloor(int target) { 331 | if (target == 1) { 332 | return 1; 333 | } 334 | if (target == 2) { 335 | return 2; 336 | } 337 | int[] a = new int[target + 1]; /// a[i] 代表从起点到第i阶的总的情况数 338 | a[1] = 1; /// 第一阶的总情况数是1 339 | a[2] = 2; /// 第二阶的总情况数是2 340 | for (int i = 3; i <= target; i++) { 341 | a[i] = a[i - 1] + a[i - 2]; /// 对于第i阶的总情况数就等于从起点到第i-1阶的情况数(从0 -> i-1 -> +1 = i)加上从起点到第i-2阶的情况数(0 -> i-2 -> +2 ->i) 342 | } 343 | return a[target]; 344 | } 345 | ~~~ 346 | 347 | ### 变态跳台阶 348 | ### 方法一:采用递推的方式,对于第i阶台阶的跳法的总次数,他是等于从第一阶到第i-1阶的情况数总和然后再加上从起点到终点的这一种情况数。 349 | ~~~ java 350 | public int JumpFloorII(int target) { 351 | if (target == 1) { 352 | return 1; 353 | } 354 | int[] a = new int[target + 1]; 355 | int sum = 1; /// 设置一个sum变量去记录1到n-1阶的总的情况数 356 | for (int i = 2; i <= target; i++) { 357 | a[i] = sum + 1; /// 对于第i阶台阶他是等于从第1阶到第i-1阶台阶的情况数之和然后再加上1(从起点到i阶的情况) 358 | sum = sum + a[i]; /// 需要去更新1到i阶的情况数 359 | } 360 | return a[target]; 361 | } 362 | ~~~ 363 | 364 | ### 矩阵覆盖 365 | ### 方法一:对于2*i的矩形,他的情况数就是等于2*(i-1)的基础上在右边放置一个竖着的2*1的小矩阵,然后再加上2*(i-2)的矩形的基础上在右边横着放置两个2*1的小矩阵。 366 | ~~~ java 367 | public int RectCover(int target) { 368 | if (target == 0) { 369 | return 0; 370 | } 371 | if (target == 1) { 372 | return 1; 373 | } 374 | if (target == 2) { 375 | return 2; 376 | } 377 | int[] a = new int[target + 1]; 378 | a[1] = 1; 379 | a[2] = 2; 380 | for (int i = 3; i <= target; i++) { 381 | a[i] = a[i - 1] + a[i - 2]; /// 对于2*i的矩形,他的情况数就是等于2*(i-1)的基础上在右边放置一个竖着的2*1的小矩阵,然后再加上2*(i-2)的矩形的基础上在右边横着放置两个2*1的小矩阵。 382 | } 383 | return a[target]; 384 | } 385 | ~~~ 386 | 387 | ## 二进制中1的个数 388 | ### 方法一:本质上就是对n的二进制表示中的每一位进行判断。 389 | eg: 390 | 5 -》 101 & 1 —》 10 & 1 -》 1 & 1 -》 0 & 1这种方法是有问题的。 391 | 1 -> 0000000...01 -> (-1) -> 11....11111 -> 右移1位,数字-1的二进制的左边是补1的,也就是说,无论你右移多少次,结果都是-1. 392 | 393 | 改进:对n&运算的后面的那个数字进行操作: 394 | 5-》 101 & 1 -》 101 & 10 -》 101 & 100 395 | 396 | ~~~ java 397 | public int NumberOf1(int n) { 398 | int sum = 0; /// 记录1的个数 399 | int temp = 1; /// 本质上是用temp变量去判断n的每一位数字是否为1 400 | while (temp != 0) { /// 当temp为0的时候,说明已经移动了32次,然后就说明已经遍历完了n的每一位 401 | sum = (n & temp) != 0 ? sum + 1 : sum; 402 | temp = temp << 1; 403 | } 404 | return sum; 405 | } 406 | ~~~ 407 | 408 | ### 方法二:本质上对n的二进制表示中的1的位置的判断。 409 | eg: 410 | 5 -》 101 & 100(101 - 1) = 100 -》 100 & 011(100 - 1) = 000 -》 000 411 | ~~~ java 412 | public int NumberOf1(int n) { 413 | int sum = 0; /// 记录1的个数 414 | while (n != 0) { /// 说明当前n的二进制表示中肯定有1 415 | sum++; 416 | n = n & (n - 1); /// 本质上就是消除从右往左数的第一个位置的1。 417 | } 418 | return sum; 419 | } 420 | ~~~ 421 | 422 | ## 数值的整数次方 423 | ### 方法一:对exponent进行分类讨论,主要是当exponent小于0的时候,我们需要求出base的-exponent次方的值,然后拿1除以这个结果即可。 424 | ~~~ java 425 | public double Power(double base, int exponent) { 426 | double ans = 1.0; 427 | if (exponent >= 0) { 428 | for (int i = 1; i<= exponent; i++) { 429 | ans = ans * base; 430 | } 431 | } else { 432 | for (int i = 1; i<= -exponent; i++) { /// 注意一下exponent是一个负数 433 | ans = ans * base; 434 | } 435 | ans = 1 / ans; 436 | } 437 | return ans; 438 | } 439 | ~~~ 440 | 441 | ## 调整数组顺序使奇数位于偶数前面 442 | ### 方法一:类似于插入排序的思想,遇见奇数就将当前的奇数往前移动,知道往前移动的过程中,遇到奇数时停止移动。时间复杂度是O(n^2) 443 | ~~~ java 444 | public void reOrderArray(int [] array) { 445 | int len = array.length; 446 | 447 | for (int i = 0; i < len; i++) { 448 | if (array[i] % 2 != 0) { 449 | for (int j = i - 1; j >= 0; j--) { 450 | if (array[j] % 2 == 0) { 451 | int temp = array[j]; 452 | array[j] = array[j + 1]; 453 | array[j + 1] = temp; 454 | } else { 455 | break; 456 | } 457 | } 458 | } 459 | } 460 | } 461 | ~~~ 462 | ### 方法二: 本质上就是开辟两个空间去存储奇数和偶数,最终将这两个空间中的值合并即可。时间复杂度是O(n),但是空间复杂度比方法一要大。 463 | ~~~ java 464 | public void reOrderArray(int[] array) { 465 | int len = array.length; 466 | ArrayList list1 = new ArrayList<>(); /// 保存奇数 467 | ArrayList list2 = new ArrayList<>(); /// 保存偶数 468 | 469 | for (int i = 0; i < len; i++) { 470 | if (array[i] % 2 != 0) { 471 | list1.add(array[i]); 472 | } else { 473 | list2.add(array[i]); 474 | } 475 | } 476 | int index = 0; 477 | for (int x : list1) { 478 | array[index++] = x; 479 | } 480 | for (int x : list2) { 481 | array[index++] = x; 482 | } 483 | } 484 | ~~~ 485 | ## 链表中倒数第k个节点 486 | ### 方法一:采用递归的方式去模拟链表从尾到头的这样一个方向,然后在从尾到头的过程中,去判断当前节点的位置,是否为倒数第k个即可。 487 | ~~~ java 488 | private ListNode ans; /// 最终返回的结果 489 | private int sum; /// 用来记录当前节点是倒数第几个节点 490 | 491 | private void dfs(ListNode node, int k) { 492 | if (node.next != null) { 493 | dfs(node.next, k); /// 继续递归到下一节点。 494 | } 495 | // 下面这部分其实就是判断当前层的节点是倒数第几个节点。 496 | sum++; 497 | if (sum == k) { 498 | ans = node; 499 | } 500 | } 501 | 502 | public ListNode FindKthToTail(ListNode head, int k) { 503 | ans = null; 504 | sum = 0; 505 | if (head == null) { /// 说明链表为null,就没有必要去递归的需要了 506 | return null; 507 | } 508 | dfs(head, k); /// 递归遍历链表 509 | return ans; 510 | } 511 | ~~~ 512 | ### 方法二:通过初始化两个移动节点的位置距离为k,然后同时移动两个节点,知道第二个节点移动到链表的末尾时,移动节点1的位置就是链表倒数第k个节点。 513 | ~~~ java 514 | public ListNode FindKthToTail(ListNode head,int k) { 515 | ListNode removeNode = head; 516 | while (k != 0) { 517 | if (removeNode == null) { /// k 大于链表的长度,直接返回null 518 | return null; 519 | } 520 | removeNode = removeNode.next; 521 | k--; 522 | } 523 | while (removeNode != null) { /// 这个循环其实就是同时移动head和removeNode两个节点。 524 | removeNode = removeNode.next; 525 | head = head.next; 526 | } 527 | return head; 528 | } 529 | ~~~ 530 | ## 反转链表 531 | ### 方法一:就是通过两个距离为1的移动节点,去不断的去反转原链表相邻的节点之间的指向。 532 | ~~~ java 533 | public ListNode ReverseList(ListNode head) { 534 | if (head == null) { 535 | return null; 536 | } 537 | 538 | ListNode frontNode = head; 539 | ListNode removeNode = head.next; 540 | 541 | while (removeNode != null) { 542 | ListNode tempNode = removeNode.next; /// 用来保存移动节点的下一个节点,不然的话,就会造成节点最终无法往右移动的情况。 543 | removeNode.next = frontNode; /// 实现链表的反置 544 | // 下面两行代码就是实现两个节点的向右平移操作。 545 | frontNode = removeNode; 546 | removeNode = tempNode; 547 | } 548 | head.next = null; 549 | return frontNode; 550 | } 551 | ~~~ 552 | ### 方法二:通过栈去模拟反置的过程(不推荐) 553 | ~~~ java 554 | public ListNode ReverseList(ListNode head) { 555 | if (head == null) { 556 | return null; 557 | } 558 | Stack stack = new Stack<>(); 559 | while (head != null) { 560 | stack.push(head); 561 | head = head.next; 562 | } 563 | 564 | ListNode removeNode = stack.pop(); /// 创建新的链表,需要创建一个新的引用 565 | ListNode ans = removeNode; 566 | removeNode.next = null; /// 初始化 567 | while (!stack.isEmpty()) { 568 | ListNode x = stack.pop(); /// 取出栈顶节点元素,然后初始化节点元素的next值 569 | x.next = null; 570 | /// 可以用链表的尾接法去理解 571 | removeNode.next = x; 572 | removeNode = x; 573 | } 574 | return ans; 575 | 576 | } 577 | ~~~ 578 | 579 | ## 合并两个排序的链表 580 | ### 方法一:类似于归并排序中子序列合并过程,不断去比较两个链表中节点的val值,然后去判断那个节点优先需要添加到合成链表的尾部。 581 | ~~~ java 582 | public ListNode Merge(ListNode list1,ListNode list2) { 583 | if (list1 == null) { 584 | return list2; 585 | } 586 | if (list2 == null) { 587 | return list1; 588 | } 589 | ListNode headNode; /// 最终合成链表得头节点。 590 | if (list1.val > list2.val) { 591 | headNode = list2; 592 | list2 = list2.next; 593 | } else { 594 | headNode = list1; 595 | list1 = list1.next; 596 | } 597 | ListNode removeNode = headNode; /// 其实在当前位置就是合成链表得长度为1,头节点和尾节点是一样的。 598 | 599 | while (list1 != null && list2 != null) { 600 | if (list1.val > list2.val) { 601 | removeNode.next = list2; /// 将合成链表的尾部节点添加链表2中当前所指向的节点 602 | removeNode = list2; /// 去更新合成链表的尾部节点 603 | list2 = list2.next; 604 | } else { 605 | removeNode.next = list1; /// 将合成链表的尾部节点添加链表2中当前所指向的节点 606 | removeNode = list1; /// 去更新合成链表的尾部节点 607 | list1 = list1.next; 608 | } 609 | } 610 | 611 | /// 其实就是将剩余的链表1中的节点放入到合成链表中 612 | while (list1 != null) { 613 | removeNode.next = list1; 614 | removeNode = list1; 615 | list1 = list1.next; 616 | } 617 | /// 其实就是将剩余的链表2中的节点放入到合成链表中 618 | while (list2 != null) { 619 | removeNode.next = list2; 620 | removeNode = list2; 621 | list2 = list2.next; 622 | } 623 | return headNode; 624 | } 625 | ~~~ 626 | 627 | ## 树的子结构 628 | ### 方法一:主要是分为两个过程,过程一就是查找过程,只有在查找过程中当前A中节点的val等于B中root节点val值一样时,才会进入到匹配过程,匹配过程的话对两个二叉树就是采用同样的比例方式去比较每次递归的节点的val是否一样。然后去判断两个二叉树结构是否一样。 629 | ~~~ java 630 | private boolean judge(TreeNode node1, TreeNode node2) { /// 第二部分,匹配 631 | if (node2 == null) { 632 | return true; /// 说明二叉树B的某一个方向的节点已经完全的匹配成功。 633 | } 634 | if (node1 == null) { 635 | return false; /// 说明在某一方向上,二叉树A中的节点不缺少的,相对于二叉树B 636 | } 637 | if (node1.val == node2.val) { 638 | boolean flag1 = true; /// 默认左子树是匹配的,假如说不匹配,它就会返回false 639 | boolean flag2 = true; /// 默认右子树是匹配的,假如说不匹配,它就会返回false 640 | if (node1.left != null || node2.left != null) { 641 | flag1 = judge(node1.left, node2.left); /// 比较子树A和二叉树B的左子树 642 | } 643 | if (flag1 && (node1.right != null || node2.right != null)) { /// flag1 -> 剪枝 644 | flag2 = judge(node1.right, node2.right); /// 比较子树A和二叉树B的右子树 645 | } 646 | return flag1 && flag2; /// && -> 不光某一个节点的左子树要完全匹配,右子树也是要完全匹配的 647 | } else { 648 | return false; 649 | } 650 | } 651 | 652 | /// 二叉树的先序遍历 653 | private boolean dfs(TreeNode node, TreeNode root2) { /// 第一部分,查找 654 | boolean flag = false; 655 | if (node.val == root2.val) { 656 | flag = judge(node, root2); /// 进入第二部分的匹配过程 657 | } 658 | if (flag) { 659 | return true; /// 通过当前节点已经找到二叉树B的完全匹配结果了,就没有必要再往下去遍历二叉树A了。也可以说是剪枝欸但一个过程 660 | } 661 | boolean flag1 = false; /// 用来记录当前节点的左子树中的查找结果(其实也是包含了匹配的过程),如果查找成功(包含了匹配过程)返回true 662 | boolean flag2 = false; /// 用来记录当前节点的右子树中的查找结果(其实也是包含了匹配的过程),如果查找成功(包含了匹配过程)返回true 663 | if (node.left != null) { 664 | flag1 = dfs(node.left, root2); /// 当前节点的val不等于二叉树B的root值,那么就去遍历当前节点的左子树,看否找到二叉树B 665 | } 666 | if ((!flag1) && node.right != null) { /// !flag1-》剪枝 667 | flag2 = dfs(node.right, root2); /// 当前节点的val不等于二叉树B的root值,那么就去遍历当前节点的右子树,看否找到二叉树B 668 | } 669 | return flag1 || flag2; /// || -》只需要找到节点的某一个方向的子树进行匹配成功就行了 670 | } 671 | 672 | public boolean HasSubtree(TreeNode root1,TreeNode root2) { 673 | if (root1 == null || root2 == null) { /// root1 == null -> 就是二叉树A就是一颗空树, root2 -> 约定空树不是任意一个树的子结构 674 | return false; 675 | } 676 | return dfs(root1, root2); 677 | } 678 | ~~~ 679 | 680 | ## 二叉树的镜像 681 | ### 方法一:采用二叉树的后序遍历的方式,当对某一结点的左右孩子节点遍历完之后,那么就交换左右孩子节点。 682 | ~~~ java 683 | public void Mirror(TreeNode node) { 684 | if (node != null) { 685 | if (node.left != null) { 686 | Mirror(node.left); 687 | } 688 | if (node.right != null) { 689 | Mirror(node.right); 690 | } 691 | /// 下面三行就是交换node节点的左右孩子 692 | TreeNode temp = node.left; 693 | node.left = node.right; 694 | node.right = temp; 695 | } 696 | } 697 | ~~~ 698 | ## 顺时针打印矩阵 699 | ### 方法一:通过一个flag变量去不断的去更新遍历矩阵下标x,y的值(通过越界和flag当前的值)。 700 | ~~~ java 701 | public ArrayList printMatrix(int [][] matrix) { 702 | ArrayList ans = new ArrayList<>(); 703 | int flag = 1;// 1->right, 2->down, 3->left, 4->up 704 | int x = 0; 705 | int y = 0; 706 | boolean[][] vis = new boolean[matrix.length][matrix[0].length]; // 这个就是用来标记已经走过的点 707 | while (ans.size() < matrix.length * matrix[0].length) { 708 | if(x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || vis[x][y]) { // vis[x][y] -> 已经遍历过的位置也当作越界处理 709 | if(flag == 1) { 710 | flag = 2; // 往下走 711 | y--; // 消除越界的影响 712 | x++; // 本质上就是到达下一个位置的横坐标 713 | } else if(flag == 2) { 714 | flag = 3; // 往左走 715 | x--; // 消除越界的影响 716 | y--; // 本质上就是到达下一个位置的纵坐标 717 | } else if (flag == 3) { 718 | flag = 4; // 往上走 719 | y++; // 消除越界的影响 720 | x--; // 本质上就是到达下一个位置的横坐标 721 | } else { 722 | flag = 1;//往右走 723 | x++; // 消除越界的影响 724 | y++; // 本质上就是到达下一个位置的纵坐标 725 | } 726 | 727 | } else { 728 | ans.add(matrix[x][y]); 729 | vis[x][y] = true; // 去标记已经遍历过的位置 730 | // 根据flag的值更新遍历矩阵的下标x,y的值 731 | if(flag == 1) { 732 | y++; 733 | } else if (flag == 2) { 734 | x++; 735 | } else if (flag == 3) { 736 | y--; 737 | } else { 738 | x--; 739 | } 740 | } 741 | } 742 | return ans; 743 | } 744 | ~~~ 745 | ## 包含min函数的栈 746 | ### 方法一:其实就是维护两个栈,首先第一个栈是普通的数据站,跟我们平常的栈一样,存储入栈数据;第二个栈就是建立在第一个栈的基础之上,他是维护第一个栈,就是去维护第一个栈中元素的最小值。 747 | ~~~ java 748 | import java.util.Stack; 749 | 750 | public class Main20 { 751 | private Stack dataStack = new Stack<>(); // 数据栈 752 | private Stack minStack = new Stack<>(); // 维护min函数的栈 753 | 754 | public void push(int node) { 755 | dataStack.push(node); 756 | 757 | if (minStack.isEmpty() || minStack.peek() > dataStack.peek()) { 758 | minStack.push(dataStack.peek()); // 当前minStack的栈顶元素大于数据栈的栈顶元素 759 | } else { 760 | minStack.push(minStack.peek()); // 当前minStack的栈顶元素小于数据栈的栈顶元素 761 | } 762 | } 763 | 764 | public void pop() { 765 | if (!dataStack.isEmpty()) { 766 | dataStack.pop(); 767 | } 768 | if (!minStack.isEmpty()) { 769 | minStack.pop(); 770 | } 771 | } 772 | 773 | public int top() { 774 | // 取出数据栈的栈顶元素 775 | return dataStack.peek(); 776 | } 777 | 778 | public int min() { 779 | // 取出维护min函数的栈的栈顶元素 780 | return minStack.peek(); 781 | } 782 | } 783 | 784 | ~~~ 785 | 786 | ## 栈的压入,弹出序列 787 | ### 方法一:对入栈序列进行入栈的模拟,然后在模拟的过程当中,判断栈顶元素和出栈序列的相等关系,从而判断出对栈顶元素的操作。 788 | ~~~ java 789 | public boolean IsPopOrder(int [] pushA,int [] popA) { 790 | Stack stack = new Stack<>(); 791 | int pushIndex = 0; // 入栈序列的下标 792 | int popIndex = 0; // 出栈序列的下标 793 | 794 | while (pushIndex < pushA.length) { 795 | if (!stack.isEmpty() && stack.peek() == popA[popIndex]) { 796 | stack.pop(); 797 | popIndex++; 798 | } else { 799 | stack.push(pushA[pushIndex]); 800 | pushIndex++; 801 | } 802 | } 803 | 804 | // 下面的这个while循环其实就是为了防止当所有入栈的元素都压入栈的时候,栈顶元素和出栈序列的下标所指的数字没有来得及比较。 805 | while (!stack.isEmpty()) { 806 | if (stack.peek() == popA[popIndex]) { 807 | stack.pop(); 808 | popIndex++; 809 | } else { 810 | return false; 811 | } 812 | } 813 | return true; 814 | 815 | } 816 | ~~~ 817 | ## 从上往下打印二叉树 818 | ### 方法一:利用queue去模拟对二叉树宽搜的过程。进而得到二叉树的层序遍历。 819 | ~~~ java 820 | public ArrayList PrintFromTopToBottom(TreeNode root) { 821 | ArrayList ans = new ArrayList<>(); 822 | Queue queue = new LinkedList<>(); // 放入遍历二叉树的节点(本质上是维护宽搜) 823 | if (root != null) { 824 | queue.add(root); 825 | } 826 | // 迭代的过程->宽搜 827 | while (!queue.isEmpty()) { 828 | TreeNode node = queue.peek(); 829 | ans.add(node.val); // 将当前节点的val值放入ArrayList中 830 | // 同层节点从左至右打印 831 | if (node.left != null) { 832 | queue.add(node.left); 833 | } 834 | if (node.right != null) { 835 | queue.add(node.right); 836 | } 837 | queue.poll(); // 当前节点val值已经放入ans中,所以要删去 838 | } 839 | return ans; 840 | } 841 | ~~~ 842 | ## 二叉搜索树的后序遍历序列 843 | ### 方法一:主要是根据两个性质,第一个性质就是后序遍历的末尾数字是二叉树的root节点,第二个性质是二叉搜索树的性质:对于某一个节点而言,它的左子树都是小于当前节点的,右子树都是大于当前节点的。根据性质1去确定每一个节点的位置,然后根据性质2去分割后序遍历序列。 844 | ~~~ java 845 | private boolean solve(ArrayList list) { 846 | // 递归终止的条件 847 | if (list.size() == 0 || list.size() == 1) { 848 | return true; 849 | } 850 | ArrayList minList = new ArrayList<>(); // 用来保存小于endNumber数字的序列 851 | ArrayList maxList = new ArrayList<>(); // 用来保存大于endNumber数字的序列 852 | int endNumber = list.get(list.size() - 1); 853 | int minIndex = -1; // 用来记录minList中第一个数字的位置 854 | int maxIndex = -1; // 用来记录maxList中第一个数字的位置 855 | // 下面这个循环其实就是对当前list序列的一个分割(分割条件就是endNumber) 856 | for (int i = 0; i < list.size(); i++) { 857 | if (list.get(i) > endNumber) { 858 | if (maxIndex == -1) { 859 | maxIndex = i; 860 | } 861 | maxList.add(list.get(i)); 862 | } else if (list.get(i) < endNumber) { 863 | if (minIndex == -1) { 864 | minIndex = i; 865 | } 866 | minList.add(list.get(i)); 867 | } 868 | } 869 | if (minIndex != -1 && maxIndex != -1) { 870 | if (minIndex > maxIndex) { 871 | return false; // 本质上使右子树的序列在左子树的前面,不满足后序遍历 872 | } 873 | for (int i = maxIndex; i < list.size(); i++) { 874 | if (list.get(i) < endNumber) { 875 | return false; // 说明在大于endNumber的序列初始位置到末尾,不连续,中间有小于endNumber的数字分割开来 876 | } 877 | } 878 | } 879 | return solve(minList) && solve(maxList); // && -> 每一个子序列都是需要满足的 880 | } 881 | public boolean VerifySquenceOfBST(int [] sequence) { 882 | if (sequence.length == 0) { 883 | return false; 884 | } 885 | ArrayList list = new ArrayList<>(); 886 | for (int i = 0; i < sequence.length; i++) { 887 | list.add(sequence[i]); 888 | } 889 | return solve(list); 890 | } 891 | ~~~ 892 | ## 二叉树中和为某一值的路径 893 | ### 方法一:通过深搜遍历二叉树节点元素,去搜索从二叉树root节点到叶子节点之间的路径的权值和是否等于target。 894 | ~~~ java 895 | private ArrayList> ans; 896 | 897 | /** 898 | * 899 | * @param node 二叉树节点 900 | * @param target 目标权值和 901 | * @param sum 当前路径的权值和 902 | * @param list 保存当前路径 903 | */ 904 | private void solve(TreeNode node, int target, int sum, ArrayList list) { 905 | if (node != null) { 906 | sum += node.val; 907 | list.add(node.val); 908 | if (node.left == null && node.right == null) { 909 | if (sum == target) { 910 | ArrayList res = new ArrayList<>(list); // ArrayList是引用传递 911 | ans.add(res); 912 | } 913 | } else { 914 | solve(node.left, target, sum, list); // 递归左子树 915 | solve(node.right, target, sum, list); // 递归右子树 916 | } 917 | // 消除掉当前节点对查找路径的影响 --> 至关重要 918 | list.remove(list.size() - 1); 919 | } 920 | } 921 | private void change() { 922 | for (int i = 0; i < ans.size(); i++) { 923 | int index = i; 924 | for (int j = i + 1; j < ans.size(); j++) { 925 | if (ans.get(j).size() > ans.get(index).size()) { 926 | index = j; 927 | } 928 | } 929 | if (i != index) 930 | { 931 | ArrayList temp = ans.get(i); 932 | ans.set(i, ans.get(index)); 933 | ans.set(index, temp); 934 | } 935 | } 936 | } 937 | public ArrayList> FindPath(TreeNode root, int target) { 938 | ans = new ArrayList>(); 939 | ArrayList list = new ArrayList<>(); 940 | solve(root, target, 0, list); 941 | change(); 942 | return ans; 943 | } 944 | ~~~ 945 | ## 复杂链表的复制 946 | ### 方法一:主要是通过去维护原链表节点和新链表节点之间的映射关系,然后在根据原链表中节点之间的连接关系去创建新链表中的节点之间的关系。空间复杂度是O(N) 947 | ~~~ java 948 | public RandomListNode Clone(RandomListNode pHead) { 949 | Map map = new HashMap<>(); 950 | RandomListNode removeNode = pHead; 951 | // 去创建新链表中的节点元素和原链表节点元素与新链表节点元素之间的映射关系 952 | while (removeNode != null) { 953 | RandomListNode node = new RandomListNode(removeNode.label); 954 | map.put(removeNode, node); 955 | removeNode = removeNode.next; 956 | } 957 | removeNode = pHead; 958 | // 去创建新链表中每个节点的结构关系(根据原链表的节点的结构关系) 959 | while (removeNode != null) { 960 | RandomListNode node = map.get(removeNode); 961 | node.next = map.get(removeNode.next); 962 | node.random = map.get(removeNode.random); 963 | removeNode = removeNode.next; 964 | } 965 | return map.getOrDefault(pHead, null); 966 | } 967 | ~~~ 968 | ### 方法二:主要是通过创建新链表中的节点在原链表中,去优化了第一种方法的O(N)的空间复杂度,第二种方法分为三个过程,1->创建新节点以及实现新节点和元链表节点的连接,2->根据原链表的rangdom指向去生成新的节点的random的指向,3->链表的分割。 969 | ~~~ java 970 | public RandomListNode Clone(RandomListNode pHead) { 971 | if (pHead == null) { 972 | return null; 973 | } 974 | // 第一个过程->创建新链表节点插入到原链表中 975 | RandomListNode removeNode = pHead; 976 | while (removeNode != null) { 977 | RandomListNode temp = removeNode.next; 978 | RandomListNode node = new RandomListNode(removeNode.label); 979 | removeNode.next = node; // 原节点指向新节点 980 | node.next = temp; // 新节点指向当前节点的next 981 | removeNode = temp; 982 | } 983 | // 第二个过程->创建rangdom节点指向 984 | removeNode = pHead; 985 | while (removeNode != null) { 986 | removeNode.next.random = removeNode.random == null ? null : removeNode.random.next; 987 | removeNode = removeNode.next.next; // 用两个next是把新链表节点隔过去 988 | } 989 | 990 | // 第三个过程->链表的分割 991 | removeNode = pHead; 992 | RandomListNode cloneHead = pHead.next; 993 | while (removeNode != null) { 994 | RandomListNode node = removeNode.next; 995 | removeNode.next = node.next; // 原链表中节点的结构之间关系的维护 996 | node.next = node.next == null ? null : node.next.next;// 维护新链表中节点关系的维护 997 | removeNode = removeNode.next; 998 | } 999 | return cloneHead; 1000 | } 1001 | ~~~ 1002 | ## 二叉搜索树与双向链表 1003 | ### 方法一:通过对二叉搜索树的中序遍历,在遍历过程中,动态的去创建双向链表的尾部节点即可。 1004 | ~~~ java 1005 | private TreeNode ans; // 最终返回得双向链表得头部 1006 | private TreeNode removeNode; // 双向链表的尾部节点 1007 | // flag -> 代表的是第n层节点到达第n+1层节点的方向,0->第n+1层节点是第n层节点得左孩子,1->第n+1层节点是第n层节点得右孩子 1008 | private void dfs(TreeNode node, int flag) { 1009 | if (node.left != null) { 1010 | dfs(node.left, 0); 1011 | } 1012 | if (ans == null) { 1013 | ans = node; 1014 | removeNode = node; 1015 | } else { 1016 | // 做一般处理->添加边,修改边 1017 | if(flag == 0) { 1018 | removeNode.right = node; // 从尾部节点引出一条边指向当前节点,也就是说创建一条从小到大的边 1019 | node.left = removeNode; // 这行代码对于非root节点是没有影响的,主要是为了修改root的左孩子的指向 1020 | } else { 1021 | removeNode.right = node; // 这行代码对于非root节点是没有影响的,主要是为了修改root的右孩子的指向 1022 | node.left = removeNode; // 从当前节点引出一条边指向尾部节点,也就是说创建一条从大到小的边 1023 | } 1024 | removeNode = node; // 更新双向链表得尾部节点的值 1025 | } 1026 | if (node.right != null) { 1027 | dfs(node.right, 1); 1028 | } 1029 | } 1030 | public TreeNode Convert(TreeNode pRootOfTree) { 1031 | if(pRootOfTree == null) { 1032 | return null; 1033 | } 1034 | ans = null; 1035 | removeNode = null; 1036 | dfs(pRootOfTree, 0); 1037 | return ans; 1038 | } 1039 | ~~~ 1040 | ## 字符串的排列 1041 | ### 方法一:通过递归的去查找每一个位置的字符可能出现情况。比如说现在要找index下标位置的字符,那么体现在代码中就是交换index以及index位置之后的那些字符即可。 1042 | ~~~ java 1043 | private String change(char[] a) { 1044 | StringBuilder res = new StringBuilder(); 1045 | for (char value : a) { 1046 | res.append(value); 1047 | } 1048 | return res.toString(); 1049 | } 1050 | private void solve(ArrayList ans, char[] a, int index, int length) { 1051 | if (index == length - 1) { 1052 | String res = change(a); 1053 | ans.add(res); 1054 | } else { 1055 | // 就说明现在要去确定index位置的字符 1056 | for (int i = index; i < length; i++) { 1057 | char temp = a[i]; 1058 | a[i] = a[index]; 1059 | a[index] = temp; 1060 | // 当前index位置的字符已经通过交换找到了,那么就递归去找下一个位置的字符 1061 | solve(ans, a, index + 1, length); 1062 | // 其实就是去为了消除当前层去递归的时候的进行交换字符的影响,如果不消除的话,那么就会造成原index位置的字符发生变化 1063 | temp = a[i]; 1064 | a[i] = a[index]; 1065 | a[index] = temp; 1066 | 1067 | } 1068 | } 1069 | } 1070 | public ArrayList Permutation(String str) { 1071 | char[] a = str.toCharArray(); 1072 | ArrayList ans = new ArrayList<>(); 1073 | solve(ans, a, 0, str.length()); 1074 | ans = new ArrayList(new HashSet(ans)); // 去重操作 1075 | Collections.sort(ans); // 字典排序 -> ans.sort(null); 1076 | return ans; 1077 | } 1078 | ~~~ 1079 | ## 数组中初夏你次数超过一半的数字 1080 | ### 方法一:用Map去得到每一个数字出现的次数u,最后找到出现次数最大的那个数字 1081 | ~~~ java 1082 | public int MoreThanHalfNum_Solution(int [] array) { 1083 | Map map = new HashMap<>(); // 去存储每个数字出现的次数 1084 | int target = 0; // 用来去存储出现次数最多的那个数字 1085 | int sum = 0; // 用来去存储出现次数最多的那个数字出现的次数 1086 | for (int x : array) { 1087 | map.put(x, map.getOrDefault(x, 0) + 1); // 更新当前位置数字出现的次数 1088 | if (sum < map.get(x)) { 1089 | // 就是说明当前位置的数字出现的次数比之前统计的target数字出现的次数大 1090 | sum = map.get(x); 1091 | target = x; 1092 | } 1093 | } 1094 | if(sum > array.length / 2) { 1095 | return target; 1096 | } 1097 | return 0; 1098 | } 1099 | ~~~ 1100 | ### 方法二:设置一个sum变量用来保存数组从第1个位置到第i个位置中,target出现的次数 - 不是target出现的次数,最终保存的那个数字即为所求 1101 | ~~~ java 1102 | private boolean check(int target, int[] array) { 1103 | int sum = 0; 1104 | for (int x : array) { 1105 | if (x == target) { 1106 | sum++; 1107 | } 1108 | } 1109 | return sum > array.length / 2; 1110 | } 1111 | public int MoreThanHalfNum_Solution(int [] array) { 1112 | if (array.length == 0) { 1113 | return 0; 1114 | } 1115 | int target = array[0]; // 用来保存最终出现次数最多的数字 1116 | int sum = 0; // 用来保存数组从第1个位置到第i个位置中,target出现的次数 - 不是target出现的次数 1117 | 1118 | for (int x : array) { 1119 | if (x == target) { 1120 | sum ++; 1121 | } else { 1122 | sum--; 1123 | } 1124 | if (sum == 0) { 1125 | target = x; 1126 | sum = 1; 1127 | } 1128 | } 1129 | if (check(target, array)) { 1130 | return target; 1131 | } 1132 | return 0; 1133 | } 1134 | ~~~ 1135 | 1136 | ## 最小的K个数 1137 | ### 方法一:通过维护大顶堆去实现最小的K个数字的查找,本质就是大顶堆的维护 1138 | ~~~ java 1139 | public ArrayList GetLeastNumbers_Solution(int [] input, int k) { 1140 | if (k > input.length || k == 0) { 1141 | return new ArrayList<>(); 1142 | } 1143 | 1144 | int[] a = new int[k]; // 用数组去模拟k个节点的堆结构 1145 | System.arraycopy(input, 0, a, 0, k); // 初始化堆中元素 1146 | // 下面就开始维护堆使其成为大顶堆 - > 堆的初始化 1147 | for (int i = k / 2 - 1; i >= 0; i--) { 1148 | // i -> i其实就是我们所要去维护堆的节点下标 1149 | initiate(i, a, k); 1150 | } 1151 | // 去遍历剩余的len - k个节点 1152 | for (int i = k; i < input.length; i++) { 1153 | if (input[i] < a[0]) { 1154 | a[0] = input[i]; 1155 | initiate(0, a, k); 1156 | } 1157 | } 1158 | // 将大顶堆中的节点元素进行升序操作 1159 | for (int i = a.length - 1; i > 0; i--) { 1160 | // 分为两个过程, 第一步交换,第二步固定(固定的操作其实是通过控制堆的节点个数去实现的) 1161 | int temp = a[i]; 1162 | a[i] = a[0]; 1163 | a[0] = temp; 1164 | initiate(0, a, i); 1165 | } 1166 | // 返回 1167 | ArrayList ans = new ArrayList<>(); 1168 | for (int x : a) { 1169 | ans.add(x); 1170 | } 1171 | return ans; 1172 | } 1173 | 1174 | /** 1175 | * 初始化堆的函数,其实就是维护每一个节点的位置的函数 1176 | * @param index 维护当前堆的下标 1177 | * @param a 数组->堆 1178 | * @param length 堆的节点个数 1179 | */ 1180 | private void initiate(int index, int[] a, int length) { 1181 | int temp = a[index]; // 先去保存当前位置的值 1182 | for (int k = index * 2 + 1; k < length; k = k * 2 + 1) { 1183 | if ((k + 1) < length && a[k + 1] > a[k]) { 1184 | // 取出当前位置的左右孩子中节点值最大的节点 1185 | k++; 1186 | } 1187 | if (a[k] > temp) { 1188 | a[index] = a[k]; 1189 | index = k; // 更新index的值,index -> 代表的是temp数字最终在堆中位置,当k = k * 2 + 1执行后,index和k的关系其实就是父亲节点和孩子节点的关系。 1190 | } else { 1191 | break; // 由于我们是从下往上去维护的,所以说我们就没有往下更新的必要了 1192 | } 1193 | } 1194 | a[index] = temp; // index所在的位置进行更新就行了 1195 | 1196 | } 1197 | ~~~ 1198 | ## 连续子序列的最大和 1199 | ### 方法一:通过枚举起点和终点去统计起点到终点的序列的和。时间复杂度O(n^2) 1200 | ~~~ java 1201 | public int FindGreatestSumOfSubArray(int[] array) { 1202 | int[] sum = new int[array.length]; // 用来去统计0-i位置的和 1203 | sum[0] = array[0]; 1204 | for (int i = 1; i < array.length; i++) { 1205 | sum[i] = sum[i - 1] + array[i]; 1206 | } 1207 | int Max = sum[0]; // 默认第一个元素 1208 | // i是终点,j是起点 1209 | for (int i = 0; i < array.length; i++) { 1210 | for (int j = 0; j <= i; j++) { 1211 | if (j == 0) { 1212 | Max = Math.max(Max, sum[i]); // 说明起点在0位置 1213 | } else { 1214 | Max = Math.max(Max, sum[i] - sum[j - 1]); // j-i的和它就等于从起点到i位置之和减去从起点到j-1的位置之和 1215 | } 1216 | } 1217 | } 1218 | return Max; 1219 | } 1220 | ~~~ 1221 | ### 方法二:通过定义一个sum变量去统计若干段连续子序列的和,然后再去比较出每段子序列和的最大值即可。时间复杂度为O(n) 1222 | ~~~ java 1223 | public int FindGreatestSumOfSubArray(int[] array) { 1224 | int sum = 0; 1225 | int Max = array[0]; 1226 | for (int i = 0; i < array.length; i++) { 1227 | // 这几行代码的过程就是:通过sum变量去统计当前连续子序列的和,统计完之后,更新Max的值,最后判断是否更新sum的值 1228 | sum += array[i]; 1229 | Max = Math.max(Max, sum); 1230 | if (sum < 0) { 1231 | sum = 0; 1232 | } 1233 | } 1234 | return Max; 1235 | } 1236 | ~~~ 1237 | ## 整数中1出现的次数 1238 | ### 方法一:暴力1-n个数字即可。时间复杂度O(n*log(n)) 1239 | ~~~ java 1240 | public int NumberOf1Between1AndN_Solution(int n) { 1241 | int sum = 0; 1242 | for (int i = 1; i <= n; i++) { 1243 | int x = i; 1244 | while (x != 0) { 1245 | if (x % 10 == 1) { 1246 | sum++; 1247 | } 1248 | x = x / 10; 1249 | } 1250 | } 1251 | return sum; 1252 | } 1253 | ~~~ 1254 | ### 方法二:通过对1-n的分区间讨论(递归的过程),在求1-n的时候,分为两个区间,第一个区间是1-b(b是n去掉首部数字之后的数字), 第二个区间是(b+1, n)。对于每个区间的计算时,分为了两种情况,第一种情况是当前n的首部数字是1,第二种情况是除了首位的其他位是1。主要是这两中情乱的讨论。 1255 | ~~~ java 1256 | public int NumberOf1Between1AndN_Solution(int n) { 1257 | if (n == 0) { 1258 | return 0; 1259 | } 1260 | String str = "" + n; 1261 | int len = str.length(); 1262 | if (len == 1) { 1263 | return 1; 1264 | } 1265 | int res = (int) Math.pow(10, len - 1); // 是获取当前n的幂级 1266 | // int firstNumber = str.charAt(0) - '0'; 1267 | int firstNumber = n / res; 1268 | int firstBit = firstNumber == 1 ? (n % res) + 1 : res; 1269 | int otherBit = (len - 1) * firstNumber * res / 10; //(len - 1)的意思就是剩余位的个数(C(len-1, 1) -> 从剩余的len-1位中选取一位来作为1),res/10的意思就是剩余的len-2位可能出现的情况 1270 | return firstBit + otherBit + NumberOf1Between1AndN_Solution(n % res); 1271 | } 1272 | ~~~ 1273 | ## 把数组排成最小的数 1274 | ### 方法一:通过去设置一种比较优先级排序即可,优先级为:将比较的两个元素拼接的两种结果去比较大小,然后由他们的大小关系去比较所拼接元素的优先级。 1275 | ~~~ java 1276 | public String PrintMinNumber(int [] numbers) { 1277 | ArrayList list = new ArrayList<>(); 1278 | for (int x : numbers) { 1279 | list.add(x + ""); 1280 | } 1281 | list.sort((o1, o2) -> { 1282 | // 下面的排序规则是核心 1283 | String a1 = o1 + o2; 1284 | String a2 = o2 + o1; 1285 | return a1.compareTo(a2); 1286 | }); 1287 | StringBuilder ans = new StringBuilder(); 1288 | for (String x : list) { 1289 | ans.append(x); 1290 | } 1291 | return ans.toString(); 1292 | } 1293 | ~~~ 1294 | ## 丑数 1295 | ### 方法一:就是说通过去根据2*丑数,3*丑数,5*丑数这三个队列去判断出当前位置的值,然后去更新遍历这三个队列下标的值即可 1296 | ~~~ java 1297 | public int GetUglyNumber_Solution(int index) { 1298 | int[] a = new int[index]; 1299 | a[0] = 1; 1300 | int index1 = 0; // 遍历丑数*2的队列 1301 | int index2 = 0; // 遍历丑数*3的队列 1302 | int index3 = 0; // 遍历丑数*5的队列 1303 | 1304 | for (int i = 1; i < index; i++) { 1305 | a[i] = Math.min(Math.min(a[index1] * 2, a[index2] * 3) , a[index3] * 5); 1306 | // 根据放在第i个位置上的数字更新遍历三个队列的下标 1307 | if (a[i] == a[index1] * 2) { 1308 | index1++; 1309 | } 1310 | if (a[i] == a[index2] * 3) { 1311 | index2++; 1312 | } 1313 | if (a[i] == a[index3] * 5) { 1314 | index3++; 1315 | } 1316 | } 1317 | return a[index - 1]; 1318 | } 1319 | ~~~ 1320 | ## 第一个只出现一次的字符位置 1321 | ### 方法一:通过map结构去保存每个字符出现的次数,然后再对字符进行遍历判断即可。 1322 | ~~~ java 1323 | public int FirstNotRepeatingChar(String str) { 1324 | Map map = new HashMap<>(); 1325 | for (int i = 0; i < str.length(); i++) { 1326 | map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1); 1327 | } 1328 | for (int i = 0; i < str.length(); i++) { 1329 | if (map.get(str.charAt(i)) == 1) { 1330 | return i; 1331 | } 1332 | } 1333 | return -1; 1334 | } 1335 | ~~~ 1336 | ## 数组中的逆序对 1337 | ### 方法一:通过对并排序的合并过程去统计逆序对的个数,那么统计逆序对的前提就是在归并排序的合并过程中,合并的两个子序列都是有序的,所以说才可以用归并排序去统计逆序对的个数 1338 | ~~~ java 1339 | private long sum; // 用来去统计逆序对的个数 1340 | public int InversePairs(int [] array) { 1341 | sum = 0; 1342 | int l = 0; 1343 | int r = array.length - 1; 1344 | divide(l ,r, array); 1345 | return (int) (sum % 1000000007); 1346 | } 1347 | 1348 | private void divide(int l, int r, int[] array) { 1349 | if (l != r) { 1350 | int mid = (l + r) >> 1; 1351 | divide(l, mid, array); 1352 | divide(mid + 1, r, array); 1353 | merge(l, r, mid, array); 1354 | } 1355 | } 1356 | 1357 | private void merge(int l, int r, int mid, int[] array) { 1358 | int i = l; // 左区间的起点 1359 | int j = mid + 1; // 右区间的起点 1360 | int[] temp = new int[r - l + 1]; 1361 | int index = 0; 1362 | while (i <= mid && j <= r) { 1363 | if (array[i] > array[j]) { 1364 | temp[index++] = array[j++]; 1365 | sum += mid - i + 1; // 这一行是核心,去统计逆序对个数,统计的基础是在归并排序的合并过程中,合并的两个子序列都是有序的 1366 | } else { 1367 | temp[index++] = array[i++]; 1368 | } 1369 | } 1370 | while (i <= mid) { 1371 | temp[index++] = array[i++]; 1372 | } 1373 | while (j <= r) { 1374 | temp[index++] = array[j++]; 1375 | } 1376 | index = 0; 1377 | for (int k = l; k <= r; k++) { 1378 | array[k] = temp[index++]; 1379 | } 1380 | } 1381 | ~~~ 1382 | ## 两个链表的第一个公共结点 1383 | ###方法一:通过栈去模拟从链表的尾部往前遍历两个链表的重合的部分,找到最左侧重合点即可 1384 | ~~~ java 1385 | public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { 1386 | Stack stack1 = new Stack<>(); 1387 | Stack stack2 = new Stack<>(); 1388 | 1389 | while (pHead1 != null) { 1390 | stack1.add(pHead1); 1391 | pHead1 = pHead1.next; 1392 | } 1393 | while (pHead2 != null) { 1394 | stack2.add(pHead2); 1395 | pHead2 = pHead2.next; 1396 | } 1397 | ListNode ans = null; 1398 | while (!stack1.isEmpty() && !stack2.isEmpty()) { 1399 | if(stack1.peek().val == stack2.peek().val) { 1400 | ans = stack1.peek(); 1401 | stack1.pop(); 1402 | stack2.pop(); 1403 | } else { 1404 | break; 1405 | } 1406 | } 1407 | return ans; 1408 | } 1409 | ~~~ 1410 | ### 方法二:先去判断两个链表的长度,移动其中一个链表的头节点,使其两个链表的长度一样,最后从两个链表的头部开始遍历,找到第一个重合点即可。 1411 | ~~~ java 1412 | public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { 1413 | int len1 = 0; 1414 | int len2 = 0; 1415 | ListNode removeNode1 = pHead1; 1416 | ListNode removeNode2 = pHead2; 1417 | while (removeNode1 != null) { 1418 | len1++; 1419 | removeNode1 = removeNode1.next; 1420 | } 1421 | while (removeNode2 != null) { 1422 | len2++; 1423 | removeNode2 = removeNode2.next; 1424 | } 1425 | 1426 | // 下面的两个判断就是是的两个链表的length相同 1427 | if (len1 > len2) { 1428 | for (int i = 1; i <= len1 - len2; i++) { 1429 | pHead1 = pHead1.next; 1430 | } 1431 | } else if (len2 > len1) { 1432 | for (int i = 1; i <= len2 - len1; i++) { 1433 | pHead2 = pHead2.next; 1434 | } 1435 | } 1436 | ListNode ans = null; 1437 | while (pHead1 != null) { 1438 | if (pHead1.val ==pHead2.val) { 1439 | ans = pHead1; 1440 | break; 1441 | } 1442 | pHead1 = pHead1.next; 1443 | pHead2 = pHead2.next; 1444 | } 1445 | return ans; 1446 | } 1447 | ~~~ 1448 | ## 数字在排序数组中出现的次数 1449 | ### 方法一:根据二分查找找到数字K的起始位置和终止位置即可 1450 | ~~~ java 1451 | private int findFirstPosition(int[] array, int k) { 1452 | int l = 0; 1453 | int r = array.length - 1; 1454 | while (l < r) { 1455 | int mid = (l + r) >> 1; 1456 | if (array[mid] == k) { 1457 | if(mid - 1 >= 0 && array[mid - 1] == k) { 1458 | // 说明mid当前的位置不是初始位置,k的初始位置是在l~mid-1区间 1459 | r = mid - 1; 1460 | } else { 1461 | // 就可以说明mid位置的数字就是k的初始位置 1462 | return mid; 1463 | } 1464 | } else if (array[mid] > k) { 1465 | r = mid - 1; // k是属于l~mid-1区间 1466 | } else { 1467 | l = mid + 1; // k是属于mid+1~r区间 1468 | } 1469 | } 1470 | return l; 1471 | } 1472 | 1473 | private int findLastPosition(int[] array, int k) { 1474 | int l = 0; 1475 | int r = array.length - 1; 1476 | while (l < r) { 1477 | int mid = (l + r) >> 1; 1478 | if (array[mid] == k) { 1479 | if(mid + 1 < array.length && array[mid + 1] == k) { 1480 | // 说明mid当前的位置不是终止位置,k的初始位置是在mid+1~r区间 1481 | l = mid + 1; 1482 | } else { 1483 | // 就可以说明mid位置的数字就是k的终止位置 1484 | return mid; 1485 | } 1486 | } else if (array[mid] > k) { 1487 | r = mid - 1; // k是属于l~mid-1区间 1488 | } else { 1489 | l = mid + 1; // k是属于mid+1~r区间 1490 | } 1491 | } 1492 | return l; 1493 | } 1494 | 1495 | public int GetNumberOfK(int [] array , int k) { 1496 | if (array.length == 0) { 1497 | return 0; 1498 | } 1499 | int firstPosition = findFirstPosition(array, k); 1500 | int lastPosition = findLastPosition(array, k); 1501 | if (array[firstPosition] != k) { 1502 | return 0; 1503 | } 1504 | return lastPosition - firstPosition + 1; 1505 | } 1506 | ~~~ 1507 | ## 二叉树的深度 1508 | ### 方法一:通过递归去求解从每一个节点的左右孩子节点的出发到叶子节点的节点个数,去推断出当前节点到叶子节点的节点个数 1509 | ~~~ java 1510 | public int TreeDepth(TreeNode node) { 1511 | if (node == null) { 1512 | return 0; 1513 | } 1514 | return Math.max(TreeDepth(node.left), TreeDepth(node.right)) + 1; // + 1就是当前node对路径产生的影响 1515 | } 1516 | ~~~ 1517 | ## 平衡二叉树 1518 | ### 方法一:判断二叉树中的每一个节点的左右孩子的高度差的绝对值是否大于1即可 1519 | ~~~ java 1520 | private boolean ans; 1521 | public boolean IsBalanced_Solution(TreeNode root) { 1522 | if (root == null) { 1523 | return true; 1524 | } 1525 | ans = true; 1526 | TreeDepth(root); 1527 | return ans; 1528 | } 1529 | 1530 | private int TreeDepth(TreeNode node) { 1531 | if (node == null) { 1532 | return 0; 1533 | } 1534 | if (ans) { // 剪枝操作 1535 | int leftDepth = TreeDepth(node.left); // 求出当前节点的左子树的高度 1536 | int rightDepth = TreeDepth(node.right); // 求出当前节点的右子树的高度 1537 | if (Math.abs(leftDepth - rightDepth) > 1) { 1538 | ans = false; 1539 | } 1540 | return Math.max(leftDepth, rightDepth) + 1; 1541 | } 1542 | return 0; // 这个地方返回什么已经不重要了,因为我们已经找一个节点不满足条件了 1543 | } 1544 | ~~~ 1545 | ## 数组中只出现过一次的数字 1546 | ### 方法一:通过对原数组中的所有数字异或运算之后,找到划分出只出现过一次的数字的方式,然后在对剩余数组也采取相同的划分方式,对于划分的两个子序列,进行异或运算即可 1547 | ~~~ java 1548 | public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { 1549 | if (array.length != 0) { 1550 | int ans = 0; 1551 | // 通过第一个循环找到那两个出现过一次的数字的异或结果 1552 | for (int x : array) { 1553 | ans ^= x; 1554 | } 1555 | // 根据这个异或结果去找到分割出这两个数字的方式->从右往左找到第一个位置不为0的地方 1556 | int lastNumberOfOne = find(ans); 1557 | num1[0] = 0; 1558 | num2[0] = 0; 1559 | for (int x : array) { 1560 | if (judge(x, lastNumberOfOne) == 0) { 1561 | num1[0] ^= x; 1562 | } else { 1563 | num2[0] ^= x; 1564 | } 1565 | } 1566 | } 1567 | } 1568 | 1569 | // 判断x的从右往左看,第lastNumberOfOne位是否为1 1570 | private int judge(int x, int lastNumberOfOne) { 1571 | x >>= (lastNumberOfOne - 1); // 将x的第lastNumberOfOne位移到最右边 1572 | return x & 1; 1573 | } 1574 | 1575 | private int find(int ans) { 1576 | int sum = 1; 1577 | int res = 1; 1578 | while ((ans & res) == 0) { 1579 | sum++; 1580 | res <<= 1; 1581 | } 1582 | return sum; 1583 | } 1584 | ~~~ 1585 | ## 和为S的两个数字 1586 | ### 方法一:通过设置两个所有指针去查找和为S的两个数字,对于当前l和r指针指向的两个数字和而言,如果说小于S,那就往右移动L指针,如果说大于S,那就往左移动R指针。 1587 | ~~~ java 1588 | public ArrayList FindNumbersWithSum(int [] array, int sum) { 1589 | ArrayList list = new ArrayList<>(); 1590 | int l = 0; 1591 | int r = array.length - 1; 1592 | 1593 | while (l <= r - 1) { 1594 | if (array[l] + array[r] == sum) { 1595 | list.add(array[l]); 1596 | list.add(array[r]); 1597 | break; 1598 | } else if (array[l] + array[r] < sum) { 1599 | l++; 1600 | } else { 1601 | r--; 1602 | } 1603 | } 1604 | return list; 1605 | } 1606 | ~~~ 1607 | ## 和为S的连续正数序列 1608 | ### 方法一:通过区动态的移动滑动窗口的左右区间的端点位置,找出所有连续序列数字之和等于S的情况。 1609 | ~~~ java 1610 | public ArrayList > FindContinuousSequence(int sum) { 1611 | ArrayList> ans = new ArrayList<>(); 1612 | int l = 1; 1613 | int r = 2; 1614 | ArrayList list = new ArrayList<>(); 1615 | list.add(1); 1616 | list.add(2); 1617 | while (l < (sum + 1) / 2) { 1618 | int tempSum = cul(l, r); 1619 | while (tempSum > sum) { 1620 | tempSum -= l; 1621 | l++; 1622 | list.remove(0); 1623 | } 1624 | if (tempSum == sum) { 1625 | ans.add(new ArrayList<>(list)); 1626 | l++; 1627 | list.remove(0); 1628 | } 1629 | r++; 1630 | list.add(r); 1631 | } 1632 | return ans; 1633 | } 1634 | 1635 | private int cul(int l, int r) { 1636 | return (l + r) * (r - l + 1) / 2; 1637 | } 1638 | ~~~ 1639 | ### 方法二:通过等差数列的求和公式去得出第一项和项数以及S的关系,通过去枚举第一项,然后算出项数n,判断n是否为整数即可 1640 | ~~~ java 1641 | public ArrayList > FindContinuousSequence(int sum) { 1642 | ArrayList> ans = new ArrayList<>(); 1643 | for (int i = 1; i <= sum; i++) { 1644 | int x = 2 * i - 1; 1645 | double temp = Math.sqrt(x * x + 8 * sum); 1646 | if (judge(temp)) { 1647 | int res = (int) temp; 1648 | double n1 = (double) (-x + res) / 2; 1649 | double n2 = (double) (-x - res) / 2; 1650 | if (judge(n1) && n1 > 1) { 1651 | ArrayList list = new ArrayList<>(); 1652 | for (int j = i, k = 1; k <= n1; j++, k++) { 1653 | list.add(j); 1654 | } 1655 | ans.add(list); 1656 | } 1657 | if (judge(n2) && n2 > 1) { 1658 | ArrayList list = new ArrayList<>(); 1659 | for (int j = i, k = 1; k <= n2; j++, k++) { 1660 | list.add(j); 1661 | } 1662 | ans.add(list); 1663 | } 1664 | } 1665 | } 1666 | return ans; 1667 | } 1668 | 1669 | private boolean judge(double x) { 1670 | int res = (int) x; 1671 | return x - res <= 0.00000001; 1672 | } 1673 | ~~~ 1674 | ## 翻转单词序列 1675 | ### 方法一:通过两次翻转,第一次翻转使得每一个单词处于最终的位置,第二次翻转为了消除第一次翻转的时候对每一个单词产生的影响。 1676 | ~~~ java 1677 | public String ReverseSentence(String str) { 1678 | String flipStr = new StringBuilder(str).reverse().toString(); // 第一次翻转 1679 | StringBuilder res = new StringBuilder(); // 用来遍历每一个单词 1680 | StringBuilder ans = new StringBuilder(); // 用来保存结果 1681 | for (int i = 0; i < flipStr.length(); i++) { 1682 | if (flipStr.charAt(i) == ' ') { 1683 | ans.append(res.reverse().toString()).append(" "); // 第二次翻转 1684 | res = new StringBuilder(); 1685 | } else { 1686 | res.append(flipStr.charAt(i)); 1687 | } 1688 | } 1689 | ans.append(res.reverse().toString()); // 最后那个单词的翻转结果保存到ans当中 1690 | return ans.toString(); 1691 | } 1692 | ~~~ 1693 | ## 左旋转字符串 1694 | ### 方法一:通过两次翻转,第一次翻转使得两个子序列处于最终的位置,第二次翻转为了消除第一次翻转的时候对每一个子序列产生的影响。 1695 | ~~~ java 1696 | public String LeftRotateString(String str,int n) { 1697 | if (str.length() == 0) { 1698 | return ""; 1699 | } 1700 | StringBuilder flipStr = new StringBuilder(str).reverse(); // 第一次翻转 1701 | String str1 = flipStr.substring(0, flipStr.length() - n); // 取出第一个子序列 1702 | String str2 = flipStr.substring(flipStr.length() - n); // 取出第二个子序列 1703 | return new StringBuilder(str1).reverse().append(new StringBuilder(str2).reverse()).toString(); // 第二次翻转 1704 | } 1705 | ~~~ 1706 | ## 扑克牌顺子 1707 | ### 方法一:先去统计出数组中0的个数,然后在对数组排序,最后判断数组中相邻两个位置之间是否需要0填充以及0的个数是否够用即可。 1708 | ~~~ java 1709 | public boolean isContinuous(int [] numbers) { 1710 | if (numbers.length == 0) { 1711 | return false; 1712 | } 1713 | int sum = 0; 1714 | for (int x : numbers) { 1715 | if (x == 0) { 1716 | sum++; 1717 | } 1718 | } 1719 | Arrays.sort(numbers); 1720 | for (int i = sum + 1; i < numbers.length; i++) { 1721 | sum -= numbers[i] - numbers[i - 1] - 1; 1722 | if (sum < 0 || numbers[i] == numbers[i - 1]) { 1723 | return false; 1724 | } 1725 | } 1726 | return true; 1727 | } 1728 | ~~~ 1729 | ## 孩子们的游戏(圆圈中最后剩下的数) 1730 | ### 方法一:模拟每一个学生的被移除的过程,通过一个vis数组来去标记已经移除过的学生的位置。 1731 | ~~~ java 1732 | public static int LastRemaining_Solution(int n, int m) { 1733 | if (n == 0 || m == 0) { 1734 | return -1; 1735 | } 1736 | boolean[] vis = new boolean[n]; // vis[i] = true代表第i个小朋友移除圆桌 1737 | int sum = 0; // 用来记录当前已经移除的人数总和 1738 | int res = 0; // 用来记录某一次循环的过程中已经计数人数的个数 1739 | int index = 0; 1740 | while (sum < n - 1) { 1741 | res = 0; 1742 | // 在某一次循环中,让index处于没有被移除的学生位置 1743 | while (vis[index]) { 1744 | index = (index + 1) % n; 1745 | } 1746 | // 模拟找第m个位置的学生 1747 | while (res < m) { 1748 | if(!vis[index]) { 1749 | res++; 1750 | } 1751 | index = (index + 1) % n; 1752 | } 1753 | vis[(index + n - 1) % n] = true; // 标记当前循环移除的学生位置的下标 1754 | sum++; 1755 | } 1756 | // 在返回结果时,让index处于没有被移除的学生位置 1757 | while (vis[index]) { 1758 | index = (index + 1) % n; 1759 | } 1760 | return index; 1761 | } 1762 | ~~~ 1763 | ### 方法二:通过公式的推导可以推导出:f(n, m) = (f(n-1, m) + m) % n 1764 | ~~~ java 1765 | public int LastRemaining_Solution(int n, int m) { 1766 | if (n == 0 || m == 0) { 1767 | return -1; 1768 | } 1769 | int ans = 0; 1770 | for (int i = 2; i <= n; i++) { 1771 | ans = (ans + m) % i; 1772 | } 1773 | return ans; 1774 | } 1775 | ~~~ 1776 | ## 求1+2+3+4+...+n 1777 | ### 方法一:采用递归地方式,去求出等差数列的前n项和,只不过递归终止的条件是通过&&原酸来去写的 1778 | ~~~ java 1779 | public int Sum_Solution(int n) { 1780 | int sum = n; 1781 | boolean flag = (n > 0) && (sum += Sum_Solution(n - 1)) > 0; 1782 | return sum; 1783 | } 1784 | ~~~ 1785 | ## 不用加减乘除做加法 1786 | ### 方法一:将两个数字象加分为两个步骤:第一步统计两个数字每一位的相加结果(不计算进位情况), 第二步计算两个数字的进位结果,然后把这两步的结果在进行前面所说的两步操作,直到进位结果为0即可 1787 | ~~~ java 1788 | public int Add(int num1,int num2) { 1789 | int sum1, sum2; 1790 | do{ 1791 | sum1 = num1 ^ num2; 1792 | sum2 = (num1 & num2) << 1; 1793 | num1 = sum1; 1794 | num2 = sum2; 1795 | }while (num2 != 0); 1796 | return num1; 1797 | } 1798 | ~~~ 1799 | ## 把字符串转换成整数 1800 | ### 方法一:先删除掉最左侧的空格,然后在判断最终结果的正负性,接着遍历字符,看是否合法,如果不合法,返回0,反之继续遍历,知道遍历到字符串的结尾。 1801 | ~~~ java 1802 | public static int StrToInt(String str) { 1803 | int len = str.length(); 1804 | int index = 0; 1805 | // 第一步,删除前面的空格 1806 | while (index < len) { 1807 | if (str.charAt(index) == ' ') { 1808 | index++; 1809 | } else { 1810 | break; 1811 | } 1812 | } 1813 | int flag = 0; 1814 | long ans = 0; // 最终返回的结果 1815 | boolean flag1 = false; 1816 | while (index < len) { 1817 | // "3-2" 1818 | if (!flag1 && (str.charAt(index) == '-' || str.charAt(index) == '+')) { 1819 | if (flag != 0) { 1820 | return 0; // "-123-3", 第二个-号是非法字符, 返回0 1821 | } 1822 | flag = str.charAt(index) == '-' ? -1 : 1; 1823 | } else if (str.charAt(index) >= '0' && str.charAt(index) <= '9') { 1824 | flag1 =true; 1825 | ans = ans * 10 + str.charAt(index ) -'0'; // "-123" 1826 | if (judge(ans, flag)) { // 对ans是否溢出int类型做下判断 1827 | return 0; 1828 | } 1829 | } else { 1830 | return 0; // 既不是数字,也不是正负号,那就是其他字符了,返回0 1831 | } 1832 | index++; 1833 | } 1834 | return flag == -1 ? (int) ans * (-1) : (int) ans; 1835 | } 1836 | 1837 | private static boolean judge(long ans, int flag) { 1838 | if (flag == -1) { 1839 | if (ans * (-1) < Integer.MIN_VALUE) { 1840 | return true; 1841 | } 1842 | return false; 1843 | } else { 1844 | if (ans > Integer.MAX_VALUE) { 1845 | return true; 1846 | } 1847 | return false; 1848 | } 1849 | } 1850 | ~~~ 1851 | ## 数组中重复的数字 1852 | ### 方法一:通过维护 nums[nums[i]] = nums[i]这个关系式,在对当前位置的数字进行遍历时,判断当前位置的数字是否满足前面的不等式,如果满足,说明当前的数字存在的次数超过1次(只有前面的维护过程中才能使得当前的数字满足等式)。 1853 | ~~~ java 1854 | public static int findRepeatNumber(int[] nums) { 1855 | int ans = -1; 1856 | for (int i = 0; i < nums.length; i++) { 1857 | if (nums[i] == i) { 1858 | continue; // 不需要去维护index和index对应的值相等的关系 1859 | } 1860 | if (nums[nums[i]] == nums[i]) { 1861 | ans = nums[i]; 1862 | break; 1863 | } 1864 | // 下面的三行是交换两个数字,目的是为了维护 nums[nums[i]] = nums[i] 1865 | int temp = nums[i]; 1866 | nums[i] = nums[nums[i]]; 1867 | nums[temp] = temp; 1868 | } 1869 | return ans; 1870 | } 1871 | ~~~ 1872 | ## 构造乘积数组 1873 | ### 方法一:通过维护前i项积和后i项积这两个数组即可。 1874 | ~~~ java 1875 | public static int[] multiply(int[] A) { 1876 | int[] f1 = new int[A.length]; // 0到i-1的乘积 1877 | int[] f2 = new int[A.length]; // i+1到n-1的乘积 1878 | 1879 | int ans1 = 1; // 0-(i-1)的乘积 1880 | int ans2 = 1; // (i+1)-n-1的乘积 1881 | for (int i = 0, j = A.length - 1; i < A.length; i++, j--) { 1882 | f1[i] = ans1; 1883 | ans1 *= A[i]; 1884 | 1885 | f2[j] = ans2; 1886 | ans2 *= A[j]; 1887 | } 1888 | int[] B = new int[A.length]; 1889 | for (int i = 0; i < A.length; i++) { 1890 | B[i] = f1[i] * f2[i]; 1891 | } 1892 | return B; 1893 | } 1894 | ~~~ 1895 | ## 正则表达式匹配 1896 | ### 方法一:通过深搜的方式去匹配两个字符串,主要是对*字符的讨论,通过深搜的方式去模拟*号前面的字符出现的次数。 1897 | ~~~ java 1898 | public static boolean isMatch(String s, String p) { 1899 | return solve(s, p, 0, 0); 1900 | } 1901 | 1902 | /** 1903 | * 字符串匹配 1904 | * @param s 字符串1 1905 | * @param p 字符串2 1906 | * @param index1 字符串1的下标 1907 | * @param index2 字符串2的下标 1908 | * @return 当前s和p的匹配结果 1909 | */ 1910 | private static boolean solve(String s, String p, int index1, int index2) { 1911 | 1912 | // 递归终止条件1 1913 | if (index1 == s.length() && (index2 == p.length() || (index2 + 1 == p.length() - 1 && p.charAt(index2 + 1) == '*'))) { 1914 | return true; 1915 | } 1916 | 1917 | // 递归终止条件2 1918 | if (index1 == s.length() || p.length() == index2) { 1919 | if (index1 == s.length()) { 1920 | return change(p, index2); 1921 | } else { 1922 | return false; 1923 | } 1924 | } 1925 | 1926 | // p当前字符的下一个位置的字符时* 1927 | if(index2 + 1 < p.length() && p.charAt(index2 + 1) == '*') { 1928 | if(judge(s.charAt(index1), p.charAt(index2))) { 1929 | return solve(s, p, index1, index2 + 2) || solve(s, p, index1 + 1, index2); 1930 | } else { 1931 | return solve(s, p, index1, index2 + 2); 1932 | } 1933 | } 1934 | 1935 | // 当前两个下标所指的字符匹配 1936 | if (judge(s.charAt(index1), p.charAt(index2))) { 1937 | return solve(s, p, index1 + 1, index2 + 1); 1938 | } 1939 | 1940 | return false; // 当前的index1所指的字符与index2所指的字符不一致 1941 | } 1942 | 1943 | private static boolean change(String p, int index2) { 1944 | while (index2 < p.length()) { 1945 | if (index2 + 1 < p.length() && p.charAt(index2 + 1) == '*') { 1946 | index2 += 2; 1947 | } else { 1948 | return false; 1949 | } 1950 | } 1951 | return true; 1952 | } 1953 | 1954 | /** 1955 | * 1956 | * @param s1 字符1 1957 | * @param s2 字符2 1958 | * @return 两个字符是否匹配的结果 1959 | */ 1960 | private static boolean judge(char s1, char s2) { 1961 | if (s1 == s2 || s2 == '.') { 1962 | return true; 1963 | } 1964 | return false; 1965 | } 1966 | public static boolean match(char[] str, char[] pattern) { 1967 | StringBuilder s1 = new StringBuilder(); 1968 | StringBuilder s2 = new StringBuilder(); 1969 | 1970 | for (char x : str) { 1971 | s1.append(x); 1972 | } 1973 | for (char x : pattern) { 1974 | s2.append(x); 1975 | } 1976 | return solve(s1.toString(), s2.toString(), 0, 0); 1977 | } 1978 | ~~~ 1979 | ## 表示数值的字符串 1980 | ### 方法一:通过调用Double类的转换成Double类型的方法,判断转换的过程当中是否抛出异常即可。 1981 | ~~~ java 1982 | public boolean isNumber(String s) { 1983 | if (s.endsWith("f") || s.endsWith("d") || s.endsWith("F") || s.endsWith("D")) { 1984 | return false; 1985 | } 1986 | try { 1987 | Double.parseDouble(s); 1988 | } catch (Exception e) { 1989 | return false; 1990 | } 1991 | return true; 1992 | } 1993 | ~~~ 1994 | ## 字符流中第一个不重复的字符 1995 | ### 方法一:由于字符流是不固定的,所以可以通过一个Map结构来去保存每一个字符出现的次数即可。 1996 | ~~~ java 1997 | private Map map = new HashMap<>(); // 保存每个字符出现的次数 1998 | private StringBuilder str = new StringBuilder(); // 保存字符流 1999 | private int index = 0; // 用来保存字符只出现一次的第一个位置 2000 | 2001 | //Insert one char from stringstream 2002 | public void Insert(char ch) 2003 | { 2004 | str.append(ch); 2005 | map.put(ch, map.getOrDefault(ch, 0) + 1); 2006 | } 2007 | //return the first appearence once char in current stringstream 2008 | public char FirstAppearingOnce() 2009 | { 2010 | while (index < str.length()) { 2011 | if (map.get(str.charAt(index)) == 1) { 2012 | return str.charAt(index); 2013 | } 2014 | index++; 2015 | } 2016 | return '#'; 2017 | } 2018 | ~~~ 2019 | ## 链表中环的入口结点 2020 | ### 方法一:通过Map结构保存链表中每个节点出现的次数,第一次出现两次的节点就是我们所要找的环的入口结点,如果没有找到,返回null 2021 | ~~~ java 2022 | public ListNode EntryNodeOfLoop(ListNode pHead) 2023 | { 2024 | Map map = new HashMap<>(); 2025 | ListNode node = pHead; 2026 | while (node != null) { 2027 | map.put(node, map.getOrDefault(node, 0) + 1); 2028 | if (map.get(node) == 2) { 2029 | return node; 2030 | } 2031 | node = node.next; 2032 | } 2033 | return null; 2034 | } 2035 | ~~~ 2036 | ## 删除链表中重复的节点 2037 | ### 方法一:首先判断出最终的链表的头节点,然后从头节点开始到链表的尾部节点这段区间内的节点元素,判断每一个节点是否满足非重复的的条件,如果满足,则将该节点采用尾接法的方式去添加到最终挂你的链表中去。 2038 | ~~~ java 2039 | private ListNode change(ListNode x) { 2040 | int temp = x.val; 2041 | while (x != null && x.val == temp) { 2042 | x = x.next; 2043 | } 2044 | return x; 2045 | } 2046 | public ListNode deleteDuplication(ListNode pHead) { 2047 | ListNode ans = pHead; // 最终链表的头节点 2048 | // 确定最终链表的头节点 2049 | while (ans != null) { 2050 | if (ans.next != null && ans.val == ans.next.val) { 2051 | // 当前ans所指的节点是重复节点 2052 | ans = change(ans); 2053 | } else { 2054 | // 当前ans所指的节点就是我们最终链表的头节点 2055 | break; 2056 | } 2057 | } 2058 | if (ans == null) { 2059 | return null; 2060 | } 2061 | // 判断从ans到链表的尾部,判断每一个节点是否为重复节点。 2062 | ListNode lastNode = ans; // 最终链表的尾部节点 2063 | ListNode removeNode = lastNode.next; // 遍历剩余的节点的变量 2064 | while (removeNode != null) { 2065 | if (removeNode.next != null && removeNode.val == removeNode.next.val) { 2066 | // 当前removeNode所指的节点是重复节点 2067 | removeNode = change(removeNode); 2068 | } else { 2069 | lastNode.next = removeNode; 2070 | lastNode = removeNode; 2071 | removeNode = removeNode.next; 2072 | } 2073 | } 2074 | lastNode.next = null; // 1 -> 2 -> 3 -> 4 -> 4 2075 | return ans; 2076 | } 2077 | ~~~ 2078 | ## 二叉树中的下一个节点 2079 | ### 方法一:主要是分为三种情况,第一种情况就是pNode节点有右孩子时,那么pNode的下一个节点就是右孩子对应的那颗子树的最左侧的节点;如果说当前节点的右孩子为空,并且pNode是pNode父亲节点的左孩子,那么直接返回pNode的父亲节点即可;如果说当前节点的右孩子为空,并且pNode是pNode父亲节点的右孩子那么就返回pNode节点的爷爷节点。当然还有些特殊情况,比如说:二叉树的最右侧节点的判断,以及父亲节点是否为空的判断。 2080 | ~~~ java 2081 | public TreeLinkNode GetNext(TreeLinkNode pNode) { 2082 | if (pNode.right != null) { 2083 | // 第一种情况,pNode节点的右孩子不为空 2084 | pNode = pNode.right; 2085 | while (pNode.left != null) { 2086 | pNode = pNode.left; 2087 | } 2088 | return pNode; 2089 | } else { 2090 | TreeLinkNode tempNode = pNode.next; 2091 | if (tempNode == null) { 2092 | return null; 2093 | } 2094 | if (tempNode.left == pNode) { 2095 | // 第二种情况,当前节点右孩子为空,并且当前节点是父亲节点的左孩子 2096 | return tempNode; 2097 | } else { 2098 | // 第二种情况,当前节点右孩子为空,并且当前节点是父亲节点的右孩子 2099 | boolean flag = false; 2100 | while (tempNode.next != null) { 2101 | if (tempNode.next.left == tempNode) { 2102 | flag = true; 2103 | break; 2104 | } 2105 | tempNode = tempNode.next; 2106 | } 2107 | return flag ? tempNode.next : null; // flag尾true时,说明pNode所指的节点不是二叉树中最右侧节点 2108 | } 2109 | } 2110 | } 2111 | ~~~ 2112 | ## 对称的二叉树 2113 | ### 方法一:通过定义连个变量去遍历root节点对应的两个子树种的对应位置的节点是否相同即可。 2114 | ~~~ java 2115 | public boolean isSymmetrical(TreeNode pRoot) { 2116 | if (pRoot == null) { 2117 | return true; 2118 | } 2119 | return solve(pRoot.left, pRoot.right); 2120 | } 2121 | 2122 | private boolean solve(TreeNode node1, TreeNode node2) { 2123 | if (node1 == null && node2 == null) { 2124 | return true; 2125 | } 2126 | if (node1 == null || node2 == null) { 2127 | return false; 2128 | } 2129 | if (node1.val != node2.val) { 2130 | return false; 2131 | } 2132 | return solve(node1.left, node2.right) && solve(node1.right, node2.left); 2133 | } 2134 | ~~~ 2135 | ## 按之字形顺序打印二叉树 2136 | ### 方法一:按照宽搜的方式对二叉树进行遍历,只需要判断出每一个节点属于第几层即可,然后把每一层节点封装成一个数组,然后在判断当前层是否为偶数层,再决定是否对封装好的数组进行转置的操作 2137 | ~~~ java 2138 | /*public int[] levelOrder(TreeNode root) { 2139 | Queue queue = new LinkedList<>(); 2140 | queue.add(root); 2141 | ArrayList list = new ArrayList<>(); 2142 | while (!queue.isEmpty() && root != null) { 2143 | TreeNode node = queue.poll(); 2144 | list.add(node.val); 2145 | 2146 | if (node.left != null) { 2147 | queue.add(node.left); 2148 | } 2149 | if (node.right != null) { 2150 | queue.add(node.right); 2151 | } 2152 | } 2153 | int[] ans = new int[list.size()]; 2154 | int index = 0; 2155 | for (int x : list) { 2156 | ans[index++] = x; 2157 | } 2158 | return ans; 2159 | }*/ 2160 | 2161 | public List> levelOrder(TreeNode root) { 2162 | List> ans = new LinkedList<>(); 2163 | 2164 | Queue queue = new LinkedList<>(); 2165 | queue.add(root); 2166 | int sum = 1; // 用来保存每一层的节点的个数 2167 | int num = 1; 2168 | 2169 | while (!queue.isEmpty() && root != null) { 2170 | List list = new LinkedList<>(); 2171 | int temp = 0; 2172 | while (sum > 0) { 2173 | TreeNode node = queue.poll(); 2174 | assert node != null; 2175 | list.add(node.val); 2176 | if(node.left != null) { 2177 | temp++; 2178 | queue.add(node.left); 2179 | } 2180 | if (node.right != null) { 2181 | temp++; 2182 | queue.add(node.right); 2183 | } 2184 | sum--; 2185 | } 2186 | sum = temp; 2187 | if(num % 2 == 0) { 2188 | for (int i = 0, j = list.size() - 1; i < j; i++, j--) { 2189 | int res = list.get(i); 2190 | list.set(i, list.get(j)); 2191 | list.set(j, res); 2192 | } 2193 | } 2194 | num++; 2195 | ans.add(list); 2196 | } 2197 | return ans; 2198 | } 2199 | ~~~ 2200 | ## 把二叉树打印成多行 2201 | ### 方法一:见上道题 2202 | ~~~ java 2203 | ArrayList> Print(TreeNode root) { 2204 | ArrayList> ans = new ArrayList<>(); 2205 | 2206 | Queue queue = new LinkedList<>(); 2207 | queue.add(root); 2208 | int sum = 1; // 用来保存每一层的节点的个数 2209 | 2210 | while (!queue.isEmpty() && root != null) { 2211 | ArrayList list = new ArrayList<>(); 2212 | int temp = 0; 2213 | while (sum > 0) { 2214 | TreeNode node = queue.poll(); 2215 | assert node != null; 2216 | list.add(node.val); 2217 | if (node.left != null) { 2218 | temp++; 2219 | queue.add(node.left); 2220 | } 2221 | if (node.right != null) { 2222 | temp++; 2223 | queue.add(node.right); 2224 | } 2225 | sum--; 2226 | } 2227 | sum = temp; 2228 | ans.add(list); 2229 | } 2230 | return ans; 2231 | } 2232 | ~~~ 2233 | ## 序列化二叉树 2234 | ### 方法一:序列化操作是通过对二叉树宽搜,如果当前节点是null的话,然后判断当前节点的后面的节点当中是否有非空节点,如果有,就将null写入序列胡结果,反置不写入。反序列化操作也是采用宽搜的方式,对于最终的二叉树的节点逐个的去创建。 2235 | ~~~ java 2236 | public static String serialize(TreeNode root) { 2237 | StringBuilder ans = new StringBuilder("["); 2238 | Queue queue = new LinkedList<>(); 2239 | queue.add(root); 2240 | int sum = 1; // 用来记录当前节点及其后面非空节点的个数 2241 | while (!queue.isEmpty() && root != null) { 2242 | TreeNode node = queue.poll(); 2243 | if (node == null) { 2244 | ans.append("null"); 2245 | } else { 2246 | ans.append(node.val); 2247 | sum--; 2248 | if (node.left != null) { 2249 | sum++; 2250 | } 2251 | if (node.right != null) { 2252 | sum++; 2253 | } 2254 | queue.add(node.left); 2255 | queue.add(node.right); 2256 | } 2257 | if (sum != 0) { 2258 | ans.append(","); 2259 | } else { 2260 | break; 2261 | } 2262 | } 2263 | ans.append("]"); 2264 | return ans.toString(); 2265 | } 2266 | 2267 | // Decodes your encoded data to tree. 2268 | public static TreeNode deserialize(String data) { 2269 | String s = data.substring(1, data.length() - 1); 2270 | if ("".equals(s)) { 2271 | return null; // data = "[]" 2272 | } 2273 | String[] a = s.split(","); 2274 | int index = 0; 2275 | Queue queue = new LinkedList<>(); 2276 | TreeNode root = new TreeNode(change(a[index++])); 2277 | queue.add(root); 2278 | while (!queue.isEmpty() && index < a.length) { 2279 | TreeNode node = queue.poll(); 2280 | if (!"null".equals(a[index])) { 2281 | node.left = new TreeNode(change(a[index++])); 2282 | queue.add(node.left); 2283 | } else { 2284 | index++; 2285 | } 2286 | if (index < a.length && !"null".equals(a[index])) { 2287 | node.right = new TreeNode(change(a[index++])); 2288 | queue.add(node.right); 2289 | } else { 2290 | index++; 2291 | } 2292 | } 2293 | return root; 2294 | } 2295 | 2296 | private static int change(String s) { 2297 | int res = 0; 2298 | int i = 0; 2299 | int flag = 1; 2300 | if (s.charAt(0) == '-') { 2301 | i++; 2302 | flag = -1; 2303 | } 2304 | for (; i < s.length(); i++) { 2305 | res = res * 10 + s.charAt(i) - '0'; 2306 | } 2307 | return res * flag; 2308 | } 2309 | 2310 | ~~~ 2311 | ## 二叉搜索树的第k个节点 2312 | ### 方法一:通过对二叉搜索树的一个中序遍历即可,在遍历节点的过程中,判断当前遍历的节点是否为第k个节点就行了 2313 | ~~~ java 2314 | private TreeNode ans; 2315 | private int index; 2316 | 2317 | public TreeNode KthNode(TreeNode pRoot, int k) { 2318 | index = 1; 2319 | ans = null; 2320 | if (k != 0 && pRoot != null) { 2321 | solve(pRoot, k); 2322 | } 2323 | return ans; 2324 | } 2325 | 2326 | private void solve(TreeNode node, int k) { 2327 | if (ans == null) { 2328 | if (node.left != null) { 2329 | solve(node.left, k); 2330 | } 2331 | if (index == k) { 2332 | ans = node; 2333 | } 2334 | index++; 2335 | if (node.right != null) { 2336 | solve(node.right, k); 2337 | } 2338 | } 2339 | } 2340 | ~~~ 2341 | ## 数据流中的中位数 2342 | ### 方法一:通过大顶堆和小顶堆来去维护当前数据流中的中位数 2343 | ~~~ java 2344 | private PriorityQueue queue1 = new PriorityQueue<>(((o1, o2) -> (o2 - o1))); // 中位数的左区间 > 大顶堆 2345 | private PriorityQueue queue2 = new PriorityQueue<>(); // 中位数的右区间 > 小顶堆 2346 | private int sum = 0; // 数据流中个数 2347 | 2348 | public void Insert(Integer num) { 2349 | if (sum % 2 == 0) { 2350 | // 当两个堆的元素个数一样的时候,此时新增一个元素,放入大顶堆(左区间) 2351 | queue1.add(num); 2352 | } else { 2353 | queue2.add(num); 2354 | } 2355 | if(!queue2.isEmpty() && queue1.peek() > queue2.peek()) { 2356 | assert !queue1.isEmpty(); 2357 | int temp1 = queue1.poll(); 2358 | int temp2 = queue2.poll(); 2359 | queue1.add(temp2); 2360 | queue2.add(temp1); 2361 | } 2362 | sum++; 2363 | } 2364 | 2365 | public Double GetMedian() { 2366 | if (sum % 2 == 1) { 2367 | return (double) queue1.peek(); 2368 | } else { 2369 | return (queue1.peek() + queue2.peek()) / 2.0; 2370 | } 2371 | } 2372 | ~~~ 2373 | ## 滑动窗口的最大值 2374 | ### 方法一:通过记录之前保存的窗口中的最大值和最大值的下标来去更新当前窗口的最大值,分为两种情况,第一种情况:之前最大值还在当前数组中,那么就去比较当前区间的右端点和之前记录的最大值即可。第二种情况:之前保存的最大值不在当前区间,那么就从当前区间的左端点遍历到右端点在重新的找到一个最大值就行了 2375 | ~~~ java 2376 | public static ArrayList maxInWindows(int[] num, int size) { 2377 | ArrayList ans = new ArrayList<>(); 2378 | if (num.length == 0 || size == 0 || size > num.length) { 2379 | return ans; 2380 | } 2381 | 2382 | int Max = Integer.MIN_VALUE; 2383 | int pos = -1; 2384 | for (int i = 0; i < size; i++) { 2385 | if (num[i] > Max) { 2386 | Max = num[i]; 2387 | pos = i; 2388 | } 2389 | } 2390 | ans.add(Max); 2391 | for (int i = size; i <= num.length - 1; i++) { // i - > 窗口的右区间 2392 | if (i - size + 1 <= pos) { 2393 | if (num[i] > Max) { 2394 | Max = num[i]; 2395 | pos = i; 2396 | } 2397 | } else { 2398 | Max = Integer.MIN_VALUE; 2399 | for (int j = i - size + 1; j <= i; j++) { 2400 | if (num[j] > Max) { 2401 | Max = num[j]; 2402 | pos = j; 2403 | } 2404 | } 2405 | } 2406 | ans.add(Max); 2407 | } 2408 | return ans; 2409 | } 2410 | ~~~ 2411 | ## 矩阵中的路径 2412 | ### 方法一:深搜+回溯,深搜的过程其实就是对四个方向的一个递归调用的过程,回溯的话是为了消除某一次递归调用所产生的路径不能匹配模式串所产生的影响要被消除掉,消除的结果就是对这条路径上的每一个位置进行状态初始化,即标记为未被遍历 2413 | ~~~ java 2414 | public boolean exist(char[][] board, String word) { 2415 | boolean[][] vis = new boolean[board.length][board[0].length]; 2416 | for (int i = 0; i < board.length; i++) { 2417 | for (int j = 0; j < board[i].length; j++) { 2418 | if (solve(board, word, i, j, vis, 0)) { 2419 | // 找到一种情况即可 2420 | return true; 2421 | } 2422 | } 2423 | } 2424 | return false; 2425 | } 2426 | 2427 | private boolean solve(char[][] board, String word, int x, int y, boolean[][] vis, int index) { 2428 | // 越界处理以及每个方格只能访问一次 2429 | if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || vis[x][y]) { 2430 | return false; 2431 | } 2432 | // 匹配到某一位置不满足条件 2433 | if (word.charAt(index) != board[x][y]) { 2434 | return false; 2435 | } 2436 | // 匹配成功 2437 | if (index == word.length() - 1) { 2438 | return true; 2439 | } 2440 | 2441 | vis[x][y] = true; // x,y位置的标记 2442 | boolean flag = solve(board, word, x + 1, y, vis, index + 1) || 2443 | solve(board, word, x - 1, y, vis, index + 1) || 2444 | solve(board, word, x, y + 1, vis, index + 1) || 2445 | solve(board, word, x, y - 1, vis, index + 1); 2446 | vis[x][y] = false; // x,y位置的标记状态回溯 2447 | return flag; 2448 | } 2449 | ~~~ 2450 | ## 机器人的运动范围 2451 | ### 方法一:通过递归的去查找某一个下标位置的四个方向即可,在到达某一个位置的时候,判断是否越界,是否被访问过,是否满足数位之和小于k即可 2452 | ~~~ java 2453 | private int sum; 2454 | public int movingCount(int threshold, int rows, int cols) { 2455 | sum = 0; 2456 | boolean[][] vis = new boolean[rows][cols]; 2457 | solve(0, 0, rows, cols, vis, threshold); 2458 | return sum; 2459 | } 2460 | private int cul(int x, int y) { 2461 | int res = 0; 2462 | while (x != 0) { 2463 | res += x % 10; 2464 | x /= 10; 2465 | } 2466 | while (y != 0) { 2467 | res += y % 10; 2468 | y /= 10; 2469 | } 2470 | return res; 2471 | } 2472 | 2473 | private void solve(int x, int y, int rows, int cols, boolean[][] vis, int threshold) { 2474 | if (x < 0 || y < 0 || x >= rows || y >= cols || vis[x][y] || (cul(x, y) > threshold)) { 2475 | return; 2476 | } 2477 | 2478 | // 当前位置(x,y)是可以走的,那么就从当前位置往四个方向移动即可 2479 | vis[x][y] = true; 2480 | sum++; 2481 | solve(x + 1, y, rows, cols, vis, threshold); 2482 | solve(x - 1, y, rows, cols, vis, threshold); 2483 | solve(x, y + 1, rows, cols, vis, threshold); 2484 | solve(x, y - 1, rows, cols, vis, threshold); 2485 | } 2486 | ~~~ 2487 | ### 方法二:逐个遍历每一个放个,判断数位之和是否小于k,并且判断当前位置能否由上下左右四个方向走来即可 2488 | ~~~ java 2489 | private int movingCount(int m, int n, int k) { 2490 | int res = 1; 2491 | boolean[][] vis = new boolean[m][n]; 2492 | vis[0][0] = true; 2493 | for (int i = 0; i < m; i++) { 2494 | for (int j = 0; j < n; j++) { 2495 | if (cul(i, j) <= k) { 2496 | if (i - 1 >= 0 && vis[i - 1][j]) { 2497 | // 下 2498 | res++; 2499 | vis[i][j] = true; 2500 | } else if (i + 1 < m && vis[i + 1][j]) { 2501 | // 上 2502 | res++; 2503 | vis[i][j] = true; 2504 | } else if (j - 1 >= 0 && vis[i][j - 1]) { 2505 | // 左 2506 | res++; 2507 | vis[i][j] = true; 2508 | } else if (j + 1 < n && vis[i][j + 1]) { 2509 | // 右 2510 | res++; 2511 | vis[i][j] = true; 2512 | } 2513 | } 2514 | } 2515 | } 2516 | return res; 2517 | } 2518 | ~~~ 2519 | ## 剪绳子 2520 | ### 方法一:动态转移的方程为:dp[n] = dp[n - i] * dp[i],枚举i即可(1~n/2) 2521 | ~~~ java 2522 | public int cutRope(int n) { 2523 | int[] dp = new int[n + 1]; 2524 | if (n == 2) { 2525 | return 1; 2526 | } 2527 | if (n == 3) { 2528 | return 2; // 1 + 2 2529 | } 2530 | dp[1] = 1; 2531 | dp[2] = 2; 2532 | dp[3] = 3; // 1 + 2 2533 | for (int k = 1; k <= n; k++) { 2534 | for (int i = 1; i <= k / 2; i++) { 2535 | dp[k] = Math.max(dp[k], dp[i] * dp[k - i]); 2536 | } 2537 | } 2538 | return dp[n]; 2539 | } 2540 | ~~~ --------------------------------------------------------------------------------