第一题题解
首先写了一个初步解,后续再想优化思路
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: # sort by the abs of value abs_min = 10000 abs_min_index = 0 for i in range(len(nums)): if abs(nums[i]) < abs_min: print(nums[i]) abs_min = abs(nums[i]) abs_min_index = i res = [abs_min*abs_min] left = 1 right = 1 while len(res) != len(nums): #print("abs_min_index:", abs_min_index) #print("left:",left) #print("right:",right) if abs_min_index - left < 0: res.append(nums[abs_min_index + right] * nums[abs_min_index + right]) right += 1 continue if abs_min_index + right >= len(nums): res.append(nums[abs_min_index - left] * nums[abs_min_index - left]) left += 1 continue #print("num[abs_min_index - left]", nums[abs_min_index - left]) #print("num[abs_min_index + right]", nums[abs_min_index + right]) if abs(nums[abs_min_index - left]) < abs(nums[abs_min_index + right]): res.append(nums[abs_min_index - left] * nums[abs_min_index - left]) left += 1 else: res.append(nums[abs_min_index + right] * nums[abs_min_index + right]) right += 1 return res
标签:977,index,right,min,训练营,nums,随想录,abs,left From: https://www.cnblogs.com/hojest/p/18031823