首页 > 其他 > 详细

LintCode-Longest Increasing Subsequence

时间:2014-12-29 06:29:20      阅读:1472      评论:0      收藏:0      [点我收藏+]

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

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 [4, 4, 5, 7], return 4

Challenge

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

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_common_subsequence_problem

Solution 1 (nlogn):

 1 public class Solution {
 2     /**
 3      * @param nums: The integer array
 4      * @return: The length of LIS (longest increasing subsequence)
 5      */
 6     public int longestIncreasingSubsequence(int[] nums) {
 7         if (nums.length==0) return 0;
 8         int len = nums.length;
 9         int[] seqEnd = new int[len+1];
10         seqEnd[1] = 0;
11         int lisLen = 1;
12         for (int i=1;i<len;i++){
13             int pos = findPos(nums,seqEnd,lisLen,i);
14             seqEnd[pos] = i;
15             if (pos>lisLen) lisLen = pos;
16         }
17 
18         return lisLen;
19         
20     }
21 
22     public int findPos(int[] nums, int[] seqEnd, int lisLen, int index){
23         int start = 1;
24         int end = lisLen;
25         while (start<=end){
26             int mid = (start+end)/2;
27     
28             if (nums[index] == nums[seqEnd[mid]]){
29                 return mid;
30             } else if (nums[index]>nums[seqEnd[mid]]){
31                 start = mid+1;
32             } else end = mid-1;
33         }
34         return start;
35     }
36 }

 

LintCode-Longest Increasing Subsequence

原文:http://www.cnblogs.com/lishiblog/p/4190936.html

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