Leetcode - 75. 颜色分类

Leetcode 75. 颜色分类

1.快速排序
2.插入排序

  1. 快速排序(partition)
    定义两个变量one、two 一次将数组分层三个部分:
    [0, one) 区间存放 0;
    [one, two) 区间存放 1;
    [two, len) 区间存放 2。
    定义一个 移动变量 i 来辅助遍历多有的数据。
public class LC75ColorSort {
    public static void main(String[] args) {
        int[] nums = {2, 0, 1, 2};
        sortColors(nums);
        for (int i : nums){
            System.out.print(i);
        }
    }
    public static void sortColors(int[] nums) {
        int one = 0; //[0,one) 0, [one,two) 1
        int two = nums.length-1; //[two,l) 2
        int i = 0; //move
        while (i <= two){ //注意这里的i是可以取到two的,有"="
            if(nums[i]==0){
                swap(nums,i,one);
                one ++;
                i ++;
            }else if(nums[i] == 1){
                i ++;
            }else if (nums[i] == 2){
                swap(nums, i, two);
                two --;
            }
        }
    }
    public static void swap(int[] nums, int a, int b){
        int tmp =0;
        tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }
}
//input: nums = {2, 0, 1, 2}
//output: 0 1 2 2

复杂度分析:
时间复杂度 : O(N)。对长度 为N的数组进行了一次遍历
空间复杂度 : O(1)。交换位置,并没有开辟新的空间

  1. 插入排序 - (了解)
    wiki图解
public class insertSort {
    public static void main(String[] args) {
        int[] nums = {2, 0, 1, 2};
        sortColors(nums);
        for (int i : nums){
            System.out.print(i);
        }
    }
    public static void sortColors(int[] nums){
        for (int i=1; i < nums.length; i++){
            int k= i; //先确定终点位置,然后反向比较排序
            while (k>0 && nums[k-1] > nums[k]){ //这个循环里 对[0, i]位置的排序,
                int tmp = nums[k-1];
                nums[k-1] = nums[k];
                nums[k] = tmp;
                k --;
            }
        }
    }
}

复杂度分析:
时间复杂度 : O(N^2)。
数组排序是逆序的,每到一个 i 时,都要 “再次” 比较 前i个数,故 1+2+3+…+N-1 即 O(N^2)。
空间复杂度 : O(1)。交换位置,并没有开辟新的空间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值