[2260] Minimum Consecutive Cards to Pick Up | Medium| contest 291

yoongyum·2022년 5월 1일
0

코딩테스트 🧩

목록 보기
28/47
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.

배열을 맨앞에서 맨뒤까지 중복되는 숫자가 나올 때 까지 연속적으로 탐색합니다.

연속성의 최소길이를 비교하여 리턴하는 문제입니다.

중복숫자가 하나도 없으면 -1 반환합니다.

Example 1

Input: cards = [3,4,2,3,4,7]
Output: 4

[3,4,2,3]와 [4,2,3,4] 두가지가 나옵니다.
하지만 둘다 길이가 4라서 최소길이 4를 반환 합니다.

Example 2

Input: cards = [1,0,5,3]
Output: -1

제한사항
1 ≤ cards.length ≤ 10510^5
0 ≤ cards[i] ≤ 10610^6



🧊 파이썬 코드

class Solution:
    def minimumCardPickup(self, cards: List[int]) -> int:
        ans = 100001
        arr = defaultdict(list)
        for i,card in enumerate(cards):
            arr[card].append(i)
            if len(arr[card]) > 1:
                ans = min( ans, abs(arr[card].pop(0)-i)+1)
            
        return -1 if ans == 100001 else ans

0개의 댓글