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.


思路:一种从头往后,但是判断条件逐渐减少。还有一种一直往后走,随之one,two,three起始条件也逐渐增加。

先给出第一种思路,还有一种思路暂时没有AC成功,不过很快了。

我的方法是从前往后迭代,只要颜色不为0,那就交换,这样子就把所有颜色为0的排列好,而且此时我还知道具体停止位置。同样的方法,继续排列颜色为1,颜色为2的。

再给出第二种思路,他的技巧在于遇到为1的不进行任何操作,遇到为0的则与把代表1的one往后挪一个,两者交换。同时,one与i基本保持一致,除非出现不是一种颜色的情况。

对于第三种颜色,更是一样,遇到他就和最后一个交换,同时记得将two-1;这种列子见得很少,是个非常好的解法。


代码:

class Solution {
public:
	void sortColors(vector<int>& nums) {
		int len=nums.size();
		int one=0,two=0,three=0;

		for (int i=0;i<len;i++){
			if (nums[i]==0){
				swap(nums[i],nums[one]);
				one++;
			}
		}
		//第二次
		two=one;
		for (int i=one;i<len;i++){
			if (nums[i]==1){
				swap(nums[i],nums[two]);
				two++;
			}
		}
		//第二次
		three=two;
		for (int i=three;i<len;i++){
			if (nums[i]==2){
				swap(nums[i],nums[three]);
				three++;
			}
		}
	}
};


class Solution {
public:
	void sortColors(vector<int>& nums) {
		int len=nums.size();
		int one=0,two=len-1;

		for (int i=0;i<=two;i++){
			if (nums[i]==0){
				swap(nums[i],nums[one]);
				one++;
			}
			if (nums[i]==2){
				swap(nums[i],nums[two]);
				two--;
				i--;
			}
		}
		
	}
};




posted @ 2015-09-25 07:23  JSRGFJZ6  阅读(124)  评论(0编辑  收藏  举报