题目:搜索二维矩阵

来源:互联网 发布:qq弃号扫号软件 编辑:程序博客网 时间:2024/04/30 00:22
通过

写出一个高效的算法来搜索 m × n矩阵中的值。

这个矩阵具有以下特性:

  • 每行中的整数从左到右是排序的。
  • 每行的第一个数大于上一行的最后一个整数。

您在真实的面试中是否遇到过这个题?

Yes


哪家公司问你的这个题?AirbnbAlibaba Amazon Apple Baidu Bloomberg Cisco Dropbox Ebay Facebook Google Hulu Intel Linkedin Microsoft NetEase Nvidia Oracle Pinterest Snapchat Tencent Twitter Uber Xiaomi Yahoo Yelp Zenefits
感谢您的反馈
样例

考虑下列矩阵:

[  [1, 3, 5, 7],  [10, 11, 16, 20],  [23, 30, 34, 50]]

给出 target = 3,返回 true

挑战

O(log(n) + log(m)) 时间复杂度

标签 Expand

二分法矩阵


public class Solution {
    /**
     * @param matrix, a list of lists of integers
     * @param target, an integer
     * @return a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
          if (matrix == null || matrix.length == 0) {
               return false;
          }
          int m = matrix.length;
          int n = matrix[0].length;
          int x = 0;
          int y = n - 1;
          while (x >= 0 && y >= 0 && x < m && y < n) {
               if (matrix[x][y] == target) {
                    return true;
               } else if (matrix[x][y] < target) {
                    x = x + 1;
               } else if (matrix[x][y] > target) {
                    y = y - 1;
               }
          }
          return false;
    }
}


0 0
原创粉丝点击