首页 > 代码库 > 每日算法之二十九:Search in Rotated Sorted Array

每日算法之二十九:Search in Rotated Sorted Array

在一个经过旋转后的有序数组中查找一个目标元素。

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.

本质上还是通过二分查找来实现的,只是在使用二分查找之前要先找到旋转的节点,在以节点为端点的子段中再次使用二分查找,其中,在寻找旋转点的时候已经使用了二分查找的思想。集体实现可以在代码中窥见。

<span style="font-size:18px;">class Solution {
public:
    int findPivot(int A[],int start,int end)//寻找旋转的点,主要还是对端节点的处理上
    {
      if(start == end)
        return start;
      if(A[end]>A[start])
        return end;
      if(A[start]>A[start+1])
        return start;
      int mid = (start+end)/2;//类似二分查找哈
      if(A[mid]>A[start])
        return findPivot(A,mid,end);
      if(A[mid]<A[end])
        return findPivot(A,start,mid-1);//还是递归实现的
    }
    int binarySearch(int A[],int start,int end,int target)//正宗的二分查找
    {
      while(start<=end)
      {
        int mid = (start+end)/2;
        if(A[mid] == target)
          return mid;
        if(A[mid]<target)
          start = mid+1;
        if(A[mid]>target)
          end = mid -1;
      }
      return -1;
    }
    int search(int A[], int n, int target) {
      int pivot = findPivot(A,0,n-1);//先找到旋转点,再在子段上二分查找
      return target>=A[0]?binarySearch(A,0,pivot,target):binarySearch(A,pivot+1,n-1,target);  //只在一个子段上查找
    }
};</span>