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.

假设按照升序排列的数组在事先未知的某个关键点上旋转。(即0 1 2 4 5 6 7可能变成4 5 6 7 0 1 2)。给你一个目标值来搜索。如果在数组中发现它返回其索引,否则返回-1。你可能会认为数组中没有重复。

(1)思想1:直接遍历数组,找到索引值,如果未找到,则返回-1

 1 class Solution {
 2 public:
 3     int search(vector<int>& nums, int target) {
 4        for(int i=0;i<len;i++)
 5         {
 6             if(nums[i]==target)
 7                 return i;
 8         }
 9         return -1;
10     }
11 };

(2)思想2:使用二分法进行查找,二分搜索法的关键在于获得了中间数后,判断下面要搜索左半段还是右半段,通过观察得出规律,如果中间的数小于最右边的数,则右半段是有序的,若中间数大于最右边数,则左半段是有序的,我们只要在有序的半段里用首尾两个数组来判断目标值是否在这一区域内,这样就可以确定保留哪半边了,代码如下:

 1 class Solution {
 2 public:
 3     int search(vector<int>& nums, int target) {
 4         int len=nums.size();
 5         int begin=0;
 6         int end=len-1;
 7         while(begin<=end)
 8         {
 9             int mid=begin+(end-begin)/2;
10             if(nums[mid]==target)
11                 return mid;
12             else if(nums[mid]<nums[end])
13             {
14                 if(nums[mid]<target && nums[end]>=target)
15                     begin=mid+1;
16                 else
17                     end=end-1;
18             }
19             else
20             {
21                 if(nums[mid]>target && nums[begin]<=target)
22                     end=mid-1;
23                 else
24                     begin=begin+1;
25             }
26             
27         }
28         return -1;
29     }
30 };
原文地址:https://www.cnblogs.com/sword-/p/7987250.html