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 반환합니다.
Input: cards = [3,4,2,3,4,7]
Output: 4
[3,4,2,3]와 [4,2,3,4] 두가지가 나옵니다.
하지만 둘다 길이가 4라서 최소길이 4를 반환 합니다.
Input: cards = [1,0,5,3]
Output: -1
제한사항
1 ≤ cards.length ≤
0 ≤ cards[i] ≤
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