leetcode 632. Smallest Range

本文介绍了一种寻找多个已排序列表中至少每个列表有一个数的最小范围的方法。通过使用双指针技术和哈希表来高效地解决这个问题,同时给出了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

632Smallest Range

You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the klists. 

We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.

Example 1:

Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
Output: [20,24]
Explanation: 
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].

Note:

  1. The given list may contain duplicates, so ascending order means >= here.
  2. 1 <= k <= 3500
  3. -105 <= value of elements <= 105.

1、算是比较标准的two point 问题

2、这种题都有一个hash表来判断两个指针的距离条件,

不满足的时候end指针走,

满足的时候求值,并且start指针走,直到走到不满足就停下。让end走。



bool compare(const pair<int, int>& a, const pair<int, int>& b)
{
    return a.first < b.first;
}

class Solution {
public:
    vector<int> smallestRange(vector<vector<int>>& nums)
    {
        vector<pair<int, int>> all;
        for (int i = 0; i < nums.size(); i++)
        {
            for (int j = 0; j < nums[i].size(); j++)
                all.push_back(make_pair(nums[i][j], i));
        }
        sort(all.begin(), all.end(), compare);
        
        int start = 0, end = 0;
        unordered_map<int, int> hash;
        vector<int> ret(1, 0);
        ret.push_back(INT_MAX);
        while (end < all.size())
        {
            while (end < all.size() && hash.size() < nums.size())   //说明还有没有包含的行
            {
                hash[all[end].second] ++;
                end ++;
            }
            
            //然后start指针往后移动
            while (start <= end && hash.size() == nums.size())
            {
                //进入循环 说明 满足了条件了。
                if (all[end - 1].first - all[start].first < ret[1] - ret[0] )
                {
                    ret[0] = all[start].first;
                    ret[1] = all[end - 1].first;
                }
                
                if ( (--hash[all[start].second]) == 0)
                    hash.erase(all[start].second);
                start ++;
            }
        }
        return ret;
    }
};


### 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、付费专栏及课程。

余额充值