在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Constraints: 2 <= coordinates.length <= 1000 在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。 请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 <font color="#c7254e" face="Menlo, Monaco, Consolas, Courier New, monospace">true</font>,否则请返回 <font color="#c7254e" face="Menlo, Monaco, Consolas, Courier New, monospace">false</font>。 示例 1: 输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 提示: 2 <= coordinates.length <= 1000 40ms 1 class Solution { 2 func checkStraightLine(_ coordinates: [[Int]]) -> Bool { 3 let cur = coordinates[0] 4 let next = coordinates[1] 5 6 let num = next[1] - cur[1] 7 let denom = next[0]-cur[0] 8 9 let slope = Double(num)/Double(denom) 10 11 for i in 1..<coordinates.count-1{ 12 let cur = coordinates[i] 13 let next = coordinates[i+1] 14 15 let curNum = next[1] - cur[1] 16 let curDenom = next[0]-cur[0] 17 let cSlope = Double(curNum)/Double(curDenom) 18 19 if( cSlope != slope ){ 20 return false 21 } 22 } 23 return true 24 } 25 } 44ms 1 class Solution { 2 func checkStraightLine(_ coordinates: [[Int]]) -> Bool { 3 let dx = coordinates[1][0] - coordinates[0][0] 4 let dy = coordinates[1][1] - coordinates[0][1] 5 for i in 2..<coordinates.count { 6 let dx1 = coordinates[i][0] - coordinates[0][0] 7 let dy1 = coordinates[i][1] - coordinates[0][1] 8 if dx == 0 && dx1 != 0 { 9 return false 10 } 11 if dy == 0 && dy1 != 0 { 12 return false 13 } 14 if dy == 0 && dy1 == 0 { 15 continue 16 } 17 let dx2 = Double(dx) * Double(dy1) / Double(dy) 18 if Double(dx1) != dx2 { 19 return false 20 } 21 } 22 return true 23 } 24 } 48ms 1 class Solution { 2 func getGradient(x2: Int, x1: Int, y2: Int, y1: Int) -> Double { 3 return Double(y2 - y1) / Double(x2 - x1) 4 } 5 6 func checkStraightLine(_ coordinates: [[Int]]) -> Bool { 7 var coordinates = coordinates 8 if coordinates.count < 2 { 9 return false 10 } 11 12 var first = coordinates.removeFirst() 13 var gradient: Double = 0.0 14 15 for point in coordinates { 16 let currentGradient = getGradient(x2: point[0], x1: first[0], y2: point[1], y1: first[1]) 17 if gradient == 0.0 { 18 gradient = currentGradient 19 } 20 if gradient != currentGradient { 21 return false 22 } 23 } 24 return true 25 } 26 }
|
请发表评论