From 53cc9b2a2d4796c4e938b343820bf2daa99699b9 Mon Sep 17 00:00:00 2001 From: Openset Date: Mon, 21 Jan 2019 09:59:12 +0800 Subject: [PATCH] Add: Squares of a Sorted Array --- .../squares_of_a_sorted_array.go | 12 ++++++++ .../squares_of_a_sorted_array_test.go | 30 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 problems/squares-of-a-sorted-array/squares_of_a_sorted_array.go create mode 100644 problems/squares-of-a-sorted-array/squares_of_a_sorted_array_test.go diff --git a/problems/squares-of-a-sorted-array/squares_of_a_sorted_array.go b/problems/squares-of-a-sorted-array/squares_of_a_sorted_array.go new file mode 100644 index 000000000..016eef327 --- /dev/null +++ b/problems/squares-of-a-sorted-array/squares_of_a_sorted_array.go @@ -0,0 +1,12 @@ +package squares_of_a_sorted_array + +import "sort" + +func sortedSquares(A []int) []int { + ans := make([]int, len(A)) + for i, v := range A { + ans[i] = v * v + } + sort.Ints(ans) + return ans +} diff --git a/problems/squares-of-a-sorted-array/squares_of_a_sorted_array_test.go b/problems/squares-of-a-sorted-array/squares_of_a_sorted_array_test.go new file mode 100644 index 000000000..2a4620869 --- /dev/null +++ b/problems/squares-of-a-sorted-array/squares_of_a_sorted_array_test.go @@ -0,0 +1,30 @@ +package squares_of_a_sorted_array + +import ( + "reflect" + "testing" +) + +type caseType struct { + input []int + expected []int +} + +func TestSortedSquares(t *testing.T) { + tests := [...]caseType{ + { + input: []int{-4, -1, 0, 3, 10}, + expected: []int{0, 1, 9, 16, 100}, + }, + { + input: []int{-7, -3, 2, 3, 11}, + expected: []int{4, 9, 9, 49, 121}, + }, + } + for _, tc := range tests { + output := sortedSquares(tc.input) + if !reflect.DeepEqual(output, tc.expected) { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}