您的位置:首页 > 其它

leecode 解题总结:74. Search a 2D Matrix

2017-02-12 09:50 344 查看
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
/*
问题:
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.
分析:程序员面试金典的一道题目。关键是要寻找一个位置如果值小于该位置上的元素,就往一个方向走;
值大于该位置上的元素,就往另一个方向走。也就是能够根据给定待查找的值和当前位置上的元素的大小决定
不同的走向。比如这里如果选择右上角,那么如果待查找元素<该右上角位置的元素,直接往左走,如果待查找
元素>该右上角的位置,就往下走。同理:左下角的位置也是可以的。而左上角向右和向下都是大于当前元素,不符合。

输入:
3(行数) 4(列数) 3(待查找元素)
1 3 5 7
10 11 16 20
23 30 34 50

3 4 -1
1 3 5 7
10 11 16 20
23 30 34 50

3 4 200
1 3 5 7
10 11 16 20
23 30 34 50

2 1 0
1
3
输出:
true
false
false

关键:
1 能够根据给定待查找的值和当前位置上的元素的大小决定
不同的走向
//如果一行为空,直接返回
if(matrix.at(0).empty())
{
return false;
}
int curCol = col - 1;//列数减1

*/
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty())
{
return false;
}
int row = matrix.size();
//如果一行为空,直接返回
if(matrix.at(0).empty())
{
return false;
}
int col = matrix.at(0).size();

//从右上角开始寻找
int curRow = 0;
int curCol = col - 1;//列数减1
while(curRow < row && curCol >= 0 )
{
if( matrix.at(curRow).at(curCol) == target )
{
return true;
}
//向下查找,行号累加
else if(matrix.at(curRow).at(curCol) < target)
{
curRow++;
}
else
{
curCol--;
}
}
return false;
}
};

void print(vector<vector<int> >& result)
{
if(result.empty())
{
cout << "no result" << endl;
return;
}
int size = result.size();
int len;
for(int i = 0 ; i < size ; i++)
{
len = result.at(i).size();
for(int j = 0 ; j < len ; j++)
{
cout << result.at(i).at(j) << " " ;
}
cout << endl;
}
}

void process()
{
vector<vector<int> > nums;
int value;
int row;
int col;
Solution solution;
vector<vector<int> > result;
int searchValue;
while(cin >> row >> col >> searchValue )
{
nums.clear();
for(int i = 0 ; i < row ; i++)
{
vector<int> data;
for(int j = 0 ; j < col ; j++)
{
cin >> value;
data.push_back(value);
}
nums.push_back(data);
}
bool isFind = solution.searchMatrix(nums , searchValue);
if(isFind)
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}
}

int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: