LeetCode632. Smallest Range(最小区间)

632. Smallest 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 k lists.

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.
  4. For Java users, please note that the input type has been changed to List. And after you reset the code template, you’ll see this point.

题目:你有 k 个升序排列的整数数组。找到一个最小区间,使得 k 个列表中的每个列表至少有一个数包含在其中。

思路:K个有序数组的归并排序,参考geeksforgeeks。

工程代码下载

class Solution {
public:
    vector<int> smallestRange(vector<vector<int>>& nums) {
        int k = nums.size();
        if(k == 0) return {};
        // K个数组对应的index指针,初始均指向0位置
        vector<int> ptr(k, 0);
        int leftval, rightval;
        int range = INT_MAX;
        int next_list = 0;
        // 类似K个有序数组的归并排序
        while(ptr[next_list] < nums[next_list].size()){
            int min = INT_MAX, max = INT_MIN;
            for(int i = 0; i < k; ++i){
                int num = nums[i][ptr[i]];  // 第i个数组当前指向的值
                
                if(num < min){
                    min = num;
                    // 选中k个值中最小的对应的数组序号,下次右移该数组对应的指针
                    next_list = i;
                }
                if(num > max){
                    max = num;
                }
            }
            
            ptr[next_list]++;
            
            if(max - min < range){
                range = max - min;
                leftval = min;
                rightval = max;
            }
        }
        return {leftval, rightval};
    }
};

你可能感兴趣的:(leetcode)