31 lines
517 B
Go
31 lines
517 B
Go
|
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
|
||
|
}
|