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.分治法(TLE了)O(mn)。从左上角出发。利用好如果这个点都不是target了,那目标肯定不会出现在右下角这个性质及时停止搜索止损。如果当前点大了,那肯定没希望了;如果当前点就是目标,那已经成功了;如果当前点小了,分治,向右或者向下找,拆成两个子问题。因

2.行走法 O(m + n)。从右上角出发。利用好如果当前点大了,这列向下都不可能了,向左走;如果当前点小了,这行向左都不可能了,向下走这个性质。用好性质不一定最差情况要走遍所有格子,走一条路径即可。

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

第二种方法

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

参考学习对象,只为自己存档和分享
https://www.cnblogs.com/jasminemzy/p/7977055.html

发布了39 篇原创文章 · 获赞 1 · 访问量 434

猜你喜欢

转载自blog.csdn.net/qq_40647378/article/details/103997859