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.
給定一個數組,由n個分別涂有紅、白、藍顏色的對象組成,給數組排序,使得有相同顏色的對象相鄰,其中,顏色順序為紅、白、藍。
使用0、1、2分別表示紅、白、藍
注意:不建議使用庫中排序函數解決問題

算法分析

利用三個索引標志,begin、end分別表示白色的首尾位置。

Java代碼

public class Solution {
    public void sortColors(int[] nums) {
        int begin = 0, end = nums.length - 1, curr = 0;//begin和end分別表示顏色為1的開始和結尾索引
        while(curr <= end) {//有等號是因為我們至判斷nums[curr],并未判斷nums[end],因此最后一步就需要判斷nums[end]
            if (nums[curr] == 0) {
                if (curr != begin) {
                    int temp = nums[curr];
                    nums[curr] = nums[begin];
                    nums[begin] = temp;
                }
                curr ++;
                begin ++;
            } else if (nums[curr] == 1) {
                curr ++;
            } else if (nums[curr] == 2) {
                if (curr != end) {
                    int temp = nums[curr];
                    nums[curr] = nums[end];
                    nums[end] = temp;
                }
                end --;
                //curr ++;此處curr不能加yi的原因是,與end索引處置換后的值還未判斷,需要再進行判斷一次
            }
        }
    }
}

參考

oschina
LeetCode

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容