2024.1.21 【数组】1.二分查找
力扣 704.二分查找
查找范围:[left,right]
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left <= right){//注意2:带等号,<=空间合法
int mid = left + (right - left) / 2;//注意1:mid放循环里
int num = nums[mid];//注意3:num存储mid位置的值,将其与target进行大小比较
if (num == target) {
return mid;
} else if (num > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
};
时间复杂度:O(logn), n为数组长度
空间复杂度:O(1)
练习1
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int left=0,right=n-1;
while(left <= right){
int mid=left+(right-left)/2;
if(nums[mid]<target)
left=mid+1;
else right=mid-1;
}
return left;
}
};
时间复杂度:O(logn), n为数组长度
空间复杂度:O(1)