LeetCode 75 _ Sort Colors 颜色排序

Description:

Given an array with n objects colored red, white or blue, sort them in-place 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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:

    • A rather straight forward solution is a two-pass algorithm using counting sort.
      First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
    • Could you come up with a one-pass algorithm using only constant space?

 

 

Solution:

 这道题告诉我们有三种颜色在数组中随机摆放,让我们把相同的颜色放在一起,以数组形式输出,三种颜色分别用0,1,2表示

题目中好像没说,但是验证实际上还得按有小到大的次序输出

 

这题说的好像花里胡哨的,什么蓝色黄色绿色然后相同色放在一起啦,实际上,就是给你一串由0,1,2组成的数组,让你按序排列。。。

说的这么简单,那我们直接使用Arrays.sort行不行呢?答案是可以的!本题只需输入Arrays.sort(nums); 点击submit,就会得到一个faster than 100% submissions的解决方案了!?其实这个方法只能说是刚好和题目的输出要求契合了而已,那么让我们来看看正常的解法应该是怎么的。

正常的思路是,创造两个指针,分别指向两头,一头用于存放0,一头用于存放2;

我们从头到尾遍历数组,如果这个数为0,就把它与左指针处的元素互换位置,并且把左指针右移一格;如果这个数为2,就把它与右指针处的元素互换位置,并且把右指针左移一格;当它为1的时候,使它留在原位不动。

由于两个指针初始时是指向两端的,只有在被填充了它所需的数字时才会移动,因此两端的数必定为对应的数(即0或2)。当遍历完成后,自然1便被挤到中间来了。

那么遍历完成的标志是什么呢?就是当数组中的所有数字都被被交换过位置。也就是说,当遍历到曾经被交换过的位置就结束了,而两边被交换过的位置实际上由两个指针指示出来了,通过这一点就可以得到循环结束的位置。

(if、while、顺序)

 

Code:

public void sortColors(int[] nums) {
    int left = 0, right = nums.length -1;
    for (int i = 0; i < nums.length; i ++){
        while (nums[i] == 2 && i < right){
            nums[i] = nums[right];
            nums[right] = 2;
            right--;
        }
        while (nums[i] == 0 && i > left) {
            nums[i] = nums[left];
            nums[left] = 0;
            left ++;
        }

    }
}

  

 

提交情况:

Runtime: 0 ms, faster than 100.00% of Java online submissions for Sort Colors.
Memory Usage: 37.2 MB, less than 68.15% of Java online submissions for Sort Colors.

posted @ 2019-04-11 20:55  Doris7  阅读(154)  评论(0编辑  收藏  举报