首页 > 其他 > 详细

*Longest Increasing Subsequence

时间:2016-01-15 06:17:04      阅读:172      评论:0      收藏:0      [点我收藏+]

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(Nlog(N))

讲解在此:

http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/

Our strategy determined by the following conditions,

1. If A[i] is smallest among all end candidates of active lists, we will start new active list of length 1.

2. If A[i] is largest among all end candidates of active lists, we will clone the largest active list, and extend it by A[i].

3. If A[i] is in between, we will find a list with largest end element that is smaller than A[i]. Clone and extend this list by A[i]. We will discard all other lists of same length as that of this modified list.

 

Note that at any instance during our construction of active lists, the following condition is maintained.

“end element of smaller list is smaller than end elements of larger lists”.

It will be clear with an example, let us take example from wiki {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}.

 

其中tailtable是用来存储过程中出现的可能的每个list的最后一个element。其中第三种情况的时候,利用binarysearch在taitalbe中寻找到可以“放”nums[i]的位置。这个“放”就是discard原来的,replace当前的nums[i].

public class Solution {
    public int lengthOfLIS(int[] nums) 
    {
        if(nums==null||nums.length==0) return 0;
        int[] tailtable = new int[nums.length];
        tailtable[0] = nums [0];
        int len = 1;
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]<tailtable[0]) tailtable[0]=nums[i];
            else if(nums[i]>tailtable[len-1]) tailtable[len++] = nums[i];
            else 
            {
                int pos = binarysearch(tailtable,-1,len-1,nums[i]);
                tailtable[pos] = nums[i];
            }
        }
        return len;
    }
    
    public int binarysearch(int[] tailtable, int left, int right, int key)
    {
        while(left<right-1)
        {
            int mid = left + (right-left)/2;
            if(tailtable[mid]>=key)
            {
                right = mid;
            }
            else left = mid;
        }
        return right;
    }
}

 

*Longest Increasing Subsequence

原文:http://www.cnblogs.com/hygeia/p/5132156.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!