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

Leetcode: Longest Increasing Subsequence

时间:2015-12-29 06:20:54      阅读:260      评论: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(nlogn)

Maintain a potential Longest Increasing Subsequence arraylist

for each element in the array, either add it to the arraylist if elem>arraylist.get(last), or use binary search to search for the correct place to put the elem in the arraylist and replace the original element.

 1 public class Solution {
 2     public int lengthOfLIS(int[] nums) {
 3         if (nums==null || nums.length==0) return 0;
 4         ArrayList<Integer> list = new ArrayList<Integer>();
 5         for (int num : nums) {
 6             if (list.size()==0 || num>list.get(list.size()-1))
 7                 list.add(num);
 8             else {
 9                 update(list, num);
10             }
11         }
12         return list.size();
13     }
14     
15     public void update(ArrayList<Integer> list, int num) {
16         int l=0, r=list.size()-1;
17         while (l <= r) {
18             int m = l + (r-l)/2;
19             if (list.get(m) == num) return;
20             else if (list.get(m) > num) {
21                 r = m-1;
22             }
23             else l = m+1;
24         }
25         list.set(l, num);
26     }
27 }

 

O(N^2)

DP

 1 public class Solution {
 2     public int lengthOfLIS(int[] nums) {
 3         if (nums==null || nums.length==0) return 0;
 4         int res = 1;
 5         int len = nums.length;
 6         int[] dp = new int[len];
 7         Arrays.fill(dp, 1);
 8         for (int i=1; i<len; i++) {
 9             for (int j=0; j<i; j++) {
10                 if (nums[j] < nums[i]) {
11                     dp[i] = Math.max(dp[i], dp[j]+1);
12                     if (dp[i] > res) res = dp[i];
13                 }
14             }
15         }
16         return res;
17     }
18 }

 

Leetcode: Longest Increasing Subsequence

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5084553.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!