215. Kth Largest Element in an Array

desciption:
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.
Input: [3,2,1,5,6,4] and k = 2
Output: 5
解法一:
排序:时间复杂度O(NlogN),空间复杂度O(1)

public static int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length-k];
}

解法二:
堆:时间复杂度O(Nlogk),空间复杂度O(1)

public static int findKthLargest(int[] nums, int k) {
        PriorityQueue pq = new PriorityQueue<>();//小顶堆
        for(int n : nums){
            pq.add(n);
            if(pq.size() > k)
                pq.poll();
        }
        return pq.peek();
    }

1、优先队列概述:

优先队列PriorityQueue是Queue接口的实现,可以对其中元素进行排序,可以放基本数据类型的包装类(如:Integer,Long等)或自定义的类对于基本数据类型的包装器类,优先队列中元素默认排列顺序是**升序排列**,但对于自己定义的类来说,需要自己定义比较器

2、常用方法

peek()//返回队首元素
poll()//返回队首元素,队首元素出队列
add()//添加元素
size()//返回队列元素个数
isEmpty()//判断队列是否为空,为空返回true,不空返回false

解法三:
快排:

你可能感兴趣的:(java,leetcode)