Skip to content

Commit c8260cb

Browse files
committed
Squares of a Sorted Array
1 parent f52c5e7 commit c8260cb

File tree

1 file changed

+26
-24
lines changed

1 file changed

+26
-24
lines changed

977-squares-of-a-sorted-array.py

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,29 +17,31 @@
1717
-10000 <= A[i] <= 10000
1818
A is sorted in non-decreasing order.
1919
"""
20-
class Solution(object):
21-
def sortedSquares(self, A):
22-
"""
23-
:type A: List[int]
24-
:rtype: List[int]
25-
"""
26-
l = len(A)
27-
j = 0
28-
while j < l and A[j] < 0:
29-
j += 1
30-
i = j - 1
20+
class Solution:
21+
def sortedSquares(self, nums: List[int]) -> List[int]:
22+
start_point = len(nums) - 1
23+
for i in range(len(nums)):
24+
if nums[i] >= 0:
25+
start_point = i
26+
break
27+
3128
res = []
32-
while i >= 0 and j < l:
33-
if A[i]**2 < A[j]**2:
34-
res.append(A[i]**2)
35-
i -= 1
29+
left, right = start_point - 1, start_point
30+
31+
while left >= 0 and right < len(nums):
32+
if abs(nums[left]) > nums[right]:
33+
res.append(nums[right] ** 2)
34+
right += 1
3635
else:
37-
res.append(A[j]**2)
38-
j += 1
39-
while i >= 0:
40-
res.append(A[i]**2)
41-
i -= 1
42-
while j < l:
43-
res.append(A[j]**2)
44-
j += 1
45-
return res
36+
res.append(nums[left] ** 2)
37+
left -= 1
38+
39+
while left >= 0:
40+
res.append(nums[left] ** 2)
41+
left -= 1
42+
43+
while right < len(nums):
44+
res.append(nums[right] ** 2)
45+
right += 1
46+
47+
return res

0 commit comments

Comments
 (0)