Leetcode题解 347. Top K Frequent Elements
2016-07-20 16:03
423 查看
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].
用桶排序来做最后处理。
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
用桶排序来做最后处理。
public class Solution { public List<Integer> topKFrequent(int[] nums, int k) { //step1—用哈希表统计数组中各元素出现的频次,表中“键”为元素数值,“值”为对应元素出现的频次 Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int num:nums)//遍历数组 { if(map.get(num)==null)//如果“键”为num的数据首次出现,则“值”设为1 map.put(num, 1); else map.put(num, map.get(num)+1);//重复出现,则累计频次 } List<Integer>[] list=new ArrayList[nums.length+1]; for(int key:map.keySet()){ int count=map.get(key); if(list[count]==null) list[count]=new ArrayList(); list[count].add(key); } List<Integer> result=new ArrayList(); for(int i=nums.length;i>=0;i--){ if(list[i]!=null&&result.size()<k){ result.addAll(list[i]); } } return result; } }
相关文章推荐
- 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 题解