关闭

LeetCode Sort Colors(排序)

314人阅读 评论(0) 收藏 举报
分类:

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.

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?

题意:给出由0,1,2三个数组成的数组,要求用时间复杂度为O(n),空间复杂度为O(1)

思路:分别从两边搜索,从左边找到第一个不为0的位置,从右边找到第一个不为2的位置,然后从这两个位置开始查找,如果为0,将其与左边的数替换,如果为2,将其与右边的数替换

代码如下:

public class Solution {
    public void sortColors(int[] nums) {
         int left = 0, right = nums.length - 1;

        while (left <= right && nums[left] == 0) left++;
        while (right >= 0 && nums[right] == 2) right--;

        if (left >= right) return;

        int tmp;
        int a = left;
        while (a <= right) {
            if (nums[a] == 0) {
                tmp = nums[a];
                nums[a] = nums[left];
                nums[left] = tmp;
                a++;
                left++;
            } else if (nums[a] == 2) {
                tmp = nums[right];
                nums[right] = nums[a];
                nums[a] = tmp;
                while (nums[right] == 2) right--;
                if (nums[a] == 1) a++;
            } else a++;
        }
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:722265次
    • 积分:18830
    • 等级:
    • 排名:第472名
    • 原创:1235篇
    • 转载:226篇
    • 译文:0篇
    • 评论:26条
    博客专栏
    最新评论