class Solution:
def isConsecutive(self, nums):
if not nums:
return False
n = len(nums)
min_num = min(nums)
max_num = max(nums)
if max_num - min_num + 1 != n:
return False
seen = set()
for num in nums:
if num in seen:
return False
seen.add(num)
return True
class Solution {
public:
bool isConsecutive(vector<int>& nums) {
if (nums.empty()) return false;
int n = nums.size();
int min_num = *min_element(nums.begin(), nums.end());
int max_num = *max_element(nums.begin(), nums.end());
if (max_num - min_num + 1 != n) return false;
unordered_set<int> seen;
for (int num : nums) {
if (seen.count(num)) return false;
seen.insert(num);
}
return true;
}
};
class Solution {
public boolean isConsecutive(int[] nums) {
if (nums == null || nums.length == 0) return false;
int n = nums.length;
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int num : nums) {
if (num < min) min = num;
if (num > max) max = num;
}
if (max - min + 1 != n) return false;
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (seen.contains(num)) return false;
seen.add(num);
}
return true;
}
}
var isConsecutive = function(nums) {
if (!nums || nums.length === 0) return false;
let minNum = Math.min(...nums);
let maxNum = Math.max(...nums);
if (maxNum - minNum + 1 !== nums.length) return false;
let seen = new Set();
for (let num of nums) {
if (seen.has(num)) return false;
seen.add(num);
}
return true;
};
Given an integer array nums
, determine if it contains a set of consecutive numbers (with no duplicates and no gaps), regardless of their order in the array.
In other words, after sorting, the numbers should form a sequence where each number is exactly one greater than the previous.
The array must not contain any repeated elements.
nums
must be unique.False
.True
if the array is consecutive, False
otherwise.The most direct way to check if an array is consecutive is to sort it and then check if every element differs from the previous by exactly one. However, sorting takes O(n log n) time, and we can do better.
Let's think about the properties of consecutive numbers:
max - min + 1 == n
.Instead of sorting, we can find the minimum and maximum, check the range, and use a set to check for duplicates. This approach leverages hash sets for O(1) lookups.
False
.False
.True
.We use a hash set because it allows us to check for duplicates in constant time, and the min/max checks ensure the range is exactly right for consecutiveness.
Let's use the input nums = [4, 2, 3, 5, 6]
.
If the input had been [1, 2, 4, 5]
, then max - min + 1 = 5 - 1 + 1 = 5 but the length is 4, so we'd return False due to the gap.
The optimized approach is faster for large arrays and avoids the overhead of sorting.
To check if an array is consecutive, we: