码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode-Longest Increasing Subsequence

时间:2014-12-29 06:31:53      阅读:131      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!