Created
October 15, 2017 11:00
-
-
Save unilecs/684674468cbe9614d560be9572db8b6b to your computer and use it in GitHub Desktop.
Найти элемент в отсортированной матрице
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function searchElementInSortedMatrix(matrix, inputX) { | |
let resultPos = { row: -1, col: -1 }; | |
let row = 0, col = matrix[0].length - 1; | |
// начинаем с 1-й строки и последнего столбца | |
while (row < matrix.length && col >= 0) { | |
if (matrix[row][col] === inputX) { | |
return { row: row, col: col }; | |
} else if (matrix[row][col] > inputX) { | |
// если текущий элемент больше искомого, то уменьшаем номер столбца | |
col--; | |
} else { | |
// если текущий элемент меньше искомого, то увеличиваем номер строки | |
row++; | |
} | |
} | |
// если не нашли искомый элемент в матрице | |
return resultPos; | |
} | |
const matrix = [ | |
[ 1, 5, 10, 20 ], | |
[ 7, 9, 15, 28 ], | |
[ 12, 25, 30, 36 ], | |
[ 22, 35, 45, 50 ] | |
]; | |
console.info(searchElementInSortedMatrix(matrix, 45)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment