8000 Update SortColors.cpp · smilegithub01/leetcode@0db08f5 · GitHub
[go: up one dir, main page]

Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

8000
Appearance settings

Commit 0db08f5

Browse files
committed
< 8000 /div>
Update SortColors.cpp
1 parent e335150 commit 0db08f5

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

SortColors/SortColors.cpp

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,19 @@
1-
21
class Solution {
32
public:
43
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;
4+
int p0 = -1;
5+
int p1 = 0;
6+
int p2 = n;
7+
while (p1 < p2) {
8+
if (A[p1] == 1) {
9+
p1++;
10+
} else if (A[p1] == 0) {
11+
swap(A[p0+1], A[p1]);
12+
p0++;
13+
p1++;
14+
} else {
15+
swap(A[p1], A[p2-1]);
16+
p2--;
2217
}
2318
}
2419
}
@@ -46,4 +41,4 @@ class Solution2 {
4641
}
4742
return i;
4843
}
49-
};
44+
};

0 commit comments

Comments
 (0)
0