LeetCode Top 100 Liked Questions 75. Sort Colors (Java版; Medium)

welcome to my blog

LeetCode Top 100 Liked Questions 75. Sort Colors (Java版; Medium)

题目描述
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]
class Solution {
    public void sortColors(int[] nums) {
        int n = nums.length;
        if(n<=1){
            return;
        }
        partition(nums, 0, n-1);
    }

    private void partition(int[] nums, int L, int R){
        int small=L-1, big=R+1;
        int p = L;
        while(p<big){
            if(nums[p] < 1){
                swap(nums, ++small, p++);
            }else if(nums[p] > 1){
                swap(nums, --big, p);
            }else{
                p++;
            }
        }
    }

    private void swap(int[] arr, int i, int j){
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
荷兰国旗, 实际上就是执行了一次partition; 关键点: 循环终止条件
第二次做; 最朴素的想法: 桶排序; 时间复杂度O(N^2), 不推荐这个方法
class Solution {
    public void sortColors(int[] nums) {
        //用计数排序解决一次
        int[] arr = new int[3];
        for(int a : nums)
            arr[a]++;
        //从桶中倒出来
        int j = 0;
        for(int i=0; i<arr.length; i++){
            while(arr[i]>0){
                nums[j++] = i;
                arr[i]--;
            }
        }
    }
}
第一次做, 荷兰国旗问题, 遍历一次数组即可; partition将数组分成三部分:小于区,等于区,大于区; 口诀:换扩跳, 换扩, 跳; 细节: 必须用1作为划分值, 因为题目要求1在等于区; 小于区向右扩, 大于区向左扩, 剩下的是等于区;
/*
荷兰国旗问题,就是一轮partition过程
将数组分成三个部分
细节:划分值必须选1, 因为题目规定了1在中间, 所以不能选0或者2在中间
*/
class Solution {
    public void sortColors(int[] nums) {
        if(nums==null || nums.length==0)
            return;
        int small = -1;//小于区向右扩
        int big = nums.length; //大于区向左扩
        int pivot = 1; //划分值必须选1, 因为题目规定了1在中间
        int i = 0;
        while(i<big){
            if(nums[i] < pivot)
                swap(nums, i++, ++small);
            else if(nums[i] > pivot)
                swap(nums, i, --big);
            else
                i++;
        }
    }
    public static void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值