Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d491e66

Browse files
committed
solve 33.搜索旋转排序数组
1 parent 46dad1e commit d491e66

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

‎zh/33.搜索旋转排序数组.java‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* @lc app=leetcode.cn id=33 lang=java
3+
*
4+
* [33] 搜索旋转排序数组
5+
*
6+
* https://leetcode-cn.com/problems/search-in-rotated-sorted-array/description/
7+
*
8+
* algorithms
9+
* Medium (37.95%)
10+
* Likes: 821
11+
* Dislikes: 0
12+
* Total Accepted: 140.8K
13+
* Total Submissions: 368.2K
14+
* Testcase Example: '[4,5,6,7,0,1,2]\n0'
15+
*
16+
* 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
17+
*
18+
* ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
19+
*
20+
* 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
21+
*
22+
* 你可以假设数组中不存在重复的元素。
23+
*
24+
* 你的算法时间复杂度必须是 O(log n) 级别。
25+
*
26+
* 示例 1:
27+
*
28+
* 输入: nums = [4,5,6,7,0,1,2], target = 0
29+
* 输出: 4
30+
*
31+
*
32+
* 示例 2:
33+
*
34+
* 输入: nums = [4,5,6,7,0,1,2], target = 3
35+
* 输出: -1
36+
*
37+
*/
38+
39+
// @lc code=start
40+
class Solution {
41+
public int search(int[] nums, int target) {
42+
int left = 0;
43+
int right = nums.length - 1;
44+
45+
while (left <= right) {
46+
int mid = left + (right - left) / 2;
47+
if (nums[mid] == target) {
48+
return mid;
49+
} else if (nums[left] <= nums[mid]) {
50+
if (nums[left] <= target && target < nums[mid]) {
51+
right = mid - 1;
52+
} else {
53+
left = mid + 1;
54+
}
55+
} else {
56+
if (nums[mid] < target && target <= nums[right]) {
57+
left = mid + 1;
58+
} else {
59+
right = mid - 1;
60+
}
61+
}
62+
}
63+
64+
return -1;
65+
}
66+
}
67+
// @lc code=end
68+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /