在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ There are some trees, where each tree is represented by (x,y) coordinate in a two-dimensional garden. Your job is to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. Your task is to help find the coordinates of trees which are exactly located on the fence perimeter. Example 1: Input: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] Output: [[1,1],[2,0],[4,2],[3,3],[2,4]] Explanation: Example 2: Input: [[1,2],[2,2],[4,2]] Output: [[1,2],[2,2],[4,2]] Explanation: Even you only have trees in a line, you need to use rope to enclose them. Note:
在一个二维的花园中,有一些用 (x, y) 坐标表示的树。由于安装费用十分昂贵,你的任务是先用最短的绳子围起所有的树。只有当所有的树都被绳子包围时,花园才能围好栅栏。你需要找到正好位于栅栏边界上的树的坐标。 示例 1: 输入: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] 输出: [[1,1],[2,0],[4,2],[3,3],[2,4]] 解释: 示例 2: 输入: [[1,2],[2,2],[4,2]] 输出: [[1,2],[2,2],[4,2]] 解释: 即使树都在一条直线上,你也需要先用绳子包围它们。 注意:
Runtime: 292 ms
Memory Usage: 20.1 MB
1 /** 2 * Definition for a point. 3 * public class Point { 4 * public var x: Int 5 * public var y: Int 6 * public init(_ x: Int, _ y: Int) { 7 * self.x = x 8 * self.y = y 9 * } 10 * } 11 */ 12 class Solution { 13 func outerTrees(_ points: [Point]) -> [Point] { 14 var res:[Point] = [Point]() 15 var first:Point = points[0] 16 var firstIdx:Int = 0 17 var n:Int = points.count 18 for i in 1..<n 19 { 20 if points[i].x < first.x 21 { 22 first = points[i] 23 firstIdx = i 24 } 25 } 26 res.append(first) 27 var cur:Point = first 28 var curIdx:Int = firstIdx 29 while(true) 30 { 31 var next:Point = points[0] 32 var nextIdx:Int = 0 33 for i in 1..<n 34 { 35 if i == curIdx {continue} 36 var cross:Int = crossProduct(cur, points[i], next) 37 if nextIdx == curIdx || cross > 0 || (cross == 0 && dist(points[i], cur) > dist(next, cur)) 38 { 39 next = points[i] 40 nextIdx = i 41 } 42 } 43 for i in 0..<n 44 { 45 if i == curIdx {continue} 46 var cross:Int = crossProduct(cur, points[i], next) 47 if cross == 0 48 { 49 if check(&res, points[i]) 50 { 51 res.append(points[i]) 52 } 53 } 54 } 55 cur = next 56 curIdx = nextIdx 57 if curIdx == firstIdx {break} 58 } 59 return res 60 } 61 62 func crossProduct(_ A:Point,_ B:Point,_ C:Point) -> Int 63 { 64 var BAx:Int = A.x - B.x; 65 var BAy:Int = A.y - B.y; 66 var BCx:Int = C.x - B.x; 67 var BCy:Int = C.y - B.y; 68 return BAx * BCy - BAy * BCx; 69 } 70 71 func dist(_ A:Point,_ B:Point) -> Int 72 { 73 return (A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y) 74 } 75 76 func check(_ res:inout [Point],_ p:Point) -> Bool 77 { 78 for r in res 79 { 80 if r.x == p.x && r.y == p.y {return false} 81 } 82 return true 83 } 84 }
|
请发表评论