【原創】75. Sort Colors --- one-pass algorithm --- leetcode算法筆記

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.

思路:遍歷數組元素,遇到0往數組頭部交換,遇到2往數組尾交換,1不做處理。

代碼:

 

public void sortColors(int[] nums) {
        int index1 = 0 ;
        int index2 = nums.length - 1;
        for(int i = 0 ; i <= index2 ;){
            if(nums[i] == 0){
                if(index1 < i){
                    nums[i] = nums[index1] ;
                    nums[index1] = 0 ;
                }
                index1 ++ ;
                i ++ ;
            }else if(nums[i] == 2){
                while(i <= index2 && nums[index2] == 2) index2 -- ;
                if(i < index2){
                    nums[i] = nums[index2] ;
                    nums[index2] = 2 ;
                    index2 -- ;
                }
            }else i++ ;
        }
    }

 

 

另一種平移插入法:

 

 

 

class Solution {
public:
    void sortColors(int A[], int n) {
        int i = -1;
        int j = -1;
        int k = -1;
        for(int p = 0; p < n; p ++)
        {
            //根據第i個數字,挪動0~i-1串。
            if(A[p] == 0)
            {
                A[++k] = 2;    //2往後挪
                A[++j] = 1;    //1往後挪
                A[++i] = 0;    //0往後挪
            }
            else if(A[p] == 1)
            {
                A[++k] = 2;
                A[++j] = 1;
            }
            else
                A[++k] = 2;
        }

    }
};

 

 

 

 

 

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