力扣链接:977. 有序数组的平方
这道题目比较简单
代码如下:
class Solution {
public int[] sortedSquares(int[] nums) {
// 找到中间数,移动left和right 进行比较后存入新数组
// 只有当输入数组中存入负数才能有效,如果不为负数直接平方存入就行
// 关键在于找到正数最小值
// 以上思路太复杂,已知数组大小,从最大往小了的存
// 即现存入length-1,再存length-2,依次比较存入
int left = 0;
int rigth = nums.length - 1;
int[] result = new int[nums.length];
int flag = nums.length - 1;
while(left <= rigth){
if(nums[left] * nums[left] > nums[rigth] * nums[rigth]){
result[flag] = nums[left] * nums[left];
left++;
}else{
result[flag] = nums[rigth] * nums[rigth];
rigth--;
}
flag--;
}
return result;
}
}