Sort Colors
Given an array with n objects colored red, white or blue, sort them 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.
Note:
You are not suppose to use the library's sort function for this problem.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
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.
Could you come up with an one-pass algorithm using only constant space?
思路:计数排序,生成新数组。
Follow Up:
用两个index。 一个red_index 从0开始;一个blue index 从n-1开始。然后扫描。
遇到A[i]==0, swap A【i】和A【red_index】;而后red_index++,i++;
遇到A[i]==2, swapA【i】和A【blue_index】;而后blue_index--;注意i没有++。因为要在下一个循环中判断交换过来的数字。
遇到A[i]==1, i++.
1 class Solution { 2 public: 3 void sortColors(int A[], int n) { 4 int red_index=0; 5 int blue_index=n-1; 6 7 for(int i=0;i<=blue_index;) 8 { 9 if(A[i]==0) 10 { 11 swap(A[i],A[red_index]); 12 red_index++; 13 i++; 14 continue; 15 } 16 else if(A[i]==2) 17 { 18 swap(A[i],A[blue_index]); 19 blue_index--; 20 continue; 21 } 22 i++; 23 24 25 26 } 27 } 28 };
浙公网安备 33010602011771号