LeetCode 300 Longest Increasing Subsequence
2016-07-03 21:28
531 查看
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given
The longest increasing subsequence is
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(n^2)解法(运行时间33
ms),参考:西施豆腐渣
维护一个单调序列。遍历nums数组,二分查找每一个数在单调序列中的位置,然后替换。
另外,Arrays.binarySearch(dp, 0, len, x)的底层实现为:
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(n^2)解法(运行时间33
ms),参考:西施豆腐渣
public int lengthOfLIS(int[] nums) { int max = 0; int[] dp = new int[nums.length];//d[i]为subset0...i的Longest increasing sub. for (int i = 0; i < nums.length; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (nums[i] > nums[j]) dp[i] = Math.max(dp[i], dp[j] + 1); } max = Math.max(max, dp[i]); } return max; }方法二: O(n * log n)解法(运行时间1ms):
维护一个单调序列。遍历nums数组,二分查找每一个数在单调序列中的位置,然后替换。
public int lengthOfLIS2(int[] nums) { int[] dp = new int[nums.length]; int len = 0; for (int x : nums) { int i = Arrays.binarySearch(dp, 0, len, x);//二分查找x在单调序列的位置 if (i < 0) i = -(i + 1); dp[i] = x; if (i == len) len++; } return len; }
另外,Arrays.binarySearch(dp, 0, len, x)的底层实现为:
// Like public version, but without range checks. private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解