Advertisement
Guest User

Untitled

a guest
May 27th, 2015
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     /**
  4.      * @param matrix: A list of lists of integers
  5.      * @param target: An integer you want to search in matrix
  6.      * @return: An integer indicate the total occurrence of target in the given matrix
  7.      */
  8.     int searchMatrix(vector<vector<int> > &matrix, int target) {
  9.         // write your code here
  10.         int m=matrix.size();
  11.         int n=matrix[0].size();
  12.         return searchRec(matrix, 0, n-1, 0, m-1, target);
  13.     }
  14.    
  15.     int searchRec(vector<vector<int>> &matrix, int l, int r, int u, int d, int target) {
  16.         if(l>r || u>d) return 0;
  17.         int um=u+(d-u)/2;
  18.         int lm=binary(matrix[um], l, r, target);
  19.         int ur=searchRec(matrix, lm, r, u, um-1, target);
  20.         int ld=searchRec(matrix, l, lm-1, um, u, target);
  21.         return (matrix[um][lm]==target? 1:0) + ur + ld;
  22.     }
  23.    
  24.     int binary(vector<int> &row, int l, int r, int target) {
  25.         if(row[r]<target) return r+1;
  26.         int low=l, high=r;
  27.         int mid=(high+low+1)/2;
  28.         while(low<high) {
  29.             if(mid>=target) {
  30.                 high=mid;
  31.             } else {
  32.                 low=mid+1;
  33.             }
  34.             mid=(high+low+1)/2;
  35.         }
  36.         return mid;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement