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.

     

            思路:这是一个非常典型的二分查找法的应用场景,只不过是把一维数组扩展成了二维数组,因此,解题的关键是将二维数组“转换”为一维数组。代码如下:

    int searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) 
    {
    	int begin = 0, end =  matrixColSize *   matrixRowSize - 1;
    	int mid;
    	int row, col;
    
    	while(begin <= end)
    	{
    		mid = begin+(end-begin)/2;
    		row = mid/matrixColSize;
    		col = mid%matrixColSize;
    
    		if(matrix[row][col] == target)	return 1;
    
    		if(matrix[row][col] < target)	begin = mid+1;
    		else	end = mid-1;
    	}
    	return 0;
    }

     

  • 相关阅读:
    发送邮件程序
    T-SQL存储过程、游标
    GPS经纬度换算成XY坐标
    开博了
    你应该知道的 50 个 Python 单行代码
    想提升java知识的同学请进
    adb工具包使用方法
    红米note3刷安卓原生
    hadoop 使用和javaAPI
    django学习——url的name
  • 原文地址:https://www.cnblogs.com/gqtcgq/p/7247116.html
Copyright © 2011-2022 走看看