mercredi 25 août 2021

Time complexity exceeding while using "else-if" but works fine when using "If statement"

ques: Given an array of integers in increasing order, return an array containing positions(index+1) of two numbers that add up to a specific target number

Sol: When I write the code without using else-if for checking second condition, then I get the desired result:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left=0;
        int right=numbers.length-1;
        int arr[]=new int[2];
        while(left<right)
        {
            if(numbers[left]+numbers[right]==target)
            {
                arr[0]=left+1;
                arr[1]=right+1;
            }
             if(numbers[left]+numbers[right]<target)
            {
                left++;
            }
            else
                right--;
        }
        return arr;
        
    }
}

But when I am using else-if instead of "if" for checking the second condition, then the time limit is exceeded. Can anyone explain the reason behind this:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left=0;
        int right=numbers.length-1;
        int arr[]=new int[2];
        while(left<right)
        {
            if(numbers[left]+numbers[right]==target)
            {
                arr[0]=left+1;
                arr[1]=right+1;
            }
             else if(numbers[left]+numbers[right]<target) // using else if
            {
                left++;
            }
            else
                right--;
        }
        return arr;
        
    } }

Aucun commentaire:

Enregistrer un commentaire