您好,欢迎访问一九零五行业门户网

JavaScript 程序在按行排序的矩阵中查找中位数

我们将描述使用 javascript 在按行排序的矩阵中查找中位数的过程。首先,我们将遍历矩阵以将所有元素收集到一个数组中。然后,我们对数组进行排序以找到中间的值,这将是我们的中位数。如果元素个数为偶数,则中位数为中间两个值的平均值。
方法给定一个按行排序的矩阵,可以通过以下方法找到中位数 -
将所有行合并到一个排序数组中。
找到组合数组的中间元素,这将是中位数。
如果组合数组中的元素数量为奇数,则返回中间元素作为中位数。
如果组合数组中的元素个数为偶数,则返回中间两个元素的平均值作为中位数。
此方法的时间复杂度为 o(m * n log (m * n)),其中 m 是矩阵中的行数,n 是矩阵中的列数。
李>空间复杂度为 o(m * n),因为整个矩阵需要组合成一个数组。
示例这是一个 javascript 函数的完整工作示例,用于查找按行排序的矩阵中的中位数 -
function findmedian(matrix) { // get the total number of elements in the matrix const totalelements = matrix.length * matrix[0].length; // calculate the middle index of the matrix const middleindex = math.floor(totalelements / 2); // initialize start and end variables to keep track of the search space let start = matrix[0][0]; let end = matrix[matrix.length - 1][matrix[0].length - 1]; while (start <= end) { // calculate the mid point let mid = math.floor((start + end) / 2); // initialize a counter to keep track of the number of elements less than or equal to the mid value let count = 0; // initialize a variable to store the row index of the last element less than or equal to the mid value let rowindex = -1; // loop through each row in the matrix for (let i = 0; i < matrix.length; i++) { // use binary search to find the first element greater than the mid value in the current row let columnindex = binarysearch(matrix[i], mid); // if the current row has no element greater than the mid value, increment the count by the length of the row if (columnindex === -1) { count += matrix[i].length; rowindex = i; } else { // otherwise, increment the count by the column index of the first element greater than the mid value count += columnindex; break; } } // check if the count of elements less than or equal to the mid value is greater than or equal to the middle index if (count >= middleindex) { end = mid - 1; } else { start = mid + 1; rowindex++; } // check if we have reached the middle index if (count === middleindex) { return matrix[rowindex][middleindex - count]; } } return start;}// helper function for binary searchfunction binarysearch(arr, target) { let start = 0; let end = arr.length - 1; while (start <= end) { let mid = math.floor((start + end) / 2); if (arr[mid] === target) { return mid; } else if (arr[mid] < target) { start = mid + 1; } else { end = mid - 1; } } return start === 0 ? -1 : start - 1;}const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]];console.log(findmedian(arr));
说明findmedian函数接受矩阵作为参数。它首先分别使用 totalelements 和 middleindex 计算矩阵中的元素总数和中间索引(中位数)。
start和end变量分别初始化为矩阵的第一个和最后一个元素,因为它们是矩阵中的最小值和最大值.
以上就是javascript 程序在按行排序的矩阵中查找中位数的详细内容。
其它类似信息

推荐信息