704. 二分查找
为保证权益,题目请参考 704. 二分查找(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
int search(vector<int> &nums, int target)
{
if (nums.size() == 0 || target < nums[0] || target > nums[nums.size() - 1])
{
return -1;
}
int left = 0;
int right = nums.size() - 1;
int m = (left + right) / 2;
while (left <= right)
{
m = (left + right) / 2;
if (nums[m] < target)
{
left = m + 1;
}
else if (nums[m] > target)
{
right = m - 1;
}
else
{
return m;
}
}
return -1;
}
};
int main()
{
return 0;
}
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
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
Python
python
# 704. 二分查找
# https://leetcode-cn.com/problems/binary-search/
################################################################################
# from typing import List
# import bisect
# class Solution:
# def search(self, nums: List[int], target: int) -> int:
# t = bisect.bisect_left(nums, target)
# if t >= len(nums) or t < 0 or nums[t] != target:
# return -1
# return t
################################################################################
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
l = 0
r = len(nums) - 1
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return m
elif nums[m] > target:
r = m - 1
else:
l = m + 1
return -1
################################################################################
if __name__ == "__main__":
solution = Solution()
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
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