74. Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.

Simply use binary search. Time complexity is O(logn). No extra space used.

    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix.length == 0) return false;
        int length = matrix.length * matrix[0].length;
        int left = 0;
        int right = length - 1;
        while (left <= right) {
            int mid = (left + right)/2;
            int row = mid / matrix[0].length;
            int col = mid % matrix[0].length;
            if (matrix[row][col]==target){
                return true;
            }
            else if(matrix[row][col]<target){
                left = mid+1;
            }
            else right = mid -1;

        }
        return false;
    }

--

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 春天,叶子用自己的嫩绿表达欣喜。 夏天,叶子为小鸟和路人遮风挡雨。 秋天,叶子用绚丽的色彩演绎华章。 冬天,叶子平...
    洛神婺女阅读 1,616评论 2 2
  • 你知道吗我有两个姐姐,小时候啊,在我心里,她们都是我的超人。 今天,我想说说我大姐,她呀小学没毕业,十三岁出门打工...
    陈默梓阅读 2,490评论 1 2
  • 我从迷糊中惊醒,满怀疑虑的倾听了一番,可是只有风的呼啸和那夹杂的雨点下落的声音,根本没有什么其奇怪的。我暗自嘲笑自...
    尹涓生阅读 2,944评论 0 0
  • 藏在心里的话,换个身份说给你听 (一)朋友或者恋人,都是被对方的优点所吸引而成为朋友或恋人,但关系是否能够继续...
    大萍子耶阅读 2,865评论 0 1

友情链接更多精彩内容