把所有元素按值排序之后,用双指针找出最小的包含每个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;
}
}