当前位置:网站首页>剑指 Offer 04. 二维数组中的查找
剑指 Offer 04. 二维数组中的查找
2022-06-25 15:32:00 【anieoo】

solution:
暴力模拟,时间复杂度O(m * n)
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
for(auto &x : matrix)
for(auto &y : x) {
if(y == target) return true;
}
return false;
}
};逐行进行二分查找时间复杂度O(nlogn)
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
if (matrix.size() == 0 || matrix[0].size() == 0)
return false;
for(int i = 0;i < n;i++) {
if(binSearch(matrix[i], target)) return true;
}
return false;
}
bool binSearch(vector<int> &nums, int target) {
int l = 0,r = nums.size() - 1;
while(l < r) {
int mid = l + (r - l) / 2;
if(nums[mid] >= target) r = mid;
else l = mid + 1;
}
if(nums[l] == target) return true;
return false;
}
};从右上角开始查找,如果matrix[x][y] > target,y++,else x--
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0 || matrix[0].size() == 0) return false;
int n = matrix.size(),m = matrix[0].size();
int x = n - 1,y = 0;
while(x >= 0 && y < m) {
if(matrix[x][y] == target) return true;
if(matrix[x][y] < target) y++;
else x--;
}
return false;
}
};
边栏推荐
- AB string interchange
- Summary of four parameter adjustment methods for machine learning
- 在国信金太阳开股票账户安全吗?
- QT article outline
- Common operations in VIM
- QT set process startup and self startup
- One code per day - day one
- MySQL field truncation principle and source code analysis
- Shared memory synchronous encapsulation
- Thread - learning notes
猜你喜欢

剑指 Offer 05. 替换空格

Talk about the creation process of JVM objects
![[paper notes] street view change detection with deconvolutional networks](/img/2d/777fd0d85ff4d349516b95923410fd.jpg)
[paper notes] street view change detection with deconvolutional networks

System Verilog — interface

google_ Breakpad crash detection

Yolov5 Lite: fewer parameters, higher accuracy and faster detection speed
![[paper notes] overview of case segmentation](/img/93/57ad42e0c058b7d5fd1b4066678707.jpg)
[paper notes] overview of case segmentation

Js- get the mouse coordinates and follow them

Globally unique key generation strategy - implementation principle of the sender

Single user mode
随机推荐
55 specific ways to improve program design (1)
How to download and install Weka package
iconv_ Open returns error code 22
0703 interface automation - MySQL database connection, encapsulation, adding database verification in use cases
剑指 Offer 06. 从尾到头打印链表
JS select all exercise
Kali SSH Remote Login
在打新债开户证券安全吗,需要什么准备
解决Visio和office365安装兼容问题
CV pre training model set
在国信金太阳开股票账户安全吗?
1090.Phone List
[paper notes] overview of case segmentation
到底要不要去外包公司?这篇带你全面了解外包那些坑!
MySQL performance optimization - index optimization
Why do I need message idempotence?
Weka download and installation
[paper notes] semi supervised object detection (ssod)
双目3D感知(一):双目初步认识
Business layer - upper and lower computer communication protocol