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]]
Output: true
Example 2:



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

Constraints:

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

这题求给出的N个坐标点是否能连成一条直线。我们可以解出两两坐标点之间的斜率,看看是否相等即可。

所以我踩了一个坑,没有考虑到y坐标一样的情况。这种场景要单独考虑。

class CheckIfItIsAStraightLine : public Solution {
public:
    void Exec() {

    }

    bool checkStraightLine(vector<vector<int>>& coordinates) {
        float prev_value = 0.0f;
        int hor = 0;
        for (int i = 1; i < coordinates.size(); i++) {
            float value = 0;
            bool cur_hor = false;
            if (coordinates[i][1] - coordinates[i - 1][1] == 0) {
                cur_hor = true;
            } else {
                value =
                    ((float)coordinates[i][0] - (float)coordinates[i - 1][0]) /
                    ((float)coordinates[i][1] - float(coordinates[i - 1][1]));
            }

            if (cur_hor || hor == 1) {
                if (cur_hor != (hor == 1 || hor == 0)) {
                    return false;
                }
                hor = 1;
            } else {
                hor = 2;
                if (i == 1) {
                    prev_value = value;
                } else if (prev_value != value) {
                    return false;
                }
            }
        }
        return true;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day