2260. Minimum Consecutive Cards to Pick Up Medium
1use std::collections::HashMap;
2
3/**
4 * [2260] Minimum Consecutive Cards to Pick Up
5 *
6 * You are given an integer array cards where cards[i] represents the value of the i^th card. A pair of cards are matching if the cards have the same value.
7 * 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.
8 *
9 * Example 1:
10 *
11 * Input: cards = [3,4,2,3,4,7]
12 * Output: 4
13 * 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.
14 *
15 * Example 2:
16 *
17 * Input: cards = [1,0,5,3]
18 * Output: -1
19 * Explanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards.
20 *
21 *
22 * Constraints:
23 *
24 * 1 <= cards.length <= 10^5
25 * 0 <= cards[i] <= 10^6
26 *
27 */
28pub struct Solution {}
29
30// problem: https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/
31// discuss: https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/?currentPage=1&orderBy=most_votes&query=
32
33// submission codes start here
34
35impl Solution {
36 pub fn minimum_card_pickup(cards: Vec<i32>) -> i32 {
37 let mut map: HashMap<i32, usize> = HashMap::new();
38 let mut ans: i32 = i32::MAX;
39 for i in 0..cards.len() {
40 let current: i32 = match map.get(&cards[i]) {
41 None => i32::MAX,
42 Some(last) => (i - *last + 1) as i32,
43 };
44
45 if current < ans {
46 ans = current;
47 }
48
49 map.insert(cards[i], i);
50 }
51
52 if ans == i32::MAX {
53 -1
54 } else {
55 ans
56 }
57 }
58}
59
60// submission codes end
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 #[test]
67 fn test_2260_1() {
68 assert_eq!(Solution::minimum_card_pickup(vec!(3, 4, 2, 3, 4, 7)), 4);
69 assert_eq!(Solution::minimum_card_pickup(vec!(1, 0, 5, 3)), -1);
70
71 assert_eq!(
72 Solution::minimum_card_pickup(vec!(
73 70, 37, 70, 41, 1, 62, 71, 49, 38, 50, 29, 76, 29, 41, 22, 66, 88, 18, 85, 53
74 )),
75 3
76 );
77 }
78}
79
Back
© 2025 bowen.ge All Rights Reserved.