forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
partition-array.cpp
42 lines (36 loc) · 941 Bytes
/
partition-array.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
38
39
40
41
42
// Time: O(n)
// Space: O(1)
class Solution {
public:
int partitionArray(vector<int> &nums, int k) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
while (left <= right && nums[left] < k) {
++left;
}
while (left <= right && nums[right] >= k) {
--right;
}
if (left <= right) {
swap(nums[left++], nums[right--]);
}
}
return left;
}
};
class Solution2 {
public:
int partitionArray(vector<int> &nums, int k) {
int left = 0;
int right = nums.size();
while (left < right) {
if (nums[left] < k) { // Increase left boundary.
++left;
} else { // Put every element > k to the right.
swap(nums[left], nums[--right]);
}
}
return left;
}
};