Skip to content

Latest commit

 

History

History
148 lines (115 loc) · 3.39 KB

File metadata and controls

148 lines (115 loc) · 3.39 KB

English Version

题目描述

给你一个整数数组 cards ,其中 cards[i] 表示第 i 张卡牌的 。如果两张卡牌的值相同,则认为这一对卡牌 匹配

返回你必须拿起的最小连续卡牌数,以使在拿起的卡牌中有一对匹配的卡牌。如果无法得到一对匹配的卡牌,返回 -1

 

示例 1:

输入:cards = [3,4,2,3,4,7]
输出:4
解释:拿起卡牌 [3,4,2,3] 将会包含一对值为 3 的匹配卡牌。注意,拿起 [4,2,3,4] 也是最优方案。

示例 2:

输入:cards = [1,0,5,3]
输出:-1
解释:无法找出含一对匹配卡牌的一组连续卡牌。

 

提示:

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

解法

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;
}

...