码迷,mamicode.com
首页 > 编程语言 > 详细

215. 数组中的第K个最大元素

时间:2020-07-14 13:25:29      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:ret   元素   nbsp   链接   off   turn   kth   bsp   输出   

在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:

输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:

输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:

你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array

水题,整个多解

Heap(PriorityQueue)

class KthLargestElementHeap {
  public int findKthLargest(int[] nums, int k) {
      PriorityQueue<Integer> pq = new PriorityQueue<>();
      for (auto num : nums) {
        pq.offer(num);
        if (pq.size() > k) {
          pq.poll();
        }
      }
      return pq.poll();
  }
}

排序

class KthLargestElementSort {
 public int findKthlargest2(int[] nums, int k) {
    Arrays.sort(nums);
    return nums[nums.length - k];
  }
}

215. 数组中的第K个最大元素

标签:ret   元素   nbsp   链接   off   turn   kth   bsp   输出   

原文地址:https://www.cnblogs.com/xxxsans/p/13298414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!