LeetCode OJ: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.

将数组中的0,1,2分别排序,使得相同的数字相邻,这个比较简单,直接看代码:

 1 class Solution {
 2 public:
 3     void sortColors(vector<int>& nums) {
 4         int redNum = count(nums.begin(), nums.end(), 0);
 5         int whiteNum = count(nums.begin(), nums.end(), 1);
 6         int blueNum = count(nums.begin(), nums.end(), 2);
 7         int sz = nums.size();
 8         vector<int> ret(sz, 0);
 9         int redCount = 0, whiteCount = 0, blueCount = 0 ;
10         for(int i = 0; i < sz; ++i){
11             if(nums[i] == 0){
12                 ret[redCount++] = 0;
13             }else if(nums[i] == 1){
14                 ret[whiteCount + redNum] = 1;
15                 whiteCount++;
16             }else{
17                 ret[blueCount + redNum + whiteNum] = 2;
18                 blueCount++;
19             }
20         }
21         nums = ret;
22     }
23 };

 当时题目要求的事one-pass,const-space algorithm,当时硬是没想出来,现在看了下别人的解答,真简洁,原理很简单,3指针,画个图就能看懂了,代码如下所示:

 1 public class Solution {
 2     public void sortColors(int[] nums) {
 3         int i = 0;
 4         int j = nums.length - 1;
 5         int k = nums.length - 1;
 6         while(i <= j){
 7             if(nums[i] == 2){
 8                 int tmp = nums[k];
 9                 nums[k] = nums[i];
10                 nums[i] = tmp;
11                 k--;
12                 if(k < j)
13                     j = k;
14             }else if(nums[i] == 1){
15                 int tmp = nums[j];
16                 nums[j] = nums[i];
17                 nums[i] = tmp;
18                 j--;
19             }else{
20                 i++;
21             }
22         }
23     }
24 }

 

转载于:https://www.cnblogs.com/-wang-cheng/p/4903631.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值