977. 有序数组的平方-day1-代码随想录打卡

双指针法
数组其实是有序的, 只不过负数平方之后可能成为最大数了。

那么数组平方的最大值就在数组的两端,不是最左边就是最右边,不可能是中间。

此时可以考虑双指针法了,i指向其实位置,j指向终止位置。

定义一个新数组result,和A数组一样的大小,让k指向result数组终止位置。

1602811839-xiaxXW-977

`class Solution {
public int[] sortedSquares(int[] nums) {
int left=0;
int right=nums.length-1;
int[] res= new int[nums.length];

for(int i=nums.length-1;i>-1;i--)
{
if(Math.abs(nums[left])>Math.abs(nums[right]))
{
res[i]=nums[left]nums[left];
left++;
}else{
res[i]=nums[right]
nums[right];
right--;
}

}
return res;

}
}`

posted @ 2026-03-16 09:34  大头海绵宝宝  阅读(13)  评论(0)    收藏  举报