Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
Two Pointer Solution:
Unlike merge sort, we need to merge these two arrays in place. So start from the end (A[m+n-1]), we compare each pointer. Until one of the pointers reached 0, copy the rest of B to A.
1
2
3
4
5
6
7
8
publicvoidmerge(int A[], int m, int B[], int n) {
int cur=m+n;
while(m>0 && n>0){
if(A[m-1]<B[n-1]){A[--cur]=B[--n];}
else {A[--cur]=A[--m];}
}
while(n>0){A[--cur]=B[--n];}
}
Merge Intervals
Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18].
Correct Solution
At first sort the Intervals, then I thought of three basic cases:
cur.end > next.end (&& cur.end > next.start)
cur.end < next.end && cur.end > next.start
cur.end < next.end && cur.end < next.start
we can leave the third case alone, and only the first two cases need to be merged: if(cur.end > next.start) we set cur.end to the max out of two ends.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
//sort according to start using inline comparator
Collections.sort(intervals, new Comparator<Interval>(){
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
Solution(while loop)
Still three cases:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {