LeetCode小白菜笔记[8]:Remove Duplicates from Sorted Array
LeetCode小白菜笔记[8]:Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Array [Easy]
题目: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 by modifying the input array in-place with O(1) extra memory.
Example:
Given 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.
这个问题即将 list 中不重复的元素按照原有的顺序排起来并返回 list 中不同数值的数量,注意这里要求原位操作,所以必须 O(1) 的空间复杂度。这样我们将每次检测到的与之前不同的值(如 example 中检测到一个2)应当放在之前那个值(即第一个1)所在位置的后一个位置,然后更新要比较的值(更新为2)继续比较,知道遍历完所有元素。emmm。。。这次机制的我吸取教训,先判断是不是特殊情况,如果为空list,直接返回0 。代码如下:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return 0
idx = 0
for item in nums:
if not item == nums[idx]:
idx = idx + 1
nums[idx] = item
return idx + 1
尽量减少变量名,取 list 元素for循环直接取不要用下标取。结果如下:
总结:
时间复杂度线性,空间复杂度常数。这个题比较简单,没啥好总结的。
THE END
2017/12/16 Sat 16:26