所以我试图解决这个问题: http: //oj.leetcode.com/problems/merge-intervals/
我的解决方案是:
public class Solution {
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
// Start typing your Java solution below
// DO NOT write main() function
// ArrayList<Interval> result = new ArrayList<Interval>();
//First sort the intervals
Collections.sort(intervals,new Comparator<Interval>(){
public int compare(Interval interval1, Interval interval2) {
if(interval1.start > interval2.start) return 1;
if(interval1.start == interval2.start) return 0;
if(interval1.start < interval2.start) return -1;
return 42;
}
});
for(int i = 0; i < intervals.size() - 1; i++){
Interval currentInterval = intervals.get(i);
Interval nextInterval = intervals.get(i+1);
if(currentInterval.end >= nextInterval.start){
intervals.set(i,new Interval(currentInterval.start,nextInterval.end));
intervals.remove(i+1);
i--;
}
}
return intervals;
}
}
我看到一些博客使用完全相同的解决方案,但被接受了,但我的被拒绝了,因为它需要太长时间。你能告诉我为什么它需要比预期更长的时间吗?干杯
编辑:已解决,删除成本太高,使用新的数组列表存储结果更快