C语言练习:杨氏矩阵

杨氏矩阵

有一个数字矩阵,矩阵的每行从左到右是递增的,矩阵从上到下是递增的,请编写程序在这样的矩阵中查找某个数字是否存在。

要求:时间复杂度小于O(N);

解法一:利用返回值判断释放某一列是否存在相关数值

#include <stdio.h>
int FindNumber(int n, int arr[2][3])
{
	int col;
	for (col = 3;col >= 0; col--)
	{
		if (arr[0][col] > n)
			continue;
		else
			return col;
	}
	//找不到比要查找值更小的数字
	return -1;
}
int main()
{
	int n;
	printf("请输入要查找的数字:");
	scanf("%d",&n);
	int arr[3][4] = { 
		{2,4,9,18} ,
		{3,8,10,19}, 
		{5,14,12,20} 
	};

	int col= FindNumber(n,arr[3][4],col);

	//利用返回值判断释放某一列是否存在相关数值
	if (col != -1)
	{
		for (int row = 0;row < 3;row++)
		{
			if (arr[row][col] == n)
			{
				printf("找到了位于:%d行%d列\n", row, col);
			}
		}
	}
	printf("找不到\n");

	return 0;
}

 解法二:直接利用寻找行时是否有符合比其更小值,若有直接进行寻找(更简便)

int main() 
{
    int n;
    printf("请输入要查找的数字: ");
    scanf("%d", &n);

    int arr[3][4] = {
        {2, 4, 9, 18},
        {3, 8, 10, 19},
        {5, 14, 12, 20}
    };

    int row = 0;
    int col = 3;

    while (row < 3 && col >= 0) 
    {
        if (arr[row][col] == n) 
        {
            printf("找到了位于:%d行%d列\n", row, col);
            return 0;
        }
        else if (arr[row][col] > n) 
        {
            col--;
        }
        else 
        {
            row++;
        }
    }

    printf("找不到\n");

    return 0;
}

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值