您的位置:首页 > 其它

leetcode_74题——Search a 2D Matrix(数组查找)

2015-05-07 21:46 459 查看

Search a 2D Matrix

Total Accepted: 40009 Total Submissions: 127082My Submissions
Question Solution

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.

For example,

Consider the following matrix:

[
[1,   3,  5,  7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

Given target =
3
, return
true
.

Hide Tags
Array Binary Search

Have you met this question in a real interview?
Yes

No

Discuss

#include<iostream>
#include <vector>
using namespace std;

/*这道题是在一个排好序的数组中查找一个指定的数
从上到下递增,从左到右递增,所以从右往左,每次与最上面的那个数作比较*/
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int x=matrix.size();
int y=matrix[0].size();

for(int j=y-1;j>=0;j--)
{
if(target==matrix[0][j])
return true;
if(target>matrix[0][j])
{
for(int i=1;i<=x-1;i++)
if(target==matrix[i][j])
return true;
}
}
return false;
}

int main()
{
vector<vector<int> > vec0;
vector<int> vec;
vec.push_back(1);
vec0.push_back(vec);
vec.clear();
vec.push_back(3);
vec0.push_back(vec);
cout<<searchMatrix(vec0,3)<<endl;

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: