mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2026-03-13 10:02:05 +08:00
add 80 solution explain
This commit is contained in:
@@ -2,8 +2,8 @@ package leetcode
|
||||
|
||||
func removeDuplicates(nums []int) int {
|
||||
slow := 0
|
||||
for i, v := range nums {
|
||||
if i < 2 || nums[slow-2] != v {
|
||||
for fast, v := range nums {
|
||||
if fast < 2 || nums[slow-2] != v {
|
||||
nums[slow] = v
|
||||
slow++
|
||||
}
|
||||
|
||||
@@ -51,6 +51,6 @@ for (int i = 0; i < len; i++) {
|
||||
|
||||
## 解题思路
|
||||
|
||||
这道题和第 26 题很像。是第 26 题的加强版。这道题和第 283 题,第 27 题基本一致,283 题是删除 0,27 题是删除指定元素,这一题是删除重复元素,实质是一样的。
|
||||
|
||||
这里数组的删除并不是真的删除,只是将删除的元素移动到数组后面的空间内,然后返回数组实际剩余的元素个数,OJ 最终判断题目的时候会读取数组剩余个数的元素进行输出。
|
||||
问题提示有序数组,一般最容易想到使用双指针的解法,双指针的关键点:移动两个指针的条件。
|
||||
在该题中移动的条件:快指针从头遍历数组,慢指针指向修改后的数组的末端,当慢指针指向倒数第二个数与快指针指向的数不相等时,才移动慢指针,同时赋值慢指针
|
||||
处理边界条件:当数组小于两个元素时,不做处理
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
## 题目
|
||||
|
||||
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
|
||||
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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.
|
||||
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**:
|
||||
|
||||
@@ -34,7 +36,8 @@ It doesn't matter what values are set beyond the returned length.
|
||||
|
||||
Confused why the returned value is an integer but your answer is an array?
|
||||
|
||||
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
|
||||
Note that the input array is passed in by reference, which means modification to the input array will be known to the
|
||||
caller as well.
|
||||
|
||||
Internally you can think of this:
|
||||
|
||||
@@ -69,10 +72,10 @@ package leetcode
|
||||
|
||||
func removeDuplicates(nums []int) int {
|
||||
slow := 0
|
||||
for i, v := range nums {
|
||||
if i < 2 || nums[slow-2] != v{
|
||||
for fast, v := range nums {
|
||||
if fast < 2 || nums[slow-2] != v {
|
||||
nums[slow] = v
|
||||
slow ++
|
||||
slow++
|
||||
}
|
||||
}
|
||||
return slow
|
||||
@@ -81,7 +84,6 @@ func removeDuplicates(nums []int) int {
|
||||
|
||||
```
|
||||
|
||||
|
||||
----------------------------------------------
|
||||
<div style="display: flex;justify-content: space-between;align-items: center;">
|
||||
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0079.Word-Search/">⬅️上一页</a></p>
|
||||
|
||||
Reference in New Issue
Block a user