Search In Shifted Sorted Array II

Given a target integer T and an integer array A, A is sorted in ascending order first, then shifted by an arbitrary number of positions.

For Example, A = {3, 4, 5, 1, 2} (shifted left by 2 positions). Find the index i such that A[i] == T or return -1 if there is no such index.

Assumptions

There could be duplicate elements in the array.

Examples

A = {3, 4, 5, 1, 2}, T = 4, return 1
A = {3, 3, 3, 1, 3}, T = 1, return 3
A = {3, 1, 3, 3, 3}, T = 1, return 1

?Corner Cases

What if A is null or A is of zero length? We should return -1 in this case.

class Solution(object):
  def search(self, array, target):
    if len(array) < 1:
      return -1
    left = 0
    right = len(array) - 1
    while left < right - 1:
      mid = (left + right)/2
      if array[mid] == target:
        return mid
      while left < mid and array[left] == array[mid]:
        left += 1
      if array[left] <= array[mid]:
        if array[left] <= target < array[mid]:
          right = mid - 1
        else:
          left = mid + 1
      else:
        if array[mid] < target <= array[right]:
          left = mid + 1
        else:
          right = mid - 1
    if array[left] == target:
      return left
    if array[right] == target:
      return right
    return -1

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容