1232. Check If It Is a Straight Line

判斷直線基本題

AC Code

 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
28
29
30
class Solution
{
    /*
    [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
    [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
    [[-3,-2],[-1,-2],[2,-2],[-2,-2],[0,-2]]
    */
public:
    bool checkStraightLine(vector<vector<int>> &coordinates)
    {
        int n = coordinates.size();

        for (int i = 2; i < n; i++) {
            int x[3] = {coordinates[i - 2][0], coordinates[i - 1][0],
                        coordinates[i][0]
                       };
            int y[3] = {coordinates[i - 2][1], coordinates[i - 1][1],
                        coordinates[i][1]
                       };

            int left = (y[1] - y[0]) * (x[2] - x[1]);
            int right = (y[2] - y[1]) * (x[1] - x[0]);

            if (left != right)
                return false;
        }

        return true;
    }
};