Skip to content

Commit bcfd590

Browse files
committed
feat: solved 300
1 parent 852a6f5 commit bcfd590

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.fghpdf.LongestIncreasingSubsequence;
2+
3+
/**
4+
* @author fghpdf
5+
* @date 2019/12/26
6+
* https://leetcode.com/problems/longest-increasing-subsequence/
7+
* https://leetcode.com/problems/longest-increasing-subsequence/discuss/74824/JavaPython-Binary-search-O(nlogn)-time-with-explanation
8+
* len = 1 : [4], [5], [6], [3] => tails[0] = 3
9+
* len = 2 : [4, 5], [5, 6] => tails[1] = 5
10+
* len = 3 : [4, 5, 6] => tails[2] = 6
11+
* (1) if x is larger than all tails, append it, increase the size by 1
12+
* (2) if tails[i-1] < x <= tails[i], update tails[i]
13+
**/
14+
public class Solution {
15+
public int lengthOfLIS(int[] nums) {
16+
int[] tails = new int[nums.length];
17+
int size = 0;
18+
for (int x : nums) {
19+
int i = 0;
20+
int j = size;
21+
while (i != j) {
22+
int middle = (i + j) / 2;
23+
if (tails[middle] < x) {
24+
i = middle + 1;
25+
} else {
26+
j = middle;
27+
}
28+
}
29+
tails[i] = x;
30+
if (i == size) {
31+
size++;
32+
}
33+
}
34+
return size;
35+
}
36+
}

0 commit comments

Comments
 (0)