[LeetCode]632. Smallest Range

本文介绍了一种解决LeetCode中“最小范围”问题的方法,该问题要求从多个递增数组中找到一个覆盖所有数组元素的最小区间。通过使用优先队列(PQ)和类似归并排序的思想,实现了一种高效算法。

https://leetcode.com/problems/smallest-range/#/description

给k个递增数组,找出一个最小范围,保证每个数组内至少有一个数字落在这个区间上






类似归并排序思想——多维有序数组问题考虑mergeSort+pq思想

pq内每次poll出当前最小值,max保存当前已访问的最大值,当前pq中的所有值一定在这个区间内(满足该区间覆盖所有数组条件),只要看这个区间是否为更小的那个区间即可

public class Solution {
    public int[] smallestRange(List<List<Integer>> nums) {
        int start = -1;
        int end = -1;
        int max = Integer.MIN_VALUE;
        int range = Integer.MAX_VALUE;
        PriorityQueue<Element> queue = new PriorityQueue(new Comparator<Element>() {
            public int compare(Element e1, Element e2) {
                return e1.val - e2.val;
            }
        });
        for (int i = 0; i < nums.size(); i++) {
            Element e = new Element(nums.get(i).get(0), 0, i);
            queue.offer(e);
            max = Math.max(max, e.val);
        }
        while (queue.size() == nums.size()) {
            Element e = queue.poll();
            if (max - e.val < range) {
                range = max - e.val;
                start = e.val;
                end = max;
            }
            if (e.index + 1 < nums.get(e.row).size()) {
                e.index = e.index + 1;
                e.val = nums.get(e.row).get(e.index);
                queue.offer(e);
                if (e.val > max) {
                    max = e.val;
                }
            }
        }
        return new int[]{start, end};
    }
    class Element {
        int index;
        int row;
        int val;
        public Element(int val, int index, int row) {
            this.val = val;
            this.index = index;
            this.row = row;
        }
    }
}


### LeetCode 215 的 Python 解法 对于 LeetCode 第 215 题,即寻找数组中的第 K 大元素,可以采用多种方法解决。其中一种高效的方法是利用快速选择算法 (Quickselect),这是基于快速排序的一种变体。 #### 方法一:使用内置函数 最简单的办法就是先对整个列表进行排序再选取倒数第 k 个位置上的数值: ```python class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: return sorted(nums)[-k] ``` 这种方法虽然简洁但是效率不高,在数据量较大时性能较差[^1]。 #### 方法二:堆排序 另一种方式是构建最大堆或最小堆来获取前 K 大的元素之一: ```python import heapq from typing import List class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: min_heap = [] for num in nums: if len(min_heap) < k or num > min_heap[0]: heapq.heappush(min_heap, num) if len(min_heap) > k: heapq.heappop(min_heap) return min_heap[0] if min_heap else None ``` 此方案的时间复杂度为 O(N log K), 更适合处理大规模的数据集[^2]. #### 方法三:快速选择 QuickSelect 最后推荐的是更高效的解决方案——快速选择算法。该算法平均情况下时间复杂度仅为O(n): ```python from random import randint from typing import List def partition(left, right, pivot_index, nums): pivot_value = nums[pivot_index] # Move pivot to end nums[pivot_index], nums[right] = nums[right], nums[pivot_index] store_index = left for i in range(left, right): if nums[i] < pivot_value: nums[store_index], nums[i] = nums[i], nums[store_index] store_index += 1 # Place pivot after the last smaller element nums[right], nums[store_index] = nums[store_index], nums[right] return store_index def select(left, right, k_smallest, nums): """ Returns the k-th smallest element of list within left..right. """ if left == right: # If the list contains only one element, return nums[left] # return that element. # Select a random pivot_index between pivot_index = randint(left, right) # Find the pivot position in a sorted list pivot_index = partition(left, right, pivot_index, nums) # The pivot is in its final sorted position if k_smallest == pivot_index: return nums[k_smallest] elif k_smallest < pivot_index: return select(left, pivot_index - 1, k_smallest, nums) else: return select(pivot_index + 1, right, k_smallest, nums) class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: # Convert to index-based by subtracting from length k = len(nums) - k return select(0, len(nums)-1, k, nums) ``` 上述代码实现了完整的 `findKthLargest` 函数以及辅助性的分区 (`partition`) 和选择 (`select`) 函数。通过随机化枢轴的选择过程提高了算法稳定性并减少了最坏情况发生的可能性[^4].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值