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

Search in Rotated Sorted Array

时间:2014-12-08 17:35:48      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

Search in Rotated Sorted Array 

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.

这道题主要思路:先找到pivot,查找pivot过程中前面的已经查找过,只需对后面的进行二分查找即可

 1 public class Solution {
 2     public int search(int[] A, int target) {
 3         int i = 0;
 4         for(; i < A.length; i++){
 5             if(i > 0 && A[i - 1] > A[i])            //找出轴的位置
 6                 break;
 7             if(A[i] == target)
 8                 return i;
 9         }
10         if(i == A.length)                            //没有找到
11             return -1;
12         //从轴的位置到最后开始二分查找从i的位置开始到length - 1
13         int low = i;
14         int high = A.length - 1;
15         int middle;
16         while(low <= high){
17             middle = (low + high) / 2;
18             if(A[middle] == target)
19                 return middle;
20             else if(A[middle] > target){        //前半段找
21                 high = middle - 1;
22             }else{                                //后半段找
23                 low = middle + 1;
24             }
25         }
26         
27         return  -1;
28     }
29 }

 

Search in Rotated Sorted Array

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/luckygxf/p/4151368.html

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