此题解使用了哈希表来存储每个卡牌值最近一次出现的索引。遍历卡牌数组,对于每张卡牌,如果它之前出现过(即在哈希表中存在),则计算当前索引与上一次出现索引的差(即连续卡牌的数量),并更新最小数量。如果没有找到任何匹配的卡牌对,则返回-1。这种方法直接通过索引差计算得到最小连续卡牌数,避免了不必要的重复计算。
时间复杂度: O(n)
空间复杂度: O(n)
class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
# Initialize a dictionary to store the latest index of each card value
d = dict()
# Initialize the minimum number of cards to a large value
ans = len(cards)+1
# Iterate over the card list
for i, item in enumerate(cards):
# If the card value has been seen before, calculate the distance
if (item in d):
ans = min(ans, i - d[item] + 1)
# Update the dictionary with the current index for the card value
d[item] = i
# Return -1 if no such pair is found, else return the minimum distance
return -1 if ans == len(cards)+1 else ans