LeetCode/rs/can-make-arithmetic-progression-from-sequence.rs

32 lines
907 B
Rust
Raw Permalink Normal View History

struct Solution {}
impl Solution {
pub fn can_make_arithmetic_progression(mut arr: Vec<i32>) -> bool {
arr.sort();
let diffs: Vec<i32> = arr.windows(2).map(|pair| pair[1] - pair[0]).collect();
diffs.windows(2).all(|pair| pair[0] == pair[1])
}
}
fn main() {}
#[cfg(test)]
mod tests {
use super::*;
// Input: arr = [3,5,1]
// Output: true
// Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
#[test]
fn example_1() {
assert!(Solution::can_make_arithmetic_progression(vec![3, 5, 1]));
}
// Input: arr = [1,2,4]
// Output: false
// Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
#[test]
fn example_2() {
assert!(!Solution::can_make_arithmetic_progression(vec![2, 4, 1]));
}
}