★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-zlqfsogo-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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. git
Example 1:github
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:app
在一個二維的花園中,有一些用 (x, y) 座標表示的樹。因爲安裝費用十分昂貴,你的任務是先用最短的繩子圍起全部的樹。只有當全部的樹都被繩子包圍時,花園才能圍好柵欄。你須要找到正好位於柵欄邊界上的樹的座標。ui
示例 1:spa
輸入: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] 輸出: [[1,1],[2,0],[4,2],[3,3],[2,4]] 解釋:
示例 2:3d
輸入: [[1,2],[2,2],[4,2]] 輸出: [[1,2],[2,2],[4,2]] 解釋:
即便樹都在一條直線上,你也須要先用繩子包圍它們。
注意:code
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 }