Accepted C Solution with some explanation


  • -1
    R
    bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {
    	if(0==matrixRowSize) return false;
    
    	int p1=0;
    	int p2=matrixRowSize-1;
    	bool bfound=false;
    	int cur;
    	// locate row
    	while(p1<=p2){
    		cur=(p1+p2)/2;
    		if(target<matrix[cur][0]){
    			p2=cur-1;
    			continue;
    		}
    		if(target>matrix[cur][matrixColSize-1]){
    			p1=cur+1;
    			continue;
    		}
    		//found
    		bfound=true;
    		break;
    	}
    
    	if(!bfound) return false;
    
    	int *arr=matrix[cur];
    	p1=0;
    	p2=matrixColSize-1;
    	while(p1<=p2){
    		cur=(p1+p2)/2;
    		if(target==arr[cur]){
    			return true;
    		}
    		if(target<arr[cur]){
    			p2=cur-1;
    		}else{
    			p1=cur+1;
    		}
    	}
        
    	return false;
    }
    

    well, the code is neat enough.first using binary search to locate the array,that may contains the target,u should know what to do next


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.