【牛客网-名企高频面试题】 NC88 寻找第K大

NC88 寻找第K大

题目描述

有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。

给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。

示例1

输入

[1,3,5,2,2],5,3

返回值

2

  1. 先排序再查找
    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length - k];
    }
  1. 使用最小堆
import java.util.*;

public class Finder {
    public int findKth(int[] a, int n, int K) {
        // write code here
        PriorityQueue<Integer> q = new PriorityQueue<>();
        for(int i = 0;i<n;i++){
            if(q.size() < K){
                q.add(a[i]);
            }else if(a[i] > q.peek()){
                q.remove();
                q.add(a[i]);
            }
        }
        return q.peek();
    }
}
  1. 快速排序
    public int findKthLargest(int[] nums, int k) {
        return quickSelect(nums, 0, nums.length - 1, k);
    }

    int quickSelect(int[] nums, int lo, int hi, int k) {
        int pivot = lo;
        for (int j = lo; j < hi; j++) {
            if (nums[j] <= nums[hi]) {
                swap(nums, pivot++, j);
            }
        }
        swap(nums, pivot, hi);
        int count = hi - pivot + 1;
        // 如果找到直接返回
        if (count == k)
            return nums[pivot];
        // 从右边部分找
        if (count > k)
            return quickSelect(nums, pivot + 1, hi, k);
        // 从左边部分找
        return quickSelect(nums, lo, pivot - 1, k - count);
    }

    private void swap(int[] nums, int i, int j) {
        if (i != j) {
            nums[i] ^= nums[j];
            nums[j] ^= nums[i];
            nums[i] ^= nums[j];
        }
    }

posted @ 2020-12-23 21:18  your_棒棒糖  阅读(91)  评论(0编辑  收藏  举报