How to find the sort Matrix in LeetCode
Today, I will talk to you about how to find the sorting matrix in LeetCode. Many people may not know much about it. In order to let everyone know more, Xiaobian summarized the following contents for everyone. I hope you can gain something according to this article.
1. Brief description of the problem
Given an M×N matrix, where each row and column is arranged in ascending order, write code to find an element.
2, example
Examples:
The existing matrix is as follows:
[ [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, returns true.
Given target = 20, returns false.
3, the solution to the problem
Normal solutions.
4, the solution program
public class SearchMatrixTest2 { public static void main(String[] args) { int[][] 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} }; int target = 5; boolean searchMatrix = searchMatrix(matrix, target); System.out.println("searchMatrix = " + searchMatrix); }
public static boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return false; } int rowLength = 0; int colLength = matrix[0].length - 1; while (rowLength
< matrix.length && colLength >= 0) { if (matrix[rowLength][colLength] == target) { return true; } else if (matrix[rowLength][colLength] > target) { colLength--; } else { rowLength++; } } return false; }}
5, the solution program picture version
After reading the above, do you have any further understanding of how to find the sorting matrix in LeetCode? If you still want to know more knowledge or related content, please pay attention to the industry information channel, thank you for your support.