关于这道题,我使用了两种方法:
- 使用enumerate
nums = [1,2,4,5,6,6,6,6,7,8,9]
target = 6
index = [i for i ,x in enumerate(nums) if x==target]
返回对应target在数组中的下标:
[4, 5, 6, 7]
如果使用index来做,只会返回target在数组中第一个位置:
nums = [1,2,4,5,6,6,6,6,7,8,9]
target = 6
newindex = nums.index(target)
4
- 使用二分法
官方也是使用的二分法,在这里说一下我自己写的
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
a = len(nums)
low = 0
high = a-1
r = []
if len(nums) == 1 and nums[0] == target:
return [0,0]
elif len(nums) == 1 and nums[0] != target:
return [-1,-1]
while(low<=high):
if (low+high)%2 == 1:
mid = (low+high-1)//2
else:
mid = (low+high)//2
if nums[mid]==target:
r.append(mid)
if (mid +1) < a and nums[mid] == nums[mid+1]:#判断右边是否有相同的target
k = 1
while(k <=(high-mid)):
if nums[mid+k] == nums[mid]:
r.append(mid+k)
k +=1
if (mid-1)>=0 and nums[mid] == nums[mid-1]:#判断左边是否有相同的target
kk = 1
while(kk <=(mid-low)):
if nums[mid-kk] == nums[mid]:
r.append(mid-kk)
kk+=1
break
elif nums[mid] > target:
high = mid -1
else:
low = mid+1
r.sort()
if len(r) == 1:
return [r[0],r[0]]
elif r == []:
return [-1,-1]
else:
c = r[len(r)-1]
return [r[0],c]
- 使用二分法的框架找到target,虽然一个数组中有多个target,但是没关系,先找到任意一个
- 判断该位置的左右两边有没有等于target的元素,然后在区间内迭代寻找是否有相同的target
该算法还有一定的优化空间