leetcode 75. Sort Colors 很不错的3种元素排序方法 + O(n)

来源:互联网 发布:东方的漫画软件 编辑:程序博客网 时间:2024/05/29 19:56

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?

题意很简答,就是问能不能O(n)解决?答案是可以的。这个可以采用一遍扫描即可成功排序,类似快排。

设置两个index,left记录第一个1的位置,left左边为0,right记录第一个非2的位置,right右边为2。

然后使用i从头到尾扫一遍,直到与right相遇。 i遇到0就换到左边去,遇到2就换到右边去,遇到1就跳过。

需要注意的是:由于left记录第一个1的位置,因此A[left]与A[i]交换后,A[left]为0。A[i]为1,因此i++;

而right记录第一个非2的位置,可能为0或1,因此A[right]与A[i]交换后,A[right]为2。A[i]为0或1,i不能前进,要后续判断。

代码如下:

public class Solution {    /*     * http://www.cnblogs.com/ganganloveu/p/3703746.html     * 这个可以采用一遍扫描即可成功排序,类似快排     * 设置两个index,left记录第一个1的位置,left左边为0,     * right记录第一个非2的位置,right右边为2.     * 然后使用i从头到尾扫一遍,直到与right相遇。     * i遇到0就换到左边去,遇到2就换到右边去,遇到1就跳过。     * 需要注意的是:由于left记录第一个1的位置,因此A[left]与A[i]交换后,A[left]为0,A[i]为1,因此i++;     * 而right记录第一个非2的位置,可能为0或1,因此A[right]与A[i]交换后,A[right]为2,A[i]为0或1,i不能前进,要后续判断。     *      * */    public void sortColors(int[] nums)     {        if(nums==null || nums.length<=0)            return;        int minIndex=0,maxIndex=nums.length-1;        int i=0;        while (i<=maxIndex)        {            if(nums[i]==0)            {                swap(nums,i,minIndex);                minIndex++;                i++;            }else if(nums[i]==1)                i++;            else             {                swap(nums,i,maxIndex);                maxIndex--;            }        }    }    public void swap(int[] nums, int a, int b)     {        int tmp=nums[a];        nums[a]=nums[b];        nums[b]=tmp;    }}

下面是C++的做法,说实话不太容易想到,但是这个做法很棒

代码如下:

#include <iostream>#include <vector>using namespace std;class Solution {public:    void sortColors(vector<int>& nums)     {        if (nums.size() <= 1)            return;        int i = 0 , minIndex = 0, maxIndex = nums.size() - 1;        while(i <= maxIndex)        {            if (nums[i] == 0)            {                swap(nums, i, minIndex);                minIndex++;                i++;            }            else if (nums[i] == 1)                i++;            else            {                swap(nums, i, maxIndex);                maxIndex--;            }        }    }    void swap(vector<int>& a, int i, int j)    {        int tmp = a[i];        a[i] = a[j];        a[j] = tmp;    }};