Leetcode 75. 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.

题意:有一个包含红白蓝三色的数组,分别用0、1、2表示三种颜色,对这个颜色数组按照红白蓝的顺序排序。不允许用库函数。

思路:这道题想到了之前学过的双指针方法,用left和right两个指针记录当前左边红色和右边蓝色已经排序好的位置,用一个游标来遍历数组。
如果游标处的颜色是0,并且游标大于left,则交换游标和left,left右移;如果游标的颜色是2,并且游标小于right,交换游标和right,right左移;如果游标当前是1、或者是0并且小于等于left、或者是2并且大于等于right,则游标右移。

public void sortColors(int[] nums) {
    if (nums == null || nums.length == 0) {
        return;
    }

    int left = 0, right = nums.length - 1, cur = 0;
    while (cur <= right) {
        if (cur > left && nums[cur] == 0) {
            int tmp = nums[left];
            nums[left] = nums[cur];
            nums[cur] = tmp;
            left++;
        }

        if (cur < right && nums[cur] == 2) {
            int tmp = nums[right];
            nums[right] = nums[cur];
            nums[cur] = tmp;
            right--;
        }

        if (nums[cur] == 1 || (nums[cur] == 0 && cur <= left) || (nums[cur] == 2 && cur >= right)) {
            cur++;
        }
    }
}

你可能感兴趣的:(Leetcode 75. Sort Colors)