[코테 풀이] Check If It Is a Straight Line

시내·2024년 6월 9일
0

Q_1232) Check If It Is a Straight Line

출처 : https://leetcode.com/problems/check-if-it-is-a-straight-line/?envType=study-plan-v2&envId=programming-skills

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.

class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
        if (coordinates.length == 2) return true;

        Arrays.sort(coordinates, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] == o2[0]) return o1[1] - o2[1];
                return o1[0] - o2[0];
            }
        });

        double lin = (double) (coordinates[1][0] - coordinates[0][0]) / (coordinates[1][1] - coordinates[0][1]);
        for (int i = 1; i < coordinates.length - 1; i++) {
            double next = (double) (coordinates[i + 1][0] - coordinates[i][0]) / (coordinates[i + 1][1] - coordinates[i][1]);
            if (next != lin) return false;
        }
        return true;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글

관련 채용 정보