Skip to content

Commit ea43fce

Browse files
solves #300: Longest Increasing Subsequence in java
1 parent bcbcdd9 commit ea43fce

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Diff for: README.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@
246246
| 294 | 🔒 [Flip Game II](https://leetcode.com/problems/flip-game-ii) | | |
247247
| 298 | 🔒 [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence) | | |
248248
| 299 | [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows) | [![Java](assets/java.png)](src/BullsAndCows.java) [![Python](assets/python.png)](python/bulls_and_cows.py) | |
249-
| 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence) | | |
249+
| 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence) | [![Java](assets/java.png)](src/LongestIncreasingSubsequence.java) | |
250250
| 303 | [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable) | [![Java](assets/java.png)](src/RangeSumQueryImmutable.java) [![Python](assets/python.png)](python/range_sum_query_immutable.py) | |
251251
| 304 | [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable) | | |
252252
| 306 | [Additive Number](https://leetcode.com/problems/additive-number) | | |

Diff for: src/LongestIncreasingSubsequence.java

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// https://leetcode.com/problems/longest-increasing-subsequence
2+
// T: O(NlogN)
3+
// S: O(N)
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
public class LongestIncreasingSubsequence {
9+
public static int lengthOfLIS(int[] nums) {
10+
final List<Integer> tail = new ArrayList<>();
11+
int maxLength = 1;
12+
tail.add(nums[0]);
13+
14+
for (int i = 1 ; i < nums.length ; i++) {
15+
if (nums[i] > tail.get(maxLength - 1)) {
16+
tail.add(nums[i]);
17+
maxLength++;
18+
} else if (nums[i] < tail.get(0)) {
19+
tail.set(0, nums[i]);
20+
} else {
21+
int insertionIndex = binarySearch(tail, nums[i]);
22+
tail.set(insertionIndex, nums[i]);
23+
}
24+
}
25+
26+
return maxLength;
27+
}
28+
29+
private static int binarySearch(List<Integer> array, int x) {
30+
int left = 0, right = array.size(), middle;
31+
while (left <= right) {
32+
middle = left + (right - left) / 2;
33+
if (array.get(middle) == x) return middle;
34+
else if (array.get(middle) < x) left = middle + 1;
35+
else right = middle - 1;
36+
}
37+
return left;
38+
}
39+
40+
public static void main(String[] args) {
41+
System.out.println(lengthOfLIS(new int[] {1,3,6,7,9,4,10,5,6}));
42+
}
43+
}

0 commit comments

Comments
 (0)