码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Remove Duplicates from Sorted Array

时间:2015-12-26 10:07:23      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

LeetCode解题之Remove Duplicates from Sorted Array


原题

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

注意点:

  • 只能用常量的额外空间
  • 将不重复的数字移到数组前部,剩余的部分不需要处理

例子:

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

解题思路

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

AC源码

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!