[LeetCode] 950. Reveal Cards In Increasing Order

융쬬·2024년 4월 10일

Algorithm

목록 보기
9/24

문제 바로가기

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

 

💡 문제

You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].

You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.

You will do the following steps repeatedly until all cards are revealed:

  1. Take the top card of the deck, reveal it, and take it out of the deck.
  2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
  3. If there are still unrevealed cards, go back to step 1. Otherwise, stop.

Return an ordering of the deck that would reveal the cards in increasing order.

Note that the first entry in the answer is considered to be the top of the deck.

ex)

InputOutputExplanation
deck = [17,13,11,2,3,5,7][2,13,3,11,5,17,7]We get the deck in the order [17,13,11,2,3,5,7] (this order does not 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.

 

💡 알고리즘 설계

  • N = deck의 길이
  • Queue를 생성하여, 인덱스 값(0~N)을 넣어준다.
  • 카드 모음 deck을 오름차순 정렬한다.
  • 길이가 N인 answer 리스트를 0으로 초기화 해준다.
  • answer의 인덱스 값에 deck[0]부터 deck[N]까지를 넣어준다. 이 때, deque의 popleft()와 rotate(-1)을 사용하여 퐁당퐁당으로 넣어준다.
    ex)
    answer[0] = deck[0]
    answer[2] = deck[1]
    answer[4] = deck[2]
    answer[6] = deck[3]
    answer[3] = deck[4]
    answer[1] = deck[5]
    answer[5] = deck[6]

💡 코드

class Solution:
    def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:
        N = len(deck)
        
        q=deque()
        for i in range(N):
            q.append(i)
        
        deck.sort()
        
        answer=[0]*N
        for i in range(N):
            answer[q[0]] = deck[i]
            q.popleft()
            q.rotate(-1)
        
        
        return answer
Runtime: 87.03% of Python3 online submissions
Memory Usage: 80.95% of Python3 online submissions

 

💡 느낀점

  • 큐를 사용해서 풀어야 하는 문제임은 파악했고, pop과 rotate을 사용할 생각도 했음. 하지만 문제는 뭐를 큐에 넣고 돌려야 하는지 생각을 못 해냈음.
  • 인덱스를 활용하는 것까지 생각을 확장하자.. 인덱스를 큐에 넣고 돌려도 된다. 지난번에도 인덱스를 활용해서 푸는 문제가 있었는데, 왜 또 생각을 못 해낸건지ㅠ
profile
영어공부 하는 Computer Scientist

0개의 댓글