[Java] 74. Search two-dimensional matrix --- code optimization, the time complexity is close to O(N)!!!

Write an efficient algorithm to determine whether there is a target value in the mxn matrix. The matrix has the following characteristics:

The integers in each row are arranged in ascending order from left to right.
The first integer in each line is greater than the last integer in the previous line.

Example 1:
Insert picture description here

Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false

prompt:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104

代码:
public boolean searchMatrix(int[][] matrix, int target) {
    
    
		for(int i=0;i<matrix.length;i++) {
    
    
			if(matrix[i][matrix[i].length-1]>=target) {
    
    
				for(int j=0;j<matrix[i].length;j++) {
    
    
					if(matrix[i][j]==target) {
    
    
						return true;
					}
				}
				return false;
			}
		}
    	return false;
    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/115316576