C/C++ 基础算法2

146 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

C/C++ 基础算法2

二维数组中的查找

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

示例:
现有矩阵 matrix 如下:
[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false// matrix 二维数组
// matrixW 宽
// matrixH 高
// target 是否存在目标值
int findNumberIn2DArray(int** matrix, int matrixW,, int matrixH,  int target){

}

实现/思路

#include <iostream>

using namespace std;

//二分查找
bool BinaryLook(int* arr, int value, int start, int end)
{
	while (start <= end)
	{
		int mid = (start + end) / 2;
		if (arr[mid] > value)
			end = mid - 1;
		else if (arr[mid] < value)
			start = mid + 1;
		else
			return true;
	}
	return false;
}

int findNumberIn2DArray(int** matrix, int matrixW, int matrixH, int target)
{
	int i = 0;
	int flag = -1;
	int a = matrix[i][5 - 1];
	while (i < matrixH)
	{
		if (target >= matrix[i][0] && target <= matrix[i][matrixW - 1])
		{
			if (BinaryLook(matrix[i], target, 0, matrixW - 1))
			{
				flag = 1;
				break;
			}
		}
		i++;
	}
	return flag == -1 ? -1 : 1;
}


//思路:以行为单位,判断target是否满足:target>=matrix[i][0]&&target<=matrix[i][matrixW-1],
//满足则使用二分查找,不满足则i++后循环反复判断比较。
int main()
{
	int matrix[5][5] =
	{
		{1,   4,  7, 11, 15},
		{2,   5,  8, 12, 19},
		{3,   6,  9, 16, 22},
		{10, 13, 14, 17, 24},
		{18, 21, 23, 26, 30}
	};
	int* ptrArr[5];
	for (int i = 0; i < 5; i++)
		ptrArr[i] = matrix[i];
	if (findNumberIn2DArray(ptrArr, 5, 5, 31) == 1)
		cout << "true" << endl;
	else cout << "false" << endl;
	return 0;
}

数值的整数次方(快速幂)

实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,x^n)。不得使用库函数,同时不需要考虑大数问题。

输入:x = 2.00000, n = 10
输出:1024.00000

输入:x = 2.10000, n = 3
输出:9.26100

输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25

double myPow(double x, int n){

}

实现/思路

方式一:

参考链接:https://blog.csdn.net/FanShenDeXianYu/article/details/119190295

double myPow(double x, int n)
{
	double res = 1.0;
	for (int i = n; i != 0; i /= 2)
	{
		if (i % 2 != 0)
			res *= x;
		x *= x;
	}
	return res;
}

方式二:

只要是偶数个数相乘,比如2*2*2*2,实际上我们不需要使用三次乘法,只需要使用两次乘法就可,因为2*2为4,此时不需要再次乘2,只需要乘以4即可,这个过程省略了一次乘法。

double myPow(double x, int n)
{
	double res = 1.0;
	int count = 0;
	int N = n < 0 ? -1 * n : n;
	while (N != 1 && N % 2 == 0)
	{
		++count;
		N /= 2;
	}

	for (int i = 1; i <= N; i++)
		res *= x;
	for (int j = 1; j <= count; j++)
		res *= res;
	return n < 0 ? 1 / res : res;
}

版权声明:本文为CSDN博主「ufgnix0802」的原创文章:
原文链接:blog.csdn.net/qq135595696…