mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Update0027.移除元素 Go示例代码
添加注释、代码格式化
This commit is contained in:
@ -256,17 +256,24 @@ class Solution:
|
||||
### Go:
|
||||
|
||||
```go
|
||||
// 快慢指针法
|
||||
// 时间复杂度 O(n)
|
||||
// 空间复杂度 O(1)
|
||||
func removeElement(nums []int, val int) int {
|
||||
length:=len(nums)
|
||||
res:=0
|
||||
for i:=0;i<length;i++{
|
||||
if nums[i]!=val {
|
||||
nums[res]=nums[i]
|
||||
res++
|
||||
}
|
||||
}
|
||||
nums=nums[:res]
|
||||
return res
|
||||
// 初始化慢指针 slow
|
||||
slow := 0
|
||||
// 通过 for 循环移动快指针 fast
|
||||
// 当 fast 指向的元素等于 val 时,跳过
|
||||
// 否则,将该元素写入 slow 指向的位置,并将 slow 后移一位
|
||||
for fast := 0; fast < len(nums); fast++ {
|
||||
if nums[fast] == val {
|
||||
continue
|
||||
}
|
||||
nums[slow] = nums[fast]
|
||||
slow++
|
||||
}
|
||||
|
||||
return slow
|
||||
}
|
||||
```
|
||||
```go
|
||||
|
Reference in New Issue
Block a user