leetcode240- Search a 2D Matrix II- medium

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following matrix:

[
[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]
]
Given target = 5, return true.

Given target = 20, return false.

1. Divide and Conquer (TLE a) O (mn). Starting from the top left corner. If you make good use of this point it is not a target, and that target is certainly not appear in the lower right corner of the nature of the stop in time to stop the search. If the current big point, it is certainly no hope; if the current point is the goal, it has been a success; if the current spot small, divide and conquer, looking to the right or down, split into two sub-problems. because

2. Method walking O (m + n). From the upper right corner. If the current point and make good use of, this column can not down, and go left; if the current small point, and this line can not the left, go down this nature. Good use of nature is not necessarily the worst case will pass through all the grid and follow a path.

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        return helper(matrix, target, 0, 0);
    }
    
    private boolean helper(int[][] matrix, int target, int x, int y) {
        if ( x >= matrix.length || y >= matrix[0].length || matrix[x][y] > target ) {
            return false;
        }
        if (matrix[x][y] == target) {
            return true;
        }
        if (helper(matrix, target, x + 1, y) || helper(matrix, target, x, y + 1)) {
            return true;
        }
        return false;
    }
}

The second method

public class Solution{
	public boolean searchMatrix(int[][] maxtrix, int target){//想清楚这一行怎么写的
		if(maxtrix==null||matrix.length==null||matrix[0].length==null){
			return false;
		}
	    int x=0;
		int y=maxtrix[0].length-1;
		while(isInBound(matrix,x,y)&&matrix[x][y]!=target){
			if(maxtrix[x][y]>target){
				y--;
			}else{
				x++;
			}
		}
		if(isInBound(matrix,x,y)){
			return true;
		}
		return flase;
	}
	private isInBound(int[][] matrix,int x,int y){
		return x>=0&&x<matrix.length&&y>=0&&y<matrix[0].length;
	}
}

Reference learning objects, archiving and sharing only for themselves
https://www.cnblogs.com/jasminemzy/p/7977055.html

Published 39 original articles · won praise 1 · views 434

Guess you like

Origin blog.csdn.net/qq_40647378/article/details/103997859