[LintCode] Longest Increasing Subsequence

Problem

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...

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

Challenge

Time complexity O(n^2) or O(nlogn)

Solution

DP O(n^2)

public class Solution {    public int longestIncreasingSubsequence(int[] nums) {        int n = nums.length, max = 0;        int[] dp = new int[n];        for (int i = 0; i = nums[j] ? Math.max(dp[j]+1, dp[i]) : dp[i];                max = Math.max(max, dp[i]);            }        }        return max;    }}

Binary Search O(nlogn)

public class Solution {    public int longestIncreasingSubsequence(int[] nums) {        int n = nums.length, max = 0;        if (n == 0) return 0;        int[] tails = new int[nums.length];        tails[0] = nums[0];        int index = 0;        for (int i = 1; i = tails[index]) tails[++index] = nums[i];            else tails[bisearch(tails, 0, index, nums[i])] = nums[i];        }        return index+1;    }    public int bisearch(int[] tails, int start, int end, int target) {        while (start <= end) {            int mid = start + (end-start)/2;            if (tails[mid] == target) return mid;            else if (tails[mid] < target) start = mid+1;            else end = mid-1;        }        return start;    }}

关键字:java, int, nums, tails


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部