• [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;
            }
        }
    }
    
  • 相关阅读:
    在 IdentityServer4 中创建客户端
    IdentityServer4 快速上手
    GraphQL Part IV: 浏览器内的 IDE
    GraphQL Part VII: 实现数据变更
    GraphQL Part VIII: 使用一对多查询
    GraphQL Part VI: 使用 Postgres 和 EF Core 持久化数据
    GraphQL Part V: 字段,参数和变量
    GraphQL Part III: 依赖注入
    GraphQL Part II: 中间件
    GraphQL Part I: hello, world.
  • 原文地址:https://www.cnblogs.com/wingyip/p/5495346.html
Copyright © 2020-2023  润新知