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;
    }

     

  • 相关阅读:
    map映射的用法
    相似的字串(hash+二分)
    进制 /字符串 hash
    CF#632 C.Eugene and an array
    2020牛客寒假算法基础集训营6 H-云
    Educational Codeforces Round 80 (Div. 2)
    Codeforces Round #601 (Div. 2)补题
    luogu-单调队列/单调栈专题
    Comet OJ
    Comet OJ
  • 原文地址:https://www.cnblogs.com/gqtcgq/p/7247116.html
Copyright © 2011-2022 走看看