list = new ArrayList<>();
41 | for (int i = 0; i < weight.length; i++) {
42 | weight[i][i] = 0;
43 | int val = getVal(graph, i);
44 | int x = getX(graph, i);
45 | int y = getY(graph, i);
46 | if (x == 0 || x == height - 1) {
47 | list.add(i);
48 | }
49 | if (y == 0 || y == width - 1) {
50 | list.add(i);
51 | }
52 | if (y < (width - 1) && i + 1 < total && getVal(graph, i + 1) <= val) {
53 | weight[i][i + 1] = 1;
54 | }
55 | if (y != 0 && i - 1 >= 0 && getVal(graph, i - 1) <= val) {
56 | weight[i][i - 1] = 1;
57 | }
58 | if (i + width < total && getVal(graph, i + width) <= val) {
59 | weight[i][i + width] = 1;
60 | }
61 | if (i - width >= 0 && getVal(graph, i - width) <= val) {
62 | weight[i][i - width] = 1;
63 | }
64 | }
65 |
66 | int start = startX * width + startY;
67 | int resultIndex = -1;
68 | int resultLen = 256;
69 | for (int i = 0; i < list.size(); i++) {
70 | if (getVal(graph, list.get(i)) <= start) {
71 | int len = resolve(start, list.get(i));
72 | if (len < resultLen) {
73 | resultLen = len;
74 | resultIndex = list.get(i);
75 | }
76 | }
77 | }
78 | if (resultLen >= 256) {
79 | System.out.print("-1 -1 -1");
80 | return;
81 | }
82 | System.out.print(resultIndex / graph.length + " " + resultIndex % graph.length + " " + resultLen);
83 | }
84 |
85 | public static int resolve(int start, int end) {
86 |
87 | if (start < 0 || end < 0 || start >= weight.length || end >= weight.length) {
88 | return MAX;
89 | }
90 |
91 | boolean[] isVisited = new boolean[weight.length];
92 | int[] d = new int[weight.length];
93 |
94 | for (int i = 0; i < weight.length; i++) {
95 | isVisited[i] = false;
96 | d[i] = MAX;
97 | }
98 | d[start] = 0;
99 | isVisited[start] = true;
100 | int unVisitedNum = weight.length;
101 | int index = start;
102 |
103 | while (unVisitedNum > 0 && index != end) {
104 | int min = MAX;
105 | for (int i = 0; i < weight.length; i++) {
106 | if (min > d[i] && !isVisited[i]) {
107 | min = d[i];
108 | index = i;
109 | }
110 | }
111 | for (int i = 0; i < weight.length; i++) {
112 | if (d[index] + weight[index][i] < d[i]) {
113 | d[i] = d[index] + weight[index][i];
114 | }
115 | }
116 | unVisitedNum--;
117 | isVisited[index] = true;
118 | }
119 |
120 | return d[end];
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/src/其他/阿拉伯数字转中文/Main.java:
--------------------------------------------------------------------------------
1 | package 其他.阿拉伯数字转中文;
2 |
3 | /**
4 | * @author yuanguangxin
5 | */
6 | public class Main {
7 | private static final char[] numArrays = {'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'};
8 | private static final char[] units = {'十', '百', '千', '万', '亿'};
9 | private static final StringBuilder ans = new StringBuilder();
10 |
11 | private static void intToChineseNum(int num) {
12 | String s = String.valueOf(num);
13 | char[] chars = s.toCharArray();
14 | int n = chars.length;
15 |
16 | // 只剩下一位时, 直接返回 numArrays 数组中对应的数字
17 | if (n == 1) {
18 | ans.append(numArrays[chars[0] - '0']);
19 | // 如果 num 超过 5 位, 则先判断是否上亿, 然后将 num 拆分
20 | } else if (n >= 5) {
21 | n = n >= 9 ? 9 : 5;
22 | int multi = (int) Math.pow(10, n - 1);
23 | // div 表示 num 中上亿或上万的部分数值
24 | int div = num / multi;
25 | // mod 表示剩余的部分数值
26 | int mod = num % multi;
27 | // 对前一部分数值进行转换, 然后添加单位万/亿
28 | intToChineseNum(div);
29 | ans.append(n == 5 ? units[3] : units[4]);
30 | String s1 = String.valueOf(div);
31 | String s2 = String.valueOf(mod);
32 | // 判断中间是否有 0
33 | if (s.charAt(s1.length() - 1) == '0' || s2.length() < n - 1) ans.append("零");
34 | // 转换剩余部分
35 | intToChineseNum(mod);
36 | // 如果 num 不超过 5 位, 处理过程与上面相似
37 | } else {
38 | int multi = (int) Math.pow(10, n - 1);
39 | int div = num / multi;
40 | int mod = num % multi;
41 | ans.append(numArrays[div]).append(units[n - 2]);
42 | if (mod != 0) {
43 | if (String.valueOf(mod).length() < n - 1) {
44 | ans.append("零");
45 | }
46 | intToChineseNum(mod);
47 | }
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/分治法/q23_合并K个排序链表/ListNode.java:
--------------------------------------------------------------------------------
1 | package 分治法.q23_合并K个排序链表;
2 |
3 | public class ListNode {
4 | int val;
5 | ListNode next;
6 |
7 | ListNode(int x) {
8 | val = x;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/分治法/q23_合并K个排序链表/Solution.java:
--------------------------------------------------------------------------------
1 | package 分治法.q23_合并K个排序链表;
2 |
3 | /**
4 | * 做k-1次mergeTwoLists o(N*k) 可用分治法优化至o(N*log(k))) N为所有list的总节点数
5 | */
6 | class Solution {
7 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
8 | if (l1 == null) {
9 | return l2;
10 | }
11 | if (l2 == null) {
12 | return l1;
13 | }
14 | ListNode head = new ListNode(Integer.MIN_VALUE);
15 | head.next = l1;
16 | ListNode pre = head;
17 | while (l2 != null) {
18 | ListNode t1 = pre.next;
19 | ListNode t2 = l2.next;
20 | while (l2.val > t1.val) {
21 | if (t1.next == null) {
22 | t1.next = l2;
23 | return head.next;
24 | } else {
25 | pre = pre.next;
26 | t1 = t1.next;
27 | }
28 | }
29 | pre.next = l2;
30 | l2.next = t1;
31 | l2 = t2;
32 | }
33 | return head.next;
34 | }
35 |
36 | public ListNode mergeKLists(ListNode[] lists) {
37 | if (lists.length == 0) {
38 | return null;
39 | }
40 | if (lists.length == 1) {
41 | return lists[0];
42 | }
43 | ListNode result = lists[0];
44 | for (int i = 1; i < lists.length; i++) {
45 | result = mergeTwoLists(result, lists[i]);
46 | }
47 | return result;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/分治法/q33_搜索旋转排序数组/Solution.java:
--------------------------------------------------------------------------------
1 | package 分治法.q33_搜索旋转排序数组;
2 |
3 | /**
4 | * 循环有序数组查找 二分法o(log(n))
5 | */
6 | class Solution {
7 | public int search(int[] nums, int target) {
8 | return search(nums, 0, nums.length - 1, target);
9 | }
10 |
11 | private int search(int[] nums, int low, int high, int target) {
12 | if (low > high) {
13 | return -1;
14 | }
15 | int mid = (low + high) / 2;
16 | if (nums[mid] == target) {
17 | return mid;
18 | }
19 | //nums[mid] < nums[high]说明后半段有序
20 | if (nums[mid] < nums[high]) {
21 | //说明target在后半段
22 | if (nums[mid] < target && target <= nums[high]) {
23 | return search(nums, mid + 1, high, target);
24 | }
25 | return search(nums, low, mid - 1, target);
26 | } else {
27 | //后半段无序前半段有序,target在前半段
28 | if (nums[low] <= target && target < nums[mid]) {
29 | return search(nums, low, mid - 1, target);
30 | }
31 | return search(nums, mid + 1, high, target);
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/src/分治法/q34_在排序数组中查找元素的第一个和最后一个位置/Solution.java:
--------------------------------------------------------------------------------
1 | package 分治法.q34_在排序数组中查找元素的第一个和最后一个位置;
2 |
3 | /**
4 | * 二分法 o(log(n))
5 | */
6 | public class Solution {
7 |
8 | public int[] searchRange(int[] nums, int target) {
9 | if (nums == null || nums.length < 1) {
10 | return new int[]{-1, -1};
11 | }
12 | int midIndex = find(0, nums.length - 1, nums, target);
13 | int[] rs = new int[2];
14 | rs[0] = midIndex;
15 | rs[1] = midIndex;
16 | if (midIndex == -1) {
17 | return rs;
18 | }
19 | while (nums[rs[0]] == target && rs[0] > 0) {
20 | int temp = find(0, rs[0] - 1, nums, target);
21 | if (temp == -1) {
22 | break;
23 | } else {
24 | rs[0] = temp;
25 | }
26 | }
27 |
28 | while (nums[rs[1]] == target && rs[1] < nums.length - 1) {
29 | int temp = find(rs[1] + 1, nums.length - 1, nums, target);
30 | if (temp == -1) {
31 | break;
32 | } else {
33 | rs[1] = temp;
34 | }
35 | }
36 | return rs;
37 | }
38 |
39 | public int find(int beginIndex, int endIndex, int[] nums, int target) {
40 | if (beginIndex == endIndex) {
41 | if (nums[beginIndex] == target) {
42 | return beginIndex;
43 | } else {
44 | return -1;
45 | }
46 | }
47 | int mid = (endIndex - beginIndex) / 2 + beginIndex;
48 | if (nums[mid] > target) {
49 | return find(beginIndex, mid, nums, target);
50 | } else if (nums[mid] < target) {
51 | return find(mid + 1, endIndex, nums, target);
52 | } else {
53 | return mid;
54 | }
55 | }
56 |
57 | public static void main(String[] args) {
58 | new Solution().searchRange(new int[]{2, 2}, 2);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/动态规划/q1143_最长公共子序列/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q1143_最长公共子序列;
2 |
3 | /**
4 | * 动态规划 dp[i + 1][j + 1] = Math.max(dp[i+1][j], dp[i][j+1]) o(m*n)
5 | *
6 | * 若题目为最长公共子串,则在c1,c2不相等时不做处理(赋值0),在遍历过程中记录最大值即可
7 | */
8 | public class Solution {
9 |
10 | public int longestCommonSubsequence(String text1, String text2) {
11 | int m = text1.length();
12 | int n = text2.length();
13 | int[][] dp = new int[m + 1][n + 1];
14 |
15 | for (int i = 0; i < m; i++) {
16 | for (int j = 0; j < n; j++) {
17 | char c1 = text1.charAt(i);
18 | char c2 = text2.charAt(j);
19 | if (c1 == c2) {
20 | dp[i + 1][j + 1] = dp[i][j] + 1;
21 | } else {
22 | dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]);
23 | }
24 | }
25 | }
26 | return dp[m][n];
27 | }
28 |
29 | /**
30 | * 最长公共字串
31 | *
32 | * @param str1
33 | * @param str2
34 | * @return
35 | */
36 | public static String longestCommonSubstring(String str1, String str2) {
37 | int m = str1.length();
38 | int n = str2.length();
39 | int[][] dp = new int[m + 1][n + 1];
40 | int maxLength = 0;
41 | int endIndex = -1;
42 |
43 | for (int i = 1; i <= m; i++) {
44 | for (int j = 1; j <= n; j++) {
45 | if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
46 | dp[i][j] = dp[i - 1][j - 1] + 1;
47 | if (dp[i][j] > maxLength) {
48 | maxLength = dp[i][j];
49 | endIndex = i - 1;
50 | }
51 | } else {
52 | dp[i][j] = 0;
53 | }
54 | }
55 | }
56 | if (maxLength == 0) {
57 | return "";
58 | }
59 | return str1.substring(endIndex - maxLength + 1, endIndex + 1);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/动态规划/q118_杨辉三角/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q118_杨辉三角;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * 找规律,动态规划 o(n^2)
8 | */
9 | public class Solution {
10 |
11 | public List> generate(int numRows) {
12 | List> triangle = new ArrayList>();
13 |
14 | if (numRows == 0) {
15 | return triangle;
16 | }
17 |
18 | triangle.add(new ArrayList<>());
19 | triangle.get(0).add(1);
20 |
21 | for (int rowNum = 1; rowNum < numRows; rowNum++) {
22 | List row = new ArrayList<>();
23 | List prevRow = triangle.get(rowNum-1);
24 | row.add(1);
25 |
26 | for (int j = 1; j < rowNum; j++) {
27 | row.add(prevRow.get(j-1) + prevRow.get(j));
28 | }
29 |
30 | row.add(1);
31 | triangle.add(row);
32 | }
33 | return triangle;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/动态规划/q1277_统计全为1的正方形子矩阵/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q1277_统计全为1的正方形子矩阵;
2 |
3 | /**
4 | * 动态规划 dp[i][j]表示 matrix[i][j] 这个点可以往左上构造的最大正方形的边长 o(n^2)
5 | */
6 | public class Solution {
7 | public int countSquares(int[][] matrix) {
8 | if (matrix.length < 1) {
9 | return 0;
10 | }
11 | int m = matrix.length;
12 | int n = matrix[0].length;
13 |
14 | int[][] dp = new int[m][n];
15 |
16 | int rs = 0;
17 | for (int i = 0; i < m; i++) {
18 | for (int j = 0; j < n; j++) {
19 | if (matrix[i][j] == 0) {
20 | dp[i][j] = 0;
21 | } else {
22 | if (i > 0 && j > 0) {
23 | dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
24 | } else {
25 | dp[i][j] = 1;
26 | }
27 | rs += dp[i][j];
28 | }
29 | }
30 | }
31 | return rs;
32 | }
33 |
34 | public static void main(String[] args) {
35 | new Solution().countSquares(new int[][]{{0, 1, 1, 1}, {1, 1, 1, 1}, {0, 1, 1, 1}});
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/动态规划/q300_最长上升子序列/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q300_最长上升子序列;
2 |
3 | /**
4 | * 动态规划 dp[i]表示以i索引下标结束的最长上升子序列 o(n*log(n))
5 | */
6 | public class Solution {
7 |
8 | public int lengthOfLIS(int[] nums) {
9 | if (nums == null || nums.length == 0) {
10 | return 0;
11 | }
12 |
13 | if (nums.length == 1) {
14 | return 1;
15 | }
16 |
17 | int n = nums.length;
18 | int[] dp = new int[n];
19 | int rs = 0;
20 |
21 | for (int i = 0; i < n; i++) {
22 | dp[i] = 1;
23 | int max = 0;
24 | for (int j = i - 1; j >= 0; j--) {
25 | if (nums[j] < nums[i] && dp[j] > max) {
26 | max = dp[j];
27 | }
28 | }
29 | dp[i] += max;
30 | if (dp[i] > rs) {
31 | rs = dp[i];
32 | }
33 | }
34 | return rs;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/动态规划/q53_最大子序和/f1/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q53_最大子序和.f1;
2 |
3 | /**
4 | * 贪心法 遍历一次 o(n)
5 | */
6 | public class Solution {
7 | public int maxSubArray(int[] nums) {
8 | if (nums.length == 1) {
9 | return nums[0];
10 | }
11 | int sum = nums[0];
12 | int temp = sum;
13 | for (int i = 1; i < nums.length; i++) {
14 | temp = temp + nums[i];
15 | if (temp >= sum) {
16 | sum = temp;
17 | } else if (temp < 0) {
18 | temp = 0;
19 | }
20 | if (nums[i] > sum) {
21 | temp = nums[i];
22 | sum = nums[i];
23 | }
24 | }
25 | return sum;
26 | }
27 |
28 | public static void main(String[] args) {
29 | System.out.println(new Solution().maxSubArray(new int[]{-1, 1, 2, 1}));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/动态规划/q53_最大子序和/f2/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q53_最大子序和.f2;
2 |
3 | /**
4 | * 动态规划 dp[i]表示以nums[i]结尾的最大子序和 o(n)
5 | */
6 | public class Solution {
7 | public int maxSubArray(int[] nums) {
8 | int[] dp = new int[nums.length];
9 | dp[0] = nums[0];
10 |
11 | int rs = dp[0];
12 |
13 | for (int i = 1; i < nums.length; i++) {
14 | int temp = dp[i - 1] + nums[i];
15 | dp[i] = Math.max(nums[i],temp);
16 | rs = Math.max(rs, dp[i]);
17 | }
18 | return rs;
19 | }
20 |
21 | public static void main(String[] args) {
22 | System.out.println(new Solution().maxSubArray(new int[]{-2}));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/动态规划/q5_最长回文子串/f1/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q5_最长回文子串.f1;
2 |
3 | /**
4 | * o(n^2) 以每个字符为中心计算回文长度
5 | */
6 | class Solution {
7 |
8 | public String getPalindrome(String s, int index) {
9 | String rs = "";
10 | int sLen = s.length();
11 | int i = index;
12 | int j = index;
13 | while (j < sLen) {
14 | if (s.charAt(j) == s.charAt(index)) {
15 | rs = rs + s.charAt(j);
16 | j++;
17 | } else {
18 | break;
19 | }
20 | }
21 | i--;
22 | while (i >= 0 && j < sLen) {
23 | if (s.charAt(i) == s.charAt(j)) {
24 | rs = s.charAt(i) + rs;
25 | rs = rs + s.charAt(i);
26 | i--;
27 | j++;
28 | } else {
29 | break;
30 | }
31 | }
32 | return rs;
33 | }
34 |
35 | public String longestPalindrome(String s) {
36 | int maxLen = -1;
37 | String rs = "";
38 | for (int i = 0; i < s.length(); i++) {
39 | String t = getPalindrome(s, i);
40 | if (t.length() > maxLen) {
41 | maxLen = t.length();
42 | rs = t;
43 | }
44 | }
45 | return rs;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/动态规划/q5_最长回文子串/f2/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q5_最长回文子串.f2;
2 |
3 | /**
4 | * 动态规划 o(n^2)
5 | * 转移方程:字符串两边界值相等并且子字符串是回文字符串则该字符串是回文字符串
6 | * dp数组含义:字符串s从i到j的索引子字符串是否是回文字符串
7 | */
8 | public class Solution {
9 | public String longestPalindrome(String s) {
10 | int len = s.length();
11 |
12 | if (len < 2) {
13 | return s;
14 | }
15 | boolean[][] dp = new boolean[len][len];
16 | for (int i = 0; i < len; i++) {
17 | dp[i][i] = true;
18 | }
19 |
20 | int maxLen = 1;
21 | int start = 0;
22 |
23 | for (int j = 1; j < len; j++) {
24 | for (int i = 0; i < j; i++) {
25 | if (s.charAt(i) == s.charAt(j)) {
26 | if (j - i < 3) {
27 | dp[i][j] = true;
28 | } else {
29 | dp[i][j] = dp[i + 1][j - 1];
30 | }
31 | } else {
32 | dp[i][j] = false;
33 | }
34 |
35 | if (dp[i][j]) {
36 | int curLen = j - i + 1;
37 | if (curLen > maxLen) {
38 | maxLen = curLen;
39 | start = i;
40 | }
41 | }
42 |
43 | }
44 | }
45 | return s.substring(start, start + maxLen);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/动态规划/q62_不同路径/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q62_不同路径;
2 |
3 | /**
4 | * 动态规划 dp[i][j]是到达i, j的最多路径 dp[i][j] = dp[i-1][j] + dp[i][j-1] o(m*n)
5 | */
6 | public class Solution {
7 |
8 | public int uniquePaths(int m, int n) {
9 | if (m < 1 || n < 1) {
10 | return 0;
11 | }
12 | int[][] dp = new int[m][n];
13 | for (int i = 0; i < n; i++) {
14 | dp[0][i] = 1;
15 | }
16 | for (int i = 0; i < m; i++) {
17 | dp[i][0] = 1;
18 | }
19 | for (int i = 1; i < m; i++) {
20 | for (int j = 1; j < n; j++) {
21 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
22 | }
23 | }
24 | return dp[m - 1][n - 1];
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/动态规划/q64_最小路径和/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q64_最小路径和;
2 |
3 | /**
4 | * 动态规划 dp(j)=grid(i,j)+min(dp(j),dp(j+1)) o(m*n)
5 | */
6 | public class Solution {
7 |
8 | public int minPathSum(int[][] grid) {
9 | int[] dp = new int[grid[0].length];
10 | for (int i = grid.length - 1; i >= 0; i--) {
11 | for (int j = grid[0].length - 1; j >= 0; j--) {
12 | if (i == grid.length - 1 && j != grid[0].length - 1) {
13 | dp[j] = grid[i][j] + dp[j + 1];
14 | } else if (j == grid[0].length - 1 && i != grid.length - 1) {
15 | dp[j] = grid[i][j] + dp[j];
16 | } else if (j != grid[0].length - 1 && i != grid.length - 1) {
17 | dp[j] = grid[i][j] + Math.min(dp[j], dp[j + 1]);
18 |
19 | } else {
20 | dp[j] = grid[i][j];
21 | }
22 | }
23 | }
24 | return dp[0];
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/动态规划/q70_爬楼梯/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q70_爬楼梯;
2 |
3 | /**
4 | * 动态规划 dp[i]表示到达第i阶的方法总数dp[i]=dp[i−1]+dp[i−2] o(n)
5 | */
6 | public class Solution {
7 |
8 | public int climbStairs(int n) {
9 | if (n == 1) {
10 | return 1;
11 | }
12 | int[] dp = new int[n + 1];
13 | dp[1] = 1;
14 | dp[2] = 2;
15 | for (int i = 3; i <= n; i++) {
16 | dp[i] = dp[i - 1] + dp[i - 2];
17 | }
18 | return dp[n];
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/动态规划/q746_使用最小花费爬楼梯/Solution.java:
--------------------------------------------------------------------------------
1 | package 动态规划.q746_使用最小花费爬楼梯;
2 |
3 | /**
4 | * 动态规划 o(n) f[i] = cost[i] + min(f[i+1], f[i+2])
5 | */
6 | class Solution {
7 | public int minCostClimbingStairs(int[] cost) {
8 | int f1 = 0, f2 = 0;
9 | for (int i = cost.length - 1; i >= 0; i--) {
10 | int f0 = cost[i] + Math.min(f1, f2);
11 | f2 = f1;
12 | f1 = f0;
13 | }
14 | return Math.min(f1, f2);
15 | }
16 |
17 | public static void main(String[] args) {
18 | int[] a = new int[]{0, 2, 2, 1};
19 | System.out.println(new Solution().minCostClimbingStairs(a));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/区间合并/q56_合并区间/Solution.java:
--------------------------------------------------------------------------------
1 | package 区间合并.q56_合并区间;
2 |
3 |
4 | import java.util.*;
5 |
6 | /**
7 | * 先根据start进行排序之后merge o(n*log(n))
8 | */
9 | class Solution {
10 | public int[][] merge(int[][] intervals) {
11 | if(intervals.length <= 1){
12 | return intervals;
13 | }
14 |
15 | Arrays.sort(intervals, Comparator.comparingInt(arr -> arr[0]));
16 |
17 | int[] currInterval = intervals[0];
18 | List resArr = new ArrayList<>();
19 | resArr.add(currInterval);
20 |
21 | for(int[] interval: intervals){
22 | int currEnd = currInterval[1];
23 |
24 | int nextBegin = interval[0];
25 | int nextEnd = interval[1];
26 |
27 | if(currEnd >= nextBegin){
28 | currInterval[1] = Math.max(currEnd, nextEnd);
29 | } else{
30 | currInterval = interval;
31 | resArr.add(currInterval);
32 | }
33 | }
34 |
35 | return resArr.toArray(new int[resArr.size()][]);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/双指针遍历/q11_盛最多水的容器/Solution.java:
--------------------------------------------------------------------------------
1 | package 双指针遍历.q11_盛最多水的容器;
2 |
3 | /**
4 | * 双指针遍历 o(n)
5 | */
6 | public class Solution {
7 | public int maxArea(int[] height) {
8 | if (height.length < 2) {
9 | return 0;
10 | }
11 | int left = 0;
12 | int right = height.length - 1;
13 | int result = 0;
14 | while (right > left) {
15 | int c = (Math.min(height[right], height[left])) * (right - left);
16 | if (c >= result) {
17 | result = c;
18 | }
19 | if (height[left] < height[right]) {
20 | left++;
21 | } else {
22 | right--;
23 | }
24 | }
25 | return result;
26 | }
27 |
28 | public static void main(String[] args) {
29 | int[] a = new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7};
30 | System.out.println(new Solution().maxArea(a));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/双指针遍历/q121_买卖股票的最佳时机/Solution.java:
--------------------------------------------------------------------------------
1 | package 双指针遍历.q121_买卖股票的最佳时机;
2 |
3 | /**
4 | * 维护一个最低股价变量,同时维护当前收益o(n)
5 | */
6 | class Solution {
7 | public int maxProfit(int[] prices) {
8 | int min = Integer.MAX_VALUE;
9 | int money = 0;
10 | for (int i = 0; i < prices.length; i++) {
11 | if (prices[i] < min) {
12 | min = prices[i];
13 | }
14 | if (prices[i] - min > money) {
15 | money = prices[i] - min;
16 | }
17 | }
18 | return money;
19 | }
20 |
21 | public static void main(String[] args) {
22 | int[] a = new int[]{7, 1, 5, 3, 6, 4};
23 | System.out.println(new Solution().maxProfit(a));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/双指针遍历/q15_三数之和/Solution.java:
--------------------------------------------------------------------------------
1 | package 双指针遍历.q15_三数之和;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * 数组遍历 + 双指针遍历 o(n^2)
7 | */
8 | class Solution {
9 | public List> threeSum(int[] nums) {
10 | List> rs = new ArrayList<>();
11 |
12 | if (nums.length < 3) {
13 | return rs;
14 | }
15 |
16 | Arrays.sort(nums);
17 | if (nums[0] > 0) {
18 | return rs;
19 | }
20 |
21 | for (int i = 0; i < nums.length - 2; i++) {
22 | if (i > 0 && nums[i] == nums[i - 1]) {
23 | continue;
24 | }
25 | int left = i + 1;
26 | int right = nums.length - 1;
27 | while (left < right) {
28 | int sum = nums[i] + nums[left] + nums[right];
29 | if (sum == 0) {
30 | List temp = new ArrayList<>();
31 | temp.add(nums[i]);
32 | temp.add(nums[left]);
33 | temp.add(nums[right]);
34 | rs.add(temp);
35 | while (left < right && nums[left] == nums[left + 1]) {
36 | left++;
37 | }
38 | while (left < right && nums[right] == nums[right - 1]) {
39 | right--;
40 | }
41 | left++;
42 | right--;
43 | } else if (sum > 0) {
44 | right--;
45 | } else {
46 | left++;
47 | }
48 | }
49 | }
50 | return rs;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/双指针遍历/q16_最接近的三数之和/Solution.java:
--------------------------------------------------------------------------------
1 | package 双指针遍历.q16_最接近的三数之和;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * q15类型题 数组遍历 + 双指针遍历 o(n^2)
7 | */
8 |
9 | public class Solution {
10 | public int threeSumClosest(int[] nums, int target) {
11 | if (nums.length < 3) {
12 | return 0;
13 | }
14 |
15 | Arrays.sort(nums);
16 | int rs = nums[0] + nums[1] + nums[2];
17 |
18 | for (int i = 0; i < nums.length - 2; i++) {
19 | if (i > 0 && nums[i] == nums[i - 1]) {
20 | continue;
21 | }
22 | int left = i + 1;
23 | int right = nums.length - 1;
24 | while (left < right) {
25 | int sum = nums[i] + nums[left] + nums[right];
26 | int c = sum - target;
27 | if (Math.abs(c) < Math.abs(rs - target)) {
28 | rs = sum;
29 | }
30 | if (c == 0) {
31 | return target;
32 | } else if (c > 0) {
33 | right--;
34 | } else {
35 | left++;
36 | }
37 | }
38 | }
39 | return rs;
40 | }
41 |
42 | public static void main(String[] args) {
43 | int[] a = new int[]{-3, -2, -5, 3, -4};
44 | System.out.println(new Solution().threeSumClosest(a, -1));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/双指针遍历/q209_长度最小的子数组/Solution.java:
--------------------------------------------------------------------------------
1 | package 双指针遍历.q209_长度最小的子数组;
2 |
3 | /**
4 | * 两个指针滑动窗口o(n)
5 | */
6 | public class Solution {
7 |
8 | public int minSubArrayLen(int s, int[] nums) {
9 | int sum = 0;
10 | int i = 0;
11 | int k = 0;
12 | int min = Integer.MAX_VALUE;
13 | while (true) {
14 | if (k == nums.length && i == nums.length) {
15 | break;
16 | }
17 | if (sum < s) {
18 | if (k == nums.length) {
19 | break;
20 | }
21 | sum += nums[k];
22 | k++;
23 | } else {
24 | min = Math.min(k - i, min);
25 | sum -= nums[i];
26 | i++;
27 | }
28 | }
29 | return min == Integer.MAX_VALUE ? 0 : min;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/双指针遍历/q26_删除排序数组中的重复项/Solution.java:
--------------------------------------------------------------------------------
1 | package 双指针遍历.q26_删除排序数组中的重复项;
2 |
3 | /**
4 | * 双指针 o(n)
5 | */
6 | public class Solution {
7 | public int removeDuplicates(int[] nums) {
8 | if (nums.length < 2) {
9 | return nums.length;
10 | }
11 | int c = 0;
12 | for (int i = 1; i < nums.length; i++) {
13 | if (nums[i] != nums[c]) {
14 | c++;
15 | nums[c] = nums[i];
16 | }
17 | }
18 | return c + 1;
19 | }
20 |
21 | public static void main(String[] args) {
22 | new Solution().removeDuplicates(new int[]{1, 1, 2});
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/双指针遍历/q3_无重复字符的最长子串/Solution.java:
--------------------------------------------------------------------------------
1 | package 双指针遍历.q3_无重复字符的最长子串;
2 |
3 | import java.util.HashMap;
4 |
5 | /**
6 | * Hash+双指针滑动窗口 o(n)
7 | */
8 | public class Solution {
9 | public int lengthOfLongestSubstring(String s) {
10 | int left = 0;
11 | int right = 0;
12 | int len = 0;
13 | HashMap map = new HashMap<>();
14 | while (right < s.length()) {
15 | Integer index = map.get(s.charAt(right));
16 | map.put(s.charAt(right), right);
17 | if (index != null && index >= left) {
18 | left = index + 1;
19 | }
20 | if (right - left + 1 > len) {
21 | len = right - left + 1;
22 | }
23 | right++;
24 | }
25 | return len;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/双指针遍历/q42_接雨水/Solution.java:
--------------------------------------------------------------------------------
1 | package 双指针遍历.q42_接雨水;
2 |
3 | /**
4 | * 暴力法o(n^2) 找出每个元素(柱子)上面的水量,可提前存储最大高度数组(两个左和右),最后遍历一次优化为o(n)
5 | */
6 | public class Solution {
7 |
8 | public int trap(int[] height) {
9 | int ans = 0;
10 | int size = height.length;
11 | for (int i = 1; i < size - 1; i++) {
12 | int maxLeft = 0, maxRight = 0;
13 | for (int j = i; j >= 0; j--) {
14 | maxLeft = Math.max(maxLeft, height[j]);
15 | }
16 | for (int j = i; j < size; j++) {
17 | maxRight = Math.max(maxRight, height[j]);
18 | }
19 | ans += Math.min(maxLeft, maxRight) - height[i];
20 | }
21 | return ans;
22 | }
23 |
24 | public static void main(String[] args) {
25 | new Solution().trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1});
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/回溯法/q10_正则表达式匹配/Solution.java:
--------------------------------------------------------------------------------
1 | package 回溯法.q10_正则表达式匹配;
2 |
3 | /**
4 | * 回溯法 对于*字符,可以直接忽略模式串中这一部分,或者删除匹配串的第一个字符,前提是它能够匹配模式串当前位置字符,即 pattern[0]。如果两种操作中有任何一种使得剩下的字符串能匹配,那么初始时,匹配串和模式串就可以被匹配。
5 | */
6 | public class Solution {
7 | public boolean isMatch(String text, String pattern) {
8 | if (pattern.isEmpty()){
9 | return text.isEmpty();
10 | }
11 | boolean firstMatch = (!text.isEmpty() &&
12 | (pattern.charAt(0) == text.charAt(0) || pattern.charAt(0) == '.'));
13 |
14 | if (pattern.length() >= 2 && pattern.charAt(1) == '*') {
15 | return (isMatch(text, pattern.substring(2)) ||
16 | (firstMatch && isMatch(text.substring(1), pattern)));
17 | } else {
18 | return firstMatch && isMatch(text.substring(1), pattern.substring(1));
19 | }
20 | }
21 |
22 | public static void main(String[] args) {
23 | System.out.println(new Solution().isMatch("aaa", "a*a"));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/回溯法/q22_括号生成/f1/Solution.java:
--------------------------------------------------------------------------------
1 | package 回溯法.q22_括号生成.f1;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * 暴力法 o(2^2n*n)
7 | */
8 | public class Solution {
9 |
10 | public boolean isValid(String s) {
11 | Stack stack = new Stack<>();
12 | for (int i = 0; i < s.length(); i++) {
13 | char t = s.charAt(i);
14 | if (t == '(') {
15 | stack.push(t);
16 | } else {
17 | if (stack.empty() || stack.pop() != '(') {
18 | return false;
19 | }
20 | }
21 | }
22 | return stack.empty();
23 | }
24 |
25 | public List generateParenthesis(int n) {
26 | List rs = new ArrayList<>();
27 |
28 | if (n < 1) {
29 | return rs;
30 | }
31 | String root = "(";
32 | rs.add(root);
33 | for (int k = 0; k < 2 * n - 1; k++) {
34 | List tempList = new ArrayList<>();
35 | for (int i = 0; i < rs.size(); i++) {
36 | String temp = rs.get(i);
37 | tempList.add(temp + "(");
38 | tempList.add(temp + ")");
39 | }
40 | rs.clear();
41 | rs.addAll(tempList);
42 | }
43 | rs.removeIf(s -> !isValid(s));
44 | return rs;
45 | }
46 |
47 | public static void main(String[] args) {
48 | new Solution().generateParenthesis(3);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/回溯法/q22_括号生成/f2/Solution.java:
--------------------------------------------------------------------------------
1 | package 回溯法.q22_括号生成.f2;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * 回溯法 o((4^n)/(n^1/2))
8 | */
9 | public class Solution {
10 |
11 | public List generateParenthesis(int n) {
12 | List ans = new ArrayList();
13 | backtrack(ans, "", 0, 0, n);
14 | return ans;
15 | }
16 |
17 | public void backtrack(List ans, String cur, int open, int close, int max) {
18 | if (cur.length() == max * 2) {
19 | ans.add(cur);
20 | return;
21 | }
22 |
23 | if (open < max) {
24 | backtrack(ans, cur + "(", open + 1, close, max);
25 | }
26 | if (close < open) {
27 | backtrack(ans, cur + ")", open, close + 1, max);
28 | }
29 | }
30 |
31 | public static void main(String[] args) {
32 | System.out.println(new Solution().generateParenthesis(3));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/回溯法/q40_组合总和2/Solution.java:
--------------------------------------------------------------------------------
1 | package 回溯法.q40_组合总和2;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * 回溯法 O(n*log(n))
7 | */
8 | class Solution {
9 |
10 | public List> combinationSum2(int[] candidates, int target) {
11 | List> res = new ArrayList<>();
12 | if (candidates.length == 0) {
13 | return res;
14 | }
15 | Arrays.sort(candidates);
16 | helper(candidates, target, 0, new LinkedList<>(), res);
17 | return res;
18 | }
19 |
20 | public void helper(int[] candidates, int target, int start, LinkedList stack, List> res) {
21 | if (start > candidates.length) {
22 | return;
23 | }
24 | if (target == 0 && !stack.isEmpty()) {
25 | List item = new ArrayList<>(stack);
26 | res.add(item);
27 | }
28 | HashSet set = new HashSet<>();
29 | for (int i = start; i < candidates.length; ++i) {
30 | if (!set.contains(candidates[i]) && target >= candidates[i]) {
31 | stack.push(candidates[i]);
32 | helper(candidates, target - candidates[i], i + 1, stack, res);
33 | stack.pop();
34 | set.add(candidates[i]);
35 | }
36 | }
37 | }
38 |
39 | public static void main(String[] args) {
40 | new Solution().combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/回溯法/q46_全排列/f1/Solution.java:
--------------------------------------------------------------------------------
1 | package 回溯法.q46_全排列.f1;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * 插队法 o((n-1)!+(n-2)!+···+2!+1!)
8 | */
9 | public class Solution {
10 | public List> fc(List> nums, int c) {
11 | List> result = new ArrayList<>();
12 | for (int i = 0; i < nums.size(); i++) {
13 | for (int j = 0; j <= nums.get(i).size(); j++) {
14 | List temp = new ArrayList<>(nums.get(i));
15 | temp.add(j, c);
16 | result.add(temp);
17 | }
18 | }
19 | return result;
20 | }
21 |
22 | public List> permute(int[] nums) {
23 | List> result = new ArrayList<>();
24 | if (nums.length == 0) {
25 | return result;
26 | }
27 | List to = new ArrayList<>();
28 | to.add(nums[0]);
29 | result.add(to);
30 | for (int i = 1; i < nums.length; i++) {
31 | result = fc(result, nums[i]);
32 | }
33 | System.out.println(result);
34 | return result;
35 | }
36 |
37 | public static void main(String[] args) {
38 | new Solution().permute(new int[]{1, 2, 3});
39 | //4—>3!+2!+1!
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/回溯法/q46_全排列/f2/Solution.java:
--------------------------------------------------------------------------------
1 | package 回溯法.q46_全排列.f2;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * 回溯法(DFS深度优先遍历) o(n*n!)
8 | */
9 | public class Solution {
10 |
11 | public List> permute(int[] nums) {
12 | int len = nums.length;
13 |
14 | List> res = new ArrayList<>();
15 |
16 | if (len == 0) {
17 | return res;
18 | }
19 |
20 | boolean[] used = new boolean[len];
21 | List path = new ArrayList<>();
22 |
23 | dfs(nums, len, 0, path, used, res);
24 | return res;
25 | }
26 |
27 | private void dfs(int[] nums, int len, int depth,
28 | List path, boolean[] used,
29 | List> res) {
30 | if (depth == len) {
31 | res.add(new ArrayList<>(path));
32 | return;
33 | }
34 |
35 | for (int i = 0; i < len; i++) {
36 | if (!used[i]) {
37 | path.add(nums[i]);
38 | used[i] = true;
39 | dfs(nums, len, depth + 1, path, used, res);
40 | // 状态重置,是从深层结点回到浅层结点的过程,代码在形式上和递归之前是对称的
41 | used[i] = false;
42 | path.remove(depth);
43 | }
44 | }
45 | }
46 |
47 | public static void main(String[] args) {
48 | int[] nums = {1, 2, 3};
49 | Solution solution = new Solution();
50 | List> lists = solution.permute(nums);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/堆相关/q215_数组中的第K个最大元素/Solution.java:
--------------------------------------------------------------------------------
1 | package 堆相关.q215_数组中的第K个最大元素;
2 |
3 | import java.util.PriorityQueue;
4 |
5 | /**
6 | * 利用大根堆实现 o(n*log(k))
7 | */
8 | public class Solution {
9 |
10 | public int findKthLargest(int[] nums, int k) {
11 | PriorityQueue heap =
12 | new PriorityQueue<>((n1, n2) -> n1 - n2);
13 |
14 | for (int n: nums) {
15 | heap.add(n);
16 | if (heap.size() > k){
17 | heap.poll();
18 | }
19 | }
20 |
21 | return heap.poll();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/堆相关/q347_前K个高频元素/Solution.java:
--------------------------------------------------------------------------------
1 | package 堆相关.q347_前K个高频元素;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * 利用大根堆(PriorityQueue)实现 o(n*log(k))
7 | */
8 | class Solution {
9 | public List topKFrequent(int[] nums, int k) {
10 |
11 | HashMap count = new HashMap<>();
12 | for (int n : nums) {
13 | count.put(n, count.getOrDefault(n, 0) + 1);
14 | }
15 |
16 | PriorityQueue heap = new PriorityQueue<>(Comparator.comparingInt(count::get));
17 |
18 | for (int n : count.keySet()) {
19 | heap.add(n);
20 | if (heap.size() > k) {
21 | heap.poll();
22 | }
23 | }
24 |
25 | List topK = new LinkedList<>();
26 | while (!heap.isEmpty()) {
27 | topK.add(heap.poll());
28 | }
29 | Collections.reverse(topK);
30 | return topK;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/字典树/q648_单词替换/Solution.java:
--------------------------------------------------------------------------------
1 | package 字典树.q648_单词替换;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * 构建字典树(前缀树)o(n)
7 | */
8 | class Solution {
9 | public String replaceWords(List roots, String sentence) {
10 | TrieNode trie = new TrieNode();
11 | for (String root : roots) {
12 | TrieNode cur = trie;
13 | for (char letter : root.toCharArray()) {
14 | if (cur.children[letter - 'a'] == null) {
15 | cur.children[letter - 'a'] = new TrieNode();
16 | }
17 | cur = cur.children[letter - 'a'];
18 | }
19 | cur.word = root;
20 | }
21 |
22 | StringBuilder ans = new StringBuilder();
23 |
24 | for (String word : sentence.split(" ")) {
25 | if (ans.length() > 0) {
26 | ans.append(" ");
27 | }
28 |
29 | TrieNode cur = trie;
30 | for (char letter : word.toCharArray()) {
31 | if (cur.children[letter - 'a'] == null || cur.word != null) {
32 | break;
33 | }
34 | cur = cur.children[letter - 'a'];
35 | }
36 | ans.append(cur.word != null ? cur.word : word);
37 | }
38 | return ans.toString();
39 | }
40 | }
41 |
42 | class TrieNode {
43 | TrieNode[] children;
44 | String word;
45 |
46 | TrieNode() {
47 | children = new TrieNode[26];
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/字符串操作/q14_最长公共前缀/Solution.java:
--------------------------------------------------------------------------------
1 | package 字符串操作.q14_最长公共前缀;
2 |
3 | /**
4 | * 水平扫描 o(n)
5 | */
6 | public class Solution {
7 | public String longestCommonPrefix(String[] strs) {
8 | if (strs.length == 0) {
9 | return "";
10 | }
11 | if (strs.length == 1) {
12 | return strs[0];
13 | }
14 | String pre = "";
15 | int i = 0;
16 | while (true) {
17 | if (strs[0].length() == i) {
18 | return pre;
19 | }
20 | char temp = strs[0].charAt(i);
21 | for (int k = 1; k < strs.length; k++) {
22 | if (strs[k].length() == i || temp != strs[k].charAt(i)) {
23 | return pre;
24 | }
25 | }
26 | pre += temp;
27 | i++;
28 | }
29 | }
30 |
31 | public static void main(String[] args) {
32 | String[] s = new String[]{"c", "c"};
33 | System.out.println(new Solution().longestCommonPrefix(s));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/字符串操作/q6_Z字形变换/Solution.java:
--------------------------------------------------------------------------------
1 | package 字符串操作.q6_Z字形变换;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * o(n) 可用一boolean变量代替求余操作
8 | */
9 | public class Solution {
10 | public String convert(String s, int numRows) {
11 | if (numRows == 1) {
12 | return s;
13 | }
14 | int len = s.length();
15 | int col = 0;
16 | int n = 0;
17 | List list = new ArrayList<>();
18 | for (int i = 0; i < numRows; i++) {
19 | StringBuffer temp = new StringBuffer();
20 | list.add(temp);
21 | }
22 | while (n < len) {
23 | int y = col % (numRows - 1);
24 | if (y == 0) {
25 | for (int i = 0; i < numRows && n < len; i++) {
26 | list.get(i).append(s.charAt(n));
27 | n++;
28 | }
29 | } else {
30 | list.get(numRows - 1 - y).append(s.charAt(n));
31 | n++;
32 | }
33 | col++;
34 | }
35 | String rs = "";
36 | for (int i = 0; i < list.size(); i++) {
37 | rs += list.get(i).toString();
38 | }
39 | return rs;
40 | }
41 |
42 | public static void main(String[] args) {
43 | System.out.println(new Solution().convert("LEETCODEISHIRING", 4));
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/字符串操作/q763_划分字母区间/Solution.java:
--------------------------------------------------------------------------------
1 | package 字符串操作.q763_划分字母区间;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * 先存储每个字母最后出现的位置,最后遍历一次 o(n)
8 | */
9 | public class Solution {
10 |
11 | public List partitionLabels(String S) {
12 | int[] last = new int[26];
13 | for (int i = 0; i < S.length(); ++i) {
14 | last[S.charAt(i) - 'a'] = i;
15 | }
16 | int j = 0, anchor = 0;
17 | List ans = new ArrayList<>();
18 | for (int i = 0; i < S.length(); ++i) {
19 | j = Math.max(j, last[S.charAt(i) - 'a']);
20 | if (i == j) {
21 | ans.add(i - anchor + 1);
22 | anchor = i + 1;
23 | }
24 | }
25 | return ans;
26 | }
27 |
28 | public static void main(String[] args) {
29 | new Solution().partitionLabels("abccaddbeffe");
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/快慢指针遍历/q141_环形链表/f1/ListNode.java:
--------------------------------------------------------------------------------
1 | package 快慢指针遍历.q141_环形链表.f1;
2 |
3 |
4 | public class ListNode {
5 | int val;
6 | ListNode next;
7 |
8 | ListNode(int x) {
9 | val = x;
10 | }
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/src/快慢指针遍历/q141_环形链表/f1/Solution.java:
--------------------------------------------------------------------------------
1 | package 快慢指针遍历.q141_环形链表.f1;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * 哈希表 o(n)
8 | */
9 | public class Solution {
10 |
11 | public boolean hasCycle(ListNode head) {
12 | Set nodesSeen = new HashSet<>();
13 | while (head != null) {
14 | if (nodesSeen.contains(head)) {
15 | return true;
16 | } else {
17 | nodesSeen.add(head);
18 | }
19 | head = head.next;
20 | }
21 | return false;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/快慢指针遍历/q141_环形链表/f2/ListNode.java:
--------------------------------------------------------------------------------
1 | package 快慢指针遍历.q141_环形链表.f2;
2 |
3 |
4 | public class ListNode {
5 | int val;
6 | ListNode next;
7 |
8 | ListNode(int x) {
9 | val = x;
10 | }
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/src/快慢指针遍历/q141_环形链表/f2/Solution.java:
--------------------------------------------------------------------------------
1 | package 快慢指针遍历.q141_环形链表.f2;
2 |
3 | /**
4 | * 快慢指针 o(n)
5 | */
6 | public class Solution {
7 |
8 | public boolean hasCycle(ListNode head) {
9 | if (head == null || head.next == null) {
10 | return false;
11 | }
12 | ListNode slow = head;
13 | ListNode fast = head.next;
14 | while (slow != fast) {
15 | if (fast == null || fast.next == null) {
16 | return false;
17 | }
18 | slow = slow.next;
19 | fast = fast.next.next;
20 | }
21 | return true;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/快慢指针遍历/q202_快乐数/Solution.java:
--------------------------------------------------------------------------------
1 | package 快慢指针遍历.q202_快乐数;
2 |
3 | /**
4 | * 快慢指针,思想同q141判断是否有环,用快慢指针找出循环终止条件 o(n)
5 | */
6 | public class Solution {
7 |
8 | private int bitSquareSum(int n) {
9 | int sum = 0;
10 | while (n > 0) {
11 | int bit = n % 10;
12 | sum += bit * bit;
13 | n = n / 10;
14 | }
15 | return sum;
16 | }
17 |
18 | public boolean isHappy(int n) {
19 | int slow = n;
20 | int fast = n;
21 | do {
22 | slow = bitSquareSum(slow);
23 | fast = bitSquareSum(fast);
24 | fast = bitSquareSum(fast);
25 | } while (slow != fast);
26 |
27 | return slow == 1;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/快慢指针遍历/q876_链表的中间结点/ListNode.java:
--------------------------------------------------------------------------------
1 | package 快慢指针遍历.q876_链表的中间结点;
2 |
3 |
4 | public class ListNode {
5 | int val;
6 | ListNode next;
7 |
8 | ListNode(int x) {
9 | val = x;
10 | }
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/src/快慢指针遍历/q876_链表的中间结点/Solution.java:
--------------------------------------------------------------------------------
1 | package 快慢指针遍历.q876_链表的中间结点;
2 |
3 | /**
4 | * 快慢指针法 o(n)
5 | */
6 | public class Solution {
7 |
8 | public ListNode middleNode(ListNode head) {
9 | ListNode slow = head, fast = head;
10 | while (fast != null && fast.next != null) {
11 | slow = slow.next;
12 | fast = fast.next.next;
13 | }
14 | return slow;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/数字操作/q172_阶乘后的零/f1/Solution.java:
--------------------------------------------------------------------------------
1 | package 数字操作.q172_阶乘后的零.f1;
2 |
3 | /**
4 | * 找因子直接遍历(o(n)超时)
5 | */
6 | public class Solution {
7 | public int trailingZeroes(int num) {
8 | int rs = 0;
9 | for (int i = 1; i <= num; i++) {
10 | int j = i;
11 | while (j % 5 == 0) {
12 | rs++;
13 | j /= 5;
14 | }
15 | }
16 | return rs;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/数字操作/q172_阶乘后的零/f2/Solution.java:
--------------------------------------------------------------------------------
1 | package 数字操作.q172_阶乘后的零.f2;
2 |
3 | /**
4 | * 基于方法一,寻找5出现的规律o(log(n))
5 | */
6 | public class Solution {
7 | public int trailingZeroes(int n) {
8 | int count = 0;
9 | while (n > 0) {
10 | count += n / 5;
11 | n = n / 5;
12 | }
13 | return count;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/数字操作/q1920_基于排列构建数组/Solution.java:
--------------------------------------------------------------------------------
1 | package 数字操作.q1920_基于排列构建数组;
2 |
3 | /**
4 | * 注意观察题目,数组中数字为[0,999]闭区间
5 | */
6 | class Solution {
7 | public int[] buildArray(int[] nums) {
8 | int n = nums.length;
9 | for (int i = 0; i < n; i++) {
10 | nums[i] += 1000 * (nums[nums[i]] % 1000);
11 | System.out.println(nums[i]);
12 | }
13 | for (int i = 0; i < n; i++) {
14 | nums[i] /= 1000;
15 | }
16 | return nums;
17 | }
18 |
19 | public static void main(String[] args) {
20 | int[] nums = new int[]{3, 2, 0, 1, 4};
21 | new Solution().buildArray(nums);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/数字操作/q258_各位相加/Solution.java:
--------------------------------------------------------------------------------
1 | package 数字操作.q258_各位相加;
2 |
3 | /**
4 | * 找规律 o(1) xyz=100*x+10*y+z=99*x+9*y+x+y+z
5 | */
6 | public class Solution {
7 |
8 | public int addDigits(int num) {
9 | if (num % 9 == 0 && num != 0) {
10 | num = 9;
11 | } else {
12 | num %= 9;
13 | }
14 | return num;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/数字操作/q43_字符串相乘/Solution.java:
--------------------------------------------------------------------------------
1 | package 数字操作.q43_字符串相乘;
2 |
3 | /**
4 | * o(n) 可基于乘数某位与被乘数某位相乘产生结果的位置的规律优化
5 | */
6 | class Solution {
7 |
8 | public String multiply(String num1, String num2) {
9 | if (num1.equals("0") || num2.equals("0")) {
10 | return "0";
11 | }
12 | String res = "0";
13 |
14 | for (int i = num2.length() - 1; i >= 0; i--) {
15 | int carry = 0;
16 | StringBuilder temp = new StringBuilder();
17 | for (int j = 0; j < num2.length() - 1 - i; j++) {
18 | temp.append(0);
19 | }
20 | int n2 = num2.charAt(i) - '0';
21 |
22 | for (int j = num1.length() - 1; j >= 0 || carry != 0; j--) {
23 | int n1 = j < 0 ? 0 : num1.charAt(j) - '0';
24 | int product = (n1 * n2 + carry) % 10;
25 | temp.append(product);
26 | carry = (n1 * n2 + carry) / 10;
27 | }
28 | res = addStrings(res, temp.reverse().toString());
29 | }
30 | return res;
31 | }
32 |
33 | public String addStrings(String num1, String num2) {
34 | StringBuilder builder = new StringBuilder();
35 | int carry = 0;
36 | for (int i = num1.length() - 1, j = num2.length() - 1;
37 | i >= 0 || j >= 0 || carry != 0;
38 | i--, j--) {
39 | int x = i < 0 ? 0 : num1.charAt(i) - '0';
40 | int y = j < 0 ? 0 : num2.charAt(j) - '0';
41 | int sum = (x + y + carry) % 10;
42 | builder.append(sum);
43 | carry = (x + y + carry) / 10;
44 | }
45 | return builder.reverse().toString();
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/数字操作/q7_整数反转/f1/Solution.java:
--------------------------------------------------------------------------------
1 | package 数字操作.q7_整数反转.f1;
2 |
3 | /**
4 | * 转成String o(n) 捕获异常判断是否溢出
5 | */
6 | public class Solution {
7 | public int reverse(int x) {
8 | String s = String.valueOf(x);
9 | String rs = "";
10 | boolean f = false;
11 | for (int i = s.length() - 1; i >= 0; i--) {
12 | if (s.charAt(i) == '-') {
13 | f = true;
14 | } else {
15 | rs += s.charAt(i);
16 | }
17 | }
18 | try {
19 | return f ? Integer.parseInt(rs) * (-1) : Integer.parseInt(rs);
20 | } catch (Exception e) {
21 | return 0;
22 | }
23 | }
24 |
25 | public static void main(String[] args) {
26 | System.out.println(new Solution().reverse(1234));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/数字操作/q7_整数反转/f2/Solution.java:
--------------------------------------------------------------------------------
1 | package 数字操作.q7_整数反转.f2;
2 |
3 | /**
4 | * 求余(判断是否溢出有多种方式) o(log(n))
5 | */
6 | public class Solution {
7 | public int reverse(int x) {
8 | int rs = 0;
9 | while (true) {
10 | int y = x % 10;
11 | x = x / 10;
12 | if (rs * 10 / 10 != rs) {
13 | return 0;
14 | }
15 | rs = rs * 10 + y;
16 | if (x == 0) {
17 | break;
18 | }
19 | }
20 | return rs;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/数字操作/q8_字符串转换整数/Solution.java:
--------------------------------------------------------------------------------
1 | package 数字操作.q8_字符串转换整数;
2 |
3 | /**
4 | * o(n) 重点还是判断溢出
5 | */
6 | public class Solution {
7 |
8 | public int myAtoi(String str) {
9 | str = str.trim();
10 | if (str.length() < 1) {
11 | return 0;
12 | }
13 | boolean negative = false;
14 | if (str.charAt(0) == '-') {
15 | negative = true;
16 | str = str.substring(1);
17 | } else if (str.charAt(0) == '+') {
18 | str = str.substring(1);
19 | }
20 |
21 | int rs = 0;
22 | for (int i = 0; i < str.length(); i++) {
23 | char t = str.charAt(i);
24 | if (Character.isDigit(t)) {
25 | int temp = rs * 10 - '0' + t;
26 | if ((temp - t + '0') / 10 != rs || temp < 0) {
27 | return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
28 | }
29 | rs = temp;
30 | } else {
31 | break;
32 | }
33 | }
34 | return negative ? -rs : rs;
35 | }
36 |
37 | public static void main(String[] args) {
38 | System.out.println(new Solution().myAtoi("2147483648"));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/数字操作/q9_回文数/Solution.java:
--------------------------------------------------------------------------------
1 | package 数字操作.q9_回文数;
2 |
3 | /**
4 | * 不转换成String 反转一半的数字o(log(n))
5 | */
6 | public class Solution {
7 | public boolean isPalindrome(int x) {
8 | if (x < 0) {
9 | return false;
10 | }
11 | if (x < 10) {
12 | return true;
13 | }
14 | if (x % 10 == 0) {
15 | return false;
16 | }
17 | int rs = 0;
18 | while (rs < x / 10) {
19 | int y = x % 10;
20 | x = x / 10;
21 | rs = rs * 10 + y;
22 | if (rs == x) {
23 | return true;
24 | } else if (x / 10 == rs) {
25 | return true;
26 | }
27 | }
28 | return false;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/数组操作/q384_打乱数组/Solution.java:
--------------------------------------------------------------------------------
1 | package 数组操作.q384_打乱数组;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Random;
6 |
7 | /**
8 | * 洗牌算法 o(n)
9 | */
10 | public class Solution {
11 | private int[] array;
12 | private int[] original;
13 |
14 | private Random rand = new Random();
15 |
16 | private List getArrayCopy() {
17 | List asList = new ArrayList<>();
18 | for (int i = 0; i < array.length; i++) {
19 | asList.add(array[i]);
20 | }
21 | return asList;
22 | }
23 |
24 | public Solution(int[] nums) {
25 | array = nums;
26 | original = nums.clone();
27 | }
28 |
29 | public int[] reset() {
30 | array = original;
31 | original = original.clone();
32 | return array;
33 | }
34 |
35 | public int[] shuffle() {
36 | List aux = getArrayCopy();
37 |
38 | for (int i = 0; i < array.length; i++) {
39 | int removeIdx = rand.nextInt(aux.size());
40 | array[i] = aux.get(removeIdx);
41 | aux.remove(removeIdx);
42 | }
43 |
44 | return array;
45 | }
46 | }
--------------------------------------------------------------------------------
/src/数组操作/q54_螺旋矩阵/Solution.java:
--------------------------------------------------------------------------------
1 | package 数组操作.q54_螺旋矩阵;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * 方向变量模拟路径 o(n)
8 | */
9 | public class Solution {
10 |
11 | public List spiralOrder(int[][] matrix) {
12 | List rs = new ArrayList<>();
13 | if (matrix.length == 0 || matrix[0].length == 0) {
14 | return rs;
15 | }
16 | int m = matrix.length;
17 | int n = matrix[0].length;
18 | boolean[][] visited = new boolean[m][n];
19 |
20 | int i = 0;
21 | int j = 0;
22 | int direction = 1;
23 | while (true) {
24 | if (i < 0 || j < 0 || i == m || j == n || visited[i][j]) {
25 | break;
26 | }
27 | rs.add(matrix[i][j]);
28 | visited[i][j] = true;
29 | switch (direction) {
30 | case 1:
31 | if (j + 1 == n || visited[i][j + 1]) {
32 | i++;
33 | direction = 2;
34 | } else {
35 | j++;
36 | }
37 | break;
38 | case 2:
39 | if (i + 1 == m || visited[i + 1][j]) {
40 | j--;
41 | direction = 3;
42 | } else {
43 | i++;
44 | }
45 | break;
46 | case 3:
47 | if (j == 0 || visited[i][j - 1]) {
48 | i--;
49 | direction = 4;
50 | } else {
51 | j--;
52 | }
53 | break;
54 | case 4:
55 | if (visited[i - 1][j]) {
56 | j++;
57 | direction = 1;
58 | } else {
59 | i--;
60 | }
61 | break;
62 | default:
63 | break;
64 | }
65 | }
66 | return rs;
67 | }
68 |
69 | public static void main(String[] args) {
70 | System.out.println(new Solution().spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}));
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/数组操作/q581_最短无序连续子数组/Solution.java:
--------------------------------------------------------------------------------
1 | package 数组操作.q581_最短无序连续子数组;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * 利用排序 o(n*log(n))
7 | */
8 | public class Solution {
9 |
10 | public int findUnsortedSubarray(int[] nums) {
11 | if (nums == null || nums.length < 1) {
12 | return 0;
13 | }
14 |
15 | int[] cloneNums = nums.clone();
16 | Arrays.sort(nums);
17 |
18 | int begin = Integer.MAX_VALUE;
19 | int end = 0;
20 | for (int i = 0; i < nums.length; i++) {
21 | if (nums[i] != cloneNums[i]) {
22 | begin = Math.min(begin, i);
23 | end = Math.max(end, i);
24 | }
25 | }
26 | return Math.max(end - begin + 1, 0);
27 | }
28 |
29 | public static void main(String[] args) {
30 | new Solution().findUnsortedSubarray(new int[]{2, 6, 4, 8, 10, 9, 15});
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/数组操作/q73_矩阵置零/Solution.java:
--------------------------------------------------------------------------------
1 | package 数组操作.q73_矩阵置零;
2 |
3 | /**
4 | * 用每行和每列的第一个元素作为标记,空间复杂度是o(1),时间复杂度 o(m*n)
5 | */
6 | public class Solution {
7 |
8 | public void setZeroes(int[][] matrix) {
9 | //第一行是否需要置零
10 | boolean row = false;
11 | //第一列是否需要置零
12 | boolean column = false;
13 | for (int i = 0; i < matrix.length; i++) {
14 | for (int j = 0; j < matrix[i].length; j++) {
15 | if (matrix[i][j] == 0) {
16 | if (i == 0) {
17 | row = true;
18 | }
19 | if (j == 0) {
20 | column = true;
21 | }
22 | //第i行第一个元素置零,表示这一行需要全部置零
23 | matrix[i][0] = 0;
24 | //第j列第一个元素置零,表示这一列需要全部置零
25 | matrix[0][j] = 0;
26 | }
27 | }
28 | }
29 | for (int i = 1; i < matrix.length; i++) {
30 | if (matrix[i][0] == 0) {
31 | for (int j = 1; j < matrix[i].length; j++) {
32 | matrix[i][j] = 0;
33 | }
34 | }
35 | }
36 | for (int j = 1; j < matrix[0].length; j++) {
37 | if (matrix[0][j] == 0) {
38 | for (int i = 1; i < matrix.length; i++) {
39 | matrix[i][j] = 0;
40 | }
41 | }
42 | }
43 | if (row) {
44 | for (int j = 1; j < matrix[0].length; j++) {
45 | matrix[0][j] = 0;
46 | }
47 | }
48 | if (column) {
49 | for (int i = 1; i < matrix.length; i++) {
50 | matrix[i][0] = 0;
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/数组操作/q78_子集/Solution.java:
--------------------------------------------------------------------------------
1 | package 数组操作.q78_子集;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * 向子集中添加子集合 o(n*2^n)
8 | */
9 | public class Solution {
10 |
11 | public List> subsets(int[] nums) {
12 | List> result = new ArrayList<>();
13 | result.add(new ArrayList<>());
14 | for (int i = 0; i < nums.length; i++) {
15 | int size = result.size();
16 | for (int j = 0; j < size; j++) {
17 | List temp = new ArrayList<>(result.get(j));
18 | temp.add(nums[i]);
19 | result.add(temp);
20 | }
21 | }
22 | return result;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/数组操作/q945_使数组唯一的最小增量/Solution.java:
--------------------------------------------------------------------------------
1 | package 数组操作.q945_使数组唯一的最小增量;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * 先排序再遍历一次 o(n*log(n))
7 | */
8 | public class Solution {
9 |
10 | public int minIncrementForUnique(int[] A) {
11 | if (A == null || A.length == 0 || A.length == 1) {
12 | return 0;
13 | }
14 |
15 | int rs = 0;
16 | Arrays.sort(A);
17 |
18 | int t = A[0];
19 | for (int i = 1; i < A.length; i++) {
20 | if (A[i] <= t) {
21 | rs = rs + t - A[i] + 1;
22 | A[i] = t + 1;
23 | }
24 | t = A[i];
25 | }
26 | return rs;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/栈相关/q155_最小栈/MinStack.java:
--------------------------------------------------------------------------------
1 | package 栈相关.q155_最小栈;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * 不使用辅助栈,每次push两个元素
7 | */
8 | public class MinStack {
9 |
10 | private Stack stack;
11 |
12 | public MinStack() {
13 | stack = new Stack<>();
14 | }
15 |
16 | public void push(int x) {
17 | if (stack.isEmpty()) {
18 | stack.push(x);
19 | stack.push(x);
20 | } else {
21 | int tmp = stack.peek();
22 | stack.push(x);
23 | if (tmp < x) {
24 | stack.push(tmp);
25 | } else {
26 | stack.push(x);
27 | }
28 | }
29 | }
30 |
31 | public void pop() {
32 | stack.pop();
33 | stack.pop();
34 | }
35 |
36 | public int top() {
37 | return stack.get(stack.size() - 2);
38 | }
39 |
40 | public int getMin() {
41 | return stack.peek();
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/栈相关/q20_有效的括号/Solution.java:
--------------------------------------------------------------------------------
1 | package 栈相关.q20_有效的括号;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * 利用栈 o(n)
7 | */
8 | public class Solution {
9 | public boolean isValid(String s) {
10 | Stack stack = new Stack<>();
11 | for (int i = 0; i < s.length(); i++) {
12 | char t = s.charAt(i);
13 | if (t == '(' || t == '[' || t == '{') {
14 | stack.push(t);
15 | } else {
16 | if (stack.empty()) {
17 | return false;
18 | }
19 | if (t == ')') {
20 | if (stack.pop() != '(') {
21 | return false;
22 | }
23 | } else if (t == ']') {
24 | if (stack.pop() != '[') {
25 | return false;
26 | }
27 | } else {
28 | if (stack.pop() != '{') {
29 | return false;
30 | }
31 | }
32 | }
33 | }
34 | return stack.empty();
35 | }
36 |
37 | public static void main(String[] args) {
38 | System.out.println(new Solution().isValid("()"));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/栈相关/q224_基本计算器/f1/Solution.java:
--------------------------------------------------------------------------------
1 | package 栈相关.q224_基本计算器.f1;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * 双栈(操作数栈+操作符栈)o(n)
7 | */
8 | public class Solution {
9 |
10 | public int calculate(String s) {
11 | char[] array = s.toCharArray();
12 | int n = array.length;
13 | Stack num = new Stack<>();
14 | Stack op = new Stack<>();
15 | int temp = -1;
16 | for (int i = 0; i < n; i++) {
17 | if (array[i] == ' ') {
18 | continue;
19 | }
20 | // 数字进行累加
21 | if (isNumber(array[i])) {
22 | if (temp == -1) {
23 | temp = array[i] - '0';
24 | } else {
25 | temp = temp * 10 + array[i] - '0';
26 | }
27 | } else {
28 | //将数字入栈
29 | if (temp != -1) {
30 | num.push(temp);
31 | temp = -1;
32 | }
33 | //遇到操作符
34 | if (isOperation(array[i] + "")) {
35 | while (!op.isEmpty()) {
36 | if (op.peek() == '(') {
37 | break;
38 | }
39 | //不停的出栈,进行运算,并将结果再次压入栈中
40 | int num1 = num.pop();
41 | int num2 = num.pop();
42 | if (op.pop() == '+') {
43 | num.push(num1 + num2);
44 | } else {
45 | num.push(num2 - num1);
46 | }
47 |
48 | }
49 | //当前运算符入栈
50 | op.push(array[i]);
51 | } else {
52 | //遇到左括号,直接入栈
53 | if (array[i] == '(') {
54 | op.push(array[i]);
55 | }
56 | //遇到右括号,不停的进行运算,直到遇到左括号
57 | if (array[i] == ')') {
58 | while (op.peek() != '(') {
59 | int num1 = num.pop();
60 | int num2 = num.pop();
61 | if (op.pop() == '+') {
62 | num.push(num1 + num2);
63 | } else {
64 | num.push(num2 - num1);
65 | }
66 | }
67 | op.pop();
68 | }
69 |
70 | }
71 | }
72 | }
73 | if (temp != -1) {
74 | num.push(temp);
75 | }
76 | //将栈中的其他元素继续运算
77 | while (!op.isEmpty()) {
78 | int num1 = num.pop();
79 | int num2 = num.pop();
80 | if (op.pop() == '+') {
81 | num.push(num1 + num2);
82 | } else {
83 | num.push(num2 - num1);
84 | }
85 | }
86 | return num.pop();
87 | }
88 |
89 | private boolean isNumber(char c) {
90 | return c >= '0' && c <= '9';
91 | }
92 |
93 | private boolean isOperation(String t) {
94 | return t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/");
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/栈相关/q224_基本计算器/f2/Solution.java:
--------------------------------------------------------------------------------
1 | package 栈相关.q224_基本计算器.f2;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * 单栈 拆分递归思想 o(n)
7 | */
8 | public class Solution {
9 |
10 | public int evaluateExpr(Stack