LeetCode 632. Smallest Range Covering Elements from K Lists

把所有元素按值排序之后,用双指针找出最小的包含每个list元素的区间



class Solution {
    
    public int[] smallestRange(List<List<Integer>> nums) {
        List<Pair<Integer,Integer>> check = new ArrayList<>();
        
        int n = nums.size();
        for(int i=0;i<n;i++){
            int m = nums.get(i).size();
            for(int j=0;j<m;j++){
                check.add(new Pair<Integer,Integer>(nums.get(i).get(j),i));
            }
        }
        Collections.sort(check,(a,b)->a.getKey()-b.getKey());
            
            
        int flag[] = new int[n];
        int cnt = 0;
        int m = check.size();
        // for(int i=0;i<m;i++)
        //     System.out.println(check.get(i).getKey());
        int l = 0, r = 0;
        int ans[] = new int[2];
        ans[1] = Integer.MAX_VALUE;
        while(l<m){
            while(cnt!=n && r!=m){
                if(cnt == n){
                    if(check.get(r-1).getKey()-check.get(l).getKey() < ans[1] - ans[0]){
                        ans[0] = check.get(l).getKey();
                        ans[1] = check.get(r-1).getKey();
                    }
                }
                int cur_list = check.get(r).getValue();
                if(flag[cur_list]++ == 0)
                    cnt++;
                r++;
            }
            if(r == m && cnt != n)
                return ans;

            while(cnt == n && l<r){
                if(cnt == n){
                    if(check.get(r-1).getKey()-check.get(l).getKey() < ans[1] - ans[0]){
                        ans[0] = check.get(l).getKey();
                        ans[1] = check.get(r-1).getKey();
                    }
                }
                int cur_list = check.get(l).getValue();
                    if(flag[cur_list]-- == 1)
                        cnt--;
                l++;
            }
            if(r == m && cnt != n)
                return ans;
        }
        return ans;
        
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值