算法:搜索数字,从有逆序的顺序数组33. Search in Rotated Sorted Array
Posted 架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:搜索数字,从有逆序的顺序数组33. Search in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。
33. Search in Rotated Sorted Array
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Example 3:
Input: nums = [1], target = 0
Output: -1
Constraints:
1 <= nums.length <= 5000
-104 <= nums[i] <= 104
All values of nums are unique.
nums is guaranteed to be rotated at some pivot.
-104 <= target <= 104
解法
想象一下二分法,判断有序的部分,
- 如果target在于
min < target < max
中,则直接在这份范围里找, - 否则肯定在另一部分。
以此类推
class Solution {
public int search(int[] nums, int target) {
return helper(nums, target, 0, nums.length -1);
}
private int helper(int[] nums, int target, int l, int r) {
if (l > r) {
return -1;
}
int mid = l + ((r - l) >> 1);
if (nums[mid] == target) {
return mid;
}
if (nums[l] <= nums[mid]) {
if (nums[mid] > target && nums[l] <= target) {
return helper(nums, target, l, mid - 1);
} else {
return helper(nums, target, mid + 1, r);
}
} else {
if (nums[r] >= target && nums[mid] < target) {
return helper(nums, target, mid + 1, r);
} else {
return helper(nums, target, l, mid - 1);
}
}
}
}
以上是关于算法:搜索数字,从有逆序的顺序数组33. Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章