Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二维数组中的查找 #16

Open
xuexueq opened this issue Sep 25, 2018 · 0 comments
Open

二维数组中的查找 #16

xuexueq opened this issue Sep 25, 2018 · 0 comments
Labels
剑指offer 剑指offer 数据结构与算法 数据结构与算法

Comments

@xuexueq
Copy link
Owner

xuexueq commented Sep 25, 2018

题目描述

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

地址:https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路

在二位数组中查找,由于数组是有顺序的,所以在右上角或者左下角开始查找,每次比较大小都能排除一行或者一列,一直循环找下去即可。

做法:采用while循环,每比较一次就按查找的目标前进一行或者一列

function Find(arr, target) {
    let row = arr.length; // 列数
    let i = row - 1;
    let j = 0;
    while(row >= 0 && arr[i][j]) {
        if(arr[i][j] < target) {
            j++;
        } else if(arr[i][j] > target) {
            i--;
        } else {
            return true;
        }
    }
    return false;
}
Find([[1,2,8,9],[2,4,9,12],[4,7,10,13]],10)
@xuexueq xuexueq added 数据结构与算法 数据结构与算法 剑指offer 剑指offer labels Sep 25, 2018
@xuexueq xuexueq changed the title 【剑指offer】二维数组中的查找 二维数组中的查找 Sep 25, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
剑指offer 剑指offer 数据结构与算法 数据结构与算法
Projects
None yet
Development

No branches or pull requests

1 participant