首页 > 代码库 > [leetcode]Search in Rotated Sorted Array
[leetcode]Search in Rotated Sorted Array
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 become4 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[mid] == target return mid;
a[mid] < target 分为两种情况
1. a[mid]和target在同半边,begin = mid + 1
2. a[mid]和target在不同的半边,则a[mid]肯定在后面,target在前半边,因此往前找end = mid - 1;
a[mid] > target同理
1. a[mid]和target在同半边,end = mid - 1;
2. a[mid]和target在不同的半边,则a[mid]肯定在前面,target在后半边,因此往前找begin = mid + 1;
代码如下:
1 public class Solution { 2 public int search(int[] a, int target) { 3 if(a == null || a.length == 0) return -1; 4 int begin = 0, end = a.length - 1; 5 while(begin <= end){ 6 int mid = (begin + end) >> 1; 7 if(a[mid] == target){ 8 return mid; 9 }else if(a[mid] < target){10 if(a[mid] < a[begin] && target >= a[begin]){11 end = mid - 1;12 }else{13 begin = mid + 1;14 }15 }else{16 if(a[mid] >= a[begin] && target < a[begin]){17 begin = mid + 1;18 }else{19 end = mid - 1;20 }21 }22 }23 return -1;24 }25 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。