Intersection of interval list
Given two closed interval lists, each interval list is disjoint and sorted.
Returns the intersection of the two interval lists.
(formally, the closed interval [a, b] (where a < = b) represents the set of real numbers x, and a < = x < = b). The intersection of two closed intervals is a set of real numbers, either empty or closed. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)
Example:
Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]] Output: [[1,2], [5,5], [8,10], [15,23], [24,24], [25,25]] Note: input and required output are lists of interval objects, not arrays or lists.
Ideas + codes + comments:
public Interval[] intervalIntersection(Interval[] A, Interval[] B) { /* Idea: traverse the interval in A to compare with the interval in B, where the start and end of interval A are s1 and e1, and the start and end of interval B are s2 and e2. If s2 < = e1 < = e2 or s1 < = e2 < = e1, then s1 is taken as intersection ,s2 The larger value of e1 and e2 is the start of the intersection, and the smaller value of e1 and e2 is the end of the intersection. If e1 < s2, it means that s2 is larger than e1, and there is no direct break of the intersection to exit the cycle of interval B */ List<Interval> res=new ArrayList<>(); for (int i = 0; i < A.length; i++) { Interval a=A[i]; int s1=a.start; int e1=a.end; for (int j = 0; j < B.length; j++) { Interval b=B[j]; int s2=b.start; int e2=b.end; if ((e1>=s2 && e1<=e2) || (e2>=s1 && e2<=e1)) { int start=0; int end=0; start=s1>s2?s1:s2; end=e1<e2?e1:e2; Interval interval=new Interval(start,end); res.add(interval); }else if (e1<s2) { break; } } } Interval[] intervals=new Interval[res.size()]; for (int i = 0; i < res.size(); i++) { intervals[i]=res.get(i); } return intervals; }