返回介绍

solution / 2200-2299 / 2229.Check if an Array Is Consecutive / README_EN

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

2229. Check if an Array Is Consecutive

中文文档

Description

Given an integer array nums, return true _if _nums_ is consecutive, otherwise return _false_._

An array is consecutive if it contains every number in the range [x, x + n - 1] (inclusive), where x is the minimum number in the array and n is the length of the array.

 

Example 1:

Input: nums = [1,3,4,2]
Output: true
Explanation:
The minimum value is 1 and the length of nums is 4.
All of the values in the range [x, x + n - 1] = [1, 1 + 4 - 1] = [1, 4] = (1, 2, 3, 4) occur in nums.
Therefore, nums is consecutive.

Example 2:

Input: nums = [1,3]
Output: false
Explanation:
The minimum value is 1 and the length of nums is 2.
The value 2 in the range [x, x + n - 1] = [1, 1 + 2 - 1], = [1, 2] = (1, 2) does not occur in nums.
Therefore, nums is not consecutive.

Example 3:

Input: nums = [3,5,4]
Output: true
Explanation:
The minimum value is 3 and the length of nums is 3.
All of the values in the range [x, x + n - 1] = [3, 3 + 3 - 1] = [3, 5] = (3, 4, 5) occur in nums.
Therefore, nums is consecutive.

 

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 105

Solutions

Solution 1

class Solution:
  def isConsecutive(self, nums: List[int]) -> bool:
    mi, mx = min(nums), max(nums)
    n = len(nums)
    return len(set(nums)) == n and mx == mi + n - 1
class Solution {
  public boolean isConsecutive(int[] nums) {
    int mi = nums[0];
    int mx = nums[0];
    Set<Integer> s = new HashSet<>();
    for (int v : nums) {
      mi = Math.min(mi, v);
      mx = Math.max(mx, v);
      s.add(v);
    }
    int n = nums.length;
    return s.size() == n && mx == mi + n - 1;
  }
}
class Solution {
public:
  bool isConsecutive(vector<int>& nums) {
    unordered_set<int> s(nums.begin(), nums.end());
    int mi = *min_element(nums.begin(), nums.end());
    int mx = *max_element(nums.begin(), nums.end());
    int n = nums.size();
    return s.size() == n && mx == mi + n - 1;
  }
};
func isConsecutive(nums []int) bool {
  s := map[int]bool{}
  mi, mx := slices.Min(nums), slices.Max(nums)
  for _, x := range nums {
    s[x] = true
  }
  return len(s) == len(nums) && mx == mi+len(nums)-1
}

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

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

发布评论

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