美文网首页
First Occurrence in Python (Bina

First Occurrence in Python (Bina

作者: GakkiLove | 来源:发表于2018-03-29 20:46 被阅读0次

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

相关文章

网友评论

      本文标题:First Occurrence in Python (Bina

      本文链接:https://www.haomeiwen.com/subject/iyuvcftx.html