25 Squares of a Sorted Array

題目

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

Example 1:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]

Example 2:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]

Note:

1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.

分析

題意:給一個非遞減數組(意思是遞增?),返回其平方後的升序數組。
題目很簡單,但是設計一個巧妙的方法降低複雜度纔是最難的。

既然是遞增數組,現然,平方值從0的左右向外蔓延,值越來越大,因此我們可以用兩個指針進行雙端遍歷,且只需要比較絕對值即可。

算法:
頭指針a指向數組A[0]
尾指針b指向數組A[n-1]
當頭部絕對值比尾部絕對值大時,將頭部平方存入結果集,然後將頭指針++;
當尾部結對之比頭部結對之大時,將尾部平方存入結果集,然後將尾指針–;
重複上述操作直到結果集被填滿。

解答

class Solution {
    public int[] sortedSquares(int[] A) {
        int n = A.length;
        //結果集
        int[] res = new int[n];
        //頭指針
        int a=0;
        //尾指針
        int b=n-1;
        //用於指向當前存放位置
        int p=n-1;
        for(;p>=0;){
            if(Math.abs(A[b])>Math.abs(A[a])){
                res[p--]=A[b]*A[b];
                b--;
            }else{
                res[p--]=A[a]*A[a];
                a++;
            }
        }
        return res;
    }
}
發佈了78 篇原創文章 · 獲贊 15 · 訪問量 5212
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章