300. Longest Increasing Subsequence

来源:互联网 发布:怎么投诉淘宝买家骚扰 编辑:程序博客网 时间:2024/06/01 09:50

the normal way:

public class Solution {    public int lengthOfLIS(int[] nums) {        if(nums == null || nums.length == 0) return 0;        int[] dp = new int[nums.length];        Arrays.fill(dp,1);        int ret = 1;        for(int i = 1; i<nums.length; i++){            int max = 1;            for(int j = 0; j<i;j++){                if(nums[i]>nums[j]){                    max = Math.max(dp[j]+1, max);                }            }            dp[i] = max;            ret = Math.max(ret,max);        }                return ret;    }}

dp[i] means the LIS from nums[0] to nums[i]. when nums[i+1] comes in, we just need to check dp[0] -> dp[i], find the max dp[k] where nums[k] < nums[i+1]

then dp[i+1] = dp[k] + 1.


the O(nlgn) way:

public class Solution {            public int lengthOfLIS(int[] nums) {        int[] dp = new int[nums.length];        Arrays.fill(dp,Integer.MAX_VALUE);        for(int i : nums){            int index = binarySearch(dp,i);            if(index < 0){                dp[-(index + 1)] = i;            }        }                for(int i = dp.length - 1; i>=0; i--){            if(dp[i] != Integer.MAX_VALUE){                return i+1;            }        }                return 0;            }        int binarySearch(int[] nums, int i){        int start = 0;        int end = nums.length;        while(start<end){            int midIndex = start + (end - start)/2;            int mid = nums[midIndex];            if(mid < i){                start = midIndex + 1;            }            else if(mid == i){                return midIndex;            }            else{                end = midIndex;            }        }        return -start - 1;             }}

we could maintain an array of the current LIS while i increase, when a new element nums[i] comes, we should replace first element larger then nums[i]. if no element larger than nums[i], we just append it to the last of the LIS.

for example,

1,3,4,2,0,6,3

1

1,3

1,3,4

1,2,4

0,2,4

0,2,4,6

0,2,3,6

Anyway the longest index ever reached in the dp array will be the length of LIS. the substitution ensures the current LIS is always optimal.

PS, we could use the built-in Arrays.binarySearch to achieve the same result.




 


 

0 0
原创粉丝点击