码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-07 23:28:14      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

Search a 2D Matrix

 Total Accepted: 40009 Total Submissions: 127082My Submissions

 

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;

}

  

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

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4486163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!