题目描述:
Given a non-empty array of integers, return the k most frequent elements.
事例:
Given [1,1,1,2,2,3] and k = 2, return [1,2]
注意事项:
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.
解题思想:
通过题目分析,key和value之间存在单向一对一关系,即通过指定的key,总能找到唯一的,确定的value。利用Map集合,从中取出数据时,只要给出指定的key,就可以取出对应的value。
Map提供一个Entry内部类,来封装key-value,以便通过value索取key。
代码:
package ACM;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Solution {
public static List topKFrequent(int[] nums, int k) {
Map