先对数组排序,然后倒序构造需要的结果。
例如:[17,13,11,2,3,5,7]
排序后,[2,3,5,7,11,13,17]
倒序构造方法。从最大值开始考虑。
17 => 17
13 => 13 17
11 => 11 17 13
7 => 7 13 11 17
5 => 5 17 7 13 11
3 => 3 11 5 17 7 13
2 => 2 13 3 11 5 17 7
C++ 代码
class Solution {
public:
vector<int> deckRevealedIncreasing(vector<int>& deck) {
deque<int> q;
sort(deck.begin(),deck.end(),greater<int>());
for(auto i: deck){
if(q.size()<2){
q.push_front(i);
}else{
q.push_front(q.back());
q.pop_back();
q.push_front(i);
}
}
vector<int> ans;
for(auto i: q){
ans.push_back(i);
}
return ans;
}
};