We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent e335150 commit 0db08f5Copy full SHA for 0db08f5
SortColors/SortColors.cpp
@@ -1,24 +1,19 @@
1
-
2
class Solution {
3
public:
4
void sortColors(int A[], int n) {
5
- // Start typing your C/C++ solution below
6
- // DO NOT write int main() function
7
8
- int low = 0, high = n - 1;
9
- int mid = 0;
10
11
- while (mid <= high) {
12
- if (A[mid] == 0) {
13
- A[mid++] = A[low];
14
- A[low++] = 0;
15
- }
16
- else if (A[mid] == 1) {
17
- mid += 1;
18
19
- else if (A[mid] == 2) {
20
- A[mid] = A[high];
21
- A[high--] = 2;
+ int p0 = -1;
+ int p1 = 0;
+ int p2 = n;
+ while (p1 < p2) {
+ if (A[p1] == 1) {
+ p1++;
+ } else if (A[p1] == 0) {
+ swap(A[p0+1], A[p1]);
+ p0++;
+ } else {
+ swap(A[p1], A[p2-1]);
+ p2--;
22
}
23
24
@@ -46,4 +41,4 @@ class Solution2 {
46
41
47
42
return i;
48
43
49
-};
44
+};
0 commit comments