剑指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;
}

思路二:

相关推荐
CS创新实验室1 小时前
算法、齿轮与硅基大脑:数值计算发展简史
人工智能·算法·数值计算
海石3 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石3 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx3 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
imbackneverdie4 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃5 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录6 小时前
prompt-optimizer skill
算法
万法若空7 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表
退休倒计时7 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
学逆向的7 小时前
汇编——内存
开发语言·汇编·算法·网络安全