Kth largest element in an array
Topic description: Given an array of integers
nums
and an array of integersk
, please return the**k**
largest element in the array.Note that you need to find the
k
th largest element of the sorted array, not thek
th distinct element.For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Array sorting
The first consideration here is to sort the original array, and the kth largest element can be directly obtained from the sorted array, so the specific processing process is as follows:
- First, use the sorting algorithm to sort the array. There are various sorting algorithms, such as bubble sort, quick sort, merge sort, etc. Here, the java library function is directly used to sort the array, which is a lazy approach;
- Then according to the sorted array index, the Kth largest element can be directly obtained and returned.
import java.util.Arrays;
public class LeetCode_215 {
/**
* 数组排序:首先使用排序算法对该数组排序,然后直接获取第K大的元素返回即可
*
* @param nums 原数组
* @param k 期望的第K大
* @return
*/
public static int findKthLargest(int[] nums, int k) {
// 排序算法有各种,这里直接使用了java的库函数进行排序
Arrays.sort(nums);
// 排序后,直接返回第K大的元素
return nums[nums.length - k];
}
public static void main(String[] args) {
int[] nums = new int[]{3, 2, 1, 5, 6, 4};
// 测试用例,期望输出: 5
System.out.println(findKthLargest(nums, 2));
}
}
[Daily Message] Is the acting career that lacks flowers and applause lonely? yes. But if you keep believing and persevering, you will silently accumulate strength – like climbing a mountain, trekking forward. Carrying all the way deserted, looking for the return of self-worth. Everyone has one or several peaks that need to be conquered and surpassed constantly.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。