Kth Largest Element in an Array

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.

思路:

  快速排序,最大堆

我的代码:

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        return helper(nums, nums.length-k);
    }
    public int helper(int[]nums, int k)
    {
        int low = 0; 
        int high = nums.length-1;
        int key = nums[0];
        while(low < high)
        {
            while(low<high && nums[high]>=key) high--;
            nums[low] = nums[high];
            while(low<high && nums[low]<key) low++;
            nums[high] = nums[low];
        }
        nums[low] = key;
        if(low == k) return nums[low];
        return low < k ? helper(Arrays.copyOfRange(nums, low+1, nums.length), k-(low+1)) : helper(Arrays.copyOfRange(nums, 0, low), k);
    }
}
View Code

他人代码:

public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>(k,new Comparator<Integer>(){
            public int compare(Integer a, Integer b) {
                return a-b;
            }
        });
        for(int i=0;i<nums.length;i++) {
            if(queue.size()<k) queue.add(nums[i]);
            else {
                if(nums[i]>queue.peek()) {
                    queue.remove();
                    queue.add(nums[i]);
                }
            }
        }
        return queue.remove();
    }
View Code

学习之处:

  • 比较常规的问题了,之前这个问题就知道两种思路,一种是快速排序的Partition,另外一种是最小堆,关键的地方在于实现Partition,java中如何调用最小堆。

posted on 2015-05-28 11:03  zhouzhou0615  阅读(259)  评论(0编辑  收藏  举报

导航