来源

LC:二维数组中的查找
牛客:二维数组中的查找

题目描述

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

代码

  1. public class Solution {
  2. public boolean Find(int [][] array,int target) {
  3. if(array.length == 0){
  4. return false;
  5. }
  6. int row=0;
  7. int col=array[0].length-1;
  8. while(row<=array.length-1&&col>=0){
  9. if(target==array[row][col])
  10. return true;
  11. else if(target>array[row][col])
  12. row++;
  13. else
  14. col--;
  15. }
  16. return false;
  17. }
  18. }
  1. bool findNumberIn2DArray(vector<vector<int>> &matrix, int target) {
  2. if (matrix.empty()) {
  3. return false;
  4. }
  5. int col = 0;
  6. int row = matrix[0].size() - 1;
  7. while (col < matrix.size() && row >= 0) {
  8. if (matrix[col][row] == target) {
  9. return true;
  10. } else if (matrix[col][row] > target) {
  11. row--;
  12. } else {
  13. col ++;
  14. }
  15. }
  16. return false;
  17. }