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 6acc5e3

Browse files
author
Openset
committed
Add: remove_duplicates_from_sorted_array
1 parent a92680d commit 6acc5e3

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package remove_duplicates_from_sorted_array
2+
3+
func removeDuplicates(nums []int) int {
4+
top, l := 0, len(nums)
5+
if l == 0 {
6+
return 0
7+
}
8+
for i := 1; i < l; i++ {
9+
if nums[i] != nums[top] {
10+
top++
11+
nums[top] = nums[i]
12+
}
13+
}
14+
return top + 1
15+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package remove_duplicates_from_sorted_array
2+
3+
import (
4+
"testing"
5+
)
6+
7+
type caseType struct {
8+
input []int
9+
expected []int
10+
}
11+
12+
func TestRemoveDuplicates(t *testing.T) {
13+
tests := [...]caseType{
14+
{
15+
input: []int{1, 1, 2},
16+
expected: []int{1, 2},
17+
},
18+
{
19+
input: []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4},
20+
expected: []int{0, 1, 2, 3, 4},
21+
},
22+
{
23+
input: []int{1, 2, 3, 4},
24+
expected: []int{1, 2, 3, 4},
25+
},
26+
{
27+
input: []int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4},
28+
expected: []int{1, 2, 3, 4},
29+
},
30+
{
31+
input: nil,
32+
expected: nil,
33+
},
34+
}
35+
36+
for _, tc := range tests {
37+
nums := make([]int, len(tc.input))
38+
copy(nums, tc.input)
39+
l := removeDuplicates(nums)
40+
output := nums[:l]
41+
if l != len(tc.expected) {
42+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
43+
}
44+
for k, v := range tc.expected {
45+
if output[k] != v {
46+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
47+
}
48+
}
49+
}
50+
}

0 commit comments

Comments
(0)

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