Title Link: https://leetcode.com/problems/search-a-2d-matrix-ii/
Topic:
Write an efficient algorithm, searches for a value in a m x n matrix. This matrix has the following properties:
- Integers in each row is sorted in ascending from left to right.
- Integers in each column is 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 , [+], [approx., +, +]]
given target = 5
, Return true
.
Given Target = 20
, return false
.
Ideas:
Start the search from the top left corner. Because Matrix[i][j] is less than all elements of >i or >j, that is, only the elements of 0~i and 0~J cannot determine the size.
Algorithm:
public boolean Searchmatrix (int[][] matrix, int target) { int j = matrix[0].length-1,i=0; while (i<matrix.length&&j>=0) { if (matrix[i][j]>target) { j--; } else if (matrix[i][j]<target) { i++; } else{ return true; } } return false; }
"Leetcode" Search a 2D Matrix II