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.

click to show follow up.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

思路:

排序
首先遍历一遍数组,分别记录0,1,2的个数,然后更新原数组,按个数分别附上0,1,2,复杂度为2n

var sortColors = function(nums) {
    var a=0,b=0,c=0;
    for(var i=0;i<nums.length;i++){
        if(nums[i]==0) a++;
        else if(nums[i]===1)b++;
        else if(nums[i]===2)c++;
    }
    for(var i=0;i<a;i++){
        nums[i]=0;
    }
    for(var j=a;j<a+b;j++){
        nums[j]=1;
    }
    for(var i=a+b;i<a+b+c;i++){
        nums[i]=2
    }
};

思路二:题目要求遍历一遍。
设置两个指针,red指向开头0,blue指向结尾。从头遍历数组,如果遇到0,交换该值和red指针指向的值,并将red指针后移一位。若遇到2,则交换该值和blue指针指向的值,并将blue前移一位,但是不知道移过去的是不是0,所以i要减一下重新遍历换好的一位。

var sortColors = function(nums) {
    var red=0;
    var blue=nums.length-1;
    for(var i=0;i<=blue;i++){
        if(nums[i]===0){
            var temp=nums[i];
                nums[i]=nums[red];
                nums[red++]=temp;
        }else if(nums[i]===2){
            var c=nums[i];
                nums[i]=nums[blue];
                nums[blue--]=c;
                i--;
        }
    }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容