ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

剑指Offer 04.二维数组中查找

2021-03-03 09:01:59  阅读:180  来源: 互联网

标签:sy sx return target 04 Offer int 查找 matrix


package Offer;

import com.sun.org.apache.xalan.internal.xsltc.trax.SmartTransformerFactoryImpl;

//二维数组中的查找
//巧妙地选取位置,使得每一次比较后,都能缩小查询的范围
//可以每次选取右上角或者左下角
/*
1 2 8  9
2 4 9  12
4 7 10 13
6 8 11 15
 */
public class Test4 {

    //枚举右上角的值
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if (matrix == null || matrix.length <= 0 || matrix[0].length <= 0) {
            return false;
        }

        int row = matrix.length, col = matrix[0].length;

        int sx = 0, sy = col - 1;

        //每次枚举右上角的值
        while (sx < row && sy >=0) {
            if (matrix[sx][sy] == target) {
                return true;
            } else if (matrix[sx][sy] > target) {   //当前位置比target大,删除当前位置所在的列
                sy--;
            } else {    //当前位置比target小,删除当前位置所在的行
                sx++;
            }
        }
        return false;
    }

    //枚举左下角的值
    public boolean findNumberIn2DArray2(int[][] matrix, int target) {
        if (matrix == null || matrix.length <= 0 || matrix[0].length <= 0) {
            return false;
        }

        int row = matrix.length, col = matrix[0].length;

        int sx = row - 1, sy = 0;
        //每次枚举左下角的值
        while (sx >=0 && sy < col) {
            if (matrix[sx][sy] == target) {
                return true;
            } else if (matrix[sx][sy] > target) {   //"删除当前行"
                sx--;
            } else {
                sy++;
            }
        }
        return false;
    }
}

 

标签:sy,sx,return,target,04,Offer,int,查找,matrix
来源: https://www.cnblogs.com/xiazhenbin/p/14472505.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有