思路: 二分搜索
-
如果
[l, mid - 1]
是有序数组,且target
的大小满足( nums[l], nums[right] )
则我们应该将搜索范围缩小至[l, mid - 1]
,否则在[mid + 1, r]
中寻找。 -
如果
[mid, r]
是有序数组,且 target 的大小满足( nums[mid+1],nums[r] )
,则我们应该将搜索范围缩小至[mid + 1, r]
,否则在[l, mid - 1]
中寻找。
class Solution {
public int search(int[] nums, int target) {
if (nums.length == 0) return -1;
if (nums.length == 1) return nums[0] == target ? 0 : -1;
return helper(nums, 0, nums.length - 1, target);
}
private int helper(int[] nums, int left, int right, int target) {
if (left <= right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] == target)
return mid;
if (nums[mid] >= nums[left]) {
if (inArea(target, nums, left, mid))
return helper(nums, left, mid - 1, target);
else
return helper(nums, mid + 1, right, target);
} else if (nums[mid] < nums[right]) {
if (inArea(target, nums, mid, right))
return helper(nums, mid + 1, right, target);
else
return helper(nums, left, mid - 1, target);
}
}
return -1;
}
private boolean inArea(int target, int[] nums, int left, int right) {
return target >= nums[left] && target <= nums[right];
}
public static void main(String[] args) {
int[] nums = {3, 1};
System.out.println(new Solution().search(nums, 1));
}
}