1. 程式人生 > >[Swift Weekly Contest 122]LeetCode986. 區間列表的交集 | Interval List Intersections

[Swift Weekly Contest 122]LeetCode986. 區間列表的交集 | Interval List Intersections

output 輸出 http order ise test tco 集合 present

Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.

(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)

Example 1:

技術分享圖片

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]]
Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.

Note:

  1. 0 <= A.length < 1000
  2. 0 <= B.length < 1000
  3. 0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9

給定兩個由一些閉區間組成的列表,每個區間列表都是成對不相交的,並且已經排序。

返回這兩個區間列表的交集。

(形式上,閉區間 [a, b](其中 a <= b)表示實數 x 的集合,而 a <= x <= b。兩個閉區間的交集是一組實數,要麽為空集,要麽為閉區間。例如,[1, 3] 和 [2, 4] 的交集為 [2, 3]。)

示例:

技術分享圖片

輸入:A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
輸出:[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
註意:輸入和所需的輸出都是區間對象組成的列表,而不是數組或列表。

提示:

  1. 0 <= A.length < 1000
  2. 0 <= B.length < 1000
  3. 0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9

1472 ms

 1 /**
 2  * Definition for an interval.
 3  * public class Interval {
 4  *   public var start: Int
 5  *   public var end: Int
 6  *   public init(_ start: Int, _ end: Int) {
 7  *     self.start = start
 8  *     self.end = end
 9  *   }
10  * }
11  */
12 class Solution {
13     func intervalIntersection(_ A: [Interval], _ B: [Interval]) -> [Interval] {
14         if A.isEmpty || B.isEmpty {return []}
15         var C:[Interval] = [Interval](repeating:Interval(0,1),count:A.count*B.count)
16         var p:Int = 0
17         for x in A
18         {
19             for y in B
20             {
21                 var l:Int = max(x.start, y.start)
22                 var r:Int = min(x.end, y.end)
23                 if l <= r
24                 {
25                     C[p] = Interval(l, r)
26                     p += 1
27                 }
28             }
29         }
30         if (p - 1) < C.count
31         {
32             var arr = C[0...(p - 1)]
33             return [Interval](arr)
34         }
35         return C
36     }
37 }

[Swift Weekly Contest 122]LeetCode986. 區間列表的交集 | Interval List Intersections