LintCode: First Position of Target
C++
Binary Search
陷阱:找到index最小的。
1 class Solution { 2 public: 3 /** 4 * @param nums: The integer array. 5 * @param target: Target number to find. 6 * @return: The first position of target. Position starts from 0. 7 */ 8 int binarySearch(vector<int> &array, int target) { 9 // write your code here 10 int ret = array.size(); 11 int left = 0, right = array.size()-1; 12 while (left <= right) { 13 int mid = (left + right) >> 1; 14 if (array[mid] == target) { 15 ret = min(ret, mid); 16 right = mid - 1; 17 } 18 if (array[mid] > target) { 19 right = mid - 1; 20 } 21 if (array[mid] < target) { 22 left = mid + 1; 23 } 24 } 25 if (ret == array.size()) { 26 ret = -1; 27 } 28 return ret; 29 } 30 };
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。