From c935b56fbbb7d97141b0ba19d82dd1ff839fb78f Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 3 Aug 2024 11:22:59 +0800 Subject: [PATCH] 20240803 Finished --- src/problem/mod.rs | 3 +- src/problem/p149_max_points_on_a_line.rs | 92 ++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 src/problem/p149_max_points_on_a_line.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 1fa1cac..89f88dd 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -192,4 +192,5 @@ mod p201_bitwise_and_of_numbers_range; mod p66_plus_one; mod p172_factorial_trailing_zeroes; mod p69_sqrtx; -mod p50_powx_n; \ No newline at end of file +mod p50_powx_n; +mod p149_max_points_on_a_line; \ No newline at end of file diff --git a/src/problem/p149_max_points_on_a_line.rs b/src/problem/p149_max_points_on_a_line.rs new file mode 100644 index 0000000..ca2506a --- /dev/null +++ b/src/problem/p149_max_points_on_a_line.rs @@ -0,0 +1,92 @@ +/** + * [149] Max Points on a Line + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::HashMap; + +#[derive(Ord, PartialOrd, Eq, PartialEq, Hash)] +struct Slope { + x: i32, + y: i32, +} + +impl Slope { + fn new(point1: &Vec, point2: &Vec) -> Self { + let mut x = point1[0] - point2[0]; + let mut y = point1[1] - point2[1]; + + if x == 0 { + y = 1; + } else if y == 0 { + x = 1; + } else { + if y < 0 { + x = -x; + y = -y; + } + + let gcd = Self::gcd(x.abs(), y.abs()); + x /= gcd; + y /= gcd; + } + + Self { + x, + y, + } + } + + fn gcd(a: i32, b: i32) -> i32 { + if b > 0 { + Self::gcd(b, a % b) + } else { + a + } + } +} + +impl Solution { + pub fn max_points(points: Vec>) -> i32 { + let n = points.len(); + if n <= 2 { + return n as i32; + } + + let mut result = 0; + for i in 0..n { + if result > n - i || result > n / 2 { + break; + } + + let mut map = HashMap::new(); + for j in i+1..n { + let slope = Slope::new(&points[i], &points[j]); + + let entry = map.entry(slope).or_insert(0); + *entry += 1; + } + + let mut max = 0; + for i in map.values() { + max = max.max(*i); + } + + result = result.max(max + 1); + } + + result as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_149() {} +}