Saturday, September 28, 2013

Sort Colors

Given an array with n objects colored red, white or blue, sort them in-place 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.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
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 a one-pass algorithm using only constant space?

A:

----------------下面这个解法,有两个错误的,自己看看,错在哪里?------

public class Solution {
    public void sortColors(int[] A) {
        int pre0 = -1,after2 = A.length;// i is pre
        for(int i = 0;i<A.length;i++){
            if(A[i] ==0){
                pre0++;
                swap(A,pre0,i);
            }else if(A[i] == 2){
                after2--;
                swap(A,i,after2);
                i--;
            }
        }
    }
    private void swap(int [] A, int i,int j){
        A[i] ^= A[j];
        A[j] ^= A[i];
        A[i] ^= A[j];
    }
}










Mistakes:

1: swap这个算法,是不对的。  问题就出自,i,j在flag sort里,有可能是相等的。
2: i<A.length 是不对的, 会导致下标越界

------------------4th pass-----------------
public class Solution {
    public void sortColors(int[] A) {
        int pre0 = -1,after2 = A.length;// i is pre
        for(int i = 0;i<after2;i++){
            if(A[i] ==0){
                pre0++;
                swap(A,pre0,i);
            }else if(A[i] == 2){
                after2--;
                swap(A,i,after2);
                i--;
            }
        }
    }
    private void swap(int [] A, int i,int j){
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }
}



---------下面是用one pass 来做的------利用到了2个pointer------
当runner遇到2 的时候, 和后面交换了之后, 要记得把该runner退一步,重新这个从后面刚switch过来的值。 -------而遇到0 的时候,不用退后。


class Solution {
public:
    void sortColors(vector<int>& nums) {
        // i0 is last index of current sorted 0,
        // i2 is (add backward) last added index of 2
        int i0 =-1, i2 = nums.size();
        for(int i =0;i<i2;++i)
        {
            if(nums[i]==0 )
            {
                nums[i] = nums[++i0];// nums[++i0] can be 0 or 1
                nums[i0] = 0;
            }else if(nums[i] ==2){
                nums[i] = nums[--i2];
                nums[i2] = 2;
                --i;
            }
        }
    }
};

No comments:

Post a Comment