zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    php上传文件大小修改
    flex布局
    restful
    mysql之windows忘记密码
    mysql常用命令
    比较级浅析1
    一般副词的位子
    still讲解
    英语学习法
    as的如下用法
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12971474.html
Copyright © 2011-2022 走看看