Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

347. Top K Frequent Elements(与451类比)重要!!! #135

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

import java.util.Map.Entry; public class Solution { public List topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int key = nums[i]; if(!map.containsKey(key)) { map.put(key, 1); } else { int val = map.get(key); map.put(key, val+1); } } Queue q = new PriorityQueue( new Comparator(){ @Override public int compare(Integer i1, Integer i2){ if(map.get(i1)<map.get(i2)){ return 1; }else if(map.get(i1)>map.get(i2)){ return -1; } return 0; } }); for(Map.Entry<Integer,Integer> val : map.entrySet()){ q.offer(val.getKey()); } List res = new ArrayList<>(); int count=0; while(count<k && !q.isEmpty()){ res.add(q.poll()); count++; } return res; } } 方法二:collection sort重写 ———————————————————————————————————————— class Node implements Comparable { int val; int count; public Node(int val, int count) { this.val = val; this.count = count; } public int compareTo(Node other) { return other.count - this.count; } }

public List<Integer> topKFrequent(int[] nums, int k) {
    List<Integer> res = new ArrayList<>();
    if (nums == null || nums.length == 0 || k <= 0) return res;
    Map<Integer, Node> map = new HashMap<>();
    for (int num : nums) {
        if (!map.containsKey(num)) map.put(num, new Node(num, 1));
        else map.get(num).count += 1;
    }
    List<Node> list = new ArrayList<Node>(map.values());
    Collections.sort(list);

    for (int i = 0; i < k; i++) {
        res.add(list.get(i).val);
    }
    return res;
}
Shawngbk commented 7 years ago

image

Shawngbk commented 7 years ago

http://www.programcreek.com/2014/05/leetcode-top-k-frequent-elements-java/