首页 > 代码库 > Sort Colors
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.
思路:先统计每种颜色个数,然后设置数组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 };
Sort Colors
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。