StarryNights

每一个你所后悔的现在,都有一个不够努力的曾经

站内检索

循着字句,邂逅星光

搜索文章标题与正文,直达命中的章节

开始一次轻盈的站内探索

从这些主题开始探索

输入关键词

可同时输入多个词语缩小范围

发现内容

在摘要中查看高亮的关键词

快速直达

点击文章或章节标题继续阅读

# 引言

题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/

# 题目大意

给定排序的数组nums, 就地删除重复项, 使每个元素只出现一次并返回新的长度。

Hint: 不要为另一个数组分配额外的空间, 必须通过使用O(1)额外内存修改输入数组来实现此目的。

  • Example
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.

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.

# 题解

# 一句话题解

O(1)空间复杂度要求, 即利用原数组, 顺序遍历数组, 把不重复的项放在数组头部即可。维持一个index用于存储下标, 直接顺序遍历, 找到数组当前数据与前一个数据不一致即出现一个新数字, 放在当前index+1的位置即可。

# 复杂度

时间复杂度 O(n)

空间复杂度 O(1)

# AC代码

c++版本

class Solution
{
  public:
    int removeDuplicates(vector<int> &nums)
    {
        if (nums.empty())
        {
            return 0;
        }
        int ret = 1;
        int index = 1;
        for (int i = 1; i < nums.size(); ++i)
        {
            if (nums[i] != nums[i - 1])
            {
                ++ret;
                nums[index++] = nums[i];
            }
        }
        return ret;
    }
};

go版本

func removeDuplicates(nums []int) int {
	lens := len(nums)
	if 0 == lens {
		return 0
	}
	ret, index := 1, 1
	for i := 1; i < lens; i++ {
		if nums[i] != nums[i-1] {
			ret++
			nums[index] = nums[i]
			index++
		}
	}
	return ret
}
更新于 阅读次数 — 次
STARRY NIGHTSPERSONAL NOTES

赞赏

文章至此,故事还在继续。

Seiun

长按或右键保存收款码

文章关联

1 篇关联

顺着引用的连线,读见篇章交错的脉络

展开关系图

拖动平移 · Ctrl / ⌘ + 滚轮缩放 · 点击节点阅读使用 + / − 按钮缩放 · 放大视图后可拖动 · 点击节点阅读单指拖动平移 · 使用 + / − 按钮缩放 · 点击节点阅读

当前文章引用本文
引用列表

引用本文1

  • LeetCode Programming
    AI 摘要

    本文是作者为缓解拖延、练习 Go 语言而开启的 LeetCode 刷题记录,兼作个人题解。文中先介绍 C++ 输入输出加速技巧,通过 ios::sync_with_stdio(false) 解除 C/C++ 流同步、cin.tie(nullptr) 解除 cin 与 cout 绑定来提升效率;随后汇总多道 LeetCode 题解,列出题号、题目、难度及链接,涵盖第1至32题等。

本文引用0

暂无

文章关联