LK977有序数组的平方

57 阅读1分钟

双指针一次通过:

import static java.lang.Math.abs;
class Solution {
    public int[] sortedSquares(int[] nums) {
        int len=nums.length;
        int[] num=new int[len];
        int left=0,right=len-1,j=len-1;
        while(left<=right){
            int l=abs(nums[left]);
            int r=abs(nums[right]);
            if(l>r){
                num[j--]=nums[left]*nums[left++];
            }
            else{
                num[j--]=nums[right]*nums[right--];
            }
        }
        return num;
    }
}

这里使用了abs函数,不导包会报错,但是可以直接比较绝对值大小判断;

暴力方法也可以全绝对值之后排序;

题目链接[:](977. 有序数组的平方 - 力扣(LeetCode))