LeetCode 354. Russian Doll Envelopes
阿新 • • 發佈:2018-12-30
題目連結:俄羅斯套娃信封問題 - 力扣 (LeetCode)
You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.
What is the maximum number of envelopes can you Russian doll? (put one inside other)
Note:
Rotation is not allowed.
Example:
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
二維LIS(longest increasing subsequence,最長上升子序列)問題
O(nlogn)做法:最長上升子序列 nlogn (導彈攔截) - LovelyTotoro - CSDN部落格
- 自定義比較函式必須是靜態(static)
class Solution {
public:
static bool cmp(const pair<int, int>& p1, const pair<int, int>& p2){
if(p1.first != p2.first) return p1.first < p2.first;
return p1.second > p2.second;
}
int maxEnvelopes(vector<pair< int, int>>& envelopes) {
sort(envelopes.begin(), envelopes.end(), cmp);
for(auto x : envelopes) cout << x.first <<","<<x.second<< " ";
cout <<endl;
vector<int> v;
for(auto x : envelopes){
int y = x.second;
if(v.empty() || y > v.back()) v.push_back(y);
else{
// 二分找佇列v裡 第一個 大於等於y的位置
int l = 0, r = v.size() - 1;
while(l < r){
int mid = l + r >> 1;
if(v[mid] >= y) r = mid;
else l = mid + 1;
}
v[l] = y;
}
}
return v.size();
}
};