Given a target integer T and an integer array A sorted in ascending order, find the index of the first occurrence of T in A or return -1 if there is no such index.
Assumptions:
There can be duplicate elements in the array.
Examples:
A = {1, 2, 3}, T = 2, return 1
A = {1, 2, 3}, T = 4, return -1
A = {1, 2, 2, 2, 3}, T = 2, return 1
class Solution(object):
def firstOccur(self, array, target):
if len(array) == 0:
return -1
low = 0
high = len(array) - 1
while low < high - 1 :
mid = (low + high)/2
if array[mid] < target:
low = mid
else: high = mid
if array[low] == target:
return low
if array[high] == target:
return high
return -1