carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1232:缀点成线(check-if-it-is-a-straight-line) #197

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给定一个数组 coordinates ,其中 coordinates[i] = [x, y] , [x, y] 表示横坐标为 x、纵坐标为 y 的点。请你来判断,这些点是否在该坐标系中属于同一条直线上。

示例 1:

image

输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 输出:true

示例 2:

image

输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 输出:false  

提示:

2 <= coordinates.length <= 1000 coordinates[i].length == 2 -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 coordinates 中不含重复的点

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/check-if-it-is-a-straight-line 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

carloscn commented 1 year ago

问题分析

制作一个两个点返回斜率的函数,遍历每个点,看斜率是否相等即可。

fn slop_value(a:&Vec<i32>, b:&Vec<i32>) -> i32
{
    return (b[1] - a[1]) / (b[0] - a[0]);
}

pub fn check_straight_line(coordinates: Vec<Vec<i32>>) -> bool
{
    if coordinates.len() == 0 {
        return false;
    }

    if coordinates.len() < 2 {
        return true;
    }

    let mut last_slop:i32 = slop_value(&coordinates[0], &coordinates[1]);
    for i in 1..coordinates.len() - 1 {
        let current_slop = slop_value(&coordinates[i], &coordinates[i + 1]);
        if last_slop != current_slop {
            return false;
        }
        last_slop = current_slop;
    }

    return true;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/553016 https://github.com/carloscn/structstudy/commit/18eac460f57c1a62f2d84794892898fa7622c2d4