Code Interview Guide for Programmers Chapter 8 Arrays and Matrix Questions Find numbers in a matrix with ordered rows and columns

topic

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

java code

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));
    }
}

result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325682986&siteId=291194637