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 (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。