Skip to content

Commit

Permalink
347. Top K Frequent Elements update.
Browse files Browse the repository at this point in the history
  • Loading branch information
liusishan committed Feb 26, 2019
1 parent 7ddad83 commit 1f43551
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import java.util.*;

/**
* @Auther: lss
* @Date: 2019/2/26 19:00
* @Description:
*/
public class Solution3 {

public List<Integer> topKFrequent(int[] nums, int k) {

TreeMap<Integer, Integer> map = new TreeMap<>();
for (int num : nums) {
if (map.containsKey(num))
map.put(num, map.get(num) + 1);
else
map.put(num, 1);
}

PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return map.get(a) - map.get(b);
}
});
for (int key : map.keySet()) {
if (pq.size() < k)
pq.add(key);
else if (map.get(key) > map.get(pq.peek())) {
pq.remove();
pq.add(key);
}
}

LinkedList<Integer> res = new LinkedList<>();
while (!pq.isEmpty())
res.add(pq.remove());
return res;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import java.util.*;

/**
* @Auther: lss
* @Date: 2019/2/26 19:00
* @Description:
*/
public class Solution4 {

public List<Integer> topKFrequent(int[] nums, int k) {

TreeMap<Integer, Integer> map = new TreeMap<>();
for (int num : nums) {
if (map.containsKey(num))
map.put(num, map.get(num) + 1);
else
map.put(num, 1);
}

PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> map.get(a) - map.get(b));
for (int key : map.keySet()) {
if (pq.size() < k)
pq.add(key);
else if (map.get(key) > map.get(pq.peek())) {
pq.remove();
pq.add(key);
}
}

LinkedList<Integer> res = new LinkedList<>();
while (!pq.isEmpty())
res.add(pq.remove());
return res;
}
}

0 comments on commit 1f43551

Please sign in to comment.