剑指offer 算法题(搜索二维矩阵)

剑指offer 第二题

去力扣里测试算法

思路一:

直接暴力遍历二维数组。

cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        for (unsigned int i{ 0 }; i < matrix.size(); i++)
        {
                for (unsigned int j{ 0 }; j < matrix[i].size(); j++)
                {
                    if (matrix[i][j] == target) {
                        return true;
                    }
                }
        } 
        return false;
    }
};

本地代码:

cpp 复制代码
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int main()
{
    vector<vector<int> > vect{ { 1, 4, 7, 11, 15 },
                                {2, 5, 8, 12, 19},
                                {3, 6, 9, 16, 22},
                                {10, 13, 14, 17, 24},
                                {18, 21, 23, 26, 30}
                                                };
    int target = 30;
    //cout << vec[0].size() << endl;
    //matrix = [[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], target = 5
    for (unsigned int i{ 0 }; i < vect.size(); i++)
    {
        for (unsigned int j{ 0 }; j < vect[i].size(); j++)
        {
            cout << vect[i][j] << " ";
            if (vect[i][j] == target) {
                cout << " " << endl;
                cout << "找到了" << " ";
            }
        }
    }
    return 0;
}

思路二:

相关推荐
Dream it possible!11 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊12 小时前
算法之双指针系列(一)
算法·leetcode
十二12 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
小此方13 小时前
[算法实战论:动态规划]回文串问题的dp解法,回文串问题的母题,以及以此为基础的派生题
算法·动态规划
Pniubi13 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
D e re k ZH14 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
Pniubi14 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
東隅已逝,桑榆非晚17 小时前
算法6. 双指针法-查找总价格为目标的两个商品
c++·学习·算法
Eyfcom17 小时前
〖物联网终端实战 01〗UWB 室内高精度定位:仓储 AGV 与人员的厘米级轨迹追踪
物联网·算法·物流系统·快递系统·跨境物流快递系统·物联网终端实战
bro_Java66618 小时前
《排序的底层逻辑:比较、交换与分治》
java·算法·排序算法