Home LeetCode - 1232. Check If It Is a Straight Line
Post
Cancel

LeetCode - 1232. Check If It Is a Straight Line

1232. Check If It Is a Straight Line - easy

문제

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.

제한사항

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates contains no duplicate point.

입출력 예

example

1
2
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

example

1
2
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false

풀이

  • Math
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func checkStraightLine(coordinates [][]int) bool {
    
    // x좌표 기반으로 정렬
    sort.Slice(coordinates, func(i int, j int) bool {
        return coordinates[i][0] < coordinates[j][0]
    })
    
    // 기울기를 구함
    var gradient float64 = 0.0
    if coordinates[1][0] - coordinates[0][0] != 0 {
        gradient = float64((coordinates[1][1] - coordinates[0][1])) / 
                   float64((coordinates[1][0] - coordinates[0][0]))
    }
    
    for i := 0 ; i < len(coordinates) - 1 ; i++ {    
        // 현재좌표와 다음좌표 사이의 기울기를 구함
        calGradient := float64(coordinates[i+1][1] - coordinates[i][1]) / 
                       float64(coordinates[i+1][0] - coordinates[i][0])
        
        // 기반 기울기와 현재 계산한 기울기의 값을 비교
        if(gradient != calGradient) {
            return false
        }
    }
    
    return true
}
This post is licensed under CC BY 4.0 by the author.