leetcode 75. Sort Colors

生命不息,奮鬥不止


@author stormma
@date 2017/10/19


題目
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的數組然後你排序成0區,1區,2區的這種形式,這就是著名的荷蘭國旗問題。

思路分析
設三個指針,初始化pos0(0區指針) = 0, pos2(2區指針) = length-1 , currentPos(當前位置指針) = 0,然後從currentPos開始判斷,如果是0就和pos0這個位置的數據交換,然後pos0++, currentPos++,如果是2,那麼和pos2位置交換,pos2--此時currentPos不增加(因爲交換過來的上一個pos2位置的數據還沒進行判斷), 如果是1, currentPos++就行了,循環直到currentPos > pos2爲止。

代碼實現

/**
 * <p>荷蘭國旗問題,<a href="https://leetcode.com/problems/sort-colors">題目鏈接</a></p>
 *
 * @author stormma
 * @date 2017/10/19
 */
public class Question75 {

    static class Solution {
        public void sortColors(int[] nums) {
            int pos0 = 0, pos2 = nums.length - 1, currentPos =0;
            while (currentPos <= pos2) {
                if (nums[currentPos] == 0) {
                    swap(nums, currentPos, pos0);
                    pos0++;
                    currentPos++;
                    continue;
                }
                if (nums[currentPos] == 2) {
                    swap(nums, currentPos, pos2);
                    pos2--;
                    continue;
                }
                currentPos++;
            }
            show(nums);
        }

        private static void show(int[] array) {
            for (int anArray : array) {
                System.out.print(anArray + " ");
            }
            System.out.println();
        }

        private static void swap(int[] nums, int a, int b) {
            int temp = nums[a];
            nums[a] = nums[b];
            nums[b] = temp;
        }
    }
}
發佈了108 篇原創文章 · 獲贊 250 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章