-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInRotatedSortedArrayII.java
More file actions
76 lines (69 loc) · 2.61 KB
/
SearchInRotatedSortedArrayII.java
File metadata and controls
76 lines (69 loc) · 2.61 KB
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
74
75
76
package leetcode;
/**
* SearchInRotatedSortedArrayII
* https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/
* 81. 搜索旋转排序数组 II
* https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/solution/qu-zhong-hou-er-fen-sou-suo-by-oshdyr-zr7b/
*
* @author tobin
* @since 2021-04-07
*/
public class SearchInRotatedSortedArrayII {
public static void main(String[] args) {
SearchInRotatedSortedArrayII sol = new SearchInRotatedSortedArrayII();
System.out.println(sol.search(new int[]{1, 0, 1, 1, 1}, 0));
System.out.println(sol.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 0));
System.out.println(sol.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 1));
System.out.println(sol.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 2));
System.out.println(sol.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 3));
System.out.println(sol.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 4));
System.out.println(sol.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 5));
System.out.println(sol.search(new int[]{2, 5, 6, 6, 6, 6, 0, 0, 1, 2}, 6));
System.out.println(sol.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 7));
System.out.println(sol.search(new int[]{1}, 1));
System.out.println(sol.search(new int[]{1, 2, 3, 0, 1, 1}, 3));
}
public boolean search(int[] nums, int target) {
int lastValue = nums[0] - 1;
int gap = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == lastValue) {
gap++;
}
lastValue = nums[i];
nums[i - gap] = nums[i];
}
int realSize = nums.length - gap;
if (realSize > 1 && nums[realSize - 1] == nums[0]) { // BUG: [1]
realSize--;
}
int begin = 0;
int end = realSize - 1;
while (begin <= end) {
int mid = (begin + end) / 2;
if (target == nums[mid]) {
return true;
}
if (end - begin <= 1) {
if (target == nums[begin] || target == nums[end]) {
return true;
}
return false;
}
if (nums[0] < nums[mid]) {
if (nums[0] <= target && target <= nums[mid]) {
end = mid - 1;
} else {
begin = mid + 1;
}
} else {
if (nums[mid] <= target && target <= nums[realSize - 1]) {
begin = mid + 1;
} else {
end = mid - 1;
}
}
}
return false;
}
}