950. Reveal Cards In Increasing Order

Posted habibah-chang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了950. Reveal Cards In Increasing Order相关的知识,希望对你有一定的参考价值。

问题:

给一组数组,对其进行一个排序得到新的数组res,使得对res做一下操作最后得到target为一个递增数组。

1.取第一个数,到target数组。

2.把剩下的第一个数,排到原数组res最后。

3.重复1和2,直到原数组res为空。

Example 1:
Input: [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation: 
We get the deck in the order [17,13,11,2,3,5,7] (this order doesn‘t matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom.  The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom.  The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom.  The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom.  The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom.  The deck is now [13,17].
We reveal 13, and move 17 to the bottom.  The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.
 

Note:
1 <= A.length <= 1000
1 <= A[i] <= 10^6
A[i] != A[j] for all i != j

  

解法:

要求res数组,那么我们把res的各位index取出。

(n=deck.size())

即为:0,1,2,...,n

做题目的操作,最后得到递增的target,

那么最后经过操作得到的pos序列(index的一个排序),对应上sort后的target每一位。

即target[i]应该在res的pos[i]位上。

再将target的每一位放入相应的index上。也即是恢复了res数组。

res[pos[i]]=target[i]

 

代码参考:

 1 class Solution {
 2 public:
 3     vector<int> deckRevealedIncreasing(vector<int>& deck) {
 4         int n=deck.size();
 5         vector<int> pos;
 6         vector<int> res(n,0);
 7         queue<int> q;
 8         sort(deck.begin(), deck.end());
 9         for(int i=0; i<n; i++){
10             q.push(i);
11         }
12         pos.push_back(q.front());
13         q.pop();
14         while(!q.empty()){
15             q.push(q.front());
16             q.pop();
17             pos.push_back(q.front());
18             q.pop();
19         }
20         for(int i=0; i<n; i++){
21             res[pos[i]]=deck[i];
22         }
23         return res;
24     }
25 };

 

以上是关于950. Reveal Cards In Increasing Order的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 950. Reveal Cards In Increasing Order

[LeetCode] 950. Reveal Cards In Increasing Order 按递增顺序显示卡牌

113th LeetCode Weekly Contest Reveal Cards In Increasing Order

cocoa pods报错The dependency `Reveal-iOS-SDK` is not used in any concrete target.

Integrated Metabolomics and Lipidomics Analyses Reveal Metabolic Reprogramming in Human Glioma with

CodeForces - 950DA Leapfrog in the Array