33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order 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.

Your algorithm's runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

题目要求了时间复杂度要O(logn),明显的要求用二分查找实现。该题的难点在于判断旋转点在mid的左边还是右边,以及后面的高低索引的变化。

 1 int search(int* nums, int numsSize, int target) {
 2     int low=0,high=numsSize-1;
 3     while (low<=high){
 4         int mid=low+(high-low)/2;
 5         if(nums[mid]==target)  
 6             return mid;
 7         //只有两种情况,旋转点在mid左边,旋转点在mid右边
 8         if(nums[mid]<nums[low]){
 9                 // 6,7,0,1,2,3,4   5
10                 if (target<nums[mid] || target>=nums[low])
11                     high=mid-1;
12                 else
13                     low=mid+1;
14         }else{
15                 // 2,3,4,5,6,7,0   1
16                 if (target>nums[mid] || target<nums[low])
17                     low=mid+1;
18                 else
19                     high=mid-1;
20             }
21     }
22     return -1;
23 }
原文地址:https://www.cnblogs.com/real1587/p/9822669.html