leetcode题解 632. Smallest Range

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


题意:找到一个范围,可以存在n个list都有数在这个范围内


思路:类似于merge多个有序数组,用heap存储n个数,每个List一个,然后每次poll,找出最小的数,并安排该List加入新的元素,然后用max - min,找出范围,最后给出最小的范围,就是类似于归并排序中的merge函数,逐步合并,找出范围


public int[] smallestRange(int[][] nums) {
PriorityQueue<Element> pq = new PriorityQueue<Element>(new Comparator<Element>() {
public int compare(Element a, Element b) {
return a.val - b.val;
}
});
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
Element e = new Element(i, 0, nums[i][0]);
pq.offer(e);
max = Math.max(max, nums[i][0]);
}
int range = Integer.MAX_VALUE;
int start = -1, end = -1;
while (pq.size() == nums.length) {


Element curr = pq.poll();
if (max - curr.val < range) {
range = max - curr.val;
start = curr.val;
end = max;
}
if (curr.idx + 1 < nums[curr.row].length) {
curr.idx = curr.idx + 1;
curr.val = nums[curr.row][curr.idx];
pq.offer(curr);
if (curr.val > max) {
max = curr.val;
}
}
}


return new int[] { start, end };
}


class Element {
int val;
int idx;
int row;


public Element(int r, int i, int v) {
val = v;
idx = i;
row = r;
}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值