내 맘대로 알고리즘/LeetCode 2020 May

May LeetCoding Challenge[Day8] - Check If It Is a Straight Line

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.
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false

1. 알고리즘을 해결하기 위해서 생각한 방법

 

 - 우선 주어진 예제에서는 x와 y가 각각 증가하는 숫자에 대해서 보게 되었다.

 - [1,1]이 [2,2]로 증가하다가 [3,4]로 증가될 때 x와 y의 증가율이 일치하지 않겠다고 생각을 했다.

 - 하지만, 테스트케이스에서 옳은 접근 방법이 아니라는 것을 알게 되었고, 다시 생각하게 되었다.

 - 해당 문제는 기울기에 대한 문제라는 것을 알게 되었다.

 

 

2. 알고리즘 작성 중, 어려운 점

 

 - int / int  = int

 - float / float = float

 - 기울기는 0.25, 0.1과 같이 0에서 1사이에서 기울기가 발생한다. 나누기를 할 때는 이러한 점을 명확하게 생각하자.

 

 

3. 내가 작성한 알고리즘

 

class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
        float memory = Integer.MAX_VALUE;
        float inclination = Integer.MAX_VALUE;
        
        for(int i=0; i<coordinates.length-1; i++){
            int differenceX = coordinates[i+1][0] - coordinates[i][0];
            int differenceY = coordinates[i+1][1] - coordinates[i][1];
            if(differenceY == 0){
                inclination = 0;
            }
            else{
                inclination = (float)differenceX / (float)differenceY;    
            }
            
            if(i >= 1 && memory != inclination){
                return false;
            } 
            memory = inclination;
        }
        
        return true;
    }
}

4. 내가 작성한 알고리즘 결과

 

 

5. 반성할 점

 

 - 나누기는 int형일 때, 잘못되고 있을 지 모른다.

 

문제 : https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3323/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com