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.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
- O(1) space , one pass
- first assign all element to 2, =>
- then we check if the current element is smaller than 2, if it is, it could be 1 or 0, then assign the element to 1, =>
- then we check if the current element is 0, if it is, then assign the element to 0;
1 |
void (vector<int>& nums) { |
近期评论