leetcode33
4/27/2020 算法二分搜索
# 解题思路
和二分没有太大的差别 思想还是分治法,只要设置好进入子区间不同的判定条件就好了
# 代码
class Solution {
public int search(int[] nums, int target) {
if (nums.length == 0) {
return -1;
}
int n = nums.length - 1;
if (n == 0) {
return nums[0] == target ? 0 : -1;
}
int s = 0, e = nums.length - 1;
while (s <= e) {
int mid = (e + s) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] >=nums[s]) {
if (nums[s] > target || nums[mid] < target) {
s = mid+1;
} else {
e = mid-1;
}
} else {
if (nums[mid] > target || nums[e] < target) {
e = mid-1;
} else {
s = mid+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
24
25
26
27
28
29
30
31
32
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