Leetcode中常用排序 之 O(n)时间复杂度排序

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 08:33   11   0

通过使用额外的空间,达到O(n)的时间复杂度的排序方法

直接上代码:

import java.util.HashMap;

public class Ranking_O_n {
    public int[]ranking(int []nums){
        int []ranked=new int[nums.length];
        int times=0, min=0,max=0,index=0;
        HashMap<Integer,Integer>h=new   HashMap<Integer,Integer>();

        for(int n:nums){
            if(n<min)min=n;
            if(n>max)max=n;
            if(h.containsKey(n)){
                times=h.get(n);
                times++;
                h.put(n,times);
            }
            else 
                h.put(n, 1);
        }
        for(int n=min;n<=max;n++){
            if(h.containsKey(n)){
                times=h.get(n);
                for(int i=0;i<times;i++){
                    ranked[index]=n;
                    index++;
                }
            }
        }


        return ranked;
    }
    public static void main(String[]args){
        Ranking_O_n c=new Ranking_O_n();
        int[]nums={1,2,1,1,2,3,5,6,10,2,55,2,33,44,28,48,21};
        for(int n:c.ranking(nums)){
            System.out.print(n+" ");
        }
    }
}
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP