Leetcode_75_Sort Colors

来源:互联网 发布:虚拟币系统源码 编辑:程序博客网 时间:2024/06/05 02:14

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;    }

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

原创粉丝点击