题解 | #二分查找-一种直接赋值middle给left/right的方法I#
二分查找-I
http://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b
int search(vector<int>& nums, int target) {
// write code here
int len = nums.size();
if(len<=0) return -1;
int left = 0;
int right = len-1;
int middle = (left + right)/2;//防止溢出写法另鉴
if(nums[0]==target) return 0;
if(nums[len-1]==target) return len-1;
while(middle!=left&&middle!=right)
{
if(nums[middle]<target)
left=middle;
else if(nums[middle]>target)
right = middle;
else if(nums[middle]==target)
return middle;
middle = (left+right)/2;
}
return -1;
}
};