⚡ Sangsakala Proxy 🏠 Home
Skip to content

Commit 0dffb0a

Browse files
committed
refresh
1 parent bce0345 commit 0dffb0a

43 files changed

Lines changed: 4421 additions & 3874 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Java/4Sum.java‎

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
M
2-
1516696879
2+
1533626601
33
tags: Hash Table
44

55
#### Based on 2sum
@@ -44,26 +44,25 @@ Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b
4444
2nd part: try [i + 1, end], see if any combination sum that makes: target - sum exist in map. -> becomes same old 2sum problem.
4545
O(n)
4646
*/
47-
/*
48-
Thoughts:
49-
Can't do for loop over 3sum, which is O(n^3), not doable.
50-
We can break the nums into 2 major parts by index i.
51-
1st part: from [0 ~ i], we'll try all possible ways to pair [x, i] and store the sum of nums[x]+nums[i] in map.
52-
Note: key is sum, and the value is a hashSet of ArrayList. Where the hashset has itself functions to tell duplicate of pairs.
53-
2nd part: try [i + 1, end], see if any combination sum that makes: target - sum exist in map. -> becomes same old 2sum problem.
47+
/**
48+
Why having below front-pair-building after previous for end-pair-checking for loop?
49+
Here: we build [0 ~ i], and in next round, when we processs [i + 1, end], pairs built among [0~i] below will all be used.
50+
Rather: if we have lift the for loop below to calculate [0~i] before the end-pair-checking of same [i~end],
51+
there is one index at [i] will overlap, which turns to be incorrect.
52+
Therefore, we build front-pairs aftwarwards: it's building [0~i] here, which aims to help next round of end-pair-checking on [i+1, end].
5453
*/
5554
class Solution {
5655
public List<List<Integer>> fourSum(int[] nums, int target) {
5756
List<List<Integer>> result = new ArrayList<>();
58-
if (nums == null || nums.length <= 3) {
59-
return result;
60-
}
57+
if (nums == null || nums.length <= 3) return result;
58+
59+
int n = nums.length;
6160
Arrays.sort(nums);
6261
Map<Integer, HashSet<List>> map = new HashMap<>();
6362
Set<String> cache = new HashSet<>();
64-
for (int i = 0; i < nums.length; i++) {
63+
for (int i = 0; i < n; i++) {
6564
// Check if [i + 1, end] can be added up to target
66-
for (int k = i + 1; k < nums.length; k++) {
65+
for (int k = i + 1; k < n; k++) {
6766
int sum = nums[i] + nums[k];
6867
if (map.containsKey(target - sum)) {// Try to match up the 4 pairs
6968
for (List<Integer> frontPair : map.get(target - sum)) {
@@ -76,19 +75,11 @@ public List<List<Integer>> fourSum(int[] nums, int target) {
7675
}
7776
}
7877
}
79-
/**
80-
Why having below front-pair-building after previous for end-pair-checking for loop?
81-
Here: we build [0 ~ i], and in next round, when we processs [i + 1, end], pairs built among [0~i] below will all be used.
82-
Rather: if we have lift the for loop below to calculate [0~i] before the end-pair-checking of same [i~end],
83-
there is one index at [i] will overlap, which turns to be incorrect.
84-
Therefore, we build front-pairs aftwarwards: it's building [0~i] here, which aims to help next round of end-pair-checking on [i+1, end].
85-
*/
78+
8679
// Build up the pair from [0 ~ i]
8780
for (int j = 0; j < i; j++) {
8881
int sum = nums[j] + nums[i];
89-
if (!map.containsKey(sum)) {
90-
map.put(sum, new HashSet<>());
91-
}
82+
map.putIfAbsent(sum, new HashSet<>());
9283
map.get(sum).add(Arrays.asList(nums[j], nums[i]));
9384
}
9485
}
@@ -101,6 +92,9 @@ private String buildKey(List<Integer> list) {
10192
return sb.toString();
10293
}
10394
}
95+
96+
97+
10498
/*
10599
Thoughts
106100
Perform another layer outside of 3SUM. O(n^3).

‎Java/Best Time to Buy and Sell Stock III.java‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
- 什么时候会积累profit呢?
1515
- 1. 原本就持有股票的, 如果毫无动作, 那么状态不变, 积累profit diff.
1616
- 2. 卖出了股票, 状态改变, 积累profit diff.
17-
- 注意: 只有在状态index: 0, 2, 4, 也就是卖掉股票的时候, 猜可以积累profit
17+
- 注意: 只有在状态index: 0, 2, 4, 也就是卖掉股票的时候, 才可以积累profit
1818

1919
##### Rolling Array
2020
- [i] 只有和 [i-1] 打交道, reduce space
@@ -80,13 +80,13 @@ public int maxProfit(int[] prices) {
8080
for (int i = 1; i < n; i++) {
8181
for (int j = 1; j < 5; j++) {
8282
// Accumulate partial profit regardless of stock status.
83-
int dailyPartialProfit = prices[i] - prices[i - 1];
83+
int dailyDiff = prices[i] - prices[i - 1];
8484
if (j % 2 == 0) { // j status: no stock
85-
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] + dailyPartialProfit);
85+
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] + dailyDiff);
8686
// Find best profit when not having stock
8787
profit = Math.max(profit, dp[i][j]);
8888
} else { // j status: have stock
89-
dp[i][j] = Math.max(dp[i - 1][j] + dailyPartialProfit, dp[i - 1][j - 1]);
89+
dp[i][j] = Math.max(dp[i - 1][j] + dailyDiff, dp[i - 1][j - 1]);
9090
}
9191
}
9292
}

‎Java/Binary Tree Vertical Order Traversal.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#### BFS
1212
- 应该比较好想: naturally level-traverse all nodes, add node to appropriate col list
1313
- Use min/max to track map keys, since the keys are continous
14+
- Map does not provide random access; unless map key is marked with sequence i = [min, max]
1415

1516
#### DFS
1617
- 一开始很容易想到: enumerate一下, 先放curr node.val, 然后node.left.val, node.right.val. 非常简单

‎Java/Largest Number.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public int compare(String s1, String s2) {
6262
}
6363
});
6464

65-
StringBuffer sb = new StringBuffer();
65+
StringBuffer sb = new StringBuffer();
6666
for (int i = 0; i < num.length; i++) {
6767
sb.append(strs[i]);
6868
}

‎Java/Longest Substring Without Repeating Characters.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ public int lengthOfLongestSubstring(String s) {
8585
for (int i = 0; i < arr.length; i++) {
8686
char c = arr[i];
8787
if (map.containsKey(c)) {
88-
i = map.get(c);
88+
i = map.get(c); // reset beginning
8989
map = new HashMap<>();
9090
} else {
9191
map.put(c, i);

‎Java/Median of two Sorted Arrays.java‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
H
2-
1528263371
2+
1533619954
33
tags: Array, Binary Search, Divide and Conquer, DFS
44

55
著名的找两个sorted array的中位数. 中位数定义: 如果两个array总长为偶数, 取平均值.
@@ -17,8 +17,6 @@
1717
- 2. 如果 k == 1: 就是找A/B 里面的1st item, 那么做个 `Math.max(A[startA], B[startB])` 就可以
1818
- 总共的数字长度是 (m + n) 而且每次都有一般的内容被删除, 那么time就是 O(log(m + n))
1919

20-
#### Binary Search
21-
TODO:
2220

2321
```
2422
/*
@@ -88,17 +86,11 @@ public double findMedianSortedArrays(int[] numsA, int[] numsB) {
8886
// Find kth number in two sorted array. k is size
8987
private int findKth(int[] numsA, int startA, int[] numsB, int startB, int k) {
9088
// check edge case for startA/startB index
91-
if (startA >= numsA.length) {
92-
return numsB[startB + k - 1];
93-
}
94-
if (startB >= numsB.length) {
95-
return numsA[startA + k - 1];
96-
}
89+
if (startA >= numsA.length) return numsB[startB + k - 1]; // A exhausted, take kth in B
90+
if (startB >= numsB.length) return numsA[startA + k - 1]; // B exhausted, take kth in A
9791

98-
// handle final condition k == 1
99-
if (k == 1) {
100-
return Math.min(numsA[startA], numsB[startB]);
101-
}
92+
// handle final condition k == 1. The two elements will be sorted and the smaller one is kth.
93+
if (k == 1) return Math.min(numsA[startA], numsB[startB]);
10294

10395
// compare and partition at each [x+(k/2-1)] position
10496
int halfKthOfA = startA + k / 2 - 1 < numsA.length ? numsA[startA + k / 2 - 1] : Integer.MAX_VALUE;

‎Java/N-Queens.java‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,13 @@
5151
class Solution {
5252
public List<List<String>> solveNQueens(int n) {
5353
List<List<String>> rst = new ArrayList<>();
54-
if (n <= 0) {
55-
return rst;
56-
}
54+
if (n <= 0) return rst;
55+
5756
dfs(rst, new ArrayList<>(), n);
5857

5958
return rst;
6059
}
61-
60+
// build sequence row
6261
private void dfs(List<List<String>> rst, List<Integer> list, int n){
6362
if (list.size() == n) {
6463
rst.add(createBoard(list));

‎Java/One Edit Distance.java‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
M
2-
1522215963
2+
1533623972
33
tags: String
44

55
如果S, T只用一个operation就能变成相等, return true.
66

77
#### Edit: 删除,增加,和替换
88
- 换完之后,理论上换成的String 就应该全等
9-
- for loop, 一旦找到不一样的char, 就判断那三种可能性
9+
- for loop, 一旦找到不一样的char, 就判断那三种可能性: insert/delete/replace
1010
- insert/delete 对于2个string来说, 效果是类似的
1111
- O(n)
1212

@@ -15,6 +15,25 @@
1515
Given two strings S and T, determine if they are both one edit distance apart.
1616
1717
*/
18+
class Solution {
19+
public boolean isOneEditDistance(String s, String t) {
20+
if (s == null || t == null || s.equals(t) || Math.abs(s.length() - t.length()) > 1) {
21+
return false;
22+
}
23+
int size = Math.min(s.length(), t.length());
24+
for (int i = 0; i < size; i++) {
25+
if (s.charAt(i) != t.charAt(i)) { // check insert/delete or replace
26+
return compareStr(s, t, i + 1, i) || compareStr(s, t, i, i + 1) || compareStr(s, t, i + 1, i + 1);
27+
}
28+
}
29+
30+
return true; // size == 0, and length diff == 1
31+
}
32+
33+
private boolean compareStr(String s, String t, int x, int y) {
34+
return s.substring(x).equals(t.substring(y));
35+
}
36+
}
1837

1938
/*
2039
Thoughts:

‎Java/Permutations.java‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
M
2-
1528074589
2+
1533623494
33
tags: Backtracking, DFS, Permutation
44

55
#### Recursive: Backtracking
66
- Given a remaining list: 取, 或者不取
7+
- always iterate over full `nums[]`, use list.contains() to check if item has been added.
78
- Improvement: maintain list (add/remove elements) instead of 'list.contains'
89
- time O(n!): visit all possible outcome
910
- T(n) = n * T(n-1) + O(1)
@@ -44,6 +45,30 @@
4445
Recursion Search
4546
4647
*/
48+
class Solution {
49+
public List<List<Integer>> permute(int[] nums) {
50+
List<List<Integer>> result = new ArrayList<List<Integer>>();
51+
if (nums == null || nums.length == 0) {
52+
return result;
53+
}
54+
55+
dfs(result, new ArrayList<>(), nums);
56+
return result;
57+
}
58+
59+
private void dfs(List<List<Integer>> result, List<Integer> levelList, int[] nums) {
60+
if (levelList.size() == nums.length) {
61+
result.add(new ArrayList<>(levelList));
62+
return;
63+
}
64+
for (int i = 0; i < nums.length; i++) {
65+
if (levelList.contains(nums[i])) continue;
66+
levelList.add(nums[i]);
67+
dfs(result, levelList, nums);
68+
levelList.remove(levelList.size() - 1);
69+
}
70+
}
71+
}
4772

4873
/*
4974
Thoughts:

‎Java/Product of Array Except Self.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
M
22
1531595945
3-
tags: Array
3+
tags: Array, PreProduct
44
time: O(n)
55
space: O(1)
66

77
给一串数字, output rst[n], 每个index是 除了nums[i]以外 所有itemd的乘积.
88

9-
#### Array
9+
#### Array, PreProduct
1010
- 分析普通做法, 了结到用从左到右一遍O(n), 从右到左一遍 O(n) 就可以
1111
- 注意carry的维护
1212
- 看第二个解答, 进一步简化了代码
13+
- PreProduct, 跟preSum的感觉有点像, 就是差一位.
1314

1415
```
1516
/*

0 commit comments

Comments
 (0)