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

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)