l2 在二维数组中寻找数字

数组数字从左到右递增
从上到下递增

绿色是剩下查找范围, 永远是跟右上角的数字比较大小

类似

image.png
image.png
image.png
image.png
image.png
#include <iostream>
#include <stack>


//** matrix 数组
//** row 行
//** column 列
//** number 要查找的数字
bool Find(int * matrix, int rows ,int columns, int number) {
    bool found = false;
    
    
    // 算法的核心思想是从右上角往左下角查找,因为左边的数字比右边的数字小,上边的数字比下边小,所以两边同时缩小范围
    if (matrix != NULL && rows > 0 && columns > 0) {
        int row = 0;
        int column = columns - 1;
        while (row < rows && column >= 0 ) {
            if (matrix[row * columns + column] == number) { // 如果发现数字就跳出循环了
                found = true;
                break;
            } else {
                if (matrix [row * columns + column] > number) { // 比右边的数字小,则查找左边的,比右边的数字大,则这一行就不可能有要找的数字
                    column--;
                } else {
                    row++;
                }
            }
        }
        return found;
    }
    return found;
}

int main() {
    int matrix[] = {1,2,8,9,
                   2,3,9,12,
                   4,7,10,13,
                   6,8,11,15};
    
    if (Find(matrix, 4, 4, 7)) {
        printf("found\n");
    } else {
        printf("not found\n");
    }
    
    return 0;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 数组的相关算法要简单一些,之前写过的和现在遇到的整理了一下。 数组:数组是较为简单的数据结构,它占据一块连续的内存...
    zero_sr阅读 5,121评论 0 2
  • 题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输...
    minningl阅读 3,262评论 0 0
  • 原文链接:http://blog.csdn.net/qq_22329521/article/details/529...
    越长越圆阅读 1,475评论 0 2
  • 题目描述:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数...
    柚子槑阅读 1,085评论 0 0
  • virtualenv VENV 建立虚拟机环境django-admin startproject mywebpyt...
    陆文斌阅读 2,338评论 0 0