Skip to content

26. 删除排序数组中的重复项 #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Geekhyt opened this issue Jan 22, 2021 · 0 comments
Open

26. 删除排序数组中的重复项 #4

Geekhyt opened this issue Jan 22, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Jan 22, 2021

原题链接

双指针

题目要求原地删除重复出现的元素,不要使用额外的数组空间,返回移除后数组的新长度。

先明确,这道题给我们提供的是排好序的数组,所以重复的元素必然相邻。

所以实际上我们只需要将不重复的元素移到数组的左侧,并返回其对应的长度即可。

1.借助双指针,i 从索引 0 开始,j 从索引 1 开始。
2.当前项 nums[j] 与前一位置 nums[j - 1] 相等时,j++ 跳过重复项。
3.当二者不相等时,意味着不是重复项,此时需要将 i 指针右移, 并将 nums[j] 复制到此时的 nums[i] 位置上,然后将指针 j 右移。
4.重复上述过程,直到循环完成,最终返回 i + 1,因为题目要求返回长度,i 是索引位置,加 1 即所求。

const removeDuplicates = function(nums) {
    const n = nums.length
    let i = 0
    if (n === 0) return 0
    for (let j = 1; j < n; j++) {
        if (nums[j] !== nums[j - 1]) {
            i++
            nums[i] = nums[j]
        }
    }
    return i + 1
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
@Geekhyt Geekhyt added the 简单 label Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant