# Leetcode Array101 Squares of a Sorted Array by Go

sjinsung·2022년 2월 14일
0

Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in non-decreasing order.

### My code

func sortedSquares(nums []int) []int {
for i := range nums {
nums[i] = square(nums[i])
}
nums = bubble(nums)
return nums
}

func square(n int) int {
n = n * n
return n
}

func bubble(nums []int) []int {
for x := range nums {
for y := 0; y < len(nums)-x; y++ {
if y+1 > len(nums)-1 {
break
}
if nums[y] > nums[y+1] {
buf := nums[y+1]
nums[y+1] = nums[y]
nums[y] = buf
}
}
}
return nums
}
• go.dev/play/p/xhKIDRLSZNg

1) First I made abs function because I thought negative numbers must be positive.
2) So after abs function implemented, I implemented bubble sorting function.
3) After checking sorted number, I implemented square function.
4) So I realized, abs function was not needed.
5) I deleted abs and put only square and bubble function.

## Sample 16 ms submission

func sortedSquares(nums []int) []int {
l := 0
p := len(nums) - 1
r := p
nns := make([]int, p + 1)

for l <= r {
lv := nums[l] * nums[l]
rv := nums[r] * nums[r]

if lv > rv {
nns[p] = lv
p = p - 1
l = l + 1
} else {
nns[p] = rv
p = p - 1
r = r - 1
}
}

return nns
}
• I don't know what sort It is.
• But looks clean.
• Checking which number between left end and right end is bigger and put to new slice from End of the slice.

15/02

• That is a two pointer algorithm
• hongjuzzang.github.io/cs/two_pointers/

## sample 6600 KB submission

func sortedSquares(nums []int) []int {
n:= len(nums)
result:= make([]int, 0, n)
for _, v:= range nums{
result = append(result, v*v)
}

for i:=0; i<n-1; i++{
for j:=0; j<n-i-1; j++{
if result[j]> result[j+1]{
result[j], result[j+1]= result[j+1], result[j]
}
}
}
return result
}
• First Time, When I saw this code, I was confused. because This code looked weird.
• This code also didn't change original arrays.
• After copying them to VSC, I recognized These will copy each other without buffer.
• Bubble sort was used.
Gopyther