JavaScript 程序检查给定矩阵是否为稀疏矩阵


在数学中,矩阵是一组以矩形形式存储的整数或数字,相当于编程或 JavaScript 编程中的二维数组。稀疏矩阵是一种特殊的矩阵,其中零的数量严格大于给定矩阵中存在的元素或数字的总数。我们将得到一个矩阵,我们必须找出当前矩阵是否为稀疏矩阵。

输入

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) 空间复杂度下工作。

更新于: 2023年4月20日

125 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.