|
| 1 | +# 977 - Squares Of A Sorted Array |
| 2 | + |
| 3 | +Difficulty: easy |
| 4 | +Done: No |
| 5 | +Last edited: February 17, 2022 12:47 PM |
| 6 | +Topic: two pointers |
| 7 | + |
| 8 | +## Problem |
| 9 | + |
| 10 | +Given an integer array `nums` sorted in **non-decreasing** order, return *an array of **the squares of each number** sorted in non-decreasing order*. |
| 11 | + |
| 12 | +Example 1: |
| 13 | + |
| 14 | +``` |
| 15 | +Input: nums = [-4,-1,0,3,10] |
| 16 | +Output: [0,1,9,16,100] |
| 17 | +Explanation: After squaring, the array becomes [16,1,0,9,100]. |
| 18 | +After sorting, it becomes [0,1,9,16,100]. |
| 19 | +
|
| 20 | +``` |
| 21 | + |
| 22 | +Example 2: |
| 23 | + |
| 24 | +``` |
| 25 | +Input: nums = [-7,-3,2,3,11] |
| 26 | +Output: [4,9,9,49,121] |
| 27 | +
|
| 28 | +``` |
| 29 | + |
| 30 | +Constraints: |
| 31 | + |
| 32 | +- `1 <= nums.length <= 104` |
| 33 | +- `104 <= nums[i] <= 104` |
| 34 | +- `nums` is sorted in **non-decreasing** order. |
| 35 | + |
| 36 | +## Solution |
| 37 | + |
| 38 | +lorem ipsum |
| 39 | + |
| 40 | +## Whiteboard |
| 41 | + |
| 42 | +[http://excalidraw.com](http://excalidraw.com) |
| 43 | + |
| 44 | +## Code |
| 45 | + |
| 46 | +```python |
| 47 | +class Solution: |
| 48 | + def sortedSquares(self, nums: List[int]) -> List[int]: |
| 49 | + return sorted([x**2 for x in nums]) |
| 50 | +``` |
| 51 | + |
| 52 | +using built-in sorted |
| 53 | + |
| 54 | +```python |
| 55 | +class Solution: |
| 56 | + def sortedSquares(self, nums: List[int]) -> List[int]: |
| 57 | + left, right = 0, len(nums)-1 |
| 58 | + |
| 59 | + while left <= right: |
| 60 | + |
| 61 | + max_abs = max(nums[left:], key=abs) |
| 62 | + |
| 63 | + nums.insert(0, nums.pop(nums.index(max_abs))) |
| 64 | + nums[0] = nums[0]**2 |
| 65 | + left += 1 |
| 66 | + |
| 67 | + return nums |
| 68 | +``` |
| 69 | + |
| 70 | +custom 2 pointer approach |
0 commit comments