leetcode26题 题解 翻译 C语言版 Python版

26. Remove Duplicates from Sorted Array

Given a sorted array, 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 in place with constant memory.

For example,
Given input array 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 new length.

26.从有序数组中移除重复元素

给定一个有序数组,就地移除重复元素使得每个元素只出现一次并且返回新的数组长度。

不要分配额外的内存来创建另外的数组,你必须使用固定内存就地完成。

举例:

给定数组nums=[1,1,2]

你的函数应该返回length=2,而且nums的前两个元素分别应该是1和2。超过新数组长度的部分你就不用管了。


思路:因为是有序数组,所以每遇到一个新值时暂存然后继续向后遍历,如果等于这个值就跳过,不等于时就要更新新值。所有的新值依次保存在原数组中,因为新值的数量肯定小于等于原数组元素的数组,所以这样覆盖保存并不会出问题。



int removeDuplicates(int* nums, int numsSize) {
    if (numsSize == 0) return 0;
    int len = numsSize;
    int index = 1;
    int t = nums[0];
    for (int i = 1; i < numsSize; i++){
        if (nums[i] != t){
            nums[index++] = nums[i];
            t = nums[i];
        }
        else{
            len--;
        }
    }
    return len;
}


class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums: return 0
        length,index,t = len(nums),1,nums[0]
        for i in nums[1:]:
            if i != t:
                nums[index] = i
                index += 1
                t = i
            else:
                length -= 1
        return length


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值