码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode 中等题:kth-largest-element 第k大元素

时间:2016-01-03 23:58:50      阅读:412      评论:0      收藏:0      [点我收藏+]

标签:

题目

第k大元素

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

样例

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

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

注意

你可以交换数组中的元素的位置

挑战

要求时间复杂度为O(n),空间复杂度为O(1)

解题

理论快速排序的思想,每次都减半,这个时间复杂度也是O(N),至于为什么就不知道了

技术分享
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
        return quickSort(nums,0,nums.length-1,k);
        
    }
    public int quickSort(int[] nums,int left,int right,int k){
        int i = left;
        int j = right;
        int tmp = nums[i];
        while(i<j){
            while(i<j && tmp>=nums[j]) j--;
            if(i<j){
                nums[i]=nums[j];
                i++;
            }
            while(i<j && tmp<nums[i]) i++;
            if(i<j){
                nums[j]=nums[i];
                j--;
            }
            
        }
        if(i == k -1){
            return tmp;
        }else if(i< k-1){
            return quickSort(nums,i+1,right,k);
        }else{
            return quickSort(nums,left,i-1,k);
        }
    }
};
View Code

 

lintcode 中等题:kth-largest-element 第k大元素

标签:

原文地址:http://www.cnblogs.com/theskulls/p/5097312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!