您的位置:首页 > 其它

LeetCode Remove Duplicates from Sorted Array

2015-12-26 09:09 253 查看

LeetCode解题之Remove Duplicates from Sorted Array

原题

从一个有序的数组中去除重复的数字,返回处理后的数组长度。

注意点:

只能用常量的额外空间

将不重复的数字移到数组前部,剩余的部分不需要处理

例子:

输入: nums = [1, 1, 2]

输出: 2

解题思路

用一个下标index来标记下一个不重复的数字存放的位置,另一个下标start来表示当前是和哪个数字来比较有没有重复。遍历数字,如果不重复则放到index位置,后移index,并更新start位置;否则继续遍历。返回index即为不重复数组的长度。

AC源码

[code]class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        # The index where the character needs to be placed
        index = 1
        # The index of repeating characters
        start = 0
        for i in range(1, len(nums)):
            if nums[start] != nums[i]:
                nums[index] = nums[i]
                index += 1
                start = i
        return index

if __name__ == "__main__":
    assert Solution().removeDuplicates([1, 1, 2]) == 2


欢迎查看我的Github来获得相关源码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: