暴力
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;
}
}

这篇博客探讨了三种不同的算法在二维矩阵中查找特定元素的方法。首先介绍了暴力遍历的方法,遍历矩阵的所有元素以找到目标值。接着,展示了贪心策略,通过从右下角开始移动来提高效率。最后,利用二分查找的思想,优化了在有序矩阵列中的搜索过程。这些算法各有优缺点,适用于不同的场景。
1102

被折叠的 条评论
为什么被折叠?



