美文网首页
Sort Colors

Sort Colors

作者: Leonlong | 来源:发表于2017-01-03 07:50 被阅读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.

Notice
You are not suppose to use the library's sort function for this problem.
You should do it in-place (sort numbers in the original array).

这题用counting sort可以做,但是会遍历两遍数组,第一次把0,1,2数量记下来,第二遍把数字填上去。
也可以用insertion sort。

这里我用了三个pointer,left负责追踪0的插入位置,right负责追踪2的插入位置,i是当前遍历数字的index。
然后当前数字是0,或2就交换,然后更新left,right,i

class Solution {
    /**
     * @param nums: A list of integer which is 0, 1 or 2 
     * @return: nothing
     */
    public void sortColors(int[] nums) {
        // write your code here
        if(nums.length == 0){
            return ;
        }
        
        int left = 0;
        int right = nums.length-1;
        int i = 0;
        while( i <= right) {
            if(nums[i] == 2){
                nums[i] = nums[right];
                nums[right] = 2;
                right--;
            }else if (nums[i] == 0){
                nums[i] = nums[left];
                nums[left] = 0;
                left++;
                i++;
            }else{
                i++;
            }
        }
        
    }
}

相关文章

  • 数组follow-up

    1.Sort Colors[Sort Colors]https://leetcode.com/problems/s...

  • Sort

    Sort Colors improve: Wiggle Sort Merge Intervals

  • Sort Colors

    Given an array with n objects colored red, white or blue,...

  • Sort Colors

    Given an array with n objects colored red, white or blue,...

  • Sort Colors

    计数排序解法 ​ ​ 三路快排解法 ​ 画图/变量定义 , 区间定义/伪代码 使用keynote画效果还不错​正确...

  • Sort Colors

    https://leetcode.com/problems/sort-colors/简化题意就是,有一个arr,里...

  • 75. Sort Colors | 88. Merge Sort

    75. Sort Colors 题目要求见:https://leetcode.com/problems/sort-...

  • 75 sort colors

    Given an array with n objects colored red, white or blue,...

  • sort-colors

    荷兰国旗问题

  • LeetCode 75 Sort Colors

    LeetCode 75 Sort Colors Given an array with n objects col...

网友评论

      本文标题:Sort Colors

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