给定一个nums按非降序排序的整数数组,返回一个按非降序排序的每个数字的平方数组
示例 1:
输入: nums = [-4,-1,0,3,10]
输出: [0,1,9,16,100]
解释:平方后,数组变为 [16,1,0,9,100]。
排序后变成[0,1,9,16,100]。
示例 2:
输入: nums = [-7,-3,2,3,11]
输出: [4,9,9,49,121]
约束:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums以非降序排序。
Follow up:对每个元素进行平方并对新数组进行排序非常简单,您能找到O(n)使用不同方法的解决方案吗?
–思路–
对比数组左右两个位置的绝对值大小,选择大的添加到结果数组末尾
- 初始化一个相同长度数组
- 设置左右两个指针,一个index用来给新数组末尾添加数据
- 对比左右两个数的绝对值大小,将大的平方之后添加到末尾,根据情况移动左右指针
- index-1
class Solution {
public int[] sortedSquares(int[] nums) {
int left=0,right=nums.length-1,index=nums.length-1;
int[] res=new int[nums.length];
while (left <= right) {
if (Math.abs(nums[left]) < Math.abs(nums[right])) {
res[index]=nums[right]*nums[right];//或者用 (int)Math.pow(nums[r],2)
right--;
}else{
res[index]=nums[left]*nums[left];
left++;
}
index--;
}
return res;
}
}
时间复杂度O(n/2)