subject : Count the number of times a number appears in the sort array 、 And location .
Example :
Input : nums = [5,7,7,8,8,10], target = 8
Output :2,[3,4]
Input : nums = [5,7,7,8,8,10], target = 6
Output :0,[]
Method 1: The method of violence is for.
Method 2: Two points .
Write your own code :
class Solution:
def func(self , nums,target):
if len(nums) == 0 or nums[0] > target or nums[-1] <target:
return 0 , {}
res = {}
n = len(nums)
i , j = 0 , n-1
while i < j:
half = (i + j ) // 2
if nums[half] < target:
i = half
elif nums[half] > target:
j = half
else:
if nums[half] not in res.keys():
res[nums[half]] = [half]
else:
if half not in res[nums[half]]:
res[nums[half]].append(half)
i += 1
return res
a = [5,7,7,8,8,10]
target = 8
s = Solution()
print(s.func(a,target))
Return to one dict,key It was found target,value Is the corresponding position .