zoukankan      html  css  js  c++  java
  • Leetcode NO.75 Sort Colors 颜色分类

    1.问题描述

    给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

    此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

    2.测试用例

    示例 1
    输入:nums = [2,0,2,1,1,0]
    输出:[0,0,1,1,2,2]
    
    示例 2
    输入:nums = [2,0,1]
    输出:[0,1,2]
    
    示例 3
    输入:nums = [0]
    输出:[0]
    
    示例 4
    输入:nums = [1]
    输出:[1]
    

    3.提示

    • n == nums.length
    • 1 <= n <= 300
    • nums[i] 为 0、1 或 2

    进阶:你可以不使用代码库中的排序函数来解决这道题吗?你能想出一个仅使用常数空间的一趟扫描算法吗?

    4.代码

    1.基于选择排序&两边循环
    code
    public void sortColorsWithSelectSort(int[] nums) {
        int current = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                exchangeArrayEle(nums, i, current);
                current++;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 1) {
                exchangeArrayEle(nums, i, current);
                current++;
            }
        }
    }
    
    public void exchangeArrayEle(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
    复杂度
    * 时间O(N)
    * 空间O(1)
    
    2.基于计数排序的&两边for
    code
    private void sortColorsWithCountingSort(int[] nums) {
        int count1 = 0;
        int count2 = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                count1++;
            }
            if (nums[i] == 1) {
                count2++;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (i < count1) {
                nums[i] = 0;
            } else if (i < count1 + count2) {
                nums[i] = 1;
            } else {
                nums[i] = 2;
            }
        }
    }
    
    复杂度
    * 时间O(N)
    * 空间O(1)
    
    3.基于快速排序&一遍循环
    code
    public void sortColorsWithQuickSort(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        int current = 0;
        while (left < right && current <= right) {
            while (current <= right && nums[current] == 2) {
                exchangeArrayEle(nums, current, right--);
            }
            if (current <= right && nums[current] == 0) {
                exchangeArrayEle(nums, current, left++);
            }
            current++;
        }
    }
    
    public void exchangeArrayEle(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
    复杂度
    * 时间O(N)
    * 空间O(1)
    
  • 相关阅读:
    android4.0 及以上 版本 wifi 和 蓝牙不显示 原因
    AWK命令使用 小结
    Linux xargs命令 小结
    nginx rewrite伪静态配置参数详细说明
    简评file_get_contents与curl 效率及稳定性
    zendstudio 常用快捷键
    PHP字符串三种定义方式
    PHP连贯接口
    yii学习笔记
    PHP中str_replace函数的详解
  • 原文地址:https://www.cnblogs.com/worldline/p/15717512.html
Copyright © 2011-2022 走看看