75. Sort Colors

75. Sort Colors

題目連接:https://leetcode.com/problems...php

這題是給數組排序,數組裏面只有3個變量。一個方法是用相似bucket sort,3個桶,統計三個變量出現的個數,而後重構數組便可。html

// count appears time of each number
        int[] count = new int[3];
        for(int num : nums) count[num]++;
        int k = 0;
        for(int i = 0; i < 3; i++) {
            for(int j = 0; j < count[i]; j++) {
                nums[k++] = i;
            }
        }

還有一種方法是用three way partition,參考算法這本書上的講解和程序:
http://algs4.cs.princeton.edu...
http://algs4.cs.princeton.edu...java

public class Solution {
    public void sortColors(int[] nums) {
        int i = 0, j = nums.length - 1;
        int pivot = 1;
        int k = 0;
        while(k <= j) {
            if(nums[k] < pivot) swap(nums, i++, k++);
            else if(nums[k] > pivot) swap(nums, k, j--);
            else k++;
        }
    }
    
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
相關文章
相關標籤/搜索