def sorted_squares(a):
n = len(a)
# 獲取2個遊標,i、j,i從最後一個負數向前遍歷,j從第一個非負數向後遍歷
j = 0
while j<n and a[j]<0:
j += 1
i = j - 1
# 開始遍歷
rs = []
while 0 <= i and j < n:
if a[i]**2 <= a[j]**2:
rs.append(a[i]**2)
i -= 1
else
rs.append(a[j]**2)
j += 1
while 0 <= i:
rs.append(a[i]**2)
i -= 1
while j < n:
rs.append(a[j]**2)
j += 1
return rs
LeetCode-977有序數組的平方
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.