题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
Java代码:
解法一:
class Solution {
public int search(int[] nums, int target) {
if(nums.length > 0){
int right = nums.length - 1;
if(target > nums[right] && target < nums[0])
return -1;
if(target == nums[0])
return 0;
if(target < nums[0]){
while(right >= 0){
if(nums[right] == target)
return right;
if(right > 0 && nums[right] < nums[right-1]) break;
right--;
}
return -1;
}
if(target > nums[0]){
int left = 0;
while(left <= right){
if(nums[left] == target)
return left;
if(left < right && nums[left] > nums[left+1]) break;
left++;
}
return -1;
}
}
return -1;
}
}
解法二(二分法):
class Solution {
public int search(int[] nums, int target) {
if(nums.length > 0){
//判断是否是旋转数组
if(nums[0] < nums[nums.length - 1]){
//非旋转数组
return binarySearch(nums,0,nums.length-1,target);
}else{
//旋转数组
return searchInSpin(nums,0,nums.length-1,target);
}
}
return -1;
}
private int searchInSpin(int[] nums,int left,int right,int target){
if(left == right){
if(nums[left] == target)
return left;
return -1;
}
if(nums[left] > target && target > nums[right])
return -1;
if(right - left == 1){
if(nums[left] == target)
return left;
if(nums[right] == target)
return right;
return -1;
}
if(left < right){
int mid = (left + right) / 2;
//判断哪边是升序数组
if(nums[left] < nums[mid]){
//左边是升序数组
//判断target是否在升序数组中,如果在,就用二分查找在升序数组中寻找
if(target >= nums[left] && target <= nums[mid])
return binarySearch(nums,left,mid,target);
//在旋转数组中
return searchInSpin(nums,mid,right,target);
}else{
//右边是升序数组
if(target >= nums[mid] && target <= nums[right])
return binarySearch(nums,mid,right,target);
//在旋转数组中
return searchInSpin(nums,left,mid,target);
}
}
return -1;
}
private int binarySearch(int[] nums,int left,int right,int target){
while(left <= right){
int mid = (left + right) / 2;
if(nums[mid] == target)
return mid;
if(nums[mid] > target){
right = mid - 1;
}else{
left = mid + 1;
}
}
return -1;
}
}
网友评论