-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path300.longest-increasing-subsequence.java
More file actions
48 lines (40 loc) · 1.09 KB
/
Copy path300.longest-increasing-subsequence.java
File metadata and controls
48 lines (40 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* @lc app=leetcode id=300 lang=java
*
* [300] Longest Increasing Subsequence
*/
// @lc code=start
class Solution {
public int lengthOfLIS(int[] nums) {
ArrayList<Integer> sub = new ArrayList<>();
sub.add(nums[0]);
for (int i = 1; i < nums.length; i++) {
int num = nums[i];
if (num > sub.get(sub.size() - 1)) {
sub.add(num);
} else {
int j = binarySearch(sub, num);
sub.set(j, num);
}
}
return sub.size();
}
private int binarySearch(ArrayList<Integer> sub, int num) {
int left = 0;
int right = sub.size() - 1;
int mid = (left + right) / 2;
while (left < right) {
mid = (left + right) / 2;
if (sub.get(mid) == num) {
return mid;
}
if (sub.get(mid) < num) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}
// @lc code=end