首页 > 代码库 > 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.
思路分析:这题同样考察二分查找,但是是在rotation之后的数组中进行二分查找。这题的特点是,每次二分后,至少有一半是有序的,另一半是无序的(受到了rotation的影响)。所以要利用这一特性,通过比较target和有序的那半边数组的最小数和最大数,来决定l和m的更新规则。具体而言
1.如果target = A[m] 返回m
2 如果target 不等于A[m]
2.1 如果A[m] < A[r],说明A[m...r]有序,没有收到rotation影响,可以判断target是否在A[m...r]范围内,如果是更新l=m+1;否则更新r=m-1
2.2 如果A[m] >= A[r],说明A[l...m]有序,没有收到rotation影响,可以判断target是否在A[l...m]范围内,如果是更新r=m-1;否则更新l=m+1
所以利用每次仍然有序的半边数组,我们仍然可以进行二分查找,更新l和r,每次缩小一半的搜索范围,时间复杂度O(log(n)),空间复杂度O(1),只有常数级别的额外空间。注意判断target是否在A[m...r]范围和target是否在A[l...m]范围内的时候,要考虑target == A[r]和target == A[l]的情况,二分查找的实现等号情况的考虑要特别小心。
AC 时间:5min。
AC Code
public class Solution { public int search(int[] A, int target) { //02:46 if(A == null || A.length == 0) return -1; int l = 0; int r = A.length - 1; while(l <= r){ int m = (l + r) / 2; if(target == A[m]) return m; else{ if(A[m] < A[r]){ //m ... r is sorted if(target <= A[r] && target > A[m]) { l = m + 1; } else { r = m - 1; } } else { //l ... m is sorted if(target >= A[l] && target < A[m]){ r = m -1; } else { l = m + 1; } } } } return -1; } //02:51 }
LeetCode Search in Rotated Sorted Array