Log(n) solutions in java


  • -1
    M

    class solution{
    public boolean searchMatrix(int[][] matrix, int target) {
    boolean result=false;
    if(matrix.length==0){
    return false;
    }
    int width=matrix[0].length-1;
    int len=matrix.length-1;
    for(int i=0;i<matrix.length;i++){
    if(target<=matrix[i][width]&&target>=matrix[i][0]){
    result=searchForOneRow(matrix[i],target);
    }
    }
    return result;
    }

    private boolean searchForOneRow(int[] nums, int target) {
    	int left=0;int right=nums.length-1;
    	boolean result=false;
    	for(int i=0;i<nums.length;i++){
    		int mid=(left+right)/2;
    		if(target<nums[mid]){
    			right=mid;
    		}
    		if(target>nums[mid]){
    			left=mid+1;
    		}
    		else if(target==nums[mid]){
    			return true;
    		}
    		else if(left==right&& result==false){
    			return false;
    		}
    	}
    	return false;
    }
    

    }


Log in to reply
 

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