Kth Largest Element in an Array

题目描述:


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.

解题思路:每次找到一个第i大的元素,并将其置于后面,直至i==k

Java代码:

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        int kthMax=2147483647;
        for(int i=1;i<=k;i++){
            int max=nums[0];
            int x=0;
            for(int j=1;j<=nums.length-i;j++){//每次选择第k大元素,并将其放于倒数第k个位置
                if(nums[j]>max&&nums[j]<=kthMax) {
                    max=nums[j];
                    x=j;
                }
            }
            int temp=nums[x];
            nums[x]=nums[nums.length-i];
            nums[nums.length-i]=nums[x];
            kthMax=max;
        }
        return kthMax;
    }
}
原题地址: https://leetcode.com/problems/kth-largest-element-in-an-array/

你可能感兴趣的:(LeetCode算法,Kth,Largest,Element,Leetcode)