二分查找的JAVA实现如下:
class Solution {
public int search(int[] nums, int target) {
int low = 0;
int high = nums.length-1;
while(low<=high){
int middle = low+(high-low)/2;
if(target>nums[middle]){
low=middle+1;
}else if (target<nums[middle]){
high=middle-1;
}else{
return middle;
}
}
return -1;
}
}
二分查找的Python实现如下:
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low=0
high=len(nums)-1
while low<=high:
middle=low+(high-low)/2
if target>nums[middle]:
low=middle+1
elif target<nums[middle]:
high=middle-1
else:
return middle
return -1