zoukankan      html  css  js  c++  java
  • 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.

    根据上面的条件可以看出,该数组从左往后依次增加。所以可以将二维数组拉长看成一位数组,然后使用二分查找。重点是对于看成一维数组后的位置要对应到二维数组的位置。

    class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            if(matrix==null||matrix.length==0) return false;
            int m=matrix.length;
            int n=matrix[0].length;
            int left=0,right=m*n-1;   //看成一位数组,然后根据第几个元素转到二维数组的对应位置
            while(left<=right){
                int mid=(left+right)/2;  //mid 表示第几个元素.重点是根据这个中间值找到它对应的行和列
                int mid_value=matrix[mid/n][mid%n];
                if(mid_value==target) return true;
                else if(mid_value>target) right=mid-1;
                else left=mid+1;
            }
            return false;
        }
    }
  • 相关阅读:
    架构之道(1)
    看板管理(1)
    交互原型图
    Sequence Diagram时序图
    安卓项目的「轻」架构
    安卓ButtomBar实现方法
    工具类BitMap 把网络URL图片转换成BitMap
    使用OkHttp上传图片到服务器
    BaseAdapter教程(2) BaseAdapter的notifyDataSetChanged动态刷新
    开发中时间变换问题汇总
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8213621.html
Copyright © 2011-2022 走看看