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.

從第0行末尾元素開始,當做中間元素,比他大的一定在下一行,小的一定在同一行。總的時間複雜度。O(MAX(M,N));

#include <iostream>
#include <string>
#include <vector>

using namespace std;

bool searchMatrix(vector<vector<int> > &matrix, int target);

int main()
{
	int A[][4]={{1,3,5,7},{10,11,16,20},{23,30,34,50}};
	vector<vector<int> > matrix(4,vector<int> (4));

	for(int i = 0;i < matrix.size();i++)
	{
		for(int j = 0;j < matrix[0].size();j++)
		{
			matrix[i][j] = A[i][j];
		}
	}
	int val;
	cin>>val;
	if(searchMatrix(matrix,val))
	{
		cout<<"true"<<endl;
	}
	else
	{
		cout<<"false"<<endl;
	}
	return 0;
}


bool searchMatrix(vector<vector<int> > &matrix, int target)
{
	if(matrix.empty())return false;

	int row = 0;
	int cloumn = matrix[0].size()-1;//開始爲第0行末尾元素
	
	while(row < matrix.size() && cloumn >=0)
	{
		if(matrix[row][cloumn] == target)
		{
			return true;
		}
		else if(matrix[row][cloumn] > target)//同列查找
		{
			cloumn -- ;
		}
		else//下一行查找
		{
			row++;
		}
	}
	return false;
}

思路二:對於此題可以想象把該矩陣拉伸成一維數組,因爲此處有從小到大關係。進行定位是轉換爲二維座標即可。時間複雜度O(lg(M*N));

 bool searchMatrix(vector<vector<int> > &matrix, int target)
    {
    	if(matrix.empty())return false;	 
    
    	int left_index = 0;
    	int right_index = matrix.size()*matrix[0].size()-1;
    	int mid = 0;
    
    	while(left_index <= right_index)
    	{
    		mid = (left_index + right_index)/2;
    		if(matrix[mid/matrix[0].size()][mid%matrix[0].size()] == target)//轉換成二位座標定位
    		{
    			return true;
    		}
    		else if(matrix[mid/matrix[0].size()][mid%matrix[0].size()] < target)//轉換成二位座標定位

    		{
    			left_index = mid + 1;
    		}
    		else
    		{
    			right_index = mid - 1;
    		}
    	}
    
    	return false;
    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章