Binary Search in 2D Array

后端 未结 8 1231
南笙
南笙 2021-02-09 17:14

I wonder, can binary search be applied on a 2D array?

  • What would the conditions on the array be? Sorted on 2D??
8条回答
  •  温柔的废话
    2021-02-09 17:40

    Just pretend it's a 1D array and calculate the correct row and column as you divide and conquer:

    /**
    * @param grid {[[number]]} A 2D NxM grid of numbers
    * @param targetValue {number} The target value to search
    * @return {[number]} A list containing the row and column. For example, [0,5] means row 0 column 5 
    */
    function search (grid, targetValue) {
        let rows = grid.length;
        let cols = grid[0].length;
    
        let leftBound = 0;
        let rightBound = rows * cols - 1;
    
        while (true) {
            let currentIndex = parseInt((leftBound + rightBound) / 2);
            let currentRow = parseInt(currentIndex / cols);
            let currentColumn = currentIndex % cols;
            let currentValue = grid[currentRow][currentColumn];
    
            if (currentValue === targetValue) {
                return [currentRow, currentColumn];
            }
            else if (rightBound <= leftBound) {
                return [-1, -1];
            }
            else if (currentValue < targetValue) {
                leftBound = currentIndex + 1;
            }
            else {
                rightBound = currentIndex - 1;
            }
        }
    
    }
    
    search([[11,12,15,23],[25,28,31,32],[35,45,47,47],[50,51,55,56],[65,65,78,88]], 45);
    

提交回复
热议问题