33. 搜索旋转排序数组 Search in Rotated Sorted Array
You are given an integer array nums
sorted in ascending order, and an integer target
.
Suppose that nums
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]
).
If target
is found in the array return its index, otherwise, return -1
.
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
方法:
二分查找,利用至少有一半是递增数列。
public int search(int[] nums, int target) { int l = 0, r = nums.length - 1; while( l <= r ){ int mid = l + (r - l)/2; if( nums[mid] == target) return mid; if(nums[l] <= nums[mid]){ if(nums[l] <= target && nums[mid] > target){ r = mid - 1; }else l = mid + 1; }else{ if( nums[mid] < target && nums[r] >= target){ l = mid + 1; }else r = mid - 1; } } return -1; }
参考链接:
https://leetcode.com/problems/search-in-rotated-sorted-array/
https://leetcode-cn.com/problems/search-in-rotated-sorted-array/