Leetcode hot100
- 二分查找
- 1. 搜索插入位置
- 2. 搜索二维矩阵
二分查找
1. 搜索插入位置
搜索插入位置
标准二分的写法:
复杂度分析
时间复杂度:O(logn),其中 n 为数组的长度。二分查找所需的时间复杂度为 O(logn)。
空间复杂度:O(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 = ((right - left) / 2) + left;if (target <= nums[mid]) {right = mid - 1;} else {left = mid + 1;}}return left;}
};
2. 搜索二维矩阵
搜索二维矩阵
方法一:先二分确定列,再二分确定行
方法二:把二维n * m展开为一维数组,需要注意的是一维数组中下标为N的数,在二维数组中的对于坐标为[N / m][N % m]
class Solution {
public:bool searchMatrix(vector<vector<int>>& matrix, int target) {int n = matrix.size(), m = matrix[0].size();int low = 0, high = m * n - 1;while (low <= high) {int mid = low + (high - low) / 2;int x = matrix[mid / m][mid % m];if (x < target) low = mid + 1;else if (x > target) high = mid - 1;else return true;}return false;}
};