Prolem:
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Analysis:
In this problem, we get a random ordered input. For naive method, we could compare each pair to check whether they could merge or not. if not, add them into the list. Time complexity will be O(n^2)
Another method, we can sort the list first, and then add them into the list.
Time complexity O(nlogn)
Space complexity O(n) ~ final result storage.
Before giving the code, I would like to provide some basic knowledge about LinkedList and ArrayList
ArrayList底层是一个数组,LinkdList底层是一个 链表;
ArrayList查询比较快,因为通过数组的索引来查询;linkdlist增删快,链表通过将要添加的值变成node对象,然后将插入点的节点的next拿出来放入到要添加的值得next中,最后将要添加的值放入到插入点的节点的next中;
ArrayList遍历:
Iterator it = arrayList.iterator();while(it.hasNext())
for(int i = 0; i < arrayList.size(); i++){ System.out.print(arrayList.get(i) + " ");}
for(Integer number : arrayList){ System.out.print(number + " ");}
LinkedList遍历:
Iterator iterator = linkedList.iterator();while(iterator.hasNext()){ iterator.next();}
for(int i = 0; i < linkedList.size(); i++){ linkedList.get(i);}
for(Integer i : linkedList);
while(linkedList.size() != 0){ linkedList.pollFirst();}
while(linkedList.size() != 0){ linkedList.removeFirst();}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution1 {
public List<Interval> merge(List<Interval> intervals) {
if(intervals == null || intervals.size() == 0) {
return intervals;
}
Collections.sort(intervals, (Interval I1, Interval I2) -> I1.start - I2.start);
LinkedList<Interval> res = new LinkedList<Interval>();
for (Interval interval:intervals) {
if (res.isEmpty() || res.getLast().end < interval.start) {
res.add(interval);
}else {
res.getLast().end = Math.max(interval.end, res.getLast().end);
}
}
return res;
}
}

本文介绍了一个常见的编程面试题——合并区间问题。通过分析输入区间的特性,提出了两种解决方案:一种是朴素方法,时间复杂度为O(n^2),另一种是先排序再合并,时间复杂度降低到O(nlogn)。此外,还对比了ArrayList和LinkedList的特点,并提供了一段实现代码。
537

被折叠的 条评论
为什么被折叠?



