[LeetCode] Check if an Array Is Consecutive

2229. Check if an Array Is Consecutive

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool isConsecutive(vector<int>& A) {
int mi = *min_element(begin(A), end(A));
for(int i = 0; i < A.size(); i++) A[i] -= mi;
for(int i = 0; i < A.size(); i++) {
while(A[i] != i) {
if(A[i] >= A.size()) return false;
if(A[A[i]] == A[i]) return false;
swap(A[i], A[A[i]]);
}
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/14/PS/LeetCode/check-if-an-array-is-consecutive/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.