python dichotomy to find instance code

  • 2021-12-13 08:45:35
  • OfStack

The more elements to be searched, the faster the 2-point search is than the simple search. This is the advantage of the 2-point search algorithm, but the 2-point algorithm also has disadvantages. The 2-point algorithm is only for ordered lists, so it is difficult to insert and delete them. Therefore, the half-point search method is only suitable for ordered lists that do not change frequently

2-point search has a very important feature, that is, it will not find all the elements of the sequence, but the amount of data found actually coincides with the logarithm of the elements. Under normal circumstances, the elements found every time are reduced in 1.5 and 1.5. Therefore, there is no doubt that the time complexity of 2-minute lookup is O (log2n). Of course, the best case is to find it only once, but in the worst case and the first case, it is much better than searching sequentially.

Title 1: Given an n element ordered (ascending) integer array nums and a target value target, write a function to search target in nums. If the target value has a return subscript, otherwise it returns-1.

class Solution:
    def search(self,nums:List[int],target:int)->int:
        left=0
        right=len(nums)-1
        while(left<=right):
            mid=(left+right)//2
            if nums[mid]==target:
               return mid
            if nums[mid]<target:
                left=mid+1
            else:
                right=mid-1
        return -1
Topic 2: In a strictly decreasing array, find the subscript of the second number larger than the target value target. If it does not exist, it returns-1.

class Solution:
    def search(self,nums:List[int],target:int)->int:
        left=0
        right=len(nums)-1
        while(left<=right):
            mid=(left+right)//2
            if nums[mid]==target:
               return mid
            if nums[mid]>target:
                left=mid+1
            else:
                right=mid-1
        return -1
Topic 3: The function should return the subscript values of these two numbers as an array of integers of length 2. The subscript of numbers is counted from 1, so the answer array should satisfy 1 < = answer[0] < answer[1] < = numbers. length. You can assume that each input corresponds to only one answer, and you can't reuse the same elements.

class Solution:
     def twoSum(self, numbers: List[int], target: int) -> List[int]:
        for i in range(len(numbers)-1):
            left=i
            right=len(numbers) - 1
            while(left<=right):
                mid=(left+right)//2
                if numbers[mid]+numbers[i]==target:
                    return [i+1,mid+1]
                elif numbers[mid]+numbers[i]<target:
                    left=mid+1
                else:
                    right = mid-1
            return [-1,-1]

Summarize


Related articles: