Skip to content

950. Reveal Cards In Increasing Order

950. Reveal Cards In Increasing Order

题目: https://leetcode.com/problems/reveal-cards-in-increasing-order/

难度: Medium

题意:

  1. 有这么个操作
  2. 将牌的第一张拿出来,把下一张放到底部
  3. 重复这种操作
  4. 到最后拿出来的是一个严格递增数列
  5. 求牌开始的顺序

思路:

  • 反过来操作即可
  • 对牌排个序,备选
  • 把底部的牌放到第一张,从备选的牌中选择最大的一张放在顶部
  • 重复这种操作

解法:

class Solution {
public:
    int list[10000];
    int front, back;

    void add(int val) {
        list[front++] = val;
        if (front == 10000) {
            front = 0;
        }
    }

    int remove() {
        int ret = list[back];
        back++;
        if (back == 10000) {
            back = 0;
        } 
        return ret;
    }

    vector<int> deckRevealedIncreasing(vector<int>& deck) {
        front = back = 0;
        sort(deck.begin(), deck.end());
        add(deck[deck.size() - 1]);
        for (int i = deck.size() - 2;i >= 0;i--) {
            int x = remove();
            add(x);
            x = deck[i];
            add(x);
        }
        vector<int> ret;
        int i = back;
        while (i != front) {
            ret.push_back(list[i]);
            i++;
            if (i == 10000) {
                i = 0;
            }
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
};


回到顶部