Friday, September 20, 2019

Leetcode 950: Reveal Cards In Increasing Order

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



Notes:

This question is a very interesting one. After thinking for a while, it turns out that we need to start with the last one (or the biggest). After figuring this out, it is easy to code.

See the code below:

  1. class Solution {
  2. public:
  3.     vector<int> deckRevealedIncreasing(vector<int>& deck) {
  4.         if(deck.size() < 2) return deck;
  5.         list<int> res;
  6.         sort(deck.begin(), deck.end());
  7.         int len = deck.size(), cur = len-1;
  8.         res.push_back(deck[cur]);
  9.         while(res.size() < len - 1) {
  10.             res.push_front(deck[--cur]);
  11.             res.push_front(res.back());
  12.             res.pop_back();
  13.         }
  14.         res.push_front(deck[--cur]);
  15.         return vector<int>(res.begin(), res.end());
  16.     }
  17. };

No comments:

Post a Comment