您的位置:首页 > 产品设计 > UI/UE

LeetCode 300 Longest Increasing Subsequence

2016-07-03 21:28 531 查看
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?

方法一:动态规划。O(n^2)解法(运行时间33
ms),参考:西施豆腐渣
public int lengthOfLIS(int[] nums) {
int max = 0;
int[] dp = new int[nums.length];//d[i]为subset0...i的Longest increasing sub.
for (int i = 0; i < nums.length; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) dp[i] = Math.max(dp[i], dp[j] + 1);
}
max = Math.max(max, dp[i]);
}
return max;
}
方法二: O(n * log n)解法(运行时间1ms):

维护一个单调序列。遍历nums数组,二分查找每一个数在单调序列中的位置,然后替换。
public int lengthOfLIS2(int[] nums) {
int[] dp = new int[nums.length];
int len = 0;
for (int x : nums) {
int i = Arrays.binarySearch(dp, 0, len, x);//二分查找x在单调序列的位置
if (i < 0) i = -(i + 1);
dp[i] = x;
if (i == len) len++;
}
return len;
}

另外,Arrays.binarySearch(dp, 0, len, x)的底层实现为:

// Like public version, but without range checks.
private static int binarySearch0(int[] a, int fromIndex, int toIndex,
int key) {
int low = fromIndex;
int high = toIndex - 1;

while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];

if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1);  // key not found.
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode