二维数组中的查找

    科技2022-07-15  119

    //在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序, //每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个 //整数,判断数组中是否含有该整数。 #include<vector> #include<iostream> using namespace std; class Solution { public: bool Find(int target, vector<vector<int>> array) { //根据题意可与左下角或右下角的元素比较,缩小查找范围,类似二分 int y = array.size(); if (y == 0) return false; int x = array[0].size(); if (x == 0) return false; y = 0; x = x - 1; while (y < array.size() && x >= 0) { if (target == array[y][x]) return true; else if (target > array[y][x]) { y += 1; } else { x -= 1; } } return false; } };
    Processed: 0.014, SQL: 8