Leetcode[300] Longest Increasing Subsequence
06 Dec 2015###Task1 Given an unsorted array of integers, find the length of longest increasing subsequence.
For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
###Java ####O(n2)
public class Solution {
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return 1;
}
int N = nums.length;
int[] dp = new int[N];
dp[0] = 1;
int ret = 0;
for (int i = 1; i < N; i++) {
int cur = nums[i];
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (cur > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
ret = Math.max(ret, dp[i]);
}
return ret;
}
}
####O(nlogn) , cannot figure this out
public class Solution {
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return 1;
}
int N = nums.length;
ArrayList<Integer> dp = new ArrayList<>();
for (int i = 0; i < N; i++) {
int low = 0;
int high = dp.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (dp.get(mid) >= nums[i]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
if (low >= dp.size()) {
dp.add(nums[i]);
} else {
dp.set(low, nums[i]);
}
}
return dp.size();
}
}
###Points
遍历nums数组,二分查找每一个数在单调序列中的位置,然后替换之。