Skip to content

Latest commit

 

History

History
142 lines (115 loc) · 3.41 KB

File metadata and controls

142 lines (115 loc) · 3.41 KB

中文文档

Description

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.

 

Example 1:

Input: cards = [3,4,2,3,4,7]
Output: 4
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.

Example 2:

Input: cards = [1,0,5,3]
Output: -1
Explanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards.

 

Constraints:

  • 1 <= cards.length <= 105
  • 0 <= cards[i] <= 106

Solutions

Python3

class Solution:
    def minimumCardPickup(self, cards: List[int]) -> int:
        m = {}
        ans = 10**6
        for i, c in enumerate(cards):
            if c in m:
                ans = min(ans, i - m[c] + 1)
            m[c] = i
        return -1 if ans == 10**6 else ans

Java

class Solution {
    public int minimumCardPickup(int[] cards) {
        Map<Integer, Integer> m = new HashMap<>();
        int ans = 1000000;
        for (int i = 0; i < cards.length; ++i) {
            int c = cards[i];
            if (m.containsKey(c)) {
                ans = Math.min(ans, i - m.get(c) + 1);
            }
            m.put(c, i);
        }
        return ans == 1000000 ? -1 : ans;
    }
}

C++

class Solution {
public:
    int minimumCardPickup(vector<int>& cards) {
        unordered_map<int, int> m;
        int ans = 1e6;
        for (int i = 0; i < cards.size(); ++i) {
            int c = cards[i];
            if (m.count(c)) ans = min(ans, i - m[c] + 1);
            m[c] = i;
        }
        return ans == 1e6 ? -1 : ans;
    }
};

Go

func minimumCardPickup(cards []int) int {
	m := map[int]int{}
	ans := 1000000
	for i, c := range cards {
		if j, ok := m[c]; ok {
			ans = min(ans, i-j+1)
		}
		m[c] = i
	}
	if ans == 1000000 {
		return -1
	}
	return ans
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

TypeScript

function minimumCardPickup(cards: number[]): number {
    const n = cards.length;
    let hashMap = new Map<number, number>();
    const max = Number.MAX_SAFE_INTEGER;
    let ans = max;
    for (let i = 0; i < n; i++) {
        let num = cards[i];
        if (hashMap.has(num)) {
            ans = Math.min(i - hashMap.get(num) + 1, ans);
        }
        hashMap.set(num, i);
    }
    return ans == max ? -1 : ans;
}

...