347. Top K Frequent Element(java)

来源:互联网 发布:足球彩票过滤软件 编辑:程序博客网 时间:2024/04/29 10:58

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note: 

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

一、题目分析及解决方案

题目分析:
  • 使用桶排序。
  • 有考虑过使用桶排序,想了想还是不合适,最后采用了定义静态内部类(值+频率)的方式。
  • 采用堆排序,比较麻烦
public class Solution{/**实现接口Comparable<T>*/    public static class ObjectK  implements Comparable<ObjectK>{    public int key;    public int fre;    public ObjectK(int key,int fre){    this.key=key;    this.fre=fre;    }        @Override    public int compareTo(ObjectK ob){//写成按照从大到小的顺序排序    if(this.fre>ob.fre) return -1;    else if(this.fre==ob.fre) return 0;    else return 1;    }    }    public static List<Integer> topKFrequent(int[] nums, int k) {        List<Integer> res= new ArrayList<Integer>();        if(nums==null || nums.length==0 || k==0)             return res;                Map<Integer,Integer> map = new HashMap<Integer,Integer>();        for(int i=0;i<nums.length;i++){            if(map.containsKey(nums[i]))                 map.put(nums[i],map.get(nums[i])+1);            else                map.put(nums[i],1);        }        List<ObjectK> oblist=new ArrayList<ObjectK>();                //遍历map        for(Map.Entry<Integer, Integer> e:map.entrySet()){        ObjectK o=new ObjectK(e.getKey(),e.getValue());//此处采用的是静态内部类        oblist.add(o);        }        Collections.sort(oblist);//注意要实现接口的compareTo方法        for(int i=0;i<k;i++){        res.add(oblist.get(i).key);        }        return res;    }}

二、静态内部类和内部类的区别

    在java中我们可以有静态实例变量、静态方法、静态块。类也可以是静态的,但是只能在一个类里面定义静态类。在java中,我们不能用static修饰顶级类(top level class),只有内部类可以为static。
(1)静态内部类--可以有静态成员和非静态成员;非静态内部类--静态成员同时要有final关键词修饰
(2)静态内部类--不能访问外部类的非静态成员,只能访问外部类的静态成员;非静态内部类--能够访问外部类的静态和非静态成员。
(3)一个非静态内部类不能脱离外部类实体被创建,一个非静态内部类可以访问外部类的数据和方法,因为他就在外部类里面。


  • 使用的静态内部类,创建新对象方式(以上面代码为例
ObjectK o=new ObjectK(e.getKey(),e.getValue());//此处采用的是静态内部类
  • 采用非静态内部类,实例化的方式首先需要获取外部类的实例
Solution s=new Solution();//需要外部类的实例ObjectK o=s.new ObjectK(e.getKey(),e.getValue());

两者实例化的方式不可以互相使用!


0 0