码迷,mamicode.com
首页 > 其他好文 > 详细

950. Reveal Cards In Increasing Order

时间:2020-05-27 12:22:52      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:return   重复   otto   pos   start   个数   eve   false   code   

问题:

给一组数组,对其进行一个排序得到新的数组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

标签:return   重复   otto   pos   start   个数   eve   false   code   

原文地址:https://www.cnblogs.com/habibah-chang/p/12971474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!