1232. Check If It Is a Straight Line

Easy题,一开始的思路是直接算斜率,但是除法使用了浮点数来计算斜率,这可能导致精度问题。尽管这种情况在大多数实际应用中并不常见,但如果输入的坐标值非常大或非常小,那么就可能遇到精度问题。此外,由于浮点数的不精确性,即使两个斜率实际上是相等的,比较也可能会返回false。另外这种方法还不能很好的解决水平线的问题,算出来inf,-inf需要做额外的判断

impl Solution {
    pub fn check_straight_line(coordinates: Vec>) -> bool {
        if coordinates.len() <= 2 {
            return true
        }
        let gradient = (coordinates[1][1] as f32 - coordinates[0][1] as f32) / (coordinates[1][0] as f32 - coordinates[0][0] as f32);
        for coordinate in coordinates.iter().skip(2){
            let x = coordinate[0] as f32;
            let y = coordinate[1] as f32;
            println!("{}, {}", x, y);
            println!("gradient: {}", gradient);
            println!("gradient here: {}", (y - coordinates[0][1] as f32) / (x - coordinates[0][0] as f32));
            if (y - coordinates[0][1] as f32) / (x - coordinates[0][0] as f32) != gradient {
                return false
            }
        }
        true
    }
}

随后想到用乘法来避免找个问题。交叉乘法的斜率的核心思想基于这样一个事实:在二维平面上,两个点之间的斜率是一个常数。具体来说,对于点 (x1, y1) 和 (x2, y2),斜率 m 可以表示为:

m = (y2 - y1) / (x2 - x1)

我们可以对这个等式进行交叉乘法,将除法变为乘法,得到:

m * (x2 - x1) = y2 - y1

这样,我们就可以比较两个斜率是否相等,而不需要执行除法。例如,对于另一个点 (x3, y3),我们可以检查以下等式是否成立:

m * (x3 - x1) = y3 - y1

如果它们相等,那么这三个点在同一直线上。如果不等,那么这三个点不在同一直线上。我们实际上只是在比较两个差值的乘积是否相等。

这种方法的优点是避免了除法(特别是除以零的问题),并且使用了整数运算,避免了浮点数的精度问题。

impl Solution {
    pub fn check_straight_line(coordinates: Vec>) -> bool {
        if coordinates.len() <= 2 {
            return true
        }
        let (dx, dy) = (
            coordinates[1][0] - coordinates[0][0],
            coordinates[1][1] - coordinates[0][1]
        );
        for i in 2..coordinates.len() {
            let (dx1, dy1) = (
                coordinates[i][0] - coordinates[0][0],
                coordinates[i][1] - coordinates[0][1]
            );
            if dx * dy1 != dy * dx1 {
                return false
            }
        }
        true
    }
}

你可能感兴趣的:(leetcoderust)