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

這兩個算法的時間複雜度都很低,但是後者空間複雜度更優。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章