LeetCode:Top K Frequent Elements

Q:

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].

Note: 

  • 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.
思路:遍历nums,

如果nums[i]不存在于HashMap中,则将nums[i]作为key,1作为value(代表第一次出现).

否则将nums[i]对应的value++.

然后将map存入list中,以value降序排序,最后获取top k个entry即可.

	public List topKFrequent(int[] nums, int k) {
		HashMap map = new HashMap<>();
		int i = 0, length = nums.length;
		while (i < length) {
			int num = nums[i++];
			Integer count = map.get(num);
			if (count == null) {
				map.put(num, 1);
			} else {
				map.put(num, count + 1);
			}
		}
		Set> entrySet = map.entrySet();
		List> listToBeSorted = new ArrayList<>(entrySet);
		Collections.sort(listToBeSorted, new Comparator>() {
			@Override
			public int compare(Entry e1, Entry e2) {
				return e2.getValue() - e1.getValue();
			}
		});
		List resultList = new ArrayList<>(listToBeSorted.size());
		for (Entry entry : listToBeSorted) {
			if (k-- <= 0) {
				break;
			}
			resultList.add(entry.getKey());
		}
		return resultList;
	}




你可能感兴趣的:(--1.2.Algorithm,--1.4.LeetCode)