码迷,mamicode.com
首页 > 其他好文 > 详细

Search in Rotated Sorted Array

时间:2018-06-26 23:51:01      阅读:298      评论:0      收藏:0      [点我收藏+]

标签:ast   last   targe   unknown   span   code   arch   sts   style   

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.

 1 int Solution::search(const vector<int>& nums, int target) 
 2 {
 3     // 解题思路:当nums[mid] > nums[last-1]时,
 4     // [first,mid]有序,[mid,last)无序,
 5     // 否则[first,mid]无序,[mid,last)有序,
 6     // 因为当 nums[mid] > target 时,target 可能在mid的左边或者右边,
 7     // 所以还要将target 与 nums[first]对比
 8     int first = 0, last = nums.size();
 9     while(first != last) 
10     {
11         const int mid = first + (last - first) / 2;
12         if(nums[mid] == target)
13             return mid;
14         if(nums[mid] > nums[last-1])
15         {
16             if(nums[mid] > target && target >= nums[first])
17                 last = mid;
18             else
19                 first = mid + 1;
20         } else
21         {
22             if(nums[mid] < target && target <= nums[last-1]) 
23                 first = mid + 1;
24             else
25                 last = mid;
26         }
27     }
28     return -1;
29 }

 

Search in Rotated Sorted Array

标签:ast   last   targe   unknown   span   code   arch   sts   style   

原文地址:https://www.cnblogs.com/cccv/p/9231591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!