返回介绍

solution / 2300-2399 / 2350.Shortest Impossible Sequence of Rolls / README_EN

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

2350. Shortest Impossible Sequence of Rolls

中文文档

Description

You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i].

Return_ the length of the shortest sequence of rolls that cannot be taken from _rolls.

A sequence of rolls of length len is the result of rolling a k sided dice len times.

Note that the sequence taken does not have to be consecutive as long as it is in order.

 

Example 1:

Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4
Output: 3
Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.
Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.
The sequence [1, 4, 2] cannot be taken from rolls, so we return 3.
Note that there are other sequences that cannot be taken from rolls.

Example 2:

Input: rolls = [1,1,2,2], k = 2
Output: 2
Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.
The sequence [2, 1] cannot be taken from rolls, so we return 2.
Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.

Example 3:

Input: rolls = [1,1,3,2,2,2,3,3], k = 4
Output: 1
Explanation: The sequence [4] cannot be taken from rolls, so we return 1.
Note that there are other sequences that cannot be taken from rolls but [4] is the shortest.

 

Constraints:

  • n == rolls.length
  • 1 <= n <= 105
  • 1 <= rolls[i] <= k <= 105

Solutions

Solution 1

class Solution:
  def shortestSequence(self, rolls: List[int], k: int) -> int:
    ans = 1
    s = set()
    for v in rolls:
      s.add(v)
      if len(s) == k:
        ans += 1
        s.clear()
    return ans
class Solution {
  public int shortestSequence(int[] rolls, int k) {
    Set<Integer> s = new HashSet<>();
    int ans = 1;
    for (int v : rolls) {
      s.add(v);
      if (s.size() == k) {
        s.clear();
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int shortestSequence(vector<int>& rolls, int k) {
    unordered_set<int> s;
    int ans = 1;
    for (int v : rolls) {
      s.insert(v);
      if (s.size() == k) {
        s.clear();
        ++ans;
      }
    }
    return ans;
  }
};
func shortestSequence(rolls []int, k int) int {
  s := map[int]bool{}
  ans := 1
  for _, v := range rolls {
    s[v] = true
    if len(s) == k {
      ans++
      s = map[int]bool{}
    }
  }
  return ans
}

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

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

发布评论

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