今天双十一买的算法书到货了,路上刷到有人说的这个题,借(chao)鉴(xi)一下别人的思路,这个是C++标准库里面的经典方法,思路精巧,优雅好品味
int search(int* nums, int numsSize, int target) { int left = 0; int right = numsSize -1 ; int middle = 0; while(right>left){ middle = left + (right - left)/2; if(target>nums[middle]){ left = middle+1; }else{ right = middle; } } return target==nums[left]?left:-1;}
看看结果就知道了,性能强悍