###### ＃14 First Position of Target

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.

If the target number does not exist in the array, return -1.

Example

If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.

Challenge

If the count of numbers is bigger than 2^32, can your code work properly?

Mycode（AC ＝ 78ms）：

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<int> &array, int target) {
if (array.size() == 0) return -1;

long long l = 0, r = array.size() - 1;
while (l + 1 < r) {
int mid = l + (r - l) / 2;
if (array[mid] < target) {
l = mid + 1;
}
else if (array[mid] > target) {
r = mid - 1;
}
else {
r = mid;
}
}

if (array[l] == target || array[r] == target) {
return array[l] == target? l : r;
}
else {
return -1;
}
}
};

#### Python全栈工程师-第14周

2018年03月15日 19:37

#### Lintcode14 First Position of Target Solution 题解

2017-04-08 19:09:55

#### First Position of Target

2016-12-02 13:18:03

#### lintcode:First Position of Target

2015-11-17 11:47:33

#### 简单二分法-First Position of Target

2018-01-23 11:07:19

#### Binary Search---First Position of Target

2016-04-03 18:05:01

#### python--二分查找

2017-10-23 10:07:13

#### LintCode 14. First Position of Target

2018-02-07 15:55:42

#### [lintcode 14] First Position of Target

2016-08-07 22:22:49

#### Lintcode 14 first position of target

2018-03-18 09:33:06

## 不良信息举报

＃14 First Position of Target