[python] Minimum Consecutive Cards to Pick Up leetcode 2260

Designated Hitter Jack·2023년 10월 30일
0

leetcode

목록 보기
6/11
post-thumbnail

문제

You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value.

Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1.

Example 1:
  Input: cards = [3,4,2,3,4,7]
  Output: 4
  Explanation: We can pick up the cards [3,4,2,3] 
  which contain a matching pair of cards with value 3. 
  Note that picking up the cards [4,2,3,4] is also optimal.

Example 2:
  Input: cards = [1,0,5,3]
  Output: -1
  Explanation: There is no way to pick up a set of consecutive cards 
  that contain a pair of matching cards.
 
Constraints:
  1 <= cards.length <= 105
  0 <= cards[i] <= 106

풀이

class Solution:
    def minimumCardPickup(self, cards: List[int]) -> int:
        answer = float("inf")
        my_dict = {}
        
        for i in range(len(cards)):
            if cards[i] in my_dict:
                answer = min(answer, (i - my_dict[cards[i]]) + 1)
            my_dict[cards[i]] = i
            
        if answer == float("inf"):
            return -1
        else:
            return answer

list 대신 dictionary 를 이용하여 if~in을 이용해 해당 element가 있는지 확인하는데에 들이는 시간을 O(N)에서 O(1)로 줄일 수 있다.
my_dict라는 dictionary에 key는 card의 숫자, value로는 index를 넣어준다.

profile
Fear always springs from ignorance.

0개의 댓글