Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 44fab4c

Browse files
author
Sandy
authored
Merge pull request #199 from openset/develop
Add: Squares of a Sorted Array
2 parents 131c49c + 53cc9b2 commit 44fab4c

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package squares_of_a_sorted_array
2+
3+
import "sort"
4+
5+
func sortedSquares(A []int) []int {
6+
ans := make([]int, len(A))
7+
for i, v := range A {
8+
ans[i] = v * v
9+
}
10+
sort.Ints(ans)
11+
return ans
12+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package squares_of_a_sorted_array
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input []int
10+
expected []int
11+
}
12+
13+
func TestSortedSquares(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: []int{-4, -1, 0, 3, 10},
17+
expected: []int{0, 1, 9, 16, 100},
18+
},
19+
{
20+
input: []int{-7, -3, 2, 3, 11},
21+
expected: []int{4, 9, 9, 49, 121},
22+
},
23+
}
24+
for _, tc := range tests {
25+
output := sortedSquares(tc.input)
26+
if !reflect.DeepEqual(output, tc.expected) {
27+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
28+
}
29+
}
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /