leetcode33 Search in Rotated Sorted Array
# 33. 搜索旋转排序数组 (opens new window)
English Version (opens new window)
# 题目描述
整数数组 nums
按升序排列,数组中的值 互不相同 。
在传递给函数之前,nums
在预先未知的某个下标 k
(0 <= k < nums.length
)上进行了 旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
(下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7]
在下标 3
处经旋转后可能变为 [4,5,6,7,0,1,2]
。
给你 旋转后 的数组 nums
和一个整数 target
,如果 nums
中存在这个目标值 target
,则返回它的下标,否则返回 -1
。
示例 1:
输入:nums = [4,5,6,7,0,1,2]
, target = 0
输出:4
示例 2:
输入:nums = [4,5,6,7,0,1,2]
, target = 3
输出:-1
示例 3:
输入:nums = [1], target = 0 输出:-1
提示:
1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
nums
中的每个值都 独一无二- 题目数据保证
nums
在预先未知的某个下标上进行了旋转 -10^4 <= target <= 10^4
进阶:你可以设计一个时间复杂度为 O(log n)
的解决方案吗?
# 解法
二分查找。
# Python3
class Solution:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) >> 1
if nums[mid] == target:
return mid
if nums[mid] > target:
if nums[mid] >= nums[r] and target < nums[l]:
l = mid + 1
else:
r = mid - 1
else:
if nums[mid] <= nums[l] and target > nums[r]:
r = mid - 1
else:
l = mid + 1
return -1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Java
class Solution {
public int search(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l <= r) {
int mid = (l + r) >>> 1;
if (nums[mid] == target) return mid;
if (nums[mid] > target) {
if (nums[mid] >= nums[r] && target < nums[l]) l = mid + 1;
else r = mid - 1;
} else {
if (nums[mid] <= nums[l] && target > nums[r]) r = mid - 1;
else l = mid + 1;
}
}
return -1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# C++
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int mid = (l + r) >> 1;
if (nums[mid] == target) return mid;
if (nums[mid] > target) {
if (nums[mid] >= nums[r] && target < nums[l]) l = mid + 1;
else r = mid - 1;
} else {
if (nums[mid] <= nums[l] && target > nums[r]) r = mid - 1;
else l = mid + 1;
}
}
return -1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# JavaScript
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function (nums, target) {
let l = 0, r = nums.length - 1;
if (l > r) return -1;
while (l <= r) {
let mid = l + Math.floor((r - l) / 2);
if (nums[mid] === target) return mid;
else if (nums[mid] <= nums[r] && target <= nums[r] && target >= nums[mid])
l = mid + 1;
else if (nums[mid] >= nums[l] && target <= nums[mid] && target >= nums[l])
r = mid - 1;
else if (nums[mid] >= nums[r])
l = mid + 1;
else if (nums[mid] <= nums[l])
r = mid - 1;
else return -1;
}
return -1;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38