[LeetCode] 75. Sort Colors Java

题目:

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;
            }
        }
    }
}

  

 

posted @ 2017-12-21 09:37  荒野第一快递员  阅读(441)  评论(0编辑  收藏  举报