标签:
从一个有序的数组中去除重复的数字,返回处理后的数组长度。
注意点:
例子:
输入: nums = [1, 1, 2] 
输出: 2
用一个下标index来标记下一个不重复的数字存放的位置,另一个下标start来表示当前是和哪个数字来比较有没有重复。遍历数字,如果不重复则放到index位置,后移index,并更新start位置;否则继续遍历。返回index即为不重复数组的长度。
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来获得相关源码。
LeetCode Remove Duplicates from Sorted Array
标签:
原文地址:http://blog.csdn.net/u013291394/article/details/50407435