题目:
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?
题解:用一个TreeSet实现O(nlgn)。记录的是Pair(lis, element)。自定义comparator >=。C++和Java的TreeSort存的顺序貌似不一样。
C++版:
class Pair { public: int key; int val; Pair(int k, int v) { key = k; val = v; } }; struct comparator { bool operator()(const Pair& i, const Pair& j) const { return i.key >= j.key; } }; class Solution { public: int lengthOfLIS(vector<int>& nums) { if(nums.size() == 0) return 0; int maxL = 1; set<Pair, comparator> s; Pair p(1, nums[0]); s.insert(p); for(int i = 1; i < nums.size(); i++) { auto iter = s.begin(); bool found = false; while(iter != s.end()) { if((*iter).val < nums[i]) { int c = max(1, (*iter).key + 1); Pair q(c, nums[i]); s.insert(q); maxL = c > maxL ? c : maxL; found = true; break; } iter++; } if(found) continue; Pair q(1, nums[i]); s.insert(q); } return maxL; } };
public class Solution { private class Pair { int key; int val; Pair(int k, int v) { key = k; val = v; } } private Comparator<Pair> comparator = new Comparator<Pair>() { @Override public int compare(Pair i, Pair j) { if(i.key <= j.key) return 1; else return -1; } }; public int lengthOfLIS(int[] nums) { if(nums.length == 0) return 0; int maxL = 1; SortedSet<Pair> set = new TreeSet<>(comparator); set.add(new Pair(1, nums[0])); for(int i = 1; i < nums.length; i++) { Iterator iter = set.iterator(); boolean add = false; while(iter.hasNext()) { Pair current = (Pair) iter.next(); if((int)current.val < nums[i]) { int v = Math.max((int)current.key + 1, 1); if(v > maxL) maxL = v; set.add(new Pair(v, nums[i])); add = true; break; } } if(add) { continue; } set.add(new Pair(1, nums[i])); } return maxL; } }