squares-of-a-sorted-array
This commit is contained in:
parent
7f687781b3
commit
044576d006
|
@ -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
|
||||
}
|
Loading…
Reference in New Issue