题解 | 合并区间
合并区间
https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
import java.util.*;
/*
* public class Interval {
* int start;
* int end;
* public Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param intervals Interval类ArrayList
* @return Interval类ArrayList
*/
public ArrayList<Interval> merge (ArrayList<Interval> intervals) {
if (intervals.size()==0){
return new ArrayList(0);
}
//获得排序后的数组
Collections.sort(intervals, new Comparator<Interval>() {
public int compare(Interval first, Interval second) {
if (first.start != second.start) {
return first.start - second.start;
} else {
return first.end - second.end;
}
}
});
ArrayList<Interval> result = new ArrayList<>();
Interval current = intervals.get(0);
for (int i = 0; i < intervals.size() - 1; i++) {
Interval next = intervals.get(i + 1);
if (current.end >= next.start) {
int newEnd = next.end > current.end? next.end:current.end;
current = new Interval(current.start, newEnd);
} else {
result.add(current);
current = next;
}
}
result.add(current);
return result;
}
}
思路:利用Collections的sort函数进行排序,不过要重写compare函数 compare函数返回是int
在考虑区间的时候要考虑区间的首尾部
同时,在做区间的时候,可以将其当做链表来做

