[Swift]LeetCode850. 矩形面積 II | Rectangle Area II
阿新 • • 發佈:2019-03-25
integer aligned coo time span poi code 分享圖片 alt
Runtime: 120 ms Memory Usage: 19.7 MB
We are given a list of (axis-aligned) rectangles
. Each rectangle[i] = [x1, y1, x2, y2]
, where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the i
th rectangle.
Find the total area covered by all rectangles
in the plane. Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: [[0,0,2,2],[1,0,2,3],[1,0,3,1]] Output: 6 Explanation: As illustrated in the picture.
Example 2:
Input: [[0,0,1000000000,1000000000]] Output: 49 Explanation: The answer is 10^18 modulo (10^9 + 7), which is (10^9)^2 = (-7)^2 = 49.
Note:
1 <= rectangles.length <= 200
rectanges[i].length = 4
0 <= rectangles[i][j] <= 10^9
- The total area covered by all rectangles will never exceed
2^63 - 1
and thus will fit in a 64-bit signed integer.
我們給出了一個(軸對齊的)矩形列表 rectangles
。 對於 rectangle[i] = [x1, y1, x2, y2]
,其中(x1,y1)是矩形 i
左下角的坐標,(x2,y2)是該矩形右上角的坐標。
找出平面中所有矩形疊加覆蓋後的總面積。 由於答案可能太大,請返回它對 10 ^ 9 + 7 取模的結果。
示例 1:
輸入:[[0,0,2,2],[1,0,2,3],[1,0,3,1]] 輸出:6 解釋:如圖所示。
示例 2:
輸入:[[0,0,1000000000,1000000000]] 輸出:49 解釋:答案是 10^18 對 (10^9 + 7) 取模的結果, 即 (10^9)^2 → (-7)^2 = 49 。
提示:
1 <= rectangles.length <= 200
rectanges[i].length = 4
0 <= rectangles[i][j] <= 10^9
- 矩形疊加覆蓋後的總面積不會超越
2^63 - 1
,這意味著可以用一個 64 位有符號整數來保存面積結果。
Runtime: 120 ms Memory Usage: 19.7 MB
1 class Solution { 2 func rectangleArea(_ rectangles: [[Int]]) -> Int { 3 var M:Int = 1000000007 4 var data:[Point] = [Point]() 5 for r in rectangles 6 { 7 data.append(Point(r[0], r[1], 1)) 8 data.append(Point(r[0], r[3], -1)) 9 data.append(Point(r[2], r[1], -1)) 10 data.append(Point(r[2], r[3], 1)) 11 } 12 data.sort(by:{(a:Point,b:Point) -> Bool in 13 if a.x == b.x {return b.y <= a.y} 14 return a.x < b.x}) 15 var map:[Int:Int] = [Int:Int]() 16 var preX:Int = -1 17 var preY:Int = -1 18 var result:Int = 0 19 for i in 0..<data.count 20 { 21 var p:Point = data[i] 22 map[p.y,default:0] += p.val 23 if i == data.count - 1 || data[i + 1].x > p.x 24 { 25 if preX > -1 26 { 27 result += (preY * (p.x - preX)) % M 28 result %= M 29 } 30 preY = calcY(map) 31 preX = p.x 32 33 } 34 } 35 return result 36 } 37 38 func calcY(_ p:[Int:Int]) -> Int 39 { 40 var result:Int = 0 41 var pre:Int = -1 42 var count:Int = 0 43 var nums = Set(p.keys).sorted(by:<) 44 for key in nums 45 { 46 if pre >= 0 && count > 0 47 { 48 result += key - pre 49 } 50 count += p[key,default:0] 51 pre = key 52 } 53 return result 54 } 55 } 56 57 class Point 58 { 59 var x:Int 60 var y:Int 61 var val:Int 62 init(_ x:Int,_ y:Int,_ val:Int) 63 { 64 self.x = x 65 self.y = y 66 self.val = val 67 } 68 }
[Swift]LeetCode850. 矩形面積 II | Rectangle Area II