LeetCode 215. Kth Largest Element in an Array Java
题目:
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.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
题意:给出一个无序排列的数组,找出其中第k大的元素。数组中可能有重复元素,但是这里第K大就是指 倒数第k个数,不管其中有没有重复的元素。所以,只需要对数组排序然后从后往前找就行。
代码:
public class Solution { public int findKthLargest(int[] nums, int k) { Arrays.sort(nums); //排序 for(int i=nums.length-1;i>0;i--){ if(k==1){ return nums[i]; }else{ k--; } } return nums[0]; } }