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

This commit is contained in:
huangge1199 2021-07-15 15:00:48 +08:00
parent dedc895940
commit 4abe8a4aa8
2 changed files with 80 additions and 0 deletions

View File

@ -0,0 +1,52 @@
//给定整数数组 nums 和整数 k请返回数组中第 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
//
//
//
// 提示
//
//
// 1 <= k <= nums.length <= 104
// -104 <= nums[i] <= 104
//
// Related Topics 数组 分治 快速选择 排序 优先队列
// 👍 1170 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
import java.util.Queue;
//215:数组中的第K个最大元素
public class KthLargestElementInAnArray{
public static void main(String[] args) {
//测试代码
Solution solution = new KthLargestElementInAnArray().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length-k];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,28 @@
<p>给定整数数组 <code>nums</code> 和整数 <code>k</code>,请返回数组中第 <code><strong>k</strong></code> 个最大的元素。</p>
<p>请注意,你需要找的是数组排序后的第 <code>k</code> 个最大的元素,而不是第 <code>k</code> 个不同的元素。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> <code>[3,2,1,5,6,4] 和</code> k = 2
<strong>输出:</strong> 5
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> <code>[3,2,3,1,2,4,5,5,6] 和</code> k = 4
<strong>输出:</strong> 4</pre>
<p> </p>
<p><strong>提示: </strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>分治</li><li>快速选择</li><li>排序</li><li>堆(优先队列)</li></div></div>\n<div><li>👍 1170</li><li>👎 0</li></div>