-
Notifications
You must be signed in to change notification settings - Fork 17
/
squares-of-a-sorted-array.py
39 lines (30 loc) · 1.08 KB
/
squares-of-a-sorted-array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from typing import List
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
# find first non-negative element
left, right = 0, len(nums)
while left < right:
middle = left + (right - left) // 2
if nums[middle] < 0:
left = middle + 1
else:
right = middle
first_nonnegative = left
# Construct result
result: List[int] = []
left, right = first_nonnegative - 1, first_nonnegative
while left >= 0 or right < len(nums):
if left >= 0 and right < len(nums):
if -nums[left] < nums[right]:
result.append(nums[left] * nums[left])
left -= 1
else:
result.append(nums[right] * nums[right])
right += 1
elif left >= 0:
result.append(nums[left] * nums[left])
left -= 1
else:
result.append(nums[right] * nums[right])
right += 1
return result