# leetcode刷题记录Array篇(26&27～Remove Element)

L千年老妖 · · 964 次点击 · · 开始浏览

# 26.Remove Duplicates from Sorted Array

Do not allocate extra space for another array, you must do this in place with constant memory.

1.首先我们知道排序的数组，nums[i+1]>=nums[i]；
2.我们可以设置一个标志count,为重复数字的数量，遍历数组,当nums[i]==nums[i-1]时，count++；不等时，使nums[i-count]==nums[i]
3.解释一下i-count，它的计算值是当前元素下标-已遍历重复数数量，即为剩下的唯一数数量
4.遍历结束，len(nums)-count就是剩下的唯一数数量

golang代码:

``````package main

import (
"fmt"
)

func main() {

nums := []int{1, 1, 5, 6, 6, 6}
fmt.Println(removeDuplicates(nums))

}

func removeDuplicates(nums []int) int {
count := 0
for i := 1; i < len(nums); i++ {
if nums[i] == nums[i-1] {
count++
} else {
nums[i-count] = nums[i]
}
}
return len(nums) - count
}``````
###### #27.Remove Element

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.

golang代码:

``````package main

import (
"fmt"
)

func main() {
nums := []int{1, 2, 1, 3}
fmt.Println(removeElement(nums, 2))
}

func removeElement(nums []int, val int) int {
var result int
for i := 0; i < len(nums); i++ {
if nums[i] != val {
nums[result] = nums[i]
result++
}
}
return result
}``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

# 26.Remove Duplicates from Sorted Array

Do not allocate extra space for another array, you must do this in place with constant memory.

1.首先我们知道排序的数组，nums[i+1]>=nums[i]；
2.我们可以设置一个标志count,为重复数字的数量，遍历数组,当nums[i]==nums[i-1]时，count++；不等时，使nums[i-count]==nums[i]
3.解释一下i-count，它的计算值是当前元素下标-已遍历重复数数量，即为剩下的唯一数数量
4.遍历结束，len(nums)-count就是剩下的唯一数数量

golang代码:

``````package main

import (
"fmt"
)

func main() {

nums := []int{1, 1, 5, 6, 6, 6}
fmt.Println(removeDuplicates(nums))

}

func removeDuplicates(nums []int) int {
count := 0
for i := 1; i < len(nums); i++ {
if nums[i] == nums[i-1] {
count++
} else {
nums[i-count] = nums[i]
}
}
return len(nums) - count
}``````
###### #27.Remove Element

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.

golang代码:

``````package main

import (
"fmt"
)

func main() {
nums := []int{1, 2, 1, 3}
fmt.Println(removeElement(nums, 2))
}

func removeElement(nums []int, val int) int {
var result int
for i := 0; i < len(nums); i++ {
if nums[i] != val {
nums[result] = nums[i]
result++
}
}
return result
}``````