美文网首页
Search In Shifted Sorted Array(B

Search In Shifted Sorted Array(B

作者: GakkiLove | 来源:发表于2018-04-11 01:05 被阅读0次

    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 are no duplicate elements in the array.

    Examples:

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

    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
          if array[mid] >= array[left]:
            if array[mid] > target and array[left] <= target:
              right = mid - 1
            else:
              left = mid + 1
          elif array[mid] < array[left]:
            if array[mid] < target and array[right] >= target:
              left = mid + 1
            else:
              right = mid - 1
        if array[left] == target:
          return left
        if array[right] == target:
          return right
        return -1
    

    相关文章

      网友评论

          本文标题:Search In Shifted Sorted Array(B

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