LeetCode-【數組】-分類顏色

給定一個包含紅色、白色和藍色,一共 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。

此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。

注意:
不能使用代碼庫中的排序函數來解決這道題。

示例:

輸入: [2,0,2,1,1,0]
輸出: [0,0,1,1,2,2]

進階:

  • 一個直觀的解決方案是使用計數排序的兩趟掃描算法。
    首先,迭代計算出0、1 和 2 元素的個數,然後按照0、1、2的排序,重寫當前數組。
  • 你能想出一個僅使用常數空間的一趟掃描算法嗎?

分析:直觀解法很簡單,但算法的複雜度並不是最優,對本題而言,思考一趟掃描算法,即需每次遇到0都交換到前面,每次遇到2都交換到後面,所以需三個指針記錄首尾及當前位置

直觀解法:

class Solution {
    public void sortColors(int[] nums) {
        int[] c=new int[3];
        int m=0;
        for(int i=0;i<nums.length;i++)
            c[nums[i]]++;
        for(int i=0;i<c[0];i++)
            nums[m++]=0;
        for(int i=0;i<c[1];i++)
            nums[m++]=1;
        for(int i=0;i<c[2];i++)
            nums[m++]=2;
    }
}

一次掃描法:

class Solution {
    public void sortColors(int[] nums) {
        int start=0;
        int end=nums.length-1;
        int current=0;
        while(current<=end){
            if(nums[current]==0){
                nums[current]=nums[start];
                nums[start]=0;
                start++;
                current++;
            }else if(nums[current]==2){
                nums[current]=nums[end];
                nums[end]=2;
                end--;
            }else
                current++;
        }
    }
}

 

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