Leetcode 75. Sort Colors
1 min readJun 19, 2022
Given an array nums
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.
We will use the integers 0
, 1
, and 2
to represent the color red, white, and blue, respectively.
You must solve this problem without using the library’s sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]class Solution {
public:
void sortColors(vector<int>& nums) {
int p0 = 0;
int p1 = 0;
int curr = 0;
// scan 0
for(p0 = curr; p0 < nums.size(); p0++) {
if (nums[p0] == 0) {
swap(nums[p0], nums[curr]);
curr++;
}
}
// scan 1
for(p1 = curr; p1 < nums.size(); p1++) {
if (nums[p1] == 1) {
swap(nums[p1], nums[curr]);
curr++;
}
}
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Sort Colors.
Memory Usage: 8.3 MB, less than 70.30% of C++ online submissions for Sort Colors.