forked from yijizhichang/LeetCodeInGo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path26.go
More file actions
38 lines (28 loc) · 978 Bytes
/
26.go
File metadata and controls
38 lines (28 loc) · 978 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
package problem
/*
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
你不需要考虑数组中超出新长度后面的元素。
*/
func removeDuplicates(nums []int) int {
if len(nums) < 2 {
return len(nums)
}
left, right := 0, 1
for ; right < len(nums); right++ {
if nums[left] == nums[right] {
continue
}
left++
nums[left] = nums[right]
}
nums = nums[:left+1]
return len(nums)
}