You are given two lists of closed intervals,
Return the intersection of these two interval lists.
A closed interval
firstList
and secondList
, where firstList[i] = [starti, endi]
and secondList[j] = [startj, endj]
. Each list of intervals is pairwise disjoint and in sorted order.Return the intersection of these two interval lists.
A closed interval
[a, b]
(with a < b
) denotes the set of real numbers x
with a <= x <= b
.Example 1:
Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class IntervalListIntersections {public static void main(String[] args) {int[][] firstList = { { 0, 2 }, { 5, 10 }, { 13, 23 }, { 24, 25 } };int[][] secondList = { { 1, 5 }, { 8, 12 }, { 15, 24 }, { 25, 26 } };int[][] inter = intervalIntersection(firstList, secondList);System.out.println(Arrays.deepToString(inter));}static public int[][] intervalIntersection(int[][] A, int[][] B) {int n = A.length, m = B.length;int i = 0, j = 0;List<int[]> res = new ArrayList<int[]>();while (i < n && j < m) {int low = Math.max(A[i][0], B[j][0]);int high = Math.min(A[i][1], B[j][1]);if (low <= high) {res.add(new int[] { low, high });}if (A[i][1] < B[j][1])i++;elsej++;}return res.toArray(new int[0][2]);}}
C++
#include <bits/stdc++.h>using namespace std;vector<vector<int>> intervalIntersection(vector<vector<int>> &A,vector<vector<int>> &B){int n = A.size(), m = B.size();int i = 0, j = 0;vector<vector<int>> res;while (i < n && j < m){int low = max(A[i][0], B[j][0]);int high = min(A[i][1], B[j][1]);if (low <= high)res.push_back({low, high});if (A[i][1] < B[j][1])i++;elsej++;}return res;}int main(){vector<vector<int>> firstList = {{0, 2}, {5, 10}, {13, 23}, {24, 25}};vector<vector<int>> secondList = {{1, 5}, {8, 12}, {15, 24}, {25, 26}};vector<vector<int>> inter = intervalIntersection(firstList, secondList);cout << "[";for (int i = 0; i < inter.size(); i++){cout << "[";for (int j = 0; j < inter[i].size(); j++){cout << inter[i][j];if (j != inter[i].size() - 1)cout << ",";}cout << "]";if (i != inter.size() - 1)cout << ",";}cout << "]";return 0;}
No comments:
Post a Comment