find first occurrence of k in array

Go Back home

Write a python program that finds the first occurence of k in an array of integers.

 1 def search_first_of_k(A, k):
 2 
 3     left, right, result = 0, len(A) - 1, -1
 4     while left <= right:
 5         mid = (left + right) // 2
 6         val = A[mid]
 7         if val > k:
 8             right = mid - 1
 9         elif val == k:
10             result, right = mid, mid - 1
11         else:
12             left = mid + 1
13     return result
14 
15 search_first_of_k([-10, -5, 24, 24, 46, 46, 64, 64, 64, 180], 64)

paste-f6163ae794bc4889a68b4e8cf77b04189da22ec5.mp4