在数学中,矩阵是以矩形形式存储的一组整数或数字,相当于编程或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) 空间复杂度工作。