leetcode 215 Kth Largest Element in an array

leetcode215 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

算法分析

解法一:O(n)快速选择

其基本思想是使用快速选择算法对数组进行主元分割

Put numbers < pivot to pivot’s left
Put numbers > pivot to pivot’s right

时间复杂度为 = O(n)
算法思路每次计算,可以排除一半的数量, n+(n/2)+(n/4)…1 = n + (n-1) = O(2n-1) = O(n)
因为 n/2+n/4+n/8+…1=n-1.

解法二:O(nlog(n)) 最小堆

实现步骤

  • 首先判断边界条件,在array中也就是判断数组是否为空
  • 重新定义findKthLargest方法。
  1. 如果起始位置大于结束,返回最大值
  2. 将数组末尾index值赋值给pivot,将开始数值赋值给left
  3. 遍历数组,范围是start到end,将小于pivot的值放在左边
  4. swap方法交换数组end与left数字位置
  5. 判断left值与k对比,从而判定检查pivot那一边的值,在进行迭代
  • 完成swap方法

代码实现

快速查找

// 快速查找
class Solution {
    public int findKthLargest(int[] nums, int k) {
        if(nums == null || nums.length == 0)
            return Integer.MAX_VALUE;
        return findKthLargest(nums, 0, nums.length - 1, nums.length - k);
    }
    
    public int findKthLargest(int[] nums, int start, int end, int k){
        if(start > end)
            return Integer.MAX_VALUE;
        
        int pivot = nums[end];
        int left = start;
        for(int i = start; i < end; i++){
            if(nums[i] <= pivot) // 将 numbers < pivot 的值放入pivot左边
                swap(nums, left++, i);
        }
        
        swap(nums, left, end); // 最终, 交换 A[end] 与 A[left]
        
        if(left == k) // 找到第k个最小的数
            return nums[left];
        else if(left < k) // 检查pivot的右半部分
            return findKthLargest(nums, left + 1, end, k);
        else // 检查pivot的左半部分
            return findKthLargest(nums, start, left - 1, k);
    }
    // 实现交换内容
    void swap(int[] A, int i, int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }
}

最小堆

class Solution {
    public int findKthLargest(int[] nums, int k) {
    	//优先队列来存储第k个最大值
        PriorityQueue<Integer> p = new PriorityQueue<Integer>();
        for(int i = 0; i < nums.length; i++){
            p.add(nums[i]);
            if(p.size() > k) 
                p.poll();
        }
        return p.poll();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值