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

Python leetcode35: search insert location

編輯:Python

subject :
"""
Given a sort array and a target value , Find the target value in the array , And return its index .
If the target value does not exist in the array , Return to where it will be inserted in sequence .
"""

Law 1 : Comparative method

class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if nums[i] == target: # equal
return i
elif i < len(nums)-1 and target > nums[i] and target < nums[i+1] : #target In the middle
return i+1
elif i == 0 and target < nums[i]: # start
return i
return len(nums) # Does not exist in array 

Law two : Two points search

Just apply the dichotomy directly , That is, continue to use dichotomy approximation to find the first greater than or equal to  \textit{target}target  The subscript .

class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l,r = 0,len(nums)-1
while l <= r:
mid = (l+r)//2
if target == nums[mid]:
return mid
elif target < nums[mid]:
r = mid - 1
else:
l = mid +1
return l
nums = [1, 3, 5, 6]
target = 7
S = Solution()
result = S.searchInsert(nums,target)
print(result)


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