用于查找矩阵中奇数和偶数频率的Java程序
矩阵只是一个二维数组。就像在一维遍历操作中需要弄清楚一样。任务是找到给定矩阵中奇数和偶数的频率。
The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n
这里在矩阵
- M = 矩阵中的行数
- N = 列数
例子:
Input : M = 3
N = 5
Output: Odd Number Frequency = 9
Even Number Frequency = 6
Input : M = 3
N = 3
{{1, 2, 5},
{6, 7, 9},
{3, 2, 1}}
Output: Odd Number Frequency = 6
Even Number Frequency = 3
方法
- 将两个计数器初始化为偶数 = 0 & 奇数 = 0
- 遍历矩阵中存在的每个元素并检查是否 (element % 2 == 0)
- 如果是,则增加 even++
- 否则增加奇数++
下面是该方法在Java中的实现
Java
// Importing Classes/Files
import java.io.*;
class GFG {
// Function to compute frequency of odd/even numbers
public static void findFreq(int[][] arr, int m, int n)
{
// Initializing the counter variables
int even = 0, odd = 0;
// Nested if loops
// Traversing through each
// element in the matrix
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Checking if the element
// is divisible by 2
if (arr[i][j] % 2 == 0) {
// Increment even counter
even++;
}
else {
// Increment odd counter
odd++;
}
}
}
// Printing Counts of Enen
// and odd numbers in matrix
System.out.println("Odd Number Frequency: " + odd);
System.out.println("Even Number Frequence: "
+ even);
}
// Main Driver Method
public static void main(String[] args)
{
// Providing inputs to the matrix
int m = 3, n = 5;
// Here, m = Number of rows,
// n = Number of columns
// Entering elements in the matrix
int[][] arr = { { 3, 4, 5, 6, 3 },
{ 4, 3, 2, 7, 9 },
{ 1, 5, 7, 2, 4 } };
// Calling function to count frequency by
// passing inputs to the function findFreq
findFreq(arr, m, n);
}
}
输出
Odd Number Frequency: 9
Even Number Frequence: 6
时间复杂度:当遍历一维数组时,它取决于执行操作的数组的大小,因为其余执行要么具有相同的顺序,要么在内存(变量)中占用一些恒定空间。这里遍历行的所有元素以及矩阵中的每一行。所以它取决于行和列的乘积。因此,时间复杂度为阶(度)
空间复杂度:只是将内存分配给变量,然后在变量的范围内释放。因为没有为要执行的操作创建其他辅助空间。因此,所需的空间是恒定的,然后释放。默认分配 1,因此空间复杂度为 1。
Time Complexity = O(Rows*Columns) or O(m * n)
Space Complexity = O(1)