参考:
题目:
给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,写一个函数搜索 nums
中的 target
,如果目标值存在返回下标,否则返回 -1
。
代码:
C++:
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0;
int r = nums.size();
while(l<r){
int m = l + (r-l) / 2;
if (nums[m] > target){
r = m;
}
else if (nums[m] < target){
l = m+1;
}
else{
return m;
}
}
return -1;
}
};
Python3:
# (l, r)
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
l, r = 0, n
while l < r:
m = l + (r-l)//2
if nums[m] > target:
r = m
elif nums[m] < target:
l = m+1
else:
return m
return -1
# (l, r]
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
l, r = 0, n-1
while l <= r:
m = l + (r-l)//2
if nums[m] > target:
r = m - 1
elif nums[m] < target:
l = m + 1
else:
return m
return -1
思路:
参考:guanpengchn - 力扣(LeetCode),leetcode-solution - 力扣(LeetCode)