题目:26. Remove Duplicates from Sorted Array
题目描述
Given a sorted array nums, 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.
解题思路
只需要找array[i]=array[i+1]的项,然后把array[i+1]项删除,循环一次就好。
代码
def removeDuplicates(self, nums):
if len(nums)<=0:
return 0
key, i = nums[0], 1
while i<len(nums):
if nums[i]==key:
nums.pop(i)
else:
key = nums[i]
i += 1
return len(nums)
AC截图
题目:34. Search for a Range
题目描述
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
解题思路
先用二分查找,在列表中找到target(若找不到则返回[-1,-1])
每一次查找都记录上一次查找的区间[left, right],当找到target之后(此时区间一定满足nums[left]<=target,nums[right]>=target,且所有target一定在这个区间里)
然后这个区间的左边自增,右边自减,直至nums[left]=nums[right]=target为止
最终得到的[left,right]即为所求
代码
def searchRange(self, nums, target):
if len(nums)<=0:
return [-1, -1]
uleft, uright = 0, len(nums)
left, right = 0, len(nums)
mid, flag = 0, 1
while True:
mid = (left + right)//2
if mid<len(nums) and nums[mid]==target:
break
if left == right or mid>=len(nums):
return [-1, -1]
if nums[mid]<target:
uleft = left
left = mid + 1
else:
uright = right
right = mid
uright -= 1
while uleft<mid or uright>mid:
if nums[uleft] == target and nums[uright]==target:
break
if nums[uleft]<target and uleft<mid:
uleft += 1
if nums[uright]>target and uright>mid:
uright -= 1
return [uleft, uright]