移除元素:
- 移除整數數組中值與給定數字相等的元素,並返回其最終的長度
- 不能分配額外的內存
原題
Given an array and a value, 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 in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
分析
本題難度低,主要的為題是不能分配額外的內存,所以需要在原數組進行修改,那麼接下來就很簡單了,
遍歷數組,將和給定數值相等的元素移除即可。
實現
1func removeElement(nums []int, val int) int {
2 for i := 0; i < len(nums); {
3 if nums[i] == val {
4 // remove current element from nums,
5 // and the next element's index is i, not i++.
6 nums = append(nums[:i], nums[i+1:]...)
7 } else {
8 i++
9 }
10 }
11
12 return len(nums)
13}