240. Search a 2D Matrix II

1、題目數組

  一、審題spa

  

  二、分析code

    給出一個二維數組,每一行的元素、每一列的元素均有序。在此數組中查找 target 元素。blog

 

2、解答get

  一、思路class

    方法1、方法

      在每一行中用二分查找法。im

    public boolean searchMatrix(int[][] matrix, int target) {
        
        int rows, cols;
        if(matrix == null || (rows = matrix.length) == 0 || (cols = matrix[0].length) == 0)
            return false;
        
        int row = 0;
        while(row < rows) {
            int start = 0, end = cols - 1;
            if(matrix[row][0] > target)
                return false;
            if(matrix[row][end] < target) {
                row++;
                continue;
            }
            while(start <= end) {
                int mid = (end - start) / 2 + start;
                if(matrix[row][mid] == target)
                    return true;
                else if(matrix[row][mid] < target)
                    start = mid + 1;
                else
                    end = mid - 1;
            }
            row++;
        }
        return false;
    }

 

  方法2、二維數組

    從二維數組的右上角開始向前、向下定位:img

    ①、若 target 小於當前元素,則 target 不可能在當前列,由於列向下爲升序。

    ②、若 target 大於當前元素,則 target 不可能在當前行,由於當前行爲升序。

    public boolean searchMatrix(int[][] matrix, int target) {
        int rows, cols;
        if(matrix == null || (rows = matrix.length) == 0 || (cols = matrix[0].length) == 0)
            return false;
        
        // 從右上角開始查找
        int row = 0, col = cols - 1;
        while(col >= 0 && row < rows) {
            if(target == matrix[row][col])
                return true;
            else if(target < matrix[row][col])
                col--;
            else if(target > matrix[row][col])
                row++;
        }
        return false;
    }
相關文章
相關標籤/搜索