本文主要是介绍剑指offer 算法题(搜索二维矩阵),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
剑指offer 第二题
去力扣里测试算法
思路一:
直接暴力遍历二维数组。
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;}
};
本地代码:
#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 = 5for (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;
}
思路二:
这篇关于剑指offer 算法题(搜索二维矩阵)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!