刷题笔记
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.
思路
- 首先找具体位置的部分还是交给二分法查找,所以可以首先单写一个二分法查找的方法。
- 然后就是对情况的分类讨论,一个循环用于判断分裂点,判断条件就是后一个数是否大于前一个数。
- 分裂点P初始设置为nums.length,因为如果有分裂点,循环判断中可以更新;如果没有分裂点,那么下面对情况的判断将直接从0到结尾。
- 最后进行情况的分类,如果target小于第一个数,说明只可能在分裂点之后;如果target等于第一个数,返回0;如果大于第一个数,则只可能在分裂点之前。
代码实现
class Solution {
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
int p = nums.length, index = -1;
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] < nums[i]) {
p = i + 1;
break;
}
}
if (target < nums[0]) index = binarySearch(nums, p, nums.length - 1, target);
else if (target == nums[0]) index = 0;
else index = binarySearch(nums, 0, p - 1, target);
return index;
}
public int binarySearch (int[] nums, int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
}
这是我目前自己写出来的最成功的代码了