LeetCode每日一题——缀点成线
题目要求:
给定一个整数数组 coordinates
,其中 coordinates[i] = [x, y]
, [x, y]
表示横坐标为 x
、纵坐标为 y
的点。请你来判断,这些点是否在该坐标系中属于同一条直线上。
示例 1:
输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 输出:true
示例 2:
输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 输出:false
代码实现:
bool checkStraightLine(int** coordinates, int coordinatesSize, int* coordinatesColSize) {
//若点数小于或等于2则一定共线
if(coordinatesSize <= 2)
{
return true;
}
//建立基准
int x0 = coordinates[0][0], y0 = coordinates[0][1];
int x1 = coordinates[1][0], y1 = coordinates[1][1];
int deltaX = x1 - x0, deltaY = y1 - y0;
int i = 0;
for(i = 2; i < coordinatesSize; i++)
{
//用交叉相乘是否相等来判断是否共线
if(deltaX * (coordinates[i][1] - y0) != deltaY * (coordinates[i][0] - x0))
{
return false;//只要有一点不共线,结果都不相等
}
}
return true;//点、线都满足则共线
}
坚持编程,我一直在路上!