classSolution:defsortedSquares(self, nums: List[int])-> List[int]:
nums =[num*num for num in nums]returnsorted(nums)
小黑最简代码java版
classSolution{publicint[]sortedSquares(int[] nums){int n = nums.length;int[] ans =newint[n];for(int i =0;i < n;i++){
ans[i]=(int)Math.pow(nums[i],2);}Arrays.sort(ans);return ans;}}
双指针1
classSolution:defsortedSquares(self, nums: List[int])-> List[int]:# 声明分界线变量
negitive_end =-1
positive_start =-1
n =len(nums)for num in nums:if num <0:
negitive_end +=1else:break# 正数的开始项
positive_start = negitive_end +1# 进行双指针遍历
i = negitive_end
j = positive_start
ans =[]while i >=0or j < n:if i <0:
ans.append(nums[j]*nums[j])
j +=1elif j >= n:
ans.append(nums[i]*nums[i])
i -=1elif nums[j]*nums[j]> nums[i]*nums[i]:
ans.append(nums[i]*nums[i])
i -=1else:
ans.append(nums[j]*nums[j])
j +=1return ans
双指针1 java
classSolution{publicint[]sortedSquares(int[] nums){int n = nums.length;int[] ans =newint[n];int negative_end =-1;int positive_start =-1;for(int i =0;i < n;i++){if(nums[i]<0){
negative_end++;}else{break;}}
positive_start = negative_end +1;int i = negative_end;int j = positive_start;int t =0;while(i >=0|| j < n){if(i <0){
ans[t]= nums[j]*nums[j];
j++;}elseif(j >= n){
ans[t]= nums[i]*nums[i];
i--;}elseif(nums[i]*nums[i]< nums[j]*nums[j]){
ans[t]= nums[i]*nums[i];
i--;}else{
ans[t]= nums[j]*nums[j];
j++;}
t++;}return ans;}}
双指针2
classSolution:defsortedSquares(self, nums: List[int])-> List[int]:
n =len(nums)
i =0
ans =[0]* n
i,j,pos =0,n-1,n-1while i < j:if nums[i]*nums[i]< nums[j]*nums[j]:
ans[pos]= nums[j]*nums[j]
j -=1else:
ans[pos]= nums[i]*nums[i]
i +=1
pos -=1return ans
双指针2 java
classSolution{publicint[]sortedSquares(int[] nums){int n = nums.length;int[] ans =newint[n];for(int i =0,j = n-1,pos = n-1;i <= j;pos--){if(nums[i]*nums[i]< nums[j]*nums[j]){
ans[pos]= nums[j]*nums[j];
j --;}else{
ans[pos]= nums[i]*nums[i];
i++;}}return ans;}}