Sort Colors

来源:互联网 发布:mysql 系统错误1067 编辑:程序博客网 时间:2024/06/10 06:22

* 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.

题目的要求就是把一个0,1,2散乱的数组,变成先都是0,再到都是1,再到都是2的数组。
我采用的方式是,统计出0和1的个数,分别为N0,N1。数组总体个数是N,把[0,N0)中的非0元素和[N0,N)中的0元素对调。再把[N0,N0+N1)中的非1元素和[N0+N1,N)中的1元素对调。

class Solution {public:    void sortColors(vector<int>& nums) {        int num_0=0;        int num_1=0;        for(int i=0;i<nums.size();i++){                if(nums[i]==0)                num_0++;            if(nums[i]==1)                num_1++;        }        int j=num_0;        for(int i=0;i<num_0;i++){            if(nums[i]!=0){                for(;j<nums.size();j++){                    if(nums[j]==0){                        int temp=nums[j];                        nums[j]=nums[i];                        nums[i]=temp;                        break;                    }                }            }        }        j=num_0+num_1;        for(int i=num_0;i<num_0+num_1;i++){            if(nums[i]!=1){                for(;j<nums.size();j++){                    if(nums[j]==1){                        int temp=nums[j];                        nums[j]=nums[i];                        nums[i]=temp;                        break;                    }                }            }        }    }};
1 0
原创粉丝点击