Skip to content

Commit c7f22be

Browse files
[LEET-0000] finished migrating old code and clean up
1 parent e566521 commit c7f22be

File tree

7 files changed

+238
-1
lines changed

7 files changed

+238
-1
lines changed

leetcode-algorithms/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,13 @@
8585
|312|[Burst Balloons](https://leetcode.com/problems/burst-balloons/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/BurstBalloons.java)| O(?)|O(?)| Hard| DP
8686
|311|[Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/SparseMatrixMultiplication.java)| O(m*n*l)|O(m*l)| Medium|
8787
|310|[Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/MinimumHeightTrees.java)| ? | ? | Medium|
88+
|309|[Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-cooldown/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/BestTimeToBuyAndSellStockWithCooldown.java)| O(n)|O(1) | Medium| DP
8889
|308|[Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/RangeSumQuery2DMutable.java)| ? | ? | Hard| Tree
90+
|307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/RangeSumQueryMutable.java)| ? | ? | Medium| Tree
8991
|306|[Additive Number](https://leetcode.com/problems/additive-number/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/AdditiveNumber.java)| ? | ? | Medium|
9092
|305|[Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/NumberofIslandsII.java)| ? | ? | Hard| Union Find
9193
|304|[Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/RangeSumQuery2DImmutable.java)| ? | ? |Medium|
94+
|303|[Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/RangeSumQueryImmutable.java)| O(n) | O(1) |Easy|
9295
|302|[Smallest Rectangle Enclosing Black Pixels](https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/SmallestRectangleEnclosingBlackPixels.java)| ? | O(m*n) | Hard| DFS, BFS
9396
|301|[Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/RemoveInvalidParentheses.java)| ? | ? | Hard| BFS
9497
|299|[Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/BullsandCows.java)| O(n)|O(1) | Easy|
@@ -143,6 +146,7 @@
143146
|243|[Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/ShortestWordDistance.java) | O(n) | O(1) |
144147
|240|[Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/Searcha2DMatrixII.java)| O(log(m*n))|O(1) | Medium| Binary Search
145148
|239|[Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/SlidingWindowMaximum.java)| O(nlogn)|O(k) | Hard| Heap
149+
|238|[Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/ProductOfArrayExceptItself.java)| O(?)|O(?) | Medium|
146150
|237|[Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/DeleteNodeInALinkedList.java)| O(1)|O(1) | Easy| LinkedList
147151
|235|[Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/LowestCommonAncestorOfABinaryTree.java)| O(h)|O(1) | Medium| DFS
148152
|235|[Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/LowestCommonAncestorOfABinarySearchTree.java)| O(h)|O(1) | Easy| DFS
@@ -209,6 +213,7 @@
209213
|135|[Candy](https://leetcode.com/problems/candy/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/Candy.java)| O(n)|O(1) | Hard| Greedy
210214
|133|[Clone Graph](https://leetcode.com/problems/clone-graph/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/CloneGraph.java)| O(n)|O(n) | Medium| HashMap, BFS
211215
|132|[Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/ImplementQueueUsingStacks.java)| O(n)|O(n) | Easy| Stack, Queue
216+
|130|[Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/SurroundedRegionsBFS.java)| O(?)|O(?) | Medium|
212217
|129|[Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/SumRootToLeafNumbers.java)| O(n)|O(h) | Medium| DFS
213218
|125|[Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/ValidPalindrome.java)| O(n)|O(1) | Easy| Two Pointers
214219
|124|[Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)|[Solution](../../master/leetcode-algorithms/src/main/java/com/stevesun/solutions/BinaryTreeMaximumPathSum.java)| O(n)|O(h) | Hard | Tree
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
package com.stevesun.solutions;
2+
3+
/**Say you have an array for which the ith element is the price of a given stock on day i.
4+
5+
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
6+
7+
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
8+
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
9+
Example:
10+
11+
prices = [1, 2, 3, 0, 2]
12+
maxProfit = 3
13+
transactions = [buy, sell, cooldown, buy, sell]*/
14+
public class BestTimeToBuyAndSellStockWithCooldown {
15+
static class solutionFromProblemAuthor {
16+
/**
17+
* The series of problems are typical dp. The key for dp is to find the variables to
18+
* represent the states and deduce the transition function.
19+
*
20+
* Of course one may come up with a O(1) space solution directly, but I think it is better
21+
* to be generous when you think and be greedy when you implement.
22+
*
23+
* The natural states for this problem is the 3 possible transactions : buy, sell, rest.
24+
* Here rest means no transaction on that day (aka cooldown).
25+
*
26+
* Then the transaction sequences can end with any of these three states.
27+
*
28+
* For each of them we make an array, buy[n], sell[n] and rest[n].
29+
*
30+
* buy[i] means before day i what is the maxProfit for any sequence end with buy.
31+
*
32+
* sell[i] means before day i what is the maxProfit for any sequence end with sell.
33+
*
34+
* rest[i] means before day i what is the maxProfit for any sequence end with rest.
35+
*
36+
* Then we want to deduce the transition functions for buy sell and rest. By definition we
37+
* have:
38+
*
39+
* buy[i] = max(rest[i-1]-price, buy[i-1])
40+
* sell[i] = max(buy[i-1]+price, sell[i-1])
41+
* rest[i] = max(sell[i-1], buy[i-1], rest[i-1])
42+
*
43+
* Where price is the price of day i. All of these are very straightforward. They simply represents :
44+
*
45+
* (1) We have to `rest` before we `buy` and
46+
* (2) we have to `buy` before we `sell`
47+
* One tricky point is how do you make sure you sell before you buy, since from the equations it seems that [buy, rest, buy] is entirely possible.
48+
*
49+
* Well, the answer lies within the fact that buy[i] <= rest[i] which means rest[i] =
50+
* max(sell[i-1], rest[i-1]). That made sure [buy, rest, buy] is never occurred.
51+
*
52+
* A further observation is that and rest[i] <= sell[i] is also true therefore
53+
*
54+
* rest[i] = sell[i-1] Substitute this in to buy[i] we now have 2 functions instead of 3:
55+
*
56+
* buy[i] = max(sell[i-2]-price, buy[i-1]) sell[i] = max(buy[i-1]+price, sell[i-1]) This is
57+
* better than 3, but
58+
*
59+
* we can do even better
60+
*
61+
* Since states of day i relies only on i-1 and i-2 we can reduce the O(n) space to O(1).
62+
* And here we are at our final solution:
63+
*/
64+
public int maxProfit(int[] prices) {
65+
int sell = 0, prev_sell = 0, buy = Integer.MIN_VALUE, prev_buy;
66+
for (int price : prices) {
67+
prev_buy = buy;
68+
buy = Math.max(prev_sell - price, prev_buy);
69+
prev_sell = sell;
70+
sell = Math.max(prev_buy + price, prev_sell);
71+
}
72+
return sell;
73+
}
74+
}
75+
76+
static class solutionWithTheSecondHighestUpvotes {
77+
/**Surprisingly, this solution is even much faster than the one above provided by the author.*/
78+
/**
79+
* Here I share my no brainer weapon when it comes to this kind of problems.
80+
*
81+
* 1. Define States
82+
*
83+
* To represent the decision at index i:
84+
*
85+
* buy[i]: Max profit till index i. The series of transaction is ending with a buy.
86+
* sell[i]: Max profit till index i. The series of transaction is ending with a sell.
87+
*
88+
* 2. Define Recursion
89+
*
90+
* buy[i]: To make a decision whether to buy at i, we either take a rest, by just using the
91+
* old decision at i - 1, or sell at/before i - 2, then buy at i, We cannot sell at i - 1,
92+
* then buy at i, because of cooldown.
93+
* sell[i]: To make a decision whether to sell at i, we either take a rest, by just using the old decision at i - 1,
94+
* or buy at/before i - 1, then sell at i.
95+
*
96+
* So we get the following formula:
97+
*
98+
* buy[i] = Math.max(buy[i - 1], sell[i - 2] - prices[i]);
99+
* sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]);
100+
*
101+
* 3. Optimize to O(1) Space
102+
*
103+
* DP solution only depending on i - 1 and i - 2 can be optimized using O(1) space.
104+
*
105+
* Let b2, b1, b0 represent buy[i - 2], buy[i - 1], buy[i]
106+
* Let s2, s1, s0 represent sell[i - 2], sell[i - 1], sell[i]
107+
*
108+
* Then arrays turn into Fibonacci like recursion:
109+
*
110+
* b0 = Math.max(b1, s2 - prices[i]);
111+
* s0 = Math.max(s1, b1 + prices[i]);
112+
*
113+
* 4. Write Code in 5 Minutes
114+
*
115+
* First we define the initial states at i = 0:
116+
*
117+
* We can buy. The max profit at i = 0 ending with a buy is -prices[0].
118+
* We cannot sell. The max profit at i = 0 ending with a sell is 0.
119+
*/
120+
public int maxProfit(int[] prices) {
121+
if (prices == null || prices.length <= 1)
122+
return 0;
123+
124+
int b0 = -prices[0], b1 = b0, b2 = b0;
125+
int s0 = 0, s1 = s0, s2 = s0;
126+
127+
for (int i = 1; i < prices.length; i++) {
128+
b0 = Math.max(b1, s2 - prices[i]);
129+
s0 = Math.max(s1, b1 + prices[i]);
130+
b2 = b1;
131+
b1 = b0;
132+
s2 = s1;
133+
s1 = s0;
134+
}
135+
return s0;
136+
}
137+
}
138+
}

leetcode-algorithms/src/main/java/com/stevesun/solutions/NestedListWeightSumII.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@
55
import java.util.List;
66
import java.util.Queue;
77

8+
/**Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
9+
10+
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
11+
12+
Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.
13+
14+
Example 1:
15+
Given the list [[1,1],2,[1,1]], return 8. (four 1's at depth 1, one 2 at depth 2)
16+
17+
Example 2:
18+
Given the list [1,[4,[6]]], return 17. (one 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17)*/
819
public class NestedListWeightSumII {
920

1021
public int depthSumInverse(List<NestedInteger> nestedList) {
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.stevesun.solutions;
2+
3+
/**Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
4+
5+
Solve it without division and in O(n).
6+
7+
For example, given [1,2,3,4], return [24,12,8,6].
8+
9+
Follow up:
10+
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)*/
11+
12+
public class ProductOfArrayExceptItself {
13+
/**The trick is to construct the arrays (in the case of 4 elements)
14+
15+
{ 1, a[0], a[0]*a[1], a[0]*a[1]*a[2], }
16+
{ a[1]*a[2]*a[3], a[2]*a[3], a[3], 1, }
17+
18+
Both of which can be done in O(n) by starting at the left and right edges respectively.
19+
Then multiplying the two arrays element by element gives the required result*/
20+
public int[] productExceptSelf(int[] nums) {
21+
int len = nums.length;
22+
int[] res = new int[len];
23+
res[0] = 1;
24+
for(int i = 1; i < len; i++){
25+
res[i] = res[i-1]*nums[i-1];
26+
}
27+
int right = 1;
28+
for(int i = len-1; i >= 0; i--){
29+
/**I need to better understand this for loop: how it's constructing the 2nd array:
30+
* it's going from the right side to the left since it starts from i = len - 1;
31+
* So, what the two following lines mean:
32+
*
33+
* res[i] *= right; means to multiply element by element
34+
* right *= nums[i]; means to construct the second array
35+
*
36+
* It's basically doing the two things in this same for loop.
37+
*/
38+
res[i] *= right;
39+
right *= nums[i];
40+
}
41+
return res;
42+
}
43+
}

leetcode-algorithms/src/main/java/com/stevesun/solutions/RangeSumQueryImmutable.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
11
package com.stevesun.solutions;
22

3+
/**Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
4+
5+
Example:
6+
Given nums = [-2, 0, 3, -5, 2, -1]
7+
8+
sumRange(0, 2) -> 1
9+
sumRange(2, 5) -> -1
10+
sumRange(0, 5) -> -3
11+
Note:
12+
You may assume that the array does not change.
13+
There are many calls to sumRange function.*/
314
public class RangeSumQueryImmutable {
415

516

leetcode-algorithms/src/main/java/com/stevesun/solutions/RangeSumQueryMutable.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,17 @@
11
package com.stevesun.solutions;
22

3+
/**Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
4+
5+
The update(i, val) function modifies nums by updating the element at index i to val.
6+
Example:
7+
Given nums = [1, 3, 5]
8+
9+
sumRange(0, 2) -> 9
10+
update(1, 2)
11+
sumRange(0, 2) -> 8
12+
Note:
13+
The array is only modifiable by the update function.
14+
You may assume the number of calls to update and sumRange function is distributed evenly.*/
315
public class RangeSumQueryMutable {
416

517
public static void main(String... strings) {

leetcode-algorithms/src/main/java/com/stevesun/solutions/SurroundedRegionsBFS.java

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,24 @@
33
import java.util.*;
44

55
/**
6-
* Created by fishercoder1534 on 9/30/16.
6+
* Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
7+
8+
A region is captured by flipping all 'O's into 'X's in that surrounded region.
9+
10+
For example,
11+
X X X X
12+
X O O X
13+
X X O X
14+
X O X X
15+
After running your function, the board should be:
16+
17+
X X X X
18+
X X X X
19+
X X X X
20+
X O X X
21+
Show Tags
22+
Show Similar Problems
23+
724
*/
825
public class SurroundedRegionsBFS {
926
/**I won't call this problem hard, it's just confusing, you'll definitely want to clarify what the problem means before coding.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy