【Leetcode】977. Squares of a Sorted Array

題目地址:

https://leetcode.com/problems/squares-of-a-sorted-array/

給定一個升序數組,求其每個數平方所組成的數組的升序排列。

由於離00越遠的數字平方越大,所以平方最大的數一定在數組兩端。所以只需要用對撞雙指針iijj依次把[i,j][i,j]中最大的平方數加入最終結果即可。代碼如下:

public class Solution {
    public int[] sortedSquares(int[] A) {
        if (A == null || A.length == 0) {
            return A;
        }
    
        int[] ans = new int[A.length];
        int index = ans.length - 1;
        int i = 0, j = A.length - 1;
        while (i <= j) {
            if (A[i] * A[i] <= A[j] * A[j]) {
                ans[index--] = A[j] * A[j];
                j--;
            } else {
                ans[index--] = A[i] * A[i];
                i++;
            }
        }
        
        return ans;
    }
}

時空複雜度O(n)O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章