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

LeetCode:Search in Rotated Sorted Array

时间:2016-01-20 22:15:25      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

Problem:

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 class Solution {
 2 public:
 3     int search(vector<int>& nums, int target) {
 4         int first=0;
 5         int last=nums.size();
 6         
 7         while(first!=last)
 8         {
 9             
10             int middle=(first+last)/2;
11             if(nums[middle]==target)
12                 return middle;
13             else 
14             if(nums[first]<=nums[middle])
15             {
16                if(nums[first]<=target&&target<=nums[middle])
17                 last=middle;
18                 else
19                  first=middle+1;
20             }
21             else
22             {
23                 if(nums[middle]<target&&target<=nums[last-1])
24                     first=middle+1;
25                 else
26                     last=middle;
27             }
28         }
29         
30         return -1;
31     }
32 };

 

LeetCode:Search in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/5146616.html

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