ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

二维数组中的查找

2021-11-08 06:31:20  阅读:103  来源: 互联网

标签:rows num nums int cols 二维 查找 数组 const


/*
* 在一个二维数组中,每一行都是按照从左到右
* 递增的顺序排序,每一列都是按照从上到下递增
* 的顺序排序。请完成一个函数,输入这样的一个
二位数组和一个整数,判断数组中是否含有该整数。
*/

/*
* 解法1:暴力搜索法,时间复杂度为O(n^2)
*/

#include<iostream>

using namespace std;

bool search_num(const int* nums,int rows, int cols, const int& num)
{
	if (nums != nullptr && rows > 0 && cols > 0)
	{
		for (int i = 0; i < rows; i++)
		{
			for (int j = 0; j < cols; j++)
			{
				if (nums[i * cols + j] == num)
				{
					return true;
				}
			}
		}
	}

	return false;
}

int main()
{
	const int rows = 4;
	const int cols = 4;
	const int lens = rows * cols;
	int* nums = new int[lens]();
	for (int i = 0; i < lens; ++i)
	{
		nums[i] = i + 1;
	}

	int num;           //要查找的数字
	cin >> num;

	bool result = search_num(nums, rows, cols, num);

	if (result)
	{
		cout << "the matrix has this number." << endl;
	}
	else
	{
		cout << "the matrix do not has this number." << endl;
	}
     
     delete[] nums;
     nums = nullptr;
} /* *解法2:利用搜索数组的特性,首先选取数组中右上角的数字。如果该数字等于要查找的数字,则 * 查找结束;如果该数字大于要查找的数字,则剔除这个数字所在的列;如果这个数字小于要查找 的数字,则剔除这个数字所在的行。这样就可以一步一步的缩小范围了。* */ #include<iostream> using namespace std; bool Find(const int* matrix, int rows, int cols, const int& num) { if (matrix != nullptr && rows > 0 && cols > 0) { int row = 0; int col = cols - 1; while (row < rows && col >= 0) { if (matrix[row * cols + col] == num) { return true; } else if (matrix[row * cols + col] > num) { col--; } else { row++; } } } return false; } int main() { const int rows = 4; const int cols = 4; const int lens = rows * cols; int* nums = new int[lens](); for (int i = 0; i < lens; ++i) { nums[i] = i + 1; } int num; //要查找的数字 cin >> num; bool result = Find(nums, rows, cols, num); if (result) { cout << "the matrix has this number." << endl; } else { cout << "the matrix do not has this number." << endl; }
     delete[] nums;
     nums = nullptr;

}

  

标签:rows,num,nums,int,cols,二维,查找,数组,const
来源: https://www.cnblogs.com/xcxfury001blogs/p/15522593.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有