[Leetcode学习-java]Sort Colors(颜色排序)

问题:

难度:easy

说明:

这次就用到hash排序了吧,当然也可以不用毕竟不是最优,问题是给出乱序的0,1,2数组代表三种颜色(并没有什么意义),然后要求排序从小到大0,1,2。

问题链接:https://leetcode.com/problems/sort-colors/

相关问题:

蜗牛型排序:https://blog.csdn.net/qq_28033719/article/details/105997980

奇偶链表排序:https://blog.csdn.net/qq_28033719/article/details/105011709

输入案例:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

我的代码:

很简单的排序,水题,题目提示里面要求你只用1-pass处理,我写个2-pass的。

class Solution {
    public void sortColors(int[] nums) {
        if(nums == null || nums.length < 2) return;
        int len = nums.length;
        int[] map = new int[3];

        // 将0,1,2全部存到hashmap里面
        for(int i = 0;i < len;i ++) {
            map[nums[i]] ++;
        }
        
        // 弄一个map数组的索引
        int index = 0;
        // 然后把map里面的统计数值,将nums重新赋值
        for(int i = 0;i < nums.length;i ++) {
            while(map[index] == 0) index ++;
            nums[i] = index;
            -- map[index];
        }
    }
}

1-pass的,就是想像数组原来是空的,然后自己重新添加东西进去就是

class Solution {
    public void sortColors(int[] nums) {
        if(nums == null || nums.length < 2) return;
        int len = nums.length;
        int low = 0;
        int mid = 0;
        int high = len - 1;
        while(mid <= high){
            if(nums[mid] == 0){
                swap(nums, low, mid);
                low++;
                mid++;
            }
            else if(nums[mid] == 1){
                mid++;
            }
            else if(nums[mid] == 2){
                swap(nums, mid, high);
                high--;
            }
        }
    }
    
    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值