[LeetCode] 80. Remove Duplicates from Sorted Array II

Medium
Related Topics: Array / Two Pointers
LeetCode Source

解题想法

这题跟昨天类似,但可重複的数字从 1 个变成 2 个,且强调必须在 in-place 的规範下解题

我这里先初始两个变数

check: 计算数字出现次数index: 纪录 index 位置,换数字时和最后回传我们需要用到它

由于题目初始条件 nums 长度最小是一,所以我们从 index = 1 开始判断
当此时的数字与前一个数字相同时,check += 1
反之,check = 1,代表没有出现相同数字,重制变数

最后面判断式是重点,假设我们 check > 2,代表说有出现重複数字两次以上
check <= 2 时,我们必须替换数字
index 的位置便是关键,index 初始下是在 1,仅在 check <= 2 时加一

我们可以发现,如果重複出现超过两次,剩余的数字便会忽略
而如果只出现一次或两次,则会触发判断式,将重複出现的数字替换成只出现一到两次的数字

Python

class Solution:    def removeDuplicates(self, nums: List[int]) -> int:        index = 1        count = 1        for i in range(1, len(nums)):            if nums[i] == nums[i - 1]:                count += 1            else:                count = 1  # Reset the count for the new element            if count <= 2:                nums[index] = nums[i]                index += 1        return index

C++

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int index = 1, check = 1;        for (int i = 1; i < nums.size(); i++) {            if (nums[i] == nums[i-1]) {                check += 1;            } else {                check = 1;            }            if (check <= 2) {                nums[index] = nums[i];                index += 1;            }        }        return index;    }};

这系列文被记录在 Top Interview 150 Series


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章