刷 LeetCode 从零开始学 GoLang(8):26. Remove Duplicates from Sorted Array

题目描述

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 语法:函数

  1. 函数的定义:
func name(parameter-list) (result-list){
	// function body
}

(1)函数的返回值可以被命名。当函数返回值被命名后,可以省略返回语句的参数(bare return)
(2)函数可以指定多个返回值
2. 匿名函数的定义和命名函数类似,只是它在 func 关键字后面没有函数名。命名函数只能定义在 Package Level, 而匿名函数可以定义在任何地方:

func (parameter-list) (result-list){
	// function body
}
  1. 调用函数时,在它前面加上 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)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值