Sunday, May 19, 2013

Leetcode: Search a 2D Matrix in C++



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.
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
For example,
Consider the following matrix:
Given target = 3, return true.

Solution:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
         if(matrix.size()==0)
         return false;
         int row = matrix.size();
         int column = matrix[0].size();
         int start = 0;
         int end = row-1;
         int mid = 0;
         while(start<=end)
         {
            mid = start+(end-start)/2;
            if(matrix[mid][0]>target)
            {
                end = mid-1;
            }
            else if(matrix[mid][0]<target)
            {
                start = mid+1;
            }
            else
                return true;
         }
         if(end<0)
         return false;
         int cur = end;
         start = 0;
         end = column-1;
         while(start<=end)
         {
            mid = start+(end-start)/2;
            if(matrix[cur][mid]>target)
            {
                end = mid-1;
            }
            else if(matrix[cur][mid]<target)
            {
                start = mid+1;
            }
            else
                return true;
         }
         return false;
    }

No comments:

Post a Comment