squares-of-a-sorted-array

This commit is contained in:
Gleb Koval 2021-11-07 19:45:34 +00:00
parent 7f687781b3
commit 044576d006
No known key found for this signature in database
GPG Key ID: DF27F6A77C48FDA0
1 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package main
// Very ugly imo
// Time: O(n)
// Space: O(n)
func sortedSquares(nums []int) []int {
l := len(nums)
n, p := make([]int, 0), make([]int, 0)
for _, num := range nums {
sq := num * num
if num < 0 {
n = append(n, sq)
} else {
p = append(p, sq)
}
}
sqs := make([]int, l)
nl, pl := len(n), len(p)
np, pp := 0, 0
for np+pp < l {
if (np < nl && pp < pl && n[nl-np-1] < p[pp]) || pp >= pl {
sqs[np+pp] = n[nl-np-1]
np++
} else {
sqs[np+pp] = p[pp]
pp++
}
}
return sqs
}