zoukankan      html  css  js  c++  java
  • C#版

    二维数组中的查找

    题目描述

    在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数,如果不能找到就输出-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;
        }
    };
  • 相关阅读:
    POJ 1265 Pcik定理
    POJ 1380 坐标旋转
    POJ 1788
    POJ 3714 平面最近点对
    POJ 1905 二分
    POJ 1151 矩形面积并
    POJ 1654 多边形面积
    ZOJ 1010 判断简单多边形+求面积
    about work
    Python 打印 不换行
  • 原文地址:https://www.cnblogs.com/enjoy233/p/10408744.html
Copyright © 2011-2022 走看看