leetcode 26. Remove Duplicates from Sorted Array

题目

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
Return k.

这个和remove element in list那个是类似的,这里还再次强调了in-place, 所以一定要改变原来给的Nums这个list的元素值,而不是创建新的List,那就必须循环了,这里的constrains是重中之重,

Constraints:
1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
nums is sorted in non-decreasing order.

所以nums一定不为空,然后Nums值也有范围,最后是有排序的,所以相同的元素必然是一起的。

解法

抛砖引玉一个我的先

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        index = 0
        temp = -9999

        for i in range(len(nums)):
            if nums[i] != temp:
                nums[index] = nums[i]
                index += 1
                temp = nums[i]

        return index

这里我用了一个temp值。 实际上有更优化的,就是用第一个值来起始比较就行,然后因为重复是顺序的,那么下一个值总是去比较上一个就行了。

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        j = 1
        for i in range(1, len(nums)):
            if nums[i] != nums[i - 1]:
                nums[j] = nums[i]
                j += 1
        return j

当下一个值不等于前一个值得时候,说明不重复的值出现了,要加入目标位置中了。目标位置j标定,每次新的加入后递增。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值