C++ 程序 矩阵中偶数和奇数数字的频率
给定一个m×n矩阵,任务是找到矩阵中偶数和奇数数字的频率。
示例:
Input : m = 3, n = 3
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
Output : Frequency of odd number = 5
Frequency of even number = 4
Input : m = 3, n = 3
{ 10, 11, 12 },
{ 13, 14, 15 },
{ 16, 17, 18 }
Output : Frequency of odd number = 4
Frequency of even number = 5
// C++ Program to Find the frequency
// of even and odd numbers in a matrix
# include <bits/stdc++.h>
using namespace std;
# define MAX 100
// function for calculating frequency
void freq(int ar[][MAX], int m, int n)
{
int even = 0, odd = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
// modulo by 2 to check
// even and odd
if ((ar[i][j] % 2) == 0)
++even;
else
++odd;
}
}
// print Frequency of numbers
cout << "Frequency of odd number = " << odd << endl;
cout << "Frequency of even number = " << even << endl;
}
// Driver code
int main()
{
int m = 3, n = 3;
int array[][MAX]
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
freq(array, m, n);
return 0;
}
输出
Frequency of odd number = 5
Frequency of even number = 4
时间复杂度: O(m*n),其中 m 是给定矩阵中的行数, n 是给定矩阵中的列数。
辅助空间: O(1)
方法:使用递归方法
// C++ Program to Find the frequency
// of even and odd numbers in a matrix
# include <bits/stdc++.h>
using namespace std;
# define MAX 100
int even = 0, odd = 0;
void freq(int ar[][MAX], int m, int n, int i, int j) {
if (i == m) //基本条件
{
cout << "Frequency of odd number = " << odd << endl;
cout << "Frequency of even number = " << even << endl;
return;
}
if (j == n)
{
freq(ar, m, n, i+1, 0); //递归调用
return;
}
if (ar[i][j] & 1)
++odd;
else
++even;
freq(ar, m, n, i, j+1); //递归调用
}
int main() {
int m = 3,n = 3;
int array[][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
freq(array, m, n, 0, 0);
return 0;
}
输出
Frequency of odd number = 5
Frequency of even number = 4
时间复杂度: O(m*n)
,其中 m 是给定矩阵中的行数, n 是给定矩阵中的列数。
辅助空间: O(m*n) ,每次调用函数freq在调用堆栈中占用O(1)的空间,调用次数为m*n
。