Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit e7f5920

Browse files
committed
27. Remove Element
1 parent e350f28 commit e7f5920

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

27. Remove Element.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# 27. Remove Element
2+
3+
### 2017-03-26
4+
5+
Given an array and a value, remove all instances of that value in place and return the new length.
6+
7+
Do not allocate extra space for another array, you must do this in place with constant memory.
8+
9+
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
10+
11+
**Example:**
12+
Given input array *nums* = `[3,2,2,3]`, *val* = `3`
13+
14+
Your function should return length = 2, with the first two elements of *nums* being 2.
15+
16+
17+
18+
# Solution
19+
20+
```swift
21+
class Solution {
22+
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
23+
var count = nums.count
24+
var i = 0
25+
while i < count {
26+
if nums[i] == val {
27+
nums.remove(at:i)
28+
count -= 1
29+
} else{
30+
i += 1
31+
}
32+
}
33+
return nums.count
34+
}
35+
}
36+
```
37+

0 commit comments

Comments
 (0)