您的位置:首页 > 其它

LeetCode初级算法练习

2018-03-29 22:25 381 查看
26. 从排序数组中删除重复项给定一个有序数组,你需要原地删除其中的重复内容,使每个元素只出现一次,并返回新的长度。不要另外定义一个数组,您必须通过用 O(1) 额外内存原地修改输入的数组来做到这一点。示例:给定数组: nums = [1,1,2],

你的函数应该返回新长度 2, 并且原数组nums的前两个元素必须是1和2
不需要理会新的数组长度后面的元素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.
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
前提是已排序
判断nums[j]与nums[i-1]元素,相等j+1继续判断下一元素;不相等,nums[j]赋值给nums[i],
返回i与size的最小值(size为0时返回size,没有不相同的时候           size==i,有相同的i<size)
"""
i = 1
j = 1
size = len(nums)
while j < size:
if nums[j] == nums[i-1]:
j += 1
else:
nums[i] = nums[j]
i += 1
j += 1
return min(i,size)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: