Leetcode - 977. Squares of a Sorted Array
Leetcode - 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.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func sortedSquares(nums []int) []int {
ln := len(nums)
sortedSquared := make([]int, ln)
highestIndex := ln-1
left, right := 0, ln-1
for left<=right{
squaredLeft := nums[left]*nums[left]
squaredRight := nums[right]*nums[right]
if squaredLeft>squaredRight{
sortedSquared[highestIndex] = squaredLeft
highestIndex--
left++
}else{
sortedSquared[highestIndex] = squaredRight
highestIndex--
right--
}
}
return sortedSquared
}
This post is licensed under CC BY 4.0 by the author.