Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Reveal Cards In Increasing Order trong C++


Cho bộ bài các số duy nhất. Ta sắp xếp bộ bài, sau đó lặp: lấy bài trên cùng lộ ra, bài tiếp theo đưa xuống dưới. Tìm thứ tự sắp xếp ban đầu để các bài được lộ ra theo thứ tự tăng dần.

Ví dụ: [17,13,11,2,3,5,7] → [2,13,3,11,5,17,7].

Giải pháp mô phỏng ngược:

  • Sắp xếp deck tăng dần

  • Queue q chứa chỉ số 0..n-1

  • Với i từ 0 đến n-1:
    x = q.front(), q.pop()
    ans[x] = deck[i]
    x = q.front(), q.pop()
    q.push(x)

  • Trả về ans

Ví dụ

#include <bits/stdc++.h> using namespace std; void print_vector(vector<int> v){ cout << "["; for(int i=0;i<v.size();i++) cout << v[i] << ", "; cout << "]"<<endl; } class Solution {    public:    vector<int> deckRevealedIncreasing(vector<int>& deck) {       sort(deck.begin(), deck.end());       int n = deck.size();       queue <int> q; vector <int> ans(n);       for(int i = 0; i < n; i++) q.push(i);       for(int i = 0; i < n; i++){          int x = q.front(); q.pop();          ans[x] = deck[i];          x = q.front(); q.pop(); q.push(x);       }       return ans;    } }; int main(){ vector<int> v1 = {17,13,11,2,3,5,7}; Solution ob; print_vector(ob.deckRevealedIncreasing(v1)); }

Đầu vào

[17,13,11,2,3,5,7]

Đầu ra

[2,13,3,11,5,17,7]