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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,173评论 0 10
  • 从隔壁亲戚家吃完晚饭回来,婆婆一个人在厨房里忙碌着。我好奇问她在忙什么?婆婆说把昨天宴请客人剩下的一些鸡鸭鱼肉等重...
    AHa雅涵Ani阅读 2,920评论 0 1
  • 今天给你打电话,你却提到了钱,我不知道的我当时为什么答应你,一直以来对你我有求必应,电话打到一半时我后悔了,我自己...
    缠绵梦魇阅读 1,886评论 0 1
  • 下午坐在办公室里,不知道为什么总有点心神不宁。望着外面灰蒙蒙阴沉沉的天,感觉压顶的乌云好像聚在我的心口,我...
    流金岁月静心阅读 3,122评论 1 1

友情链接更多精彩内容