在一个排序数组中找一个数,返回该数出现的任意位置,如果不存在,返回-1
样例
给出数组 [1, 2, 2, 4, 5, 5].
- 对于 target =
2, 返回 1 或者 2. - 对于 target =
5, 返回 4 或者 5. - 对于 target =
6, 返回 -1.
挑战
O(logn) 的时间
class Solution {
public:
/*
* @param nums: An integer array sorted in ascending order
* @param target: An integer
* @return: An integer
*/
int binarySearch(vector<int> &nums,int target,int first,int last){
while(first<last){
int mid=(first+last)/2;
if(nums[mid]==target)
return mid;
else if(nums[mid]>target)
return binarySearch(nums,target,first,mid-1);
else
return binarySearch(nums,target,mid+1,last);
}
return -1;
}
int findPosition(vector<int> &nums, int target) {
// write your code here
int first=0,last=nums.size()-1;
return binarySearch(nums,target,first,last);
}
};
本文介绍了一个在排序数组中查找特定数值并返回其任意位置的算法题目。挑战在于实现O(logn)的时间复杂度。示例包括如何针对不同目标值返回相应索引。
4263

被折叠的 条评论
为什么被折叠?



