美文网首页
java数据结构和算法(01)二维数组的查找

java数据结构和算法(01)二维数组的查找

作者: ngu2008 | 来源:发表于2019-06-03 21:24 被阅读0次
    • 题目:在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组array和一个整数target,判断数组中是否含有该整数。补充完成下面的代码:
    public class Solution {
        public boolean Find(int target, int [][] array) {
    
        }
    }
    
    • 思路:二维数组从左到右递增,从上到下递增,越靠近右下方的数越大,首先找到一个起始元素,数组右上角的元素,如果它大于target,向左移动寻找,如果小于target,则向下移动寻找。
    • 最终代码如下:
    public class Solution {
        public boolean Find(int target, int[][] array) {
            int len = array[0].length - 1;
            int i = 0;
            while (len >= 0 && i < array[0].length) {
                if (array[i][len] > target) {
                    len--;
                } else if (array[i][len] < target) {
                    i++;
                } else {
                    return true;
                }
            }
            return false;
        }
    }
    

    相关文章

      网友评论

          本文标题:java数据结构和算法(01)二维数组的查找

          本文链接:https://www.haomeiwen.com/subject/kkwhxctx.html