-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
find-if-array-can-be-sorted.cpp
37 lines (35 loc) · 1.09 KB
/
find-if-array-can-be-sorted.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Time: O(n)
// Space: O(1)
// sort
class Solution {
public:
bool canSortArray(vector<int>& nums) {
for (int right = 0, left = 0, mx = 0; right < size(nums); ++right) {
if (right + 1 != size(nums) && __builtin_popcount(nums[right + 1]) == __builtin_popcount(nums[right])) {
continue;
}
if (mx > *min_element(cbegin(nums) + left, cbegin(nums) + right + 1)) {
return false;
}
mx = *max_element(cbegin(nums) + left, cbegin(nums) + right + 1);
left = right + 1;
}
return true;
}
};
// Time: O(nlogn)
// Space: O(1)
// sort
class Solution2 {
public:
bool canSortArray(vector<int>& nums) {
for (int right = 0, left = 0; right < size(nums); ++right) {
if (right + 1 != size(nums) && __builtin_popcount(nums[right + 1]) == __builtin_popcount(nums[right])) {
continue;
}
sort(begin(nums) + left, begin(nums) + right + 1);
left = right + 1;
}
return is_sorted(cbegin(nums), cend(nums));
}
};