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.

时间复杂度:O(n)
空间复杂度:O(1)

因为只有三种可能的数字0,1,2。所以可以先将0,2放入正确的位置,最后1的位置一定固定。

public void sortColors(int[] nums) {
        int length = nums.length;
        if(length <= 1)
            return;
        int left = 0;
        int right = 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--;
            }
        }
    }
    public void swap(int[] nums,int i,int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
发布了30 篇原创文章 · 获赞 0 · 访问量 861

猜你喜欢

转载自blog.csdn.net/fantow/article/details/104721095