Given an integer array nums, return trueifnums _isconsecutive , 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.
Input: nums =[1,3,4,2]Output: trueExplanation:
The minimum value is1 and the length of nums is4.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:
1
2
3
4
5
6
Input: nums =[1,3]Output: falseExplanation:
The minimum value is1 and the length of nums is2.The value 2in 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:
1
2
3
4
5
6
Input: nums =[3,5,4]Output: trueExplanation:
The minimum value is3 and the length of nums is3.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.
If the array is consecutive, it must contain all numbers from the minimum to the maximum value without any duplicates or missing numbers. Using a set helps us check for duplicates and missing numbers efficiently.
classSolution {
publicbooleanisConsecutive(int[] nums) {
int mn = nums[0], mx = nums[0], n = nums.length;
Set<Integer> s =new HashSet<>();
for (int v : nums) {
mn = Math.min(mn, v);
mx = Math.max(mx, v);
s.add(v);
}
if (mx - mn + 1 != n) returnfalse;
return s.size() == n;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funisConsecutive(nums: IntArray): Boolean {
val n = nums.size
var mn = nums[0]
var mx = nums[0]
val s = mutableSetOf<Int>()
for (v in nums) {
mn = minOf(mn, v)
mx = maxOf(mx, v)
s.add(v)
}
if (mx - mn + 1!= n) returnfalsereturn s.size == n
}
}
1
2
3
4
5
6
7
defisConsecutive(nums: list[int]) -> bool:
mn: int = min(nums)
mx: int = max(nums)
n: int = len(nums)
if mx - mn +1!= n:
returnFalsereturn len(set(nums)) == n
1
2
3
4
5
6
7
8
9
10
11
use std::collections::HashSet;
impl Solution {
pubfnis_consecutive(nums: Vec<i32>) -> bool {
let mn =*nums.iter().min().unwrap();
let mx =*nums.iter().max().unwrap();
let n = nums.len() asi32;
if mx - mn +1!= n { returnfalse; }
let s: HashSet<_>= nums.iter().collect();
s.len() asi32== n
}
}