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`
分析:
用一个数组a记录对于arr[i], 到它那里最长的subsequence是多少,那么对于arr[i + 1],我们需要从0比较到i, 如果arr[j] < arr[i + 1], 并且a[j] > a[i + 1], 我们就更新a[j + 1]的值。
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[] arr) { 7 // array a is used to store the maximum length 8 int[] a = new int[arr.length]; 9 // initialization, set all the elements in array a to 1; 10 for (int i = 0; i < a.length; i++) { 11 a[i] = 1; 12 } 13 for (int i = 1; i < arr.length; i++) { 14 for (int j = 0; j < i; j++ ) { 15 if (arr[i] >= arr[j] && a[i] <= a[j] ) { 16 a[i] = a[j] + 1; 17 } 18 } 19 } 20 int max = 0; 21 //find the longest subsequence 22 for (int i = 0; i < a.length; i++) { 23 if (a[i] > max ) max = a[i]; 24 } 25 return max; 26 } 27 }
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 }