1232. Check If It Is a Straight Line Easy
1/**
2 * [1232] Check If It Is a Straight Line
3 *
4 * 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.
5 *
6 *
7 *
8 *
9 * Example 1:
10 *
11 * <img alt="" src="https://assets.leetcode.com/uploads/2019/10/15/untitled-diagram-2.jpg" style="width: 336px; height: 336px;" />
12 *
13 *
14 * Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
15 * Output: true
16 *
17 *
18 * Example 2:
19 *
20 * <img alt="" src="https://assets.leetcode.com/uploads/2019/10/09/untitled-diagram-1.jpg" style="width: 348px; height: 336px;" />
21 *
22 *
23 * Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
24 * Output: false
25 *
26 *
27 *
28 * Constraints:
29 *
30 *
31 * 2 <= coordinates.length <= 1000
32 * coordinates[i].length == 2
33 * -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
34 * coordinates contains no duplicate point.
35 *
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/check-if-it-is-a-straight-line/
40// discuss: https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45 pub fn check_straight_line(coordinates: Vec<Vec<i32>>) -> bool {
46 if coordinates.len() < 3 {
47 return true;
48 }
49
50 let good = |v: &Vec<i32>| {
51 (coordinates[1][0] - coordinates[0][0]) as i128 * (v[1] - coordinates[0][1]) as i128
52 == (coordinates[1][1] - coordinates[0][1]) as i128
53 * (v[0] - coordinates[0][0]) as i128
54 };
55
56 for i in 2..coordinates.len() {
57 if !good(&coordinates[i]) {
58 return false;
59 }
60 }
61 true
62 }
63}
64
65// submission codes end
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 #[test]
72 fn test_1232() {
73 assert!(Solution::check_straight_line(vec![
74 vec![1, 2],
75 vec![2, 3],
76 vec![3, 4],
77 vec![4, 5],
78 vec![5, 6],
79 vec![6, 7]
80 ]));
81 }
82}
83
Back
© 2025 bowen.ge All Rights Reserved.