LeetCode 75. Sort Colors 颜色分类

题目:

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?

解答:

题目中给出了一种解题思路:首先,迭代计算出数组中0、1和2的数目,然后按照0、1、2的顺序,重写当前数组。现在要求采用一种仅使用常数空间的一趟扫描算法。

我们采用双指针的方式,按照0、1、2的顺序交换顺序并实现排序。具体思路如下:

  1. 设置双指针 left 和 right,分别指向数组的头部和尾部。设置变量 i,指向当前数组的遍历位置
  2. 从左至右遍历数组,始终保持将0移至数组的最前端,将2移至数组的最尾端。
    当nums[i] == 0时,交换nums[i]和nums[left],且left ++,i ++
    当nums[i] == 1时,不用交换,i ++
    当nums[i] == 2时,交换nums[i]和nums[right],且right –

代码实现如下:

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

你可能感兴趣的:(LeetCode)