zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 347 前 K 个高频元素

    347. 前 K 个高频元素

    给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

    示例 1:

    输入: nums = [1,1,1,2,2,3], k = 2
    输出: [1,2]
    示例 2:

    输入: nums = [1], k = 1
    输出: [1]
    说明:

    你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
    你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。

    class Solution {
        //前 K 个高频元素
         public List<Integer> topKFrequent(int[] nums, int k) {
        	 List<Integer> list=new ArrayList();
        	 Arrays.sort(nums);
        	 int distinctLen=1;
        	 for(int i=1;i<nums.length;i++){
        		 if(nums[i]!=nums[i-1]){
        			 distinctLen++;
        		 }
        	 }
        	 int counts[]=new int[distinctLen];
        	 int order[]=new int[distinctLen];
        	 int index=0;
        	 int count=1;
        	 for(int i=1;i<nums.length;i++){
        		 if(nums[i]==nums[i-1]){
        			 count++;
        		 }else{
        			 counts[index]=count;
        			 order[index]=count;
        			 nums[index]=nums[i-1];
        			 index++;
        			 count=1;
        		 }
        	 }
        	 nums[index]=nums[nums.length-1];
        	 counts[index]=count;
        	 order[index]=count;
        	 Arrays.sort(order);
        	 int kth=order[distinctLen-k];
        	 for(int i=0;i<=index;i++){
        		 if(counts[i]>=kth){
        			 list.add(nums[i]);
        		 }
        	 }
        	 return list;
         }
    }
    
  • 相关阅读:
    RAID实战案例
    文件系统常用工具实战篇
    挂载文件系统
    硬盘结构类型概述
    创建文件系统实战篇
    JumpServer的会话管理及命令过滤器应用案例
    JumpServer的权限管理
    JumpServer的用户管理
    helm基础
    hpa控制器
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946565.html
Copyright © 2011-2022 走看看