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 theminimum 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.
Input: cards =[3,4,2,3,4,7]Output: 4Explanation: 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.
To find the minimum consecutive cards with a matching pair, track the last index where each card value was seen. When a duplicate is found, calculate the distance and update the minimum.
classSolution {
public:int minimumCardPickup(vector<int>& cards) {
unordered_map<int, int> last;
int ans = INT_MAX;
for (int i =0; i < cards.size(); ++i) {
if (last.count(cards[i])) {
ans = min(ans, i - last[cards[i]] +1);
}
last[cards[i]] = i;
}
return ans == INT_MAX ?-1: ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
funcminimumCardPickup(cards []int) int {
last:= make(map[int]int)
ans:= len(cards) +1fori, v:=rangecards {
ifidx, ok:=last[v]; ok {
ifi-idx+1 < ans {
ans = i-idx+1 }
}
last[v] = i }
ifans > len(cards) {
return-1 }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
publicintminimumCardPickup(int[] cards) {
Map<Integer, Integer> last =new HashMap<>();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < cards.length; i++) {
if (last.containsKey(cards[i])) {
ans = Math.min(ans, i - last.get(cards[i]) + 1);
}
last.put(cards[i], i);
}
return ans == Integer.MAX_VALUE?-1 : ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funminimumCardPickup(cards: IntArray): Int {
val last = mutableMapOf<Int, Int>()
var ans = Int.MAX_VALUE
for (i in cards.indices) {
if (last.containsKey(cards[i])) {
ans = minOf(ans, i - last[cards[i]]!! + 1)
}
last[cards[i]] = i
}
returnif (ans ==Int.MAX_VALUE) -1else ans
}
}
1
2
3
4
5
6
7
8
defminimum_card_pickup(cards: list[int]) -> int:
last: dict[int, int] = {}
ans: int = float('inf')
for i, v in enumerate(cards):
if v in last:
ans = min(ans, i - last[v] +1)
last[v] = i
return-1if ans == float('inf') else ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnminimum_card_pickup(cards: Vec<i32>) -> i32 {
use std::collections::HashMap;
letmut last = HashMap::new();
letmut ans =i32::MAX;
for (i, &v) in cards.iter().enumerate() {
iflet Some(&idx) = last.get(&v) {
ans = ans.min((i asi32) - idx +1);
}
last.insert(v, i asi32);
}
if ans ==i32::MAX { -1 } else { ans }
}
}