题解 | #矩阵元素查找#
矩阵元素查找
https://www.nowcoder.com/practice/3afe6fabdb2c46ed98f06cfd9a20f2ce
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param mat int整型二维数组 * @param n int整型 * @param m int整型 * @param x int整型 * @return int整型一维数组 */ public int[] findElement (int[][] mat, int n, int m, int x) { // write code here int[] res = new int[2]; // for (int i = 0; i < n; i ++) { // for (int j = 0; j < m; j ++) { // if (mat[i][j] == x) { // res[0] = i; // res[1] = j; // break; // } // } // } int i = 0; int j = m - 1; while (i < n && j >= 0) { if (mat[i][j] == x) { res[0] = i; res[1] = j; break; } if (mat[i][j] > x) { j --; } else { i ++; } } return res; } }