Leetcode题目之删除有序列表中的重复元素

本文介绍了一种在原地去除数组中重复元素的算法,通过双指针技术实现元素的唯一性保留,并确保空间复杂度为O(1)。适用于排序数组,示例展示了如何通过该算法获得不含重复项的新数组长度及内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a sorted array nums, remove the duplicates in-place such that each element appear only once 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.

Example 1:

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.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],Your function should return length = 5, with the first five elements o

nums being modified to 0,1,2,3 and 4 respectively.

It doesn't matter what values are set beyond the returned length.

时间原因,题目就不解释了,然后说下我的思路。

这个想法和快速排序差不多,就是用两个指针去依次遍历数组,i从0开始,j从1开始,然后开始遍历,当发现下标i和j的元素相等时,就让j继续走下去,因为此时i和j指向的元素是相同的,接下来如果i和j指向的元素不相等,那就让i先向下走一步,保证i的值不会被覆盖,然后将j指向的元素赋值给i指向的元素,然后继续重复以上步骤。

代码如下:

class Solution:
    def removeDuplicates(self, nums):
        print(nums)
        i = 0
        j = 1
        while j<=len(nums)-1:
            if nums[i] == nums[j]:
                j += 1
                continue
            else:
                i += 1
                nums[i] = nums[j]
                j += 1
                continue
        print(i+1)
        return nums[:i+1]

最终运行结果如下:

 

 谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值