-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution27.go
More file actions
95 lines (85 loc) · 1.58 KB
/
solution27.go
File metadata and controls
95 lines (85 loc) · 1.58 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package solution27
// ============================================================================
// 27. Remove Element
// URL: https://leetcode.com/problems/remove-element/
// ============================================================================
/*
goos: linux
goarch: amd64
pkg: GoLeetCode/solutions/27---Remove-Element
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
Benchmark_removeElement
Benchmark_removeElement-24 311189276 3.689 ns/op 0 B/op 0 allocs/op
Benchmark_removeElementV1
Benchmark_removeElementV1-24 217852231 5.496 ns/op 0 B/op 0 allocs/op
PASS
*/
func removeElement(nums []int, val int) int {
if len(nums) == 0 {
return 0
}
a := 0
b := len(nums) - 1
k := 0
for a <= b && b >= a {
if nums[a] != val {
a++
continue
}
nums[a] = nums[b]
nums[b] = -1
b--
k++
}
return len(nums) - k
}
func removeElementV1(nums []int, val int) int {
n := len(nums)
if n == 0 {
return 0
}
idx := -1
i := 0
c := 0
for {
if nums[i] == val {
nums[i] = -1
idx = i
c++
}
if idx != -1 {
for j := idx; j < n; j++ {
if j < n-1 {
nums[j] = nums[j+1]
}
}
nums[n-1] = -1
idx = -1
continue
}
i++
if i >= n {
break
}
}
return n - c
}
func removeElement_stdlib(nums []int, val int) int {
loop:
n := len(nums)
for i := n - 1; i >= 0; i-- {
if nums[i] == val {
if i == 0 {
nums = nums[1:]
goto loop
} else if i < n-1 {
nums = append(nums[:i], nums[i+1:]...)
goto loop
} else {
nums = nums[:i]
goto loop
}
}
}
return len(nums)
}