##Description:
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.
##问题描述
在旋转后的数组中查询某元素,找到返回索引,否则返回-1…
##解法一:
###思路:
虽然数组整体来说不是有序的,但是如果分割成两部分,则两个部分都分别严格有序。。。
###Code:
public class Solution {
public int search(int[] nums, int target) {
int lo = 0;
int hi = nums.length -1;
while(lo <= hi){
int mid = lo + (hi - lo) /2;
if(nums[mid] == target){
return mid;
}
if(nums[lo] <= nums[mid]){
if(target >= nums[lo] && target < nums[mid]){
hi = mid - 1;
}
else{
lo = mid + 1;
}
}else{
if(target > nums[mid] && target <= nums[hi]){
lo = mid + 1;
}
else{
hi = mid -1;
}
}
}
return -1;
}
}
Tips:
需要特别注意这里的判断条件中的*=*