首页 > 代码库 > LeetCode:Sort Colors
LeetCode: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.
思路:运用counting sort的思想。先遍历一遍数组,分别统计出0,1,2的个数n0,n1,n2。然后分别将n0个0,n1个1,n2个2写入到原数组中。
代码:
void Solution::sortColors(int A[], int n) { int zero = 0; int one = 0; int two = 0; int i; for(i = 0;i < n;i++) { if(A[i] == 0) zero++; else if(A[i] == 1) one++; else if(A[i] == 2) two++; } i = 0; while(zero > 0) { A[i] = 0; i++; zero--; } while(one > 0) { A[i] = 1; i++; one--; } while(two > 0) { A[i] = 2; i++; two--; } }
LeetCode:Sort Colors
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。