Search a 2D Matrix
来源:互联网 发布:php post传递数组 编辑:程序博客网 时间:2024/06/06 20:01
题目要求:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
示例:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
Given target = 3
, return true
.
代码实现:
#include<stdafx.h>#include <iostream>#include<vector>using namespace std;class Solution {public:bool searchMatrix(vector<vector<int> > &matrix, int target) { size_t m=matrix.size();size_t n=matrix[0].size();size_t i=0;size_t j=n-1;//从右上角开始找,如果target大于此数,二维矩阵往下找,否则往左找while(j>=0&&i<m){if(matrix[i][j]<target){i++;}else if (matrix[i][j]>target){if(j==0)return false;//此处防止j=0时,j--变成4294967295j--;}elsereturn true;}return false; }};void main(){ //初始化二维矩阵 vector< vector<int>> matrix(3,vector<int>(4,0)); matrix[0][0]=1;matrix[0][1]=3;matrix[0][2]=5;matrix[0][3]=7;matrix[1][0]=10;matrix[1][1]=11;matrix[1][2]=16;matrix[1][3]=20;matrix[2][0]=23;matrix[2][1]=30;matrix[2][2]=34;matrix[2][3]=50;//第一次验证没有通过的一组 /* vector< vector<int>> matrix(3,vector<int>(1,0)); matrix[0][0]=-11;matrix[1][0]=-7;matrix[2][0]=-5;*/Solution s;cout<<s.searchMatrix(matrix,-6)<<endl;getchar();}
0 0
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D matrix
- Search a 2D matrix
- java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;
- do...while(0)的妙用
- iOS开发XCODE5 SVN配置 使用办法
- [Linux实用命令四]文件权限详解
- 位运算的巧用
- Search a 2D Matrix
- PCL库中的PointCloud数据类型
- 1079 Calendar Game
- dl dt dd标签
- Break Word
- Android开发之onSaveInstanceState和SharedPreferences
- 枚举类
- 二叉树的前序中序后序遍历
- 开题