合并区间常考面试题
Posted 赵jc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了合并区间常考面试题相关的知识,希望对你有一定的参考价值。
合并区间
public class Solution {
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
ArrayList<Interval> ret = new ArrayList<>();
if(intervals == null || intervals.size() == 0) {
return ret;
}
intervals.sort((a, b)->(a.start - b.start));
ret.add(intervals.get(0));
for(int i = 1; i < intervals.size(); i++) {
int left = intervals.get(i).start;
int right = intervals.get(i).end;
if(ret.get(ret.size() - 1).end < left) {
ret.add(new Interval(left, right));
}else {
ret.get(ret.size() - 1).end = Math.max(ret.get(ret.size() - 1).end, right);
}
}
return ret;
}
}
合并区间
https://leetcode-cn.com/problems/merge-intervals/
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a,b)->a[0] - b[0]);
int[][] ret = new int[intervals.length][2];
int index = -1;
for(int[] nums : intervals) {
if(index == -1 || nums[0] > ret[index][1]) {
ret[++index] = nums;
}else {
ret[index][1] = Math.max(ret[index][1], nums[1]);
}
}
return Arrays.copyOf(ret, index + 1);
}
}
以上是关于合并区间常考面试题的主要内容,如果未能解决你的问题,请参考以下文章