From bab488e1013f41477737c77b671f4925a3b424bb Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 8 Sep 2024 13:57:04 +0800 Subject: [PATCH] 20240908 finished. --- src/problem/mod.rs | 3 +- src/problem/p977_squares_of_a_sorted_array.rs | 54 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 src/problem/p977_squares_of_a_sorted_array.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 7fdc7f2..0b7cabf 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -228,4 +228,5 @@ mod p2708_maximum_strength_of_a_group; mod p2860_happy_students; mod p3174_clear_digits; mod p3176_find_the_maximum_length_of_a_good_subsequence_i; -mod p3177_find_the_maximum_length_of_a_good_subsequence_ii; \ No newline at end of file +mod p3177_find_the_maximum_length_of_a_good_subsequence_ii; +mod p977_squares_of_a_sorted_array; \ No newline at end of file diff --git a/src/problem/p977_squares_of_a_sorted_array.rs b/src/problem/p977_squares_of_a_sorted_array.rs new file mode 100644 index 0000000..c294356 --- /dev/null +++ b/src/problem/p977_squares_of_a_sorted_array.rs @@ -0,0 +1,54 @@ +/** + * [977] Squares of a Sorted Array + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn sorted_squares(nums: Vec) -> Vec { + let mut stack = Vec::with_capacity(nums.len()); + let mut result = Vec::with_capacity(nums.len()); + + for i in nums { + if i < 0 { + stack.push(i); + continue; + } + + // 弹出当前栈中小于当前数字的数字 + while let Some(&tail) = stack.last() { + let tail = -tail; + if tail > i { + break; + } + + result.push(tail.pow(2)); + stack.pop(); + } + + result.push(i.pow(2)); + } + + while let Some(tail) = stack.pop() { + result.push(tail.pow(2)); + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_977() { + assert_eq!(vec![0, 1, 9, 16, 100], Solution::sorted_squares(vec![-4, -1, 0, 3, 10])); + assert_eq!(vec![4, 9, 9, 49, 121], Solution::sorted_squares(vec![-7, -3, 2, 3, 11])); + assert_eq!(vec![1, 4], Solution::sorted_squares(vec![-2, -1])); + } +}