LeetCode 977 有序数组的平方

LeetCode 977 有序数组的平方
问题描述:
给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

一次遍历

  • 利用数组原本存在的有序性(复数绝对值递减、非负数递增)

执行用时:2 ms, 在所有 Java 提交中击败了66.81%的用户
内存消耗:40.8 MB, 在所有 Java 提交中击败了15.99%的用户

class Solution {
    //双指针
    public int[] sortedSquares(int[] A) {
        if(A==null || A.length==0) {
            return A;
        }

        //找到负数最大的位置p1、非负数最小的位置p2
        int p1 = 0, p2 = 0;
        for(int i=0; i<A.length; i++) {
            if(A[i]>=0) {
                p1 = i-1;
                p2 = i;
                break;
            }
        }

        //由p1、p2向两边遍历
        int[] ans = new int[A.length];
        int curr = 0;
        while(curr<A.length) {
            if(p1>=0 && p2<A.length) {
                if(A[p1]+A[p2]>=0) {
                    ans[curr++] = (int)Math.pow(A[p1], 2);
                    p1--;
                }
                else {
                    ans[curr++] = (int)Math.pow(A[p2], 2);
                    p2++;
                }
            }
            else {
                ans[curr++] = (p1<0?0:(int)Math.pow(A[p1], 2)) 
                                + (p2>=A.length?0:(int)Math.pow(A[p2], 2));
                p1 = p1<0? p1: p1-1;
                p2 = p2>=A.length? p2: p2+1;
            }
        }

        return ans;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13824565.html