300. Longest Increasing Subsequence

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

You code should return the length of the LIS.

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_increasing_subsequence

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

正常的思路是对于每个integer,从头到当前值,看是否比当前值小,然后看那个值所对应的LIS + 1是否更大,更大则更新。
 O(nlgn)解法:
 1 public class Solution {
 2     public int lengthOfLIS(int[] nums) {
 3         if (nums == null || nums.length == 0) return 0;
 4         if (nums.length == 1) return 1;
 5 
 6         List<Integer> list = new ArrayList<>();
 7         list.add(nums[0]);
 8 
 9         for (int i = 1; i < nums.length; i++) {
10             if (nums[i] > list.get(list.size() - 1)) {
11                 list.add(nums[i]);
12             } else if (nums[i] < list.get(list.size() - 1)) {
13                 int index = findPosition(list, nums[i]);
14                 list.set(index, nums[i]);
15             }
16         }
17         return list.size();
18     }
19 
20     private int findPosition(List<Integer> list, int target) {
21         int start = 0, end = list.size() - 1;
22         while (start <= end) {
23             int mid = (end - start) / 2 + start;
24             if (list.get(mid) == target) {
25                 return mid;
26             } else if (list.get(mid) < target) {
27                 start = mid + 1;
28             } else {
29                 end = mid - 1;
30             }
31         }
32         return start;
33     }
34 }

 

posted @ 2016-07-08 00:58  北叶青藤  阅读(238)  评论(0编辑  收藏  举报