C#版 - 小红书后台开发面试题: 二维数组中的查找
二维数组中的查找
热度指数:24274 时间限制:1秒 空间限制:32768K
本题知识点: 查找
在线提交网址:
http://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&rp=1
题目描述
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数,如果不能找到就输出-1,如果含有请输出所在行数和列数。
给定: n*n矩阵
[ 
[1, 4, 7, 11, 15], 
[2, 5, 8, 12, 19], 
[3, 6, 9, 16, 22], 
[10, 13, 14, 17, 24], 
[18, 21, 23, 26, 30] 
] 
  target = 5 
 Output:
2 2
  target = 26 
 Output:
5 4
  #include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
vector<int> searchMatrix(vector<vector<int> > arr, int target)
{
    vector<int> res;
    int row = arr.size();
    int col = arr[0].size();
    int i = 0, j = col-1;
    bool found = false;
    while(i<=j && j<col && i < row)
    {
        if(arr[i][j] == target)
        {
            found = true;
            res.push_back(i+1);
            res.push_back(j+1);
            break;
        }
        else if(arr[i][j] < target) i++;
        else j--;
    }
    if(arr.size() == 0 || found == false)
    {
        res.push_back(-1);
        return res;
    }
    return res;
}
int main()
{
    vector<int> res;
    int arr[][3] = {{1,3,5}, {2,4,6}, {5,7,9}};
    vector<vector<int> > input;
    input.push_back(vector<int> (arr[0], arr[0]+3) );
    input.push_back(vector<int> (arr[1], arr[1]+3) );
    input.push_back(vector<int> (arr[2], arr[2]+3) );
    res = searchMatrix(input, 12);
    for(auto it:res)
        cout<<it<<' ';
    cout<<endl;
    return 0;
}  牛客网AC代码:
class Solution {
public:
    bool Find(vector<vector<int> > array,int target) {
        int rows=array.size();     // 行数 
        int cols=array[0].size();  // 列数 
        int i=0, j=cols-1;
        bool found = false;
        while(j>=0 && j<cols && i<rows)   // i>=0 默认满足,无须再判断 
        {
            if(array[i][j] == target) { found = true;  break; }               
            else if(array[i][j] > target) j--;  // 如果矩阵右上角的值比target大,删除所在的列,列号-1 
            else i++;                           // 如果矩阵右上角的值不大于target,删除所在的行,行号+1
        }             
        return found;
    }
};

查看19道真题和解析