Leetcode: Search in Rotated Sorted Array

来源:互联网 发布:java 时间轴数据 编辑:程序博客网 时间:2024/06/18 16:21


Get idea from Code Ganker′s (CSDN) Solution, and Leetcote article


Question

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.


Analysis

There is a property that we can take advantage of. We divide it as two parts based on the pivot element(assume we know it), part A and B. For instance, in [3,4,5,1,2], part A is [3,4,5], B is [1,2]

If middle one is larger than left most one, we can conclude that the size of part A is greater than B. So elements in range [left, middle] must be in strictly increasing order. And then we can decide which part should be to search according to the target element.

Complexity
Since we reduce the array by half each time, the complexity will be in O(log(n))


Solution

Mistake Taken

  1. I failed to take into consideration that left is less than right.
    In this case, -1 should be returned.

Code

class Solution:    # @param {integer[]} nums    # @param {integer} target    # @return {integer}    def search(self, nums, target):        if len(nums)==0 or target==None:            return -1        return self.subsearch(nums, target, 0, len(nums)-1 )    def subsearch(self, nums, target, left, right):        mid = (left + right)/2        if nums[mid]==target:            return mid        # size of right portion is larger than left portion        if nums[mid] < nums[right]:            if target>nums[mid] and target<=nums[right]:                left = mid + 1            else:                right = mid - 1        else:            if target>=nums[left] and target<nums[mid]:                right = mid - 1            else:                left = mid + 1        if left > right:            return -1        else:            return self.subsearch(nums,target,left,right)

Other′s Code (using loop)

public int search(int[] A, int target) {      if(A==null || A.length==0)          return -1;      int l = 0;      int r = A.length-1;      while(l<=r)      {          int m = (l+r)/2;          if(target == A[m])              return m;          if(A[m]<A[r])          {              if(target>A[m] && target<=A[r])                  l = m+1;              else                  r = m-1;          }          else          {              if(target>=A[l] && target<A[m])                  r = m-1;              else                  l = m+1;                              }      }      return -1;  }  

Take-home Message

  1. In binary search code, it is possible that left is greater than right.
  2. recursive can be coded in loop format ?


0 0
原创粉丝点击