题目链接:Search in Rotated Sorted Array
Suppose an array sorted in ascending order 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).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
参考:https://blog.csdn.net/linhuanmars/article/details/20525681
题意:对于一个已经排序好的在特定情况下进行翻转的数组中,查找特定值target,如果存在则返回下标,不存在返回-1;
解题思路:这道题是一道查找题,是二分查找的变形;对于进行特定翻转的数组,其有一个性质就是,从中间元素分开,那么肯定有一侧元素是已经排序好的。
所以对于数组,设left为左端,right为右端,mid = (left+right)/2 为中间点,那么有以下几种情
况:
(1)如果target==A[mid],直接返回mid;
(2)如果A[mid] < A[right],则表示mid右边是有序的且一定是升序,所有判断target是不是在A[mid]到A[right]之间,如果说明target在右边,否则到左边去找;
(3)如果A[mid] >= A[right],则表示左边有序且一定是升序,则同样判断target是否在A[left]到A[mid]之间,若在说明target在左边,否则到右边去找;
代码实现如下:
class Solution {
public int search(int[] nums, int target) {
int len = nums.length;
int left = 0;
int right = len-1;
int mid;
while(left<=right){
mid = (left+right)/2;
if(target == nums[mid])
return mid;
if(nums[mid] < nums[right]){
if(target>nums[mid] && target<=nums[right]){
left = mid + 1;
}
else{
right = mid - 1;
}
}
else {
if(target>= nums[left] && target<nums[mid]){
right = mid - 1;
}
else{
left = mid + 1;
}
}
}
return -1;
}
}
根据上诉算法,每次可以去除一半的数据,所以算法的时间复杂度为O(logn),空间复杂度为O(1)。