LintCode-5.第k大元素

题目

描述

在数组中找到第k大的元素

样例

给出数组 [9,3,2,4,8],第三大的元素是 4

给出数组 [1,2,3,4,5],第一大的元素是 5,第二大的元素是 4,第三大的元素是 3,以此类推

解答

思路

  1. 快速排序
  2. 返回倒数第k个元素

代码

class Solution {
    /*
     * @param k : description of k
     * @param nums : array of nums
     * @return: description of return
     */
    public int kthLargestElement(int k, int[] nums) {
        // write your code here
        quickSort(nums,0, nums.length-1);
        return nums[nums.length-k];
    }
    
    private void quickSort(int[] nums, int start, int end){
        if(start > end){
            return;
        }
        int i = start,j = end;
        int temp = nums[i];
        boolean flag = true;
        while(i != j){
            while(nums[j]>=temp && i

你可能感兴趣的:(LintCode-5.第k大元素)