链接:
https://leetcode.com/problems/search-in-rotated-sorted-array/
大意:
对于一个升序数组(数组中没有重复的两个元素),将这个数组按照其内某个位置旋转(右移)得到一个旋转数组。判断一个数target是否在旋转数组nums中。如果在数组中,则返回在数组中的位置;否则返回-1。要求时间复杂度为O(logn)。例子:
思路:
双指针法。首先查看旋转数组的特点:以某一点为分界,左边和右边都是升序序列(如果分界位置是0,则只有一个升序序列)。对于分界位置不是0的情况,即有两个升序序列,且第二个升序序列的最后一个数字小于第一个升序序列的第一个数字。具体情况分析如下:
(1)数组nums为空或者nums.length == 1并且nums[0] != target时,直接返回-1
(2)记录两个指针s,e。s初始为0,e初始为e.length - 1
(3)判断target和nums[s]以及nums[e]的大小关系。如果 target<nums[s]&&target>nums[e],则直接返回-1;如果 target >= nums[s] ,则遍历旋转数组的左边的升序序列;如果target<=nums[e],则遍历旋转数组的右边的升序序列(按逆序倒着遍历)
代码:
class Solution {
public int search(int[] nums, int target) {
if(nums.length == 0 || nums.length == 1 && nums[0] != target)
return -1;
int s = 0, e = nums.length - 1;
if (target > nums[e] && target < nums[s])
return -1;
if (target <= nums[e]) {
while (e > s && nums[e - 1] < nums[e] && target < nums[e]) {
e--;
}
if (nums[e] == target)
return e;
else
return -1;
} else {
while (s < e && nums[s] < nums[s + 1] && target > nums[s]) {
s++;
}
if (nums[s] == target)
return s;
else
return -1;
}
}
}
结果:
结论:
很基础的一个数组题。清楚旋转数组有什么特点就能解决了