SoFunction
Updated on 2024-11-21

Example of Python Finding Elements in an Array with Equal Values and Subscripts [Binary Finding

This article example describes Python to find the elements of an array with equal values and subscripts. Shared for your reference, as follows:

Title Description:

Assume that each element of a monotonically increasing array is an integer and unique. Program a function to find any element of the array whose value is equal to its subscript, e.g., in the array [-3, -1, 1, 3, 5], 3 is equal to his subscript.

Using binary search: if the number in the array is smaller than the subscript, because the subscript is a decreasing series of -1, but the difference between the elements in the array is greater than or equal to -1, so the left cannot be equal to the subscript. If the number in the array is greater than the subscript, similarly, after the number must be greater than the subscript, to the left to find.

Algorithm example:

# -*- coding:utf-8 -*-
#! python3
class Solution:
  def numberEqualSubscript(self, numbers):
    if numbers == []:
      return -1
    left = 0
    right = len(numbers) - 1
    while(left <= right):
      middle = (left + right) >> 1
      if numbers[middle] == middle:
        return middle
      elif numbers[middle] < middle:
        left = middle + 1
      else:
        right = middle - 1
    return -1
numbers = [-3,-1,1,3,5]
print(Solution().numberEqualSubscript(numbers))

Run results:

3

Readers interested in more Python related content can check out this site's topic: thePython Data Structures and Algorithms Tutorial》、《Python list (list) manipulation techniques summarized》、《Summary of Python coding manipulation techniques》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials

I hope the description of this article will help you in Python programming.