Sort Colors

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.

题目分析

一看到题马上想到了快排的想法,先将所有的2移到最后,再排序0和1.

代码

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int i=0, j=nums.size()-1;
        while(i < j){
            while(nums[i] == 0 && i < j){
                i++;
            }
            while(nums[j] != 0 && i < j){
                j--;
            }
            swap(nums[j], nums[i]);
        }
        j = nums.size()-1;
        while(i < j){
            while(nums[i] == 1 && i < j){
                i++;
            }
            while(nums[j] != 1 && i < j){
                j--;
            }
            swap(nums[j], nums[i]);
        }
        return ;
    }
};

一步到位

直接把所有的2移到最后,0移到最前,1自然在中间,前面的思路是对的,但是没有在多往更深的方向想。

    class Solution {
    public:
        void sortColors(int A[], int n) {
            int second=n-1, zero=0;
            for (int i=0; i<=second; i++) {
                while (A[i]==2 && i<second) swap(A[i], A[second--]);
                while (A[i]==0 && i>zero) swap(A[i], A[zero++]);
            }
        }
    };
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容