Advertisement
Nenogzar
Mar 7th, 2024
39
0
Never
This is comment for paste Untitled
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ef find_last_one(arr):
  2.     low, high = 0, len(arr) - 1
  3.     result = -1  # Initialize result to -1, in case there are no 1s in the array
  4.  
  5.     while low <= high:
  6.         mid = (low + high) // 2
  7.  
  8.         if arr[mid] == 1:
  9.             result = mid  # Update the result and continue searching on the right side
  10.             low = mid + 1
  11.         else:
  12.             high = mid - 1  # Search on the left side
  13.  
  14.     return result
  15.  
  16.  
  17. # Example usage
  18. arr = []
  19. for i in range(11):
  20.     arr.append(1)
  21. for i in range(11, 22):
  22.     arr.append(0)
  23.  
  24. index_of_last_one = find_last_one(arr)
  25.  
  26. print("Index of the last occurrence of 1:", index_of_last_one)
  27.  
  28.  
  29. def find_first_one(arr):
  30.     low, high = 0, len(arr) - 1
  31.     result = -1  # Initialize result to -1, in case there are no 1s in the array
  32.  
  33.     while low <= high:
  34.         mid = (low + high) // 2
  35.  
  36.         if arr[mid] == 1:
  37.             result = mid  # Update the result and continue searching on the left side
  38.             high = mid - 1
  39.         else:
  40.             low = mid + 1  # Search on the right side
  41.  
  42.     return result
  43.  
  44.  
  45. # Example usage
  46. arr = arr[::-1]
  47. index_of_first_one = find_first_one(arr)
  48.  
  49. print("Index of the first occurrence of 1:", index_of_first_one)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement