Suppose an array sorted in ascending order 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.
题意:搜索旋转有序数组
复杂度:时间O(logN) 空间O(1)
public class Solution {
public int search(int[] nums, int target) {
int lo = 0, hi = nums.length-1, mid = 0;
while(lo <= hi){
mid = (lo + hi)/2;
if(nums[mid] == target){
return mid;
}
//如果左半部分有序,并且target在左半部分;注意这里的判断有等号存在
if(nums[lo]<=nums[mid]){
if(nums[lo] <= target && target < nums[mid]){
hi = mid - 1;
}else{
lo = mid + 1;
}
//如果右半部分有序,并且target在右半部分
}else{
if(nums[mid] < target && target <= nums[hi]){
lo = mid + 1;
}else{
hi = mid - 1;
}
}
}//其他情况不能满足lo<hi,因为不是有序数组
return -1;
}
}
类似的题目:
81. Search in Rotated Sorted Array II
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order 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
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
题解 : 允许重复元素,则上一题中如果 A[m]>=A[l], 那么 [l,m] 为递增序列的假设就不能成立了,比如 [1,3,1,1,1]。
如果 A[m]>=A[l] 不能确定递增,那就把它拆分成两个条件:
• 若 A[m]>A[l],则区间 [l,m] 一定递增
• 若 A[m]==A[l] 确定不了,那就 l++,往下看一步即可。
public class Solution {
public boolean search(int[] nums, int target) {
int lo = 0, hi = nums.length-1 , mid = 0;
while(lo <= hi){
mid = (lo + hi)/2;
if(nums[mid] == target){
return true;
}
//左半部分
if(nums[lo] < nums[mid]){
if(nums[lo] <= target && target < nums[mid]){
hi = mid - 1;
}else{
lo = mid + 1;
}
}else if(nums[lo] > nums[mid]){
if(nums[mid] < target && target <= nums[hi]){
lo = mid + 1;
}else{
hi = mid - 1;
}
}else{
lo++;
}
}
return false;
}
}
参考:http://blog.csdn.net/ljiabin/article/details/40453607