แนวคิด
สำหรับอาร์เรย์จำนวนเต็ม M ที่ให้มาสองอาร์เรย์ ให้ถือว่าอาร์เรย์ C โดยที่จำนวนเต็มที่ i-th จะเป็น 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