我們將描述使用 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 search
function 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 程序在按行排序的矩陣中查找中位數的詳細內容,更多請關注www.92cms.cn其它相關文章!






