-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathremove_element.go
More file actions
47 lines (41 loc) · 879 Bytes
/
remove_element.go
File metadata and controls
47 lines (41 loc) · 879 Bytes
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
/*
27. Remove Element
https://leetcode.com/problems/remove-element/
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
*/
// time: 2018-12-20
package removeelement
// two pointers
// time complexity: O(n)
// space complexity: O(1)
func removeElement(nums []int, val int) int {
x := 0
for j := 0; j < len(nums); j++ {
if nums[j] != val {
if x != j {
nums[x] = nums[j]
}
x++
}
}
return x
}
/*
func removeElement1(nums []int, val int) int {
var (
l int
r = len(nums)
)
for l < r {
if nums[l] == val {
r--
nums[l] = nums[r]
} else {
l++
}
}
return r
}
*/