2
pub fn sorted_squares(nums: Vec<i32>) -> Vec<i32> {3
// The code works without this, but it removes a4
// lot of useless allocations for a base case6
return vec![i32::pow(nums[0], 2)];9
// We'll use this for inserting later10
let mut location = nums.len();12
// Pre-allocate so we can start indexing from the end13
let mut output = vec![0; location];15
// These are our markers for the 2 ends of the array16
let mut left = 0 as usize;17
let mut right = nums.len() - 1;19
// We're only going to compute each value once20
let mut computed_left = i32::pow(nums[left], 2);21
let mut computed_right = i32::pow(nums[right], 2);24
// Every loop we're moving one spot further to the left26
// Every loop iteration we check which value is larger and27
// put that at the end of the output vector that we pre-allocated28
if computed_left > computed_right {29
output[location] = computed_left;31
computed_left = i32::pow(nums[left], 2);33
output[location] = computed_right;35
computed_right = i32::pow(nums[right], 2);38
// Could do either one, because at this point they should be the40
output[0] = computed_right;