鱼C论坛

 找回密码
 立即注册
查看: 2225|回复: 0

[学习笔记] leetcode 215. Kth Largest Element in an Array

[复制链接]
发表于 2019-9-29 04:04:04 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

  2. Example 1:

  3. Input: [3,2,1,5,6,4] and k = 2
  4. Output: 5
  5. Example 2:

  6. Input: [3,2,3,1,2,4,5,5,6] and k = 4
  7. Output: 4
  8. Note:
  9. You may assume k is always valid, 1 ≤ k ≤ array's length.
复制代码

  1. class Solution {
  2.     public int findKthLargest(int[] nums, int k) {
  3.         int max = Integer.MIN_VALUE;
  4.         int min = Integer.MAX_VALUE;
  5.         
  6.         for(int i :nums){
  7.             if(i > max) max = i;
  8.             if(i < min) min = i;
  9.         }
  10.         int[] arr = new int[max - min +1];
  11.    
  12.         for(int i = 0 ; i< nums.length; i++){
  13.             arr[nums[i] - min]++;
  14.         }
  15.         for(int i = arr.length-1; i>-1; i--){
  16.             
  17.             if(arr[i] != 0) {
  18.                
  19.                 k = k - arr[i];
  20.                     
  21.                 if(k <= 0) return i +min;
  22.             }
  23.             if(k == 0) return i+min;
  24.         }
  25.         
  26.         return -1;
  27.     }
  28. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 20:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表