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

leetcode 33. Search in Rotated Sorted Array

时间:2015-02-05 23:22:34      阅读:187      评论: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.

[Solution]

1) A[middle] > A[left], 说明 A[left, middle]有序。

2) A[middle] < A[left], 说明 A[middle, right]有序。 

 1 int search(int A[], int n, int target) 
 2     {
 3         int left = 0, right = n - 1, middle;
 4         
 5         while (left <= right)
 6         {
 7             middle = (left + right) >> 1;
 8             if (A[middle] == target)
 9                 return middle;
10             if (A[middle] > A[left])
11             {
12                 if (target >= A[left] && target < A[middle])
13                     right = middle - 1;
14                 else
15                     left = middle + 1;
16             }
17             else if (A[middle] < A[left])
18             {
19                 if (target > A[middle] && target <= A[right])
20                     left = middle + 1;
21                 else 
22                     right = middle - 1;
23             }
24             else
25             {
26                 middle = right;
27                 break;
28             }
29         }
30         
31         return A[middle] == target ? middle : -1;
32     }

 

leetcode 33. Search in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4276093.html

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