One. Problem Description
Prepared by an efficient algorithm to determine the mxn matrix, the presence or absence of a target value. This matrix has the following characteristics:
An integer of from left to right in each row in ascending order.
The first integer is greater than the last row of each integer previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
two. Problem-solving ideas
Problem-solving ideas: the method of binary search to find
Step one: First, the first column binary search to find the number of possible targets in which row.
Step two: target row binary search to determine whether there is a target number (this question Step Two lazy, direct traversal).
three. Results of the
When execution: 1 ms, beat the 78.93% of all users in java submission
Memory consumption: 42.7 MB, defeated 38.63% of all users in java submission
four. Java code
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix==null||matrix.length<=0||matrix[0].length<=0) { return false; } int row=0; int first=0; int second=matrix.length-1; while(first<=second) { row=(first+second)/2; if((row<matrix.length-1&&(matrix[row][0]<=target&&matrix[row+1][0]>target))||((row==matrix.length-1)&&(matrix[row][0]<=target))){ break; } else { if(matrix[row][0]>target) { second=row-1; } else { first=row+1; } } } for(int i=0;i<matrix[row].length;i++) { if(matrix[row][i]==target) { return true; } } return false; } }