题目来源:https://leetcode.cn/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/
大致题意:
给一个二维数组和 target,其中二维数组每行每列都是升序的
设计一个高效的算法在二维数组中找出 target 是否存在
二分解法
在排序数组中查找元素可以使用二分搜索,这样时间复杂度为 O(logn)
对于该题,可以逐行进行二分搜索,这样的时间复杂度欸 O(mlogn),其中 m 是指行数,n 为列数
代码如下:
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
// 遍历所有一维数组,逐个进行搜索
for (int[] nums : matrix) {
if (binarySearch(nums, target)) {
return true;
}
}
return false;
}
// 在给定数组中二分搜索 target
public boolean binarySearch(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (nums[mid] == target) {
return true;
} else if (nums[mid] > target) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return false;
}
}
双指针解法
类似二分搜索的思路,每次比较都可排除一部分元素
方法如下:
- 开始时位置在二维数组表示矩阵的右上角,可以认为当前位置上方以及右方的元素都是排除掉的
- 那么对于当前位置,若 target 大于当前位置元素,则行指针下移,去有更大元素的行中找 target;若 target 小于当前位置元素,则列指针左移,去有更小元素的列中找 target。指针找到对应元素等于 target,或者指针越界为止
代码:
public boolean findNumberIn2DArray(int[][] matrix, int target) {
int m = matrix.length;
if (m == 0) {
return false;
}
int n = matrix[0].length;
// 指针初始位置
int row = 0;
int col = n - 1;
while (row < m && col >= 0) {
// 找到 target,直接返回
if (matrix[row][col] == target) {
return true;
}
// 大于 target,列指针左移
if (matrix[row][col] > target) {
col--;
} else { // 小于 target,行指针下移
row++;
}
}
return false;
}

这篇博客讨论了两种在二维数组中查找特定目标元素的高效算法:二分解法和双指针解法。二分解法通过逐行进行二分搜索,时间复杂度为O(mlogn)。双指针法从右上角开始,根据目标值与当前位置的比较移动行指针或列指针,时间复杂度为O(m+n)。这两种方法在处理有序二维数组时非常有效。
198

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



