返回介绍

solution / 2200-2299 / 2260.Minimum Consecutive Cards to Pick Up / README_EN

发布于 2024-06-17 01:03:08 字数 3673 浏览 0 评论 0 收藏 0

2260. Minimum Consecutive Cards to Pick Up

中文文档

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

Solution 1

class Solution:
  def minimumCardPickup(self, cards: List[int]) -> int:
    last = {}
    ans = inf
    for i, x in enumerate(cards):
      if x in last:
        ans = min(ans, i - last[x] + 1)
      last[x] = i
    return -1 if ans == inf else ans
class Solution {
  public int minimumCardPickup(int[] cards) {
    Map<Integer, Integer> last = new HashMap<>();
    int n = cards.length;
    int ans = n + 1;
    for (int i = 0; i < n; ++i) {
      if (last.containsKey(cards[i])) {
        ans = Math.min(ans, i - last.get(cards[i]) + 1);
      }
      last.put(cards[i], i);
    }
    return ans > n ? -1 : ans;
  }
}
class Solution {
public:
  int minimumCardPickup(vector<int>& cards) {
    unordered_map<int, int> last;
    int n = cards.size();
    int ans = n + 1;
    for (int i = 0; i < n; ++i) {
      if (last.count(cards[i])) {
        ans = min(ans, i - last[cards[i]] + 1);
      }
      last[cards[i]] = i;
    }
    return ans > n ? -1 : ans;
  }
};
func minimumCardPickup(cards []int) int {
  last := map[int]int{}
  n := len(cards)
  ans := n + 1
  for i, x := range cards {
    if j, ok := last[x]; ok && ans > i-j+1 {
      ans = i - j + 1
    }
    last[x] = i
  }
  if ans > n {
    return -1
  }
  return ans
}
function minimumCardPickup(cards: number[]): number {
  const n = cards.length;
  const last = new Map<number, number>();
  let ans = n + 1;
  for (let i = 0; i < n; ++i) {
    if (last.has(cards[i])) {
      ans = Math.min(ans, i - last.get(cards[i]) + 1);
    }
    last.set(cards[i], i);
  }
  return ans > n ? -1 : ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文