码迷,mamicode.com
首页 > 其他好文 > 详细

75. Sort Colors

时间:2016-09-24 12:11:38      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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甩到最左边,把2甩到最右边。0甩到左边是不用管其他的,但是2甩到右边后还要检查换过来之后的数,因为它可能是0,如果不去关注这个数,那么就直接pass了。因此换完后指针不动。注意终止条件是填充的指针小于2的指针,而不是0的指针小于2的指针。中间还有1. 自己不好好写一下还真不知道会出那么多问题。。。

public class Solution {
    public void sortColors(int[] nums) {
        if(nums==null)
        {
            return;
        }
        int start=0;
        int finish=nums.length-1;
        int curr=0;
        while(curr<=finish){
             if(nums[curr]==0)
            {
                swap(nums,curr++,start++);
            }
            else if(nums[curr]==1)
            {
                curr++;
            }
            else if(nums[curr]==2)
            {
                swap(nums,curr,finish--);
            }

        }
    }
        
    public void swap(int[] nums,int i,int j)
    {
        int tmp=nums[i];
        nums[i]=nums[j];
        nums[j]=tmp;
    }
    
}

 

75. Sort Colors

标签:

原文地址:http://www.cnblogs.com/Machelsky/p/5902767.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!