LeetCode 977. Squares of a Sorted Array
原题链接在这里:https://leetcode.com/problems/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.
题解:
There could be negative number in A.
Thus have two pointer pointing to head and tail. Compare the squares and move the bigger pointer to the middle.
Time Complexity: O(n). n = A.length.
Space: O(1). regardless res.
AC Java:
1 class Solution { 2 public int[] sortedSquares(int[] A) { 3 if(A == null || A.length == 0){ 4 return A; 5 } 6 7 int [] res = new int[A.length]; 8 int i = 0; 9 int j = A.length - 1; 10 11 for(int po = A.length - 1; po>=0; po--){ 12 int si = A[i] * A[i]; 13 int sj = A[j] * A[j]; 14 if(si > sj){ 15 res[po] = si; 16 i++; 17 }else{ 18 res[po] = sj; 19 j--; 20 } 21 } 22 23 return res; 24 } 25 }