题目描述
Given a sorted array nums, remove the duplicates in-place such that each element appear only once 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.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2,
with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5,
with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
GoLang 语法:函数
- 函数的定义:
func name(parameter-list) (result-list){
// function body
}
(1)函数的返回值可以被命名。当函数返回值被命名后,可以省略返回语句的参数(bare return)
(2)函数可以指定多个返回值
2. 匿名函数的定义和命名函数类似,只是它在 func 关键字后面没有函数名。命名函数只能定义在 Package Level, 而匿名函数可以定义在任何地方:
func (parameter-list) (result-list){
// function body
}
- 调用函数时,在它前面加上
defer
关键字,该函数调用会在执行defer
语句的函数结束后(return
语句执行完后)才执行。
AC 代码
// slice 值传递:
// (1) 指针指向 underlying array,因此会改变原数组的值
// (2) len 和 cap 是值类型,因此实参不会影响形参的值
func removeValByIdx(nums []int, idx int) (length int) {
if idx >= len(nums) {
return len(nums)
}
for i := idx + 1; i < len(nums); i++ {
nums[i-1] = nums[i]
}
nums = nums[:len(nums)-1]
return len(nums)
}
func removeDuplicates(nums []int) int {
for i := 1; i < len(nums); i++ {
if nums[i] == nums[i-1]{
nums = nums[:removeValByIdx(nums, i)]
i--
}
}
return len(nums)
}