【Leetcode】之Sort Colors

来源:互联网 发布:淘宝客推广公司 编辑:程序博客网 时间:2024/06/08 14:34

一.问题描述

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.

二.我的解题思路

这道题挺特殊的,我采用的是很简单的解法。先遍历整个vector,得到0,1,2的个数,然后再遍历一次进行赋值即可。这种做法的时间复杂度是O(n),但是需要遍历整个数组两次才行。测试通过的程序如下:

class Solution {public:    void sortColors(vector<int>& nums) {        int len = nums.size();                   int num0,num1,num2; num0=num1=num2=0;        for(int i=0;i<len;i++){            if(nums[i]==0) num0++;            if(nums[i]==1) num1++;            if(nums[i]==2) num2++;        }        int idx[3]={0,num0,num0+num1};         for(int i=0;i<len;i++){            if(i<num0) nums[i]=0;            if(i>=num0 && i<(num0+num1)) nums[i]=1;            if(i>=(num0+num1)) nums[i]=2;                        }            }        };
后来又在网上看到别人比较牛逼的思路:

class Solution {public:void sortColors(vector<int>& A) {int len = A.size();int i = -1;int j = -1;int k = -1;for (int p = 0; p < len; 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;}elseA[++k] = 2;}}};
这种思路是判断0,1,2需要往后挪动的次数,只需要遍历整个数组一次即可。


0 0
原创粉丝点击