forked from hoanhan101/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove_duplicates_test.go
66 lines (54 loc) · 1.09 KB
/
remove_duplicates_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
Problem:
- Given an array of sorted numbers and a target sum, find a pair in the
array whose sum is equal to the given target.
Example:
- Input: []int{1, 2, 6, 8, 16, 26}, target=14
Output: []int{2, 3}
Explanation: 6 (index 2) + 8 (index 3) = 14
Approach:
- Have one pointer iterate the array and one placing non-duplicate number.
Cost:
- O(n) time, O(1) space.
*/
package gtci
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestRemoveDuplicates(t *testing.T) {
tests := []struct {
in []int
expected int
}{
{[]int{}, 0},
{[]int{1}, 1},
{[]int{1, 2}, 2},
{[]int{1, 2, 2}, 2},
{[]int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4}, 4},
}
for _, tt := range tests {
common.Equal(
t,
tt.expected,
removeDuplicates(tt.in),
)
}
}
func removeDuplicates(a []int) int {
if len(a) == 0 {
return 0
}
nonDuplicate := 1
i := 1
for i < len(a) {
// if we see a non-duplicate number, move it next to the last
// non-duplicate one that we've seen.
if a[nonDuplicate-1] != a[i] {
a[nonDuplicate] = a[i]
nonDuplicate++
}
i++
}
return nonDuplicate
}