//★题目:不包含本位置值的累乘数组
//要求:给定一个整型数组arr,返回不包含本位置值的累乘数组。
// 时间复杂度O(N);除需要返回的结果数组外,空间复杂度O(1)
// 例如:arr = [2,3,1,4],返回[12,8,24,6]。除自己外,其他位置上累乘
//分析:主要考虑数组中零元素的个数
#include <iostream>
#include <vector>
using namespace std;
vector<int> multiplication(vector<int> matrix);
void printVector1(vector<int> matrix);
vector<int> generateDesignated1Vector(int *arr, int size);
int main()
{
int arrayMine[4] = { 2, 3, 1, 4 };
int *arr = arrayMine;
vector<int> matrix = generateDesignated1Vector(arr, 4);
printVector1(matrix);
cout << endl;
vector<int> result = multiplication(matrix);
printVector1(result);
system("pause");
return 0;
}
vector<int> multiplication(vector<int> matrix)
{
int multiplication = 1;
int numZero = 0;
int indexZero = 0;
vector<int> result;
result = matrix;
if (matrix.size()<2)
{
return matrix;
}
for (int i = 0; i < matrix.size(); i++)
{
if (matrix[i]==0)
{
numZero++;
indexZero = i;
}
else
{
multiplication *= matrix[i];
}
}
if (numZero == 0)
{
for (int i = 0; i < matrix.size(); i++)
{
result[i] = multiplication / matrix[i];
}
}
else if (numZero == 1)
{
for (int i = 0; i < matrix.size(); i++)
{
if (i==indexZero)
{
result[i] = multiplication;
}
else
{
result[i] = multiplication / matrix[i];
}
}
}
else if (numZero == 2)
{
for (int i = 0; i < matrix.size(); i++)
{
result[i] = 0;
}
}
return result;
}
void printVector1(vector<int> matrix)
{
int size = matrix.size();
for (int i = 0; i < size; i++)
{
cout << matrix[i] << " ";
}
}
vector<int> generateDesignated1Vector(int *arr, int size)
{
int setNum = 0;
int arrIndex = 0;
vector<int> result;
if (size == 0)
{
return result;
}
static int vecIndex = 0;
while (vecIndex < size)
{
setNum = arr[arrIndex];
arrIndex++;
result.push_back(setNum);
vecIndex++;
}
return result;
}
数组与矩阵:不包含本位置值的累乘数组(C++)
最新推荐文章于 2022-09-28 23:22:46 发布