缀点成线 - 简单

*************

C++

topic: 1232. 缀点成线 - 力扣(LeetCode)

*************

Give the topic an inspection.

缀点成线 - 简单_第1张图片

This is so important. All are based on math. I like the lines.

The very basic function is something like: y = ax + b;

So the first step is to figure out a.

class Solution {
public:
    bool checkStraightLine(vector>& coordinates) {
        
        int x0 = coordinates[0][0];
        int y0 = coordinates[0][1];
        int x1 = coordinates[1][0];
        int y1 = coordinates[1][1];

        int dx = x1 - x0;
        int dy = y1 - y0;

        int a = dy / dx;
    }
};

Then calculate the other a.

class Solution {
public:
    bool checkStraightLine(vector>& coordinates) {
        
        int x0 = coordinates[0][0];
        int y0 = coordinates[0][1];
        int x1 = coordinates[1][0];
        int y1 = coordinates[1][1];

        int dx = x1 - x0;
        int dy = y1 - y0;

        int a = dy / dx;

        int n = coordinates.size();
        for (int i = 0; i < n; i++)
        {
            int xi = coordinates[i][0];
            int yi = coordinates[i][1];
            if ((yi - y1) / (xi - x1) != (yi - y0) / (xi - x0))
            {
                return false;
            }
        }

        return true;
    }
};
缀点成线 - 简单_第2张图片

wrong. 0 cannot be devided.

class Solution {
public:
    bool checkStraightLine(vector>& coordinates) {
        
        int x0 = coordinates[0][0];
        int y0 = coordinates[0][1];
        int x1 = coordinates[1][0];
        int y1 = coordinates[1][1];

        int dx = x1 - x0;
        int dy = y1 - y0;

        int n = coordinates.size();
        for (int i = 0; i < n; i++)
        {
            int xi = coordinates[i][0];
            int yi = coordinates[i][1];
            if ((yi - y0) * dx != (xi - x0) * dy)
            {
                return false;
            }
        }

        return true;
    }
};

a is unnecessary here.

缀点成线 - 简单_第3张图片

你可能感兴趣的:(c++,leetcode)