leetcode解題模板 —— 二分查詢
1.模板
vector<int>& nums
int left = 0;//左邊界
int right = nums.size()-1;//右邊界
int mid = 0;
while(left <= right) {
mid = (left + right) / 2;
if(target == nums[mid]) {/*操作*/ }
if(target < nums[mid]) {
right = mid-1;
}
else {
left = mid+1;
}
}
2.實戰
leetcode 35. 搜尋插入位置
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums.size() == 0) return 0;
int left = 0;
int right = nums.size()-1;
if(nums[left] >= target) {return 0;}
if(nums[right] < target) {return nums.size();}
int mid = 0;
while(left <= right) {
mid = (left + right) / 2;
if(target == nums[mid]) { return mid;}
if(target < nums[mid]) {
right = mid-1;
}
else {
left = mid+1;
}
}
return left;
}
};
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0 || matrix[0].size() == 0) {return false;}
int n = matrix[0].size()-1;
int m = matrix.size()-1;
if(matrix[0][0] > target || matrix[m][n] < target) {return false;}
int left = 0;
int right = m;
int mid = 0;
while(left <= right) {
mid = (left + right) / 2;
if(matrix[mid][0] == target) {return true;}
if(target < matrix[mid][0]){
right = mid -1;
}
else {
left = mid + 1;
}
}
int a = left-1;
left = 0;
right = n;
while(left <= right) {
mid = (left + right) / 2;
if(matrix[a][mid] == target) {return true;}
if(target < matrix[a][mid]){
right = mid -1;
}
else {
left = mid + 1;
}
}
return false;
}
};
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
if(grid.size() == 0 || grid[0].size() == 0) {
return 0;
}
int m = grid.size() - 1;
int n = grid[0].size() - 1;
int ans = 0;
for(int i = 0; i <= m; i++) {
if(grid[i][0] < 0) {
ans += n + 1;
continue;
}
if(grid[i][n] >= 0) {continue;}
int left = 0;
int right = n;
int mid = 0;
while(left < right) {
mid = (left + right) / 2;
if(grid[i][mid] == 0) {
while(mid + 1 <= n && grid[i][mid + 1] == 0) {mid++;}
left = mid +1;
}
if(grid[i][mid] > 0) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
if(grid[i][left]<0){
ans += n - left + 1;
}else {
ans += n - left;
}
}
return ans;
}
};
相關文章
- 二分查詢基礎專題——二分模板
- leetcode——二分查詢LeetCode
- leetcode -- 二分查詢LeetCode
- python二分查詢模板Python
- 每日leetcode——二分查詢LeetCode
- Leetcode 704 二分查詢LeetCode
- 二分查詢-不套用模板
- leetcode題解(查詢表問題)LeetCode
- LeetCode演算法—二分查詢LeetCode演算法
- 詳解二分查詢
- Q1 LeetCode704 二分查詢LeetCode
- 查詢——二分查詢
- 圖解--二分查詢樹圖解
- 德魯週記02 --Leetcode二分查詢題目型別總結LeetCode型別
- 二分查詢 理論 例題
- 力扣刷題-二分查詢力扣
- 二分查詢 - 手寫模板與自帶函式函式
- 二分查詢(一)——純粹的二分查詢
- 二分查詢
- 查詢演算法__二分查詢演算法
- 二分查詢演算法詳解演算法
- 1-陣列-11-二分查詢-LeetCode704陣列LeetCode
- 十分好用的二分查詢模板 手撕二分還怕嗎?
- leetcode1552題解【二分+貪心】LeetCode
- 二分查詢法
- PHP二分查詢PHP
- 查詢演算法之二分查詢演算法
- 二分查詢 | 二分查詢的一種推薦寫法
- 如何找東西?查詢演算法之順序查詢和二分查詢詳解演算法
- Java中關於二分查詢的問題Java
- 704.二分查詢
- labuladong_二分查詢
- 二分查詢(c++)C++
- 二分查詢【折半查詢】演算法 PHP 版演算法PHP
- 【演算法】二分查詢演算法
- 演算法->二分查詢演算法
- 力扣之二分查詢力扣
- 二分查詢的定義