#14 First Position of Target
2016-08-30 13:11
204 查看
题目描述:
For a given sorted array (ascending order) and a
find the first index of this number in
If the target number does not exist in the array, return
Have you met this question in a real interview?
Yes
Example
If the array is
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) {
// write your code here
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;
}
}
};
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.
Have you met this question in a real interview?
Yes
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) {
// write your code here
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;
}
}
};
相关文章推荐
- Lintcode14 First Position of Target Solution 题解
- Lintcode 14 first position of target
- lintcode:First Position of Target
- 【简单】Lintcode 14:First Position of Target
- lintcode:First Position of Target
- Lintcode: First Position of Target (Binary Search)
- 简单二分法-First Position of Target
- lintcode-easy-First Position of Target
- first-position-of-target
- [LintCode] 14 First Position of Target
- Binary Search---First Position of Target
- LintCode: First Position of Target
- [lintcode 14] First Position of Target
- last position of target / first position of target
- First Position of Target
- [lintcode 14] First Position of Target
- First Position of Target
- 二分查找(first-position-of-target)
- [LeetCode] Search for a Range (sorted integers array,find start & end position of a target number)
- last-position-of-target