215. 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.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.

class Solution {
    public int findKthLargest(int[] nums, int k) {        
        ArrayList<Integer> list = new ArrayList();
        for(int i: nums){
            list.add(i);
        }
        Collections.sort(list);
        Collections.reverse(list);
        return list.get(k-1);
    }
}

有很多种解法,最先想到的是存到arraylist里再调用api。

class Solution {
    public int findKthLargest(int[] nums, int k) {        
        final Queue<Integer> q = new PriorityQueue<>();

        for (int x : nums) {
            if (q.size() < k) {
                q.offer(x);
            } else {
                final int top = q.peek();
                if (x > top) {
                    q.poll();
                    q.offer(x);
                }
            }
        }
        return q.peek();
    }
}

priorityqueue:压入随机数,按从小到大输出。设置一个长为k的队列,然后把比最大数和第二大数存入,再peek就是答案,太巧妙了

class Solution {
    public int findKthLargest(int[] nums, int k) {
        return help(nums, 0, nums.length - 1, nums.length - k);
    }
    public int help(int[] nums, int low, int high, int k) {
        int i = low - 1;
        int pivot = nums[high];
        
        for(int j = low; j < high; j++){
            if(nums[j] < pivot){
                i++;
                swap(i, j, nums);
            }
        }
        swap(i+1, high, nums);
        if(i+1 == k) return nums[i+1];
        else if(i + 1 < k) return help(nums, i + 2, high, k);
        else return help(nums, low, i, k);
    }
    public void swap(int i, int j, int[] nums){
        int a = nums[i] + nums[j];
        nums[j] = a - nums[j];
        nums[i] = a - nums[j];
    }
}

我这装个逼用quicksort(select)反而更慢了,草,注意是k还是k-1

posted @ 2019-09-10 01:50  Schwifty  阅读(161)  评论(0编辑  收藏  举报