Kth Largest Element in an Array

题目链接

思路:优先级树
java里面优先级树使用的是PriorityQueue
要传入一个比较因子。这个因子对于优先级高的返回-1;

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        Comparator<Integer> OrderIsdn =  new Comparator<Integer>(){  
            public int compare(Integer o1, Integer o2) { 
                if(o1>o2)
                {
                    return -1;
                }
                else if(o1<o2)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }


            }
        };  

        PriorityQueue<Integer> pQueue=new PriorityQueue<Integer>(OrderIsdn);
        for(int i=0;i<nums.length;i++)
        {
            pQueue.add(nums[i]);
        }
        for(int i=0;i<k-1;i++)
        {
            pQueue.poll();
        }
        return pQueue.peek();
    }
}

你可能感兴趣的:(Kth Largest Element in an Array)