力扣简977 有序数组的平方

自己写了一版 空间占用太高了 看了题解差不多也就这样

package Leetcode;
/*给你一个按 非递减顺序 排序的整数数组 nums,
 * 返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。*/
public class Leetcode977 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] test = {-1,1,3,5};
        test=Leetcode977.sortedSquares(test);
        for(int i=0;i<test.length;i++) {
            System.out.println(test[i]);
        }
    }
    public static int[] sortedSquares(int[] nums) {
        int head=0,tail=nums.length-1,flag=nums.length-1;
        int[] res =new int[nums.length];
        while(head<=tail) {
            if(nums[head]+nums[tail]>0) {//只要大于零 后面的就比前面的绝对值大
                res[flag]=nums[tail]*nums[tail];
                tail--;
                flag--;
            }
            else {
                res[flag]=nums[head]*nums[head];
                head++;
                flag--;
            }
        }     
        return res;
    }
}

 

posted @ 2023-02-20 14:23  Ssshiny  阅读(15)  评论(0)    收藏  举报