题目
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
二分查找:[low,hi]
- 无重复元素,返回target下标
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0, hi = nums.size()-1;//low是查找区间的左边界,hi是右边界
while(low <= hi){
int mid = low + (hi - low) / 2;
if(nums[mid] == target)
return mid;
if(nums[mid] < target){
low = mid + 1;
}else if(targrt < nums[mid])
hi = mid - 1;
}
}
return -1;//未找到
}
};
-
时间复杂度:O(logn)
-
空间复杂度:O(1)
-
有重复元素,返回最左侧边界
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0, hi = nums.size()-1;
while(low <= hi){
int mid = low + (hi - low) / 2;
if(nums[mid] == target)
hi = mid - 1;
if(nums[mid] < target){
low = mid + 1;
}else if(targrt < nums[mid])
hi = mid - 1;
}
}
if(low >= nums.size() || nums[low] != target)
return -1;
return left;
}
};
- 有重复元素,返回最右侧边界
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0, hi = nums.size()-1;//low是查找区间的左边界,hi是右边界
while(low <= hi){
int mid = low + (hi - low) / 2;
if(nums[mid] == target)
low = mid + 1;
if(nums[mid] < target){
low = mid + 1;
}else if(targrt < nums[mid])
hi = mid - 1;
}
}
if(hi < 0 || nums[hi] !=target)
return -1;
return right;
}
};
二分查找[lo, hi)
- 无重复元素,返回target下标
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0, hi = nums.size();/
while(low < hi){
int mid = low + (hi - low) / 2;
if(nums[mid] == target)
return mid;
if(nums[mid] < target){
low = mid + 1;
}else if(targrt < nums[mid])
hi = mid - 1;
}
}
return -1;//未找到
}
};
- 有重复元素,返回最左侧下标
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0, hi = nums.size();//low是查找区间的左边界,hi是右边界
while(low < hi){
int mid = low + (hi - low) / 2;
if(nums[mid] == target)
hi = mid;
if(nums[mid] < target){
low = mid + 1;
}else if(targrt < nums[mid])
hi = mid;
}
}
if(low >= nums.size() || nums[low] != target)
return -1;
return low;
}
};
- 有重复元素,返回最右侧下标
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0, hi = nums.size();
while(low < hi){
int mid = low + (hi - low) / 2;
if(nums[mid] == target)
low = mid +1;
if(nums[mid] < target){
low = mid + 1;
}else if(targrt < nums[mid])
hi = mid;
}
}
if(hi < 0 || nums[hi] != target)
return -1;
return low -1;
}
};
- 类似题目
- 35 搜索插入位置
- 74 搜索二维矩阵
超详解:三种二分法