Algorithm
Problem Name: 977. Squares of a Sorted Array
Given an integer array nums
sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100].
Example 2:
Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121]
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
is sorted in non-decreasing order.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int[] sortedSquares(int[] nums) {
int negativeIdx = 0;
int positiveIdx = nums.length - 1;
int[] result = new int[nums.length];
int resultIdx = nums.length - 1;
while(resultIdx >= 0) {
if (nums[negativeIdx] < 0 && nums[positiveIdx] >= 0) {
if (Math.abs(nums[negativeIdx]) > nums[positiveIdx]) {
result[resultIdx--] = nums[negativeIdx] * nums[negativeIdx];
negativeIdx++;
} else {
result[resultIdx--] = nums[positiveIdx] * nums[positiveIdx];
positiveIdx--;
}
} else if (nums[negativeIdx] < 0 && nums[positiveIdx] < 0) {
result[resultIdx--] = nums[negativeIdx] * nums[negativeIdx];
negativeIdx++;
} else {
result[resultIdx--] = nums[positiveIdx] * nums[positiveIdx];
positiveIdx--;
}
}
return result;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const sortedSquares = function(A) {
const result = [];
let i = A.length - 1;
let left = 0;
let right = A.length -1;
while (left < = right) {
if (Math.abs(A[left]) < A[right]) {
result.unshift(A[right] * A[right])
right--;
} else {
result.unshift(A[left] * A[left])
left++
}
}
return result;
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
return sorted([x ** 2 for x in A])
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System;
namespace LeetCode
{
public class _0977_SquaresOfASortedArray
{
public int[] SortedSquares(int[] A)
{
var left = 0;
var right = A.Length - 1;
var result = new int[A.Length];
var current = right;
while (left < = right)
{
if (Math.Abs(A[left]) > Math.Abs(A[right]))
{
result[current--] = A[left] * A[left];
left++;
}
else
{
result[current--] = A[right] * A[right];
right--;
}
}
return result;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output