1. 程式人生 > >[LeetCode] 75. Sort Colors Java

[LeetCode] 75. Sort Colors Java

not etc light java const sta ould lib pac

題目:

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?

題意及分析:一個包含0,1,2的數組,排序使所有0,1,2分別在一起。最好只需要遍歷一次,且需要空間復雜度為o(1);

代碼一遍歷數組計算0,1,2出現的次數,然後在nums中替換掉即可,這樣使用了兩次遍歷

 1 class Solution {
 2     public void sortColors(int[] nums) {
 3         int oneCount = 0,twoCount=0,zeroCount=0;
 4         for(int i=0;i<nums.length;i++){
 5             if(nums[i]==0) zeroCount++;
6 if(nums[i]==1) oneCount++; 7 if(nums[i]==2) twoCount++; 8 } 9 for(int i=0;i<zeroCount;i++){ 10 nums[i] = 0; 11 } 12 for(int i=zeroCount;i<zeroCount+oneCount;i++){ 13 nums[i] = 1; 14 } 15 for(int i=zeroCount+oneCount;i<zeroCount+oneCount+twoCount;i++){ 16 nums[i] = 2; 17 } 18 } 19 }

代碼二:只使用一次遍歷,雙指針法,用一個start和一個end指向數組最前面元素和後面元素,遍歷數組,若遇到0則和start交換,遇到2和end交換

class Solution {
    public void sortColors(int[] nums) {
       int start = 0;
        int end = nums.length-1;
        int i=0;
        while(i<=end){
            if(nums[i]==0){     //將0交換到前面
                int tmp=nums[i];
                nums[i]=nums[start];
                nums[start] =tmp;
                start++;
                i++;
            }
            else if(nums[i]==2){ //將2交換到後面
                int temp = nums[i];
                nums[i] = nums[end];
                nums[end] = temp;
                end--;
            }
            else     //跳過
                i++;
        }
    }
}

代碼三:平移法

class Solution {
    public void sortColors(int[] nums) {
       int i=-1,j=-1,k=-1;
        for(int x=0;x<nums.length;x++){
            if(nums[x]==0){
                nums[++k] = 2;
                nums[++j] = 1;
                nums[++i] = 0;
            }else if(nums[x]==1){
                nums[++k] = 2;
                nums[++j] = 1;
            }else {
                nums[++k] = 2;
            }
        }
    }
}

  

[LeetCode] 75. Sort Colors Java