标签:style blog color os io strong for ar div
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.
思路:先统计每种颜色个数,然后设置数组A的值。
1 class Solution { 2 public: 3 void sortColors( int A[], int n ) { 4 int colorCnt[3] = { 0 }; 5 for( int i = 0; i < n; ++i ) { ++colorCnt[A[i]]; } 6 int pos = 0; 7 for( int i = 0; i < 3; ++i ) { 8 for( int k = 0; k < colorCnt[i]; ++k ) { A[pos++] = i; } 9 } 10 return; 11 } 12 };
follow up中要求单次遍历、常空间复杂度。依次遍历输入数组,若当前元素为0,则将其交换到数组前部;若当前元素为2,则将其交换到数组后部。
1 class Solution { 2 public: 3 void sortColors( int A[], int n ) { 4 int s = 0, e = n-1; 5 int i = 0; 6 while( i <= e ) { 7 if( A[i] == 0 ) { 8 if( i == s ) { 9 ++s; ++i; 10 } else { 11 A[i] ^= A[s]; 12 A[s] ^= A[i]; 13 A[i] ^= A[s]; 14 ++s; 15 } 16 } else if( A[i] == 2 ) { 17 if( i < e ) { 18 A[i] ^= A[e]; 19 A[e] ^= A[i]; 20 A[i] ^= A[e]; 21 } 22 --e; 23 } else { 24 ++i; 25 } 26 } 27 return; 28 } 29 };
标签:style blog color os io strong for ar div
原文地址:http://www.cnblogs.com/moderate-fish/p/3932141.html