Skip to content

Commit 11d1c51

Browse files
Sort Colors
1 parent 57588fb commit 11d1c51

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

11.cpp

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
3+
Sort Colors
4+
-----------
5+
6+
Solution
7+
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
8+
9+
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
10+
11+
Note: You are not suppose to use the library's sort function for this problem.
12+
13+
Example:
14+
15+
Input: [2,0,2,1,1,0]
16+
Output: [0,0,1,1,2,2]
17+
Follow up:
18+
19+
A rather straight forward solution is a two-pass algorithm using counting sort.
20+
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
21+
Could you come up with a one-pass algorithm using only constant space?
22+
*/
23+
24+
class Solution {
25+
public:
26+
void sortColors(vector<int>& nums) {
27+
int start = 0, mid = 0, end = nums.size() - 1;
28+
while(mid <= end) {
29+
if(nums[mid] == 0) {
30+
swap(nums[start++], nums[mid++]);
31+
} else if(nums[mid] == 1) {
32+
mid++;
33+
} else {
34+
swap(nums[mid], nums[end--]);
35+
}
36+
}
37+
}
38+
};

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@
1111
| 7 | Coin Change 2 | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/7.cpp) |
1212
| 8 | Power of Two | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/8.cpp) |
1313
| 9 | Is Subsequence | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/9.cpp) |
14-
| 10 | Search Insert Position | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/10.cpp) |
14+
| 10 | Search Insert Position | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/10.cpp) |
15+
| 11 | Sort Colors | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/11.cpp) |

0 commit comments

Comments
 (0)