File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -100,6 +100,7 @@ public:
100100## 其他语言版本
101101
102102### Java:
103+
103104排序法
104105``` Java
105106class Solution {
@@ -209,6 +210,43 @@ class Solution:
209210 return new_list[::- 1 ]
210211```
211212
213+ ``` python3
214+ (双指针优化版本) 三步优化
215+ class Solution:
216+ def sortedSquares(self , nums: List[int ]) -> List[int ]:
217+ """
218+ 整体思想:有序数组的绝对值最大值永远在两头,比较两头,平方大的插到新数组的最后
219+ 优 化:1. 优化所有元素为非正或非负的情况
220+ 2. 头尾平方的大小比较直接将头尾相加与0进行比较即可
221+ 3. 新的平方排序数组的插入索引可以用倒序插入实现(针对for循环,while循环不适用)
222+ """
223+
224+ # 特殊情况, 元素都非负(优化1)
225+ if nums[0 ] >= 0 :
226+ return [num ** 2 for num in nums] # 按顺序平方即可
227+ # 最后一个非正,全负有序的
228+ if nums[- 1 ] <= 0 :
229+ return [x ** 2 for x in nums[::- 1 ]] # 倒序平方后的数组
230+
231+ # 一般情况, 有正有负
232+ i = 0 # 原数组头索引
233+ j = len (nums) - 1 # 原数组尾部索引
234+ new_nums = [0 ] * len (nums) # 新建一个等长数组用于保存排序后的结果
235+ # end_index = len(nums) - 1 # 新的排序数组(是新数组)尾插索引, 每次需要减一(优化3优化了)
236+
237+ for end_index in range (len (nums)- 1 , - 1 , - 1 ): # (优化3,倒序,不用单独创建变量)
238+ # if nums[i] ** 2 >= nums[j] ** 2:
239+ if nums[i] + nums[j] <= 0 : # (优化2)
240+ new_nums[end_index] = nums[i] ** 2
241+ i + = 1
242+ # end_index -= 1 (优化3)
243+ else :
244+ new_nums[end_index] = nums[j] ** 2
245+ j - = 1
246+ # end_index -= 1 (优化3)
247+ return new_nums
248+ ```
249+
212250# ## Go:
213251
214252```Go
You can’t perform that action at this time.
0 commit comments