Leetcode Study Day 55

Search in Rotated Sorted Array

Description

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= 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 possible 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 an ascending array that is possibly rotated.
-104 <= target <= 104

Solution

If we treat the question as a normal ascending order array, we can use binary search to deal with it easily. For this problem, we need to first check whether the middle element and the the target are in the same half of the array. If they are, we can use the normal binary search. If they are not, we need to check whether the target is in the left half or the right half of the array. If it is in the left half, we can then set the middle and right half part to infinity, and if it is in the right half, we can set the left half part to negative infinity. Then we can use the normal binary search to find the target.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
int left = 0;
int right = n - 1;
while (left <= right){
int middle = left + (right - left) / 2;
int comparator = nums[middle];
// if middle and target are on the same side
if ((nums[middle] >= nums[0] && target >= nums[0]) || (nums[middle] < nums[0] && target < nums[0])){
comparator = nums[middle];
}
else{
if (target >= nums[0]){
comparator = INT_MAX;
}
else{
comparator = INT_MIN;
}
}
if (target == comparator)
return middle;
if (target > comparator){
left = middle + 1;
}
else if (target < comparator){
right = middle - 1;
}
}
return -1;
}
};
  • Copyrights © 2020-2024 Yangyang Cui

请我喝杯咖啡吧~

支付宝
微信