75. Sort Colors

Total Accepted: 102203  Total Submissions: 291972  Difficulty: Medium

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?

Subscribe to see which companies asked this question

Hide Tags
  Array Two Pointers Sort
Hide Similar Problems
  (M) Sort List (M) Wiggle Sort (M) Wiggle Sort II

分析:

这就是题目中所说的“相当直接的解法”。

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int cntRed=0;
        int cntWhite=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]==0)
                cntRed++;
            else if(nums[i]==1)
                cntWhite++;
        }
        int cntBlue=nums.size()-cntRed-cntWhite;
        int cnt=0;
        while(cntRed--)
            nums[cnt++]=0;
        while(cntWhite--)
            nums[cnt++]=1;   
        while(cntBlue--)
            nums[cnt++]=2;    
    }
};


别人的算法1:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int second=nums.size()-1, zero=0;
        for (int i=0; i<=second; i++) {
            while (nums[i]==2 && i<second) 
                swap(nums[i], nums[second--]);//把2往右边赶
            while (nums[i]==0 && i>zero) 
                swap(nums[i], nums[zero++]);//把0往左边赶
        }
    }
};




别人的解法2:

简直漂亮至极。

class Solution {
public:
    void sortColors(int A[], int n) {
        int i = -1;
        int j = -1;
        int k = -1;
        for(int p = 0; p < n; p ++)
        {
            //根据第i个数字,挪动0~i-1串。
            if(A[p] == 0){
                A[++k] = 2;    //2往后挪
                A[++j] = 1;    //1往后挪
                A[++i] = 0;    //0往后挪
            }
            else if(A[p] == 1){
                A[++k] = 2;
                A[++j] = 1;
            }
            else
                A[++k] = 2;
        }
    }
};


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51660958

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,C++,算法,面试,遍历)