leetcode: Sort Colors

问题描述:

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.

click to show follow up.

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 an one-pass algorithm using only constant space?

原问题链接:https://leetcode.com/problems/sort-colors/

 

问题分析

  这个问题看起来像是一个对数组排序的变种。因为它里面只有3种元素,分别为0, 1, 2。所以实际上我们只需要将这些元素划分成小于1,等于1和大于1的三个部分就可以了。这样就比简单的用默认的排序方法好一些。

  按照这个思路,我们就可以想到快速排序里对元素进行划分的步骤。只是那边是一个通用的过程,这里针对有重复元素的情况下要做一些调整。总的思路就是,定义三个索引,分别表示0元素所在的最后一个,1元素所在的位置以及2元素所在的最后位置。在从头到尾开始遍历元素的时候去判断,如果当前元素是0,则left的位置增加1个,同时在将该元素交换到left的位置上。如果当前元素是1,则mid 加1,否则right的位置减一并交换它和mid所在位置的元素。

  具体的实现如下:

public class Solution {
    public void sortColors(int[] nums) {
        if(nums == null || nums.length <= 1) return;
        int left = 0, mid = 0, right = nums.length - 1;
        while(mid <= right) {
            if(nums[mid] == 0) swap(nums, left++, mid++);
            else if(nums[mid] == 1) mid++;
            else swap(nums, mid, right--);
        }
    }
    
    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

  这种方法的实现时间复杂度为O(N),同时也没有使用额外的空间进行元素处理。在时间和空间复杂度上达到一个比较理想的情况。

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2303212