Leetcode_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表示
现在请你把它们进行排序。
思路:
1.因为0,1,2取值范围有限。使用桶排序的思想。
2.开辟一个新的数组book,数组大小为3。
3.遍历一遍原数组,把原数组中的元素加入到book中。
4.遍历book数组,还原原数组。

    public void sortColors(int[] nums) {
        int []book={0,0,0};
        for(int i=0;i<nums.length;i++){
            int x=nums[i];
            book[x]++;
        }//加入桶中
        int index=0;
        for(int i=0;i<book.length;i++){//还原
            for(int j=0;j<book[i];j++){
                nums[index++]=i;
            }
        }
    }

思路特别简单。
在这里还可以使用三路快排进行排序。速度比上面一个方法要快(当然上面一个方法也很快)
思路:
因为只有0,1,2。所以我们可以进行三路快速排序
1.设置left和right两个指针。
2.用一个i从前往后走。当i>1的时候把它丢到右边去。当i<1时。把它丢到左边去。

    public void sortColors(int[] nums) {
        int left=0;
        int right=nums.length-1;
        int i=0;
        while (i<=right){
            if(nums[i]==0){ 
                swap(nums,i++,left++);
            }else if(nums[i]==2){//丢到右边去。注意这里丢到右边,右边那个数字不一定小于1所以i还不能动。
                swap(nums,i,right--);
            }else{
                i++;
            }
        }

    }
    private void swap(int []nums,int i,int j){
        int tmp=nums[i];
        nums[i]=nums[j];
        nums[j]=tmp;
    }

这两个算法的时间复杂度都很低,但是后者空间复杂度更优。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值