给定一个排序的整数数组(升序)和一个要查找的整数target
,用O(logn)
的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1
。
样例
在数组 [1, 2, 3, 3, 4, 5, 10]
中二分查找3
,返回2
。
class Solution {public: /** * @param nums: The integer array. * @param target: Target number to find. * @return: The first position of target. Position starts from 0. */ int binarySearch(vector &array, int target) { // write your code here if (array.empty()) return -1; int left = 0, right = array.size() - 1; int mid = 0; while (left <= right) { mid = left + (right - left) / 2; if (array[mid] < target) left = mid + 1; else right = mid - 1; } if (array[left] == target) return left; else return -1; }};// 1335 ms