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

Longest Increasing Subsequence

2016-07-08 00:58 369 查看
Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Clarification

What's the definition of longest increasing subsequence?

The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.

https://en.wikipedia.org/wiki/Longest_increasing_subsequence

Example

For `[5, 4, 1, 2, 3]`, the LIS is [1, 2, 3], return `3`

For `[4, 2, 4, 5, 3, 7]`, the LIS is `[2, 4, 5, 7]`, return `4`


分析:
用一个数组a记录对于arr[i], 到它那里最长的subsequence是多少,那么对于arr[i + 1],我们需要从0比较到i, 如果arr[j] < arr[i + 1], 并且a[j] > a[i + 1], 我们就更新a[j + 1]的值。

public class Solution {
/**
* @param nums: The integer array
* @return: The length of LIS (longest increasing subsequence)
*/
public int longestIncreasingSubsequence(int[] arr) {
// array a is used to store the maximum length
int[] a = new int[arr.length];
// initialization, set all the elements in array a to 1;
for (int i = 0; i < a.length; i++) {
a[i] = 1;
}
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < i; j++ ) {
if (arr[i] >= arr[j] && a[i] <= a[j] ) {
a[i] = a[j] + 1;
}
}
}
int max = 0;
//find the longest subsequence
for (int i = 0; i < a.length; i++) {
if (a[i] > max ) max = a[i];
}
return max;
}
}


O(nlgn)解法:

public class Test {
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
if (nums.length == 1)
return 1;

List<Integer> list = new ArrayList<Integer>();
list.add(nums[0]);

for (int i = 1; i < nums.length; i++) {
if (nums[i] > list.get(list.size() - 1)) {
list.add(nums[i]);
} else if (nums[i] < list.get(list.size() - 1)) {
int start = 0;
int end = list.size() - 1;
int index = findPosition(list, start, end, nums[i]);
list.set(index, nums[i]);
}
}
return list.size();
}

private int findPosition(List<Integer> list, int start, int end, int target) {
while (start <= end) {
int mid = (end - start) / 2 + start;
if (list.get(mid) == target) {
return mid;
} else if (list.get(mid) < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return start;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: