LeetCode每日一題:sort colors

weixin_34320159發表於2017-05-20

問題描述

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.
click to show follow up.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?

問題分析

這道題簡單的解法題目都規定不能使用,不能呼叫庫函式sort,不能採用迴圈兩遍的複寫A演算法,這道題只能遍歷一遍。
設三個指標,left表示從左往右第一個1的數,right表示從右往左第一個不是2的數,i從0開始向最末尾前進,遇到0,就與left交換,遇到2就與right交換,這樣一趟走下來就是有序的了。

程式碼實現

public void sortColors(int[] A) {
        int left = 0;
        int right = A.length - 1;
        int i = 0;
        while (i <= right) {
            if (A[i] == 0) {
                swap(A, left, i);
                left++;
                i++;
            } else if (A[i] == 2) {
                swap(A, i, right);
                right--;
            } else i++;
        }
    }

    private void swap(int[] A, int i, int j) {
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }

相關文章