Basic Class lintcode38- Search a 2D Matrix II - medium

Write an efficient algorithm that searches for a value in an m x n matrix, return the occurrence of it.

This matrix has the following properties:

Integers in each row are sorted from left to right.
Integers in each column are sorted from up to bottom.
No duplicate integers in each row or column.
Example
Consider the following matrix:

[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
Given target = 3, return 2.

Challenge
O(m+n) time and O(1) extra space

From the lower left corner to start roaming the right direction. Up to find a small, find a big right.

No major problems associated with this method and I (we can see from the type required time complexity out), the main thought of this idea is based on the conditions of the law.

With the top left and top right corner of significance not only exclude than a
lower left and upper right corner ratio

Supplementary basics]
matrix [0] .length obtain matrix [0] back the length of the array
matrix.length get the length of the array matrix

"Return 0; return is a return type value 0. The method may be byte, int and so return null;. Return null, the null keyword.


public int searchMatrix(int[][] matrix,int target){
	if(matrix==null || matrix.length==0){
		return 0;
	}
	if (matrix[0]==null || matrix[0].length==0){
		return 0;
	}
	
	//from left to top right
	int n=matrix.length;//所以这个指的是行
	int m=matrix[0].length;
	int x=0;
	int y=n-1;
	int count=0;
	
	while(x>=0&&y<m){
		if(matrix[x][y]<target){
			y++;
		}else if (matrix[x][y]>target){
			x--;
		}else{
			count++
			x--;
			y++;
		}
	}
	return count;
}

This question is also not difficult to prior written mainly logical reason clearly

Published 39 original articles · won praise 1 · views 436

Guess you like

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