暴力
import java.util.*;
public class Solution {
public int[] findElement(int[][] mat, int n, int m, int x) {
// write code here
for(int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if (mat[i][j] == x){
return new int[]{i , j};
}
}
}
return null;
}
}
使用贪心
import java.util.*;
public class Solution {
public int[] findElement(int[][] mat, int n, int m, int x) {
// write code here
int i = n - 1, j = 0;
while (i >= 0 && j < m){
if (mat[i][j] == x) break;
if (mat[i][j] > x) i--;
else j++;
}
return new int[]{i, j};
}
}
使用二分
import java.util.*;
public class Solution {
public int[] findElement(int[][] mat, int n, int m, int x) {
// write code here
for (int i = 0; i < n; i++){
if (mat[i][m - 1] < x) continue;
int left = 0, right = m - 1;
while (left <= right){
int mid = (left + right) >> 1;
if (mat[i][mid] == x) return new int[]{i , mid};
if (mat[i][mid] < x) left = mid + 1;
else right = mid - 1;
}
}
return null;
}
}