squares-of-a-sorted-array.py (1332B)
1 # 158ms 50.27% 2 # 18.76MB 72.31% 3 4 # This solution is a bit wordy. In a real environment I would just do the nlogn approach 5 # of squaring then sorting. 6 7 8 class Solution: 9 def sortedSquares(self, nums: List[int]) -> List[int]: 10 count = 0 11 negative = [] 12 positive = [] 13 returnList = [] 14 while count < len(nums) and nums[count] < 0: 15 negative.append(nums[count] * nums[count]) 16 count += 1 17 18 while count < len(nums): 19 positive.append(nums[count] * nums[count]) 20 count += 1 21 22 count = 0 23 negativeIndex = len(negative) - 1 24 positiveIndex = 0 25 while ( 26 count < len(nums) and negativeIndex >= 0 and positiveIndex < len(positive) 27 ): 28 if negative[negativeIndex] < positive[positiveIndex]: 29 returnList.append(negative[negativeIndex]) 30 negativeIndex -= 1 31 else: 32 returnList.append(positive[positiveIndex]) 33 positiveIndex += 1 34 count += 1 35 36 while negativeIndex >= 0: 37 returnList.append(negative[negativeIndex]) 38 negativeIndex -= 1 39 40 while positiveIndex < len(positive): 41 returnList.append(positive[positiveIndex]) 42 positiveIndex += 1 43 44 return returnList