美文网首页
75. Sort Colors

75. Sort Colors

作者: lqsss | 来源:发表于2018-03-21 14:44 被阅读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.

思路

类似快排的划分,[0,0,...,1,1,1...,2,2,2...],有三部分,题目的意思是希望我们通过交换进行排序,这里用三个指针,cur、begin、end。

  1. 如果cur指向元素为0,与begin元素交换,cur++,begin++;
  2. 如果cur指向元素为1,不交换,cur++;
  3. 如果cur指向元素为2,与end元素交换,cur不动,end--;
    第三种情况,cur不动,怕与end交换后的元素可能是0,需要继续跟begin交换。

代码

public class SortColors {
    public void sortColors(int[] nums) {
        int cur = 0;
        int begin = 0;
        int end = nums.length - 1;
        while (cur <= end) {
            if(nums[cur] == 0){
                swap(nums,cur,begin);
                begin++;
                cur++;
            }else if(nums[cur] == 1){
                cur++;
            }else{
                swap(nums,cur,end);
                end--;
            }
        }
    }
    private void swap(int[] nums, int cur, int begin) {
        int tmp = nums[cur];
        nums[cur] = nums[begin];
        nums[begin] = tmp;
    }
}

相关文章

网友评论

      本文标题:75. Sort Colors

      本文链接:https://www.haomeiwen.com/subject/pamwqftx.html