14. First Position of Target 【easy】

14. First Position of Target 【easy】

For a given sorted array (ascending order) and a targetnumber, 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?

解法一:

 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() == ) {
return -;
} int start = ;
int end = array.size() - ; while (start + < end) {
int mid = start + (end - start) / ; if (array[mid] == target) {
end = mid;
}
else if (array[mid] < target) {
start = mid;
}
else if (array[mid] > target) {
end = mid;
}
} if (array[start] == target) {
return start;
} if (array[end] = target) {
return end;
} return -;
}
};

解法二:

 class Solution {
public: int find(vector<int> &array, int start, int end, int target) {
if (start > end) {
return -;
} int mid = start + (end - start) / ; if (array[mid] == target) { if (array[mid - ] != target) {
return mid;
} return find(array, start, mid - , target);
}
else if (array[mid] > target) {
return find(array, start, mid - , target);
}
else if (array[mid] < target) {
return find(array, mid + , end, target);
} } /**
* @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) {
// write your code here int start = ;
int end = array.size(); return find(array, start, end, target); }
};
上一篇:从零开始自己搭建复杂网络(以Tensorflow为例)


下一篇:学习Linux二日稿