《程序员代码面试指南》第八章 数组和矩阵问题 在行列都排好序的矩阵中找数

题目

在行列都排好序的矩阵中找数

java代码

package com.lizhouwei;

/**
 * @Description: 在行列都排好序的矩阵中找数
 * @Author: lizhouwei
 * @CreateDate: 2018/5/7 20:49
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter8_7 {
    public boolean isContains(int[][] matrix, int k) {
        int tR = 0;
        int tC = 0;
        int dR = matrix.length-1;
        int dC = matrix[0].length-1;
        while (tR <= dR && tC <= dC) {
            if (matrix[tR][dC] < k) {
                tR++;
            } else if (matrix[tR][dC] > k) {
                dC--;
            } else {
                return true;
            }
        }
        return false;
    }
    //测试
    public static void main(String[] args) {
        Chapter8_7 chapter = new Chapter8_7();
        int[][] matrix = {{0, 1, 2, 5}, {2, 3, 4, 7}, {4, 4, 4, 8}, {5, 7, 7, 9}};
        System.out.println("矩阵 matrix = {{0,1,2,5},{2,3,4,7},{4,4,4,8},{5,7,7,9}}中");
        System.out.println("是否包含 7:" + chapter.isContains(matrix, 7));
    }
}

结果

猜你喜欢

转载自www.cnblogs.com/lizhouwei/p/9004936.html