leetcode 347. Top K Frequent Elements 解题报告
2016-06-25 20:03
441 查看
题目链接
使用TreeMap和HashMap进行利用value值进行排序
按照题目要求输出前K大
使用的方法不够好。后面又使用了另外的方法另建一个对象存储数字和对应的频率,然后将此对象作为value存储在map和list中,对list进行排序。代码就不贴了。
解题思路
使用Map将数字和对应的频率按照键值对存储起来使用TreeMap和HashMap进行利用value值进行排序
按照题目要求输出前K大
使用的方法不够好。后面又使用了另外的方法另建一个对象存储数字和对应的频率,然后将此对象作为value存储在map和list中,对list进行排序。代码就不贴了。
解题代码
public class Solution { public List<Integer> topKFrequent(int[] nums, int k) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); ValueComparator bvc = new ValueComparator(map); TreeMap<Integer,Integer> tmap = new TreeMap<Integer,Integer>(bvc); List<Integer> list = new ArrayList<Integer>(); for(int i = 0;i<nums.length;i++){ if(map.containsKey(nums[i])){ map.replace(nums[i],map.get(nums[i])+1); }else{ map.put(nums[i],1); } } tmap.putAll(map); Set set = tmap.keySet(); Iterator it = set.iterator(); while(it.hasNext() && k-- >0){ list.add((Integer) it.next()); } return list; } class ValueComparator implements Comparator<Integer> { Map<Integer,Integer> base; public ValueComparator(Map<Integer,Integer> base) { this.base = base; } public int compare(Integer a, Integer b) { if(base.get(a)>=base.get(b)){ return -1; }else{ return 1; } } } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解