22. Sorted Squares
A land surveyor measured the position of fence posts along a straight road, relative to a starting marker: negative numbers are west of the marker and positive numbers are east of it. The measurements are already sorted from west to east. To price the square plots that each post could mark out, she needs the square of every measurement.
Write a method sortedSquares that takes the sorted array nums and returns an array of the squares of all the measurements, sorted from smallest to largest.
Example 1
- Input:
- nums = [-4,-1,0,3,10]
- Output:
- [0,1,9,16,100]
- Explanation:
The squares are 16, 1, 0, 9 and 100; sorted, they read 0, 1, 9, 16, 100.
Example 2
- Input:
- nums = [-7,-3,2,3,11]
- Output:
- [4,9,9,49,121]
- Explanation:
Squaring gives 49, 9, 4, 9, 121, which sorts to [4, 9, 9, 49, 121].
Constraints
1 ≤ nums.length ≤ 1000
-104 ≤ nums[i] ≤ 104
nums is sorted in non-decreasing order
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)