-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy path81.搜索旋转排序数组-ii.java
74 lines (70 loc) · 1.71 KB
/
81.搜索旋转排序数组-ii.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* @lc app=leetcode.cn id=81 lang=java
*
* [81] 搜索旋转排序数组 II
*
* https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/description/
*
* algorithms
* Medium (35.56%)
* Likes: 187
* Dislikes: 0
* Total Accepted: 32.3K
* Total Submissions: 90.3K
* Testcase Example: '[2,5,6,0,0,1,2]\n0'
*
* 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
*
* ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。
*
* 编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。
*
* 示例 1:
*
* 输入: nums = [2,5,6,0,0,1,2], target = 0
* 输出: true
*
*
* 示例 2:
*
* 输入: nums = [2,5,6,0,0,1,2], target = 3
* 输出: false
*
* 进阶:
*
*
* 这是 搜索旋转排序数组 的延伸题目,本题中的 nums 可能包含重复元素。
* 这会影响到程序的时间复杂度吗?会有怎样的影响,为什么?
*
*
*/
// @lc code=start
class Solution {
public boolean search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return true;
}
if (nums[left] == nums[mid]) {
left++;
} else if (nums[left] < nums[mid]) {
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else if (nums[left] > nums[mid]) {
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return false;
}
}
// @lc code=end