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

Search in Rotated Sorted Array

时间:2015-04-29 18:49:53      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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.

分析:用二分查找法。mid = (low + high) / 2。考虑如下两种情形:

1. 如果nums[low] <= nums[mid]表示这一段区间是递增的,倘若target的值在两者之间,那么确定上界为mid - 1,否则下界为mid + 1;

2. 如果nums[low] > nums[mid]表示mid在最大值之后(举例: [4, 5, 6,0, 1, 2, 3]。数字0在6之后)如果target在nums[mid]和nums[high]之间,则可确定下界为mid + 1;否则上界为mid - 1。

运行时间7ms

 1 class Solution {
 2 public:
 3     int search(vector<int>& nums, int target) {
 4         if(nums.size() == 0) return -1;
 5         if(nums.size() == 1){
 6             if(nums[0] == target) return 0;
 7             else return -1;
 8         }
 9         
10         int low = 0, high = nums.size()-1;
11         while(low <= high){
12             int mid = (low + high) / 2;
13             if(nums[mid] == target) return mid;
14             if(nums[low] <= nums[mid]){
15                 if(nums[low] <= target && target < nums[mid]) high = mid;
16                 else low = mid + 1;
17             }
18             else{
19                 if(nums[mid] < target && target <= nums[high]) low = mid + 1;
20                 else high = mid;
21             }
22         }
23         return -1;
24     }
25 };

 

Search in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4466325.html

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