程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Sword finger offer python:49 Find a number in a sorted array

編輯:Python

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved