有一个二维数组.
数组的每行从左到右是递增的,每列从上到下是递增的.
在这样的数组中查找一个数字是否存在。
我们以数组
1 2 3
4 5 6
7 8 9
为例
比如这里我们要判断这个数组中是否存在7,我们将7与右上角的3比
因为3,是所在行的最大值,所在列的最小值,与3判断是比较靠谱
7>3 所以往下找一行得到6
7>6 再往下找一行得到9
7<9 往左找一列得到8
7<8 再往左找一列得到7
这个规律也适用于其他数字
具体在代码中实现
#include<stdio.h>
#include<stdlib.h>
#define Row 3
#define Col 3
int Findnum(int(*arr)[Col], int key){
int row = 0;//右上角3所在行
int col = Col - 1;//右上角3所在列
while (row < 3 && col >= 0){
if (key < arr[row][col])
col--;
else if (key>arr[row][col])
row++;
else
return 1;//找到了
}
return -1;//没找到
}
int main(){
int arr[][Col] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
};
printf("%d\n", Findnum(arr, 8));
system("pause");
return 0;
}

java实现:
题目网址:https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
public class Solution {
public boolean Find(int target, int [][] array) {
int row = 0;//右上角元素所在行
int col = array[0].length - 1;//右上角元素所在列
while(row < array.length && col >= 0){
if(target > array[row][col]){
row++;
}
else if(target < array[row][col]){
col--;
}
else{
return true;
}
}
return false;
}
}

本文介绍了如何在一个特殊的二维数组(杨氏矩阵)中查找数字。该矩阵的每行和每列都是递增的。通过比较目标数字与当前单元格的值,可以高效地定位数字。以查找7为例,展示了从右上角开始,根据比较结果向下或向左移动的查找过程。提供了具体的Java代码实现,并给出了题目链接。
260

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



