240. Search two dimensional matrix II Java solution

A. Offer B. Offer C. Offer D. Offer

Leetcode-cn.com/problems/se…

[

[1, 4, 7, 11, 15]

[2, 5, 8, 12, 19]

[3, 6, 9, 16, 22]

[10, 13, 14, 17, 24]

[18, 21, 23, 26, 30]

]

First of all, have to say this and his first version of the thought is a bit like, but not exactly the same, because the first version we can narrow the range of values in a row, but doesn’t work here, because this is the key, the final answer value scope will present a distribution of a rectangular shape. The problem requires you to start with the element in the upper right corner or the element in the lower left corner. If the target is larger than the current element, exclude the row; If the target value is smaller than the current element, exclude one of the columns. I put the whole process of looking for a flow chart, convenient for everyone to understand:

With that in mind, let’s look at the code:

show the code.

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null) {
            return false;
        } else if (matrix.length == 0) {
            return false;
        } else if (matrix[0].length == 0) {
            return false;
        }
        int len = matrix.length;
        int rowLen = matrix[0].length;
        int targetCol = rowLen - 1;

        int targetRow = 0;
        while (targetRow < len && targetCol >= 0) {
            if (matrix [targetRow][targetCol] < target) {
                targetRow++;
            } else if (matrix[targetRow][targetCol] > target) {
                targetCol--;
            } else {
                return true; }}return false; }}Copy the code

Time is O (m+n), to see the specific effect, as shown in the screenshot below, or good.