JavaScript 用于检查给定矩阵是否为稀疏矩阵
在数学中,矩阵是以矩形形式存储的一组整数或数字,与编程或JavaScript编程中的2D数组等效。稀疏矩阵是一种特殊类型的矩阵,其中零的数量严格大于给定矩阵中的总元素或数字的数量。我们将获得一个矩阵,我们必须找出当前矩阵是否为稀疏矩阵。
输入
Mat = [ [1, 0, 0],
[0, 3, 4],
[8, 0, 0]]
输出
Yes, the given matrix is a sparse matrix.
解释
在上面的矩阵中,共有5个零,给定矩阵中的整数总数为9,这意味着当前矩阵是一个稀疏矩阵。
输入
Mat = [ [1, 2, 3, 4],
[0, 0, 0, 0],
[5, 6, 7, 8],
[0, 0, 0, 0]]
输出
No, the given matrix is not a sparse matrix.
解释
在给定的矩阵中,我们总共有16个元素,其中有8个零。根据定义,我们需要大部分元素为零,这意味着超过一半的元素必须是零。
方法
我们已经看过了问题的示例,现在让我们来看一下我们要按照的步骤来实现代码的步骤 –
- 首先,我们将创建一个函数,该函数将以给定的矩阵作为参数,并返回矩阵中零的数量。
-
我们将使用嵌套的for循环遍历矩阵,使用一个变量来存储零的数量。
-
我们将调用函数,并将返回值存储在一个变量中并进行检查。
-
如果零的数量少于或等于总变量数的一半,则将打印出它不是稀疏矩阵。
-
否则,我们将打印给定的矩阵是一个稀疏矩阵。
示例
// function to count number of zeros present in the given matrix
function countZeros(mat){
// getting the number of rows present in the given matrix.
var n = mat.length;
// getting the number of columns present in the given matrix.
var m = mat.length;
var count = 0; // variable to count number of zeros
// traversing over the given matrix
for(var i = 0;i < n; i++){
for(var j = 0; j<m; j++){
// if current element is zero increase the count
if(mat[i][j] == 0){
count++;
}
}
}
// returing true as all the values matched
return count;
}
// defining the matrix
var mat = [ [1, 0, 0],
[0, 3, 4],
[8, 0, 0]]
console.log("The given matrix is: ")
console.log(mat);
// counting number of zeros in the given matrix
var zeros = countZeros(mat);
var size = (mat.length)*(mat[0].length);
if(zeros > size/2){
console.log("The given matrix is a sparse matrix")
}
else{
console.log("The given matrix is not a sparse matrix")
}
时间和空间复杂度
上述代码的时间复杂度为O(N*M),其中N是给定矩阵的行数,M是给定矩阵的列数。
上述代码的空间复杂度为O(1),因为我们没有使用任何额外的空间来存储矩阵。
结论
在本教程中,我们实现了一个JavaScript程序来检查给定的矩阵是否为稀疏矩阵。稀疏矩阵是一种特殊类型的矩阵,其中零的个数严格大于给定矩阵中的元素或数字的总数。我们实现的代码的时间复杂度为O(N*M),空间复杂度为O(1)。