mardi 15 juin 2021

Difference between flow of if....if block and if....else block

So I was just solving this question the previous day

https://leetcode.com/problems/search-a-2d-matrix-ii/

I was able to solve the problem....but was confused in the execution of if...else block vs if...if block.
The if...else block didn't give me any error while the if....if block gave me an error of IndexOutOfBoundException for length = 1.

Can someone please tell me what's the difference in Layman's term and what am I doing wrong here?

Here is my code ---->

class Solution {
    public boolean searchMatrix(int[][] m, int target) {
        
        int x =m.length;
        int n= m[0].length;
        
        int i = 0 , j=n-1;
        
        while(i<x && j>=0){
            if(m[i][j]==target){
                return true;
            }
            if(m[i][j]>target){
                j--;
            }
            if(m[i][j]<target) {
                i++;
            }
        }
        
        return false;
    }
}

************************************* VS ******************************************


class Solution {
    public boolean searchMatrix(int[][] m, int target) {
        
        int x =m.length;
        int n= m[0].length;
        
        int i = 0 , j=n-1;
        
        while(i<x && j>=0){
            if(m[i][j]==target){
                return true;
            }
            if(m[i][j]>target){
                j--;
            }
            else {
                i++;
            }
        }
        
        return false;
    }
}



Aucun commentaire:

Enregistrer un commentaire