Leetcode 精选之排序(数组中的第K个最大元素)

2020-03-27  本文已影响0人  Kevin_小飞象

题目描述

在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:

输入: [3,2,1,5,6,4] 和 k = 2
输出: 5

示例 2:

输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4

说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。

解题思路

三种方法来解决如下:

import java.util.*;
public class Main {
    
    public static void main(String[] args) {
        int[] nums = {3,2,1,5,6,4};
        int[] nums2 = {3,2,3,1,2,4,5,5,6};
        System.out.println(findKthLargest(nums,2));
        System.out.println(findKthLargest(nums2,4));
        
        System.out.println(findKthLargest2(nums,2));
        System.out.println(findKthLargest2(nums2,4));
        
        System.out.println(findKthLargest3(nums,2));
        System.out.println(findKthLargest3(nums2,4));
    }

    // 排序 :时间复杂度 O(NlogN),空间复杂度 O(1)
    public static int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length - k];
    }
    
    // 堆 :时间复杂度 O(NlogK),空间复杂度 O(K)。
    public static int findKthLargest2(int[] nums, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(); // 小顶堆
        for (int val : nums) {
            pq.add(val);
            if (pq.size() > k) {     // 维护堆的大小为 K
                pq.poll();
            }    
        }
        return pq.peek();
    }
    
    // 快速选择 :时间复杂度 O(N),空间复杂度 O(1)
    public static int findKthLargest3(int[] nums, int k) {
        k = nums.length - k;
        int l = 0, h = nums.length - 1;
        while (l < h) {
            int j = partition(nums, l, h);
            if (j == k) {
                break;
            } else if (j < k) {
                l = j + 1;
            } else {
                h = j - 1;
            }
        }
        return nums[k];
    }
    
    public static int partition(int[] a, int l, int h) {
        int i = l, j = h + 1;
        while (true) {
            while (a[++i] < a[l] && i < h);
            while (a[--j] > a[l] && j > l);
            if (i >= j) {
                break;
            }
            swap(a, i, j);
        }
        swap(a, l, j);
        return j;
    }

    public static void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
}

测试结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读