-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove-duplicates-from-sorted-array-ii.go
64 lines (61 loc) · 1.14 KB
/
remove-duplicates-from-sorted-array-ii.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
package leetcode
// https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
// o(n), inplace
func removeDuplicates(nums []int) int {
if len(nums) == 0 {
return 0
}
current := nums[0]
currentCount := 1
pos := 0
for i := 1; i < len(nums); i++ {
if current != nums[i] {
nums[pos] = current
if currentCount > 1 {
pos++
nums[pos] = current
}
current = nums[i]
currentCount = 1
pos++
} else {
currentCount++
}
}
nums[pos] = current
if currentCount > 1 {
pos++
nums[pos] = current
}
// fmt.Printf("%v\n", nums)
return pos + 1
}
// use new array
func removeDuplicates2(nums []int) int {
if len(nums) == 0 {
return 0
}
result := make([]int, 0, len(nums))
current := nums[0]
currentCount := 1
for i := 1; i < len(nums); i++ {
if current != nums[i] {
result = append(result, current)
if currentCount > 1 {
result = append(result, current)
}
current = nums[i]
currentCount = 1
continue
}
currentCount++
}
if currentCount > 0 {
result = append(result, current)
if currentCount > 1 {
result = append(result, current)
}
}
copy(nums, result)
return len(result)
}