300. Longest Increasing Subsequence
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Last updated
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Last updated
class Solution {
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) return 0;
//方法1
// int[] dp = new int[nums.length];
// Arrays.fill(dp, 1);
// int max = 1;
// for (int i = 1; i < nums.length; i++) {
// for (int j = i - 1; j >= 0; j--) {
// if (nums[j] < nums[i]) {
// dp[i]= Math.max(dp[j] + 1, dp[i]);
// max = Math.max(max, dp[i]);
// }
// }
// }
// return max;
//方法2
int[] table = new int[nums.length];
int len = 0;
table[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > table[len]) {
len++;
table[len] = nums[i];
} else if (nums[i] == table[len]) {
continue;
} else {
int index = binarySearch(table, nums[i], len);
table[index] = nums[i];
}
}
return len + 1;
}
// find the index of the first number that is equal/larger than n
private int binarySearch(int[] table, int n, int r) {
int l = 0;
while (l + 1 < r) {
int mid = l + (r - l) / 2;
if (table[mid] < n) l = mid;
else r = mid;
}
if (table[l] >= n) return l;
else return r;
}
}