20240908 finished.
This commit is contained in:
parent
8c2dfc5547
commit
bab488e101
|
@ -229,3 +229,4 @@ mod p2860_happy_students;
|
||||||
mod p3174_clear_digits;
|
mod p3174_clear_digits;
|
||||||
mod p3176_find_the_maximum_length_of_a_good_subsequence_i;
|
mod p3176_find_the_maximum_length_of_a_good_subsequence_i;
|
||||||
mod p3177_find_the_maximum_length_of_a_good_subsequence_ii;
|
mod p3177_find_the_maximum_length_of_a_good_subsequence_ii;
|
||||||
|
mod p977_squares_of_a_sorted_array;
|
54
src/problem/p977_squares_of_a_sorted_array.rs
Normal file
54
src/problem/p977_squares_of_a_sorted_array.rs
Normal file
|
@ -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<i32>) -> Vec<i32> {
|
||||||
|
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]));
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user