当前位置:网站首页>Binary search method

Binary search method

2022-06-26 03:48:00 Just call me ah Jie

The binary search method is applicable to ordered columns , Judge whether the target value is in the list by taking the number in the middle of the list each time , If the median is greater than the target value , Then the target value is to the left of the middle , On the contrary, it is on the right .

class Solution:
    def search(self,list_num:list,tag):
        low,high = 0,len(list_num)-1
        while low <=high:
            mid = (high - low ) // 2 + low
            num = list_num[mid]
            if num==tag:
                return mid
            elif num > tag:
                high =mid-1  #  The intermediate value is greater than the target value , So take the left side of the list , The subscript value on the right is updated to mid-1
            elif num <tag:
                low = mid +1 #  The intermediate value is less than the target value , So take the right side of the list , The subscript value on the left is updated to mid+1
        return -1

subject :

I'll give you a subscript from 1 The starting array of integers numbers , The array has been pressed Non decreasing order  , Please find out from the array that the sum satisfying the addition is equal to the target number target Two numbers of , If there is only one answer .

Example :
Input :numbers = [2,7,11,15], target = 9
Output :[1,2]
explain :2 And 7 The sum is equal to the number of targets 9 . therefore index1 = 1, index2 = 2 . return [1, 2] .

 Their thinking :
 Suppose a number A, And then this number A, Whether the addition with the following number is equal to the target value , Use the dichotomy method to find the second number 
class Solution:
    def twoSum(self, numbers: list, target: int) :
        n = len(numbers)
        for i in range(n):
            low,high=i+1,n-1
            while low<=high:
                mid = (high+low)//2
                if numbers[mid] == target-numbers[i]:
                    return [i+1,mid+1]
                elif numbers[mid]>target-numbers[i]:
                    high = mid-1
                else:
                    low = mid+1
        return [-1,-1]

原网站

版权声明
本文为[Just call me ah Jie]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180546016012.html