26. Remove Duplicates from Sorted Array
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i=1
j=1
while i<len(nums):
if nums[i]==nums[j-1]:
i+=1
else:
nums[j]=nums[i]
i+=1
j+=1
return min(j,len(nums))#取小,否则out of range
感觉略邪门
一开始这样写的,一直报错,原来是返回元素个数就好了,不过也不能用len(set()),估计是内部申请了额外数组
for i in range(1,len(nums)):
if nums[i]<=nums[i-1]:
nums=nums[0:i]
break
return nums
27. Remove Element
删除给定数字,不能额外申请空间
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i=0
j=0
size=len(nums)
while j<size:
if nums[j]==val:
j+=1
else:
nums[i]=nums[j]
i+=1
j+=1
return i
声明i和j,i和j一块走,i如果遇到val,原地等着,j去找一个不等于Val的元素来替换它