在C++中,找到d的值以最大化由c[i] = d*a[i] + b[i]创建的数组c[]中零的个数
概念
对于两个给定的包含M个整数的数组,假设存在一个数组C,其中第i个整数将是d*a[i] + b[i],其中d表示任意实数。我们的任务是显示或打印d的值,使得数组C中零的个数最多,并打印零的个数。
输入
a[] = {15, 40, 45}
b[] = {4, 5, 6}输出
Value of d is: -0.133333 The number of zeros in array C is: 1 If we choose d as -0.133333 then we get one zero in the array C which is the maximum possible.
方法
我们遵循以下步骤来解决上述问题:
- 我们将方程改写为d = -b[i]/a[i]
- 实现哈希表来计算任何实数出现的最大次数,以获得d的值。
- 现在,我们得出结论,零的个数将是最大计数 + (a[i]和b[i]都为0的数对个数)。
示例
// C++ program to implement the above
// approach
#include <bits/stdc++.h>
using namespace std;
// Shows function to find the value of d
// and find the number of zeros in the array
void findDandZeros1(int a[], int b[], int m){
// Shows hash table
unordered_map<long double, int> mpp1;
int count1 = 0;
// Performs iteration for i-th element
for (int i = 0; i < m; i++) {
// Now if both are not 0
if (b[i] != 0 && a[i] != 0) {
long double val1 = (long double)(-1.0 * b[i]) /
(long double)(a[i]);
mpp1[val1] += 1;
}
// Now if both are 0
else if (b[i] == 0 && a[i] == 0)
count1 += 1;
}
// Used to find max occurring d
int maxi1 = 0;
for (auto it : mpp1) {
maxi1 = max(it.second, maxi1);
}
// Used to print the d which occurs max times
for (auto it : mpp1) {
if (it.second == maxi1) {
cout << "Value of d is: "
<< it.first << endl;
break;
}
}
// Used to print the number of zeros
cout << "The number of zeros in array C is: "
<< maxi1 + count1;
}
// Driver code
int main(){
int a[] = { 15, 40, 45 };
int b[] = { 4, 5, 6 };
int m = sizeof(a) / sizeof(a[0]);
findDandZeros1(a, b, m);
return 0;
}输出
Value of d is: -0.133333 The number of zeros in array C is: 1
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP