首页 > 代码库 > Leetcode Search in Rotated Sorted Array
Leetcode 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.
对于这道题,最开始直接线性搜索竟然通过了,但自己感觉过意不去
之后尝试用二分查找法,
如果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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。