Skip to content

Commit 3411f10

Browse files
authored
Create check-if-an-array-is-consecutive.cpp
1 parent 9659f27 commit 3411f10

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
// hash table
5+
class Solution {
6+
public:
7+
bool isConsecutive(vector<int>& nums) {
8+
return (*max_element(cbegin(nums), cend(nums)) -
9+
*min_element(cbegin(nums), cend(nums)) + 1) == size(nums) &&
10+
size(nums) == size(unordered_set<int>(cbegin(nums), cend(nums)));
11+
}
12+
};
13+
14+
// Time: O(nlogn)
15+
// Space: O(1)
16+
// sort
17+
class Solution2 {
18+
public:
19+
bool isConsecutive(vector<int>& nums) {
20+
sort(begin(nums), end(nums));
21+
for (int i = 0; i + 1 < size(nums); ++i) {
22+
if (nums[i] + 1 != nums[i + 1]) {
23+
return false;
24+
}
25+
}
26+
return true;
27+
}
28+
};

0 commit comments

Comments
 (0)