From 044576d0067330d7ba971747e181735179f7e6c0 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Sun, 7 Nov 2021 19:45:34 +0000 Subject: [PATCH] squares-of-a-sorted-array --- squares-of-a-sorted-array/sol.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 squares-of-a-sorted-array/sol.go diff --git a/squares-of-a-sorted-array/sol.go b/squares-of-a-sorted-array/sol.go new file mode 100644 index 0000000..669788c --- /dev/null +++ b/squares-of-a-sorted-array/sol.go @@ -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 +}