Skip to content

Commit ca07c0f

Browse files
authored
Create 2161. Partition Array According to Given Pivot
1 parent 58d00f4 commit ca07c0f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
vector<int> pivotArray(vector<int>& nums, int pivot) {
4+
int n = nums.size();
5+
vector<int> ans(n);
6+
int lesser = 0, greater = 0, count = 0;
7+
int lesserIndex = 0, pivotIndex = 0, greaterIndex = 0;
8+
9+
for (int i = 0; i < n; i++) {
10+
if (nums[i] < pivot) {
11+
lesser++;
12+
}
13+
else if (nums[i] == pivot) {
14+
count++;
15+
}
16+
else {
17+
greater++;
18+
}
19+
}
20+
pivotIndex = lesser;
21+
greaterIndex = lesser + count;
22+
23+
for (int index = 0; index < n; index++) {
24+
if (lesserIndex < lesser && nums[index] < pivot) {
25+
ans[lesserIndex++] = nums[index];
26+
}
27+
else if (pivotIndex < (lesser + count) && nums[index] == pivot) {
28+
ans[pivotIndex++] = nums[index];
29+
}
30+
else if (greaterIndex < n && nums[index] > pivot) {
31+
ans[greaterIndex++] = nums[index];
32+
}
33+
}
34+
return ans;
35+
}
36+
};

0 commit comments

Comments
 (0)