Sort Colors

Sort Colors

leetcode75

题目:

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?

思路:题意即数组中只存储3种数字0,1,2,要求在 O(1) 空间复杂度的情况下,最好只遍历 1 次数组。

题目给出了遍历2次数组的做法:计数排序

计数排序

public void CountSort(int[] nums){
    int n0 = 0, n1 = 0, n2 = 0;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 0) n0++;
        else if (nums[i] == 1) n1++;
        else if (nums[i] == 2) n2++;
    }
    int i = 0;
    while(n0-- > 0) nums[i++] = 0;
    while(n1-- > 0) nums[i++] = 1;
    while(n2-- > 0) nums[i++] = 2;
}

想到1次遍历过程,容易想到双指针的方法。遍历到0交换到前面得到一个0或1,遍历到2交换到后面得到一个未知数,因此要继续遍历这个交换过来的数。遍历到right,即后面都为2,遍历结束。

双指针遍历

public void sortColors(int[] nums){
    if (nums.length <= 1) return;
    int left = 0, right = nums.length - 1;
    for (int i = 0; i <= right ; i++) {
        if (nums[i] == 0) {
            swap(nums, i, left++);
        } else if (nums[i] == 2) {
            swap(nums, i--, right--);
        }
    }
}
public void swap(int[] nums, int i, int j){
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

考虑不使用双指针直接在原数组上修改的方法。维护0,1,2应该写入的位置。每次遍历一次就写入一个2,遍历结果为1就补写一个1,遍历结果为0就补写一个0,并让1应写入的位置增加1个单位即可。事实上,这种方法的优点在于,当知道数组仅由n个有限值构成时,此方法依然奏效。

遍历改写

public void sortColors(int[] nums){
    if (nums.length <= 1) return;
    int n0 = -1, n1 = -1;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 0){
            nums[i] = 2;
            nums[++n1] = 1;
            nums[++n0] = 0;
        }else if (nums[i] == 1){
            nums[i] = 2;
            nums[++n1] = 1;
        }else if (nums[i] == 2){
            nums[i] = 2;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值