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.

思路:
这道题目给了我们一个颜色的array,让我们sort一下,按照0,1,2的顺序。根据题目要求,我们只能遍历array一次,可以用到two pointers来实现。设一个指针red 在开头,blue 在最后。想法就是,遇到红色0,就交换,把0放到最左边去;遇到蓝色2就交换,把2都放到最右边去,这样1就会被保留在最中间。需要注意的是,当把蓝色2交换完毕之后,需要i–, 停留 i 在原地一次,因为还需要继续检查 被2交换回来的数字。那当遇到红色0,交换完毕不需要停留i 的原因是, 交换回来的只可能是1,对于1,我们不需要做任何处理,直接过就可以。

class Solution {
    public void sortColors(int[] nums) {
        int red = 0;
        int blue = nums.length-1;
        
        for(int i=0; i<=blue; i++)
        {
            if(nums[i] == 0) // if find 0, swap with red pointer
            {
                int temp = nums[i];
                nums[i] = nums[red];
                nums[red] = temp;
                
                red++;
            }
            else if(nums[i] == 2) // if find 2, swap with blue pointer
            {
                int temp = nums[i];
                nums[i] = nums[blue];
                nums[blue] = temp;
                
                i--;
                blue--;
            }
        }
    }
}
class Solution {
    public void sortColors(int[] nums) {
        int numZero = 0;
        int numOne = 0;
        int numTwo = 0;
        for(int i : nums) {
            if(i == 0) numZero++;
            if(i == 1) numOne++;
            if(i == 2) numTwo++;
        }
        
        for(int i = 0; i < nums.length; i++) {
            if(numZero != 0) {
                nums[i] = 0;
                numZero--;
            } else if(numOne != 0) {
                nums[i] = 1;
                numOne--;
            } else if(numTwo != 0) {
                nums[i] = 2;
                numTwo--;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值