Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to find the sort Matrix in LeetCode

Shulou Source: shulou.com Published: 2022-06-02 05:29:47 10月04日 Update

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.

Tags: Matrix problem solving content sorting ideas examples programs one line code elements ascending order pictures more knowledge articles industry information channels questions channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Tech Info Shulou Information Shulou Technology MariaDB