-
Notifications
You must be signed in to change notification settings - Fork 1
/
LongestSequence.java
38 lines (36 loc) · 1.16 KB
/
LongestSequence.java
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
public class LongestSequence {
public static void main(String[] args) {
int[] test = new int[]{4,2,3,10,-4,11};
System.out.println(lengthOfLIS(test));
}
public static int findPositionToReplace(int[] a, int low, int high, int x) {
int mid;
while (low <= high) {
mid = low + (high - low) / 2;
if (a[mid] == x)
return mid;
else if (a[mid] > x)
high = mid - 1;
else
low = mid + 1;
}
return low;
}
//{4,2,3,10,-4,11};
public static int lengthOfLIS(int[] nums) {
if (nums == null | nums.length == 0)
return 0;
int n = nums.length, len = 0;
int[] increasingSequence = new int[n];
increasingSequence[len++] = nums[0];
for (int i = 1; i < n; i++) {
if (nums[i] > increasingSequence[len - 1])
increasingSequence[len++] = nums[i];
else {
int position = findPositionToReplace(increasingSequence, 0, len - 1, nums[i]);
increasingSequence[position] = nums[i];
}
}
return len;
}
}