LeetCode 75. Sort Colors

来源:互联网 发布:ubuntu怎么移动文件夹 编辑:程序博客网 时间:2024/05/16 04:59

题目:
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.

思路:
不用标准库中的排序,将所有的0、1、2排好序。
方法1:如果当前位为0,将当前位保存在tmp中,前面所有的位后移一位,第一位为tmp,且i+1;如果当前位为1,直接i+1;如果当前位为2,将当前位开始到末尾赋给一个set,如果set的大小为1,也就是只有2,那么已经排序完毕,先delete,再break跳出循环结束,如果set大小不为1,将当前位保存在tmp中,后面所有的位前移一位,最后一位为tmp,此时i不变。
方法2:直接计算nums中的0、1、2的数量,然后再给nums赋值,这样更快,3ms。

代码1:

class Solution {public:    void sortColors(vector<int>& nums) {        int len=nums.size();//计算nums的长度        for(int i=0;i<len;){            if(nums[i]==0){//如果当前位为0                int tmp=nums[i];//将当前位保存在tmp中,                for(int j=i;j>0;--j){//前面所有的位后移一位                    nums[j]=nums[j-1];                }                nums[0]=tmp;//第一位为tmp,且i+1                ++i;            }            else if(nums[i]==1){//如果当前位为1,直接i+1                ++i;            }            else{//如果当前位为2                set<int> *remain = new set<int>;                (*remain).insert(nums.begin()+i, nums.end());//将当前位开始到末尾赋给一个set                if ((*remain).size() == 1){//如果set的大小为1,也就是只有2,那么已经排序完毕                    delete remain;//先delete,再跳出循环结束                    break;                }                int tmp = nums[i];//如果set大小不为1,将当前位保存在tmp中                for (int j = i; j<len - 1; ++j){//后面所有的位前移一位                    nums[j] = nums[j + 1];                }                nums[len - 1] = tmp;//最后一位为tmp,此时i不变            }        }    }};

输出结果: 6ms

代码2:

class Solution {public:    void sortColors(vector<int>& nums) {        int count0=0;        int count1=0;        int count2=0;        int len=nums.size();        for(int i=0;i<len;++i){//分别计算0、1、2的个数保存在count0、count1、count2中            if(nums[i]==0){                ++count0;            }            else if(nums[i]==1){                ++count1;            }            else{                ++count2;            }        }        for(int i=0;i<len;++i){//给nums赋值            if(i<count0){//如果i比count0小,则当前位都为0                nums[i]=0;            }            else if(i>=count0&&i<count0+count1){//如果i大于等于count0且i小于count0+count1                nums[i]=1;//则当前位都为1            }            else{//剩下的都为2                nums[i]=2;            }        }    }};

输出结果: 3ms

0 0
原创粉丝点击