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

Leetcode Search in Rotated Sorted Array

时间:2015-02-02 15:36:38      阅读:182      评论: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.

对于这道题,最开始直接线性搜索竟然通过了,但自己感觉过意不去

之后尝试用二分查找法,

技术分享技术分享
如果A[low]<A[mid]说明mid处在区间1中,如果A[low]>A[mid]说明mid处在区间2中
如果A[low]<target<A[mid]则在该区间搜索否则去mid与high之间搜索
同理如果A[mid]<target<A[hight]则在该区间搜索,
复杂度为nlongn
 1  public int search(int[] A, int target) {
 2         return this.binarySearch(A, target, 0, A.length-1);
 3      }
 4      private int binarySearch(int[]A,int target,int low,int hi){
 5          while(low<=hi){
 6          int mid=(low+hi)/2;
 7          if(target==A[mid]) return mid;
 8          if(A[low]>A[mid]){
 9             if(target>A[mid]&&target<A[hi]){
10                 low=mid+1;
11             } else{
12                 hi=mid-1;
13             }
14          }else{
15              if(target<A[mid]&&target>A[low]){
16                  hi=mid-1;
17              }else{
18                  low=mid+1;
19              }
20          }
21          }
22          return -1;
23      }

 

Leetcode Search in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/criseRabbit/p/4267754.html

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