75. Sort Colors

75. 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三个值大量重复,可以考虑直接扫描一遍,统计这三个值出现的个数,再赋值一遍。(避开了交换的代价)

86 / 86 test cases passed. Runtime: 3 ms. Your runtime beats 13.43% of cpp submissions.

另有方法:点击打开链接

思路:设三个位置索引分别标识0.1.2的最后出现位置,默认位置为-1(即不存在该值元素),从0位置开始扫描,若遇到0,则所有位置索引+1;若遇到1,则2,1的位置索引+1,若遇到2,则只有2的位置索引需要后移;

Your runtime beats 13.43% of cpp submissions.

代码如下:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int len = nums.size();
/*        int num0=0, num1=0, num2=0;
        for( int i=0; i<len; ++i ){
            switch(nums[i]){
                case 0: ++num0; break;
                case 1: ++num1; break;
                case 2: ++num2; break; //not necessary
            }
        }
        for( int i=0; i<len; ++i ){
            if( i<num0 ){
                nums[i] = 0;
            }else{
                if( i>=num0+num1 ){
                    nums[i] = 2;
                }else{
                    nums[i] = 1;
                }
            }
        }
*/        
        int loc0 = -1, loc1 = -1, loc2 = -1;
        for( int i=0; i<len; ++i ){
            if( nums[i]==0 ){
                nums[++loc2] = 2;
                nums[++loc1] = 1;
                nums[++loc0] = 0;
            }else{
                if( nums[i]==1 ){
                    nums[++loc2] = 2;
                    nums[++loc1] = 1;
                }else{
                    nums[++loc2] = 2;
                }
            }
        }

    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值