[leetcode]347. Top K Frequent Elements

这是leetcode第347题目

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

题目意思:找出数组中前k个经常出现的元素。

解题思路

1.数组循环一遍,把元素的出现次数都记录下来
2.对元素出现次数做降序排序
3.选择前k个元素输出为结果

代码实现

public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        ArrayList<Element> elementList = new ArrayList<>();
        //Map保存的是元素和elementList对应元素下标的键值对.空间换时间.
        HashMap<Integer, Integer> number2IndexMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (number2IndexMap.containsKey(num)) {
                //如果Map中已保存该num的键值对,则获取出来并且count自增.
                int index = number2IndexMap.get(num);
                elementList.get(index).count++;
            } else {
                //否则,新建一组键值对,保存到Map中.
                Element element = new Element(num);
                elementList.add(element);
                number2IndexMap.put(num, elementList.size() - 1);
            }
        }
        //降序排序elementList.
        Collections.sort(elementList);
        //把前面k个输出到resultList中.
        List<Integer> resultList = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            resultList.add(elementList.get(i).number);
        }
        return resultList;
    }

    /**
     * 用来记录元素出现的次数
     */
    private static class Element implements Comparable<Element> {
        public final int number;
        public int count = 0;
        public Element(int number) {
            this.number = number;
        }

        @Override
        public int compareTo(Element element) {
            return element.count - this.count;
        }
    }
}

posted on 2016-05-15 16:25  wingyip  阅读(1004)  评论(0编辑  收藏  举报

导航