Optimization of brute force


  • 1
    C

    Want to optimize the algorithm a little. There are two 'for' loops in this algorithm, I want to check whether the current number, in the first or second loop, is bigger than target. If it's bigger than target, then continue. I know it's a little stupid, as it won't make big difference. But I can't implement it as there's error, 'runtime error', when I use 'continue'.
    Here's the code.

    int* twoSum(int* nums, int numsSize, int target) {
        int i,j;
        static int Index[2];
        for( i = 0; i < numsSize - 1; i++ )
        {
            if( nums[i] > target ) continue;
            for( j = i + 1; j < numsSize; j++ )
            {
                if( nums[j] > target ) continue;
                else if (nums[i] + nums[j] == target )
                {
                    Index[0] = i;
                    Index[1] = j;
                    return Index;
                }
            }
        }
    }

  • 0
    C

    If I delete those two sentence, 'if() continue;' then it works. So what's wrong with 'continue'?


  • 0
    S

    As you can see in the problem, the array of integer may be negative. So you can not continue.

    int* twoSum(int* nums, int numsSize, int target) {
    int i,j;
    static int Index[2];
    for( i = 0; i < numsSize - 1; i++ )
    {
        for( j = i + 1; j < numsSize; j++ )
        {
            if (nums[i] + nums[j] == target )
            {
                Index[0] = i;
                Index[1] = j;
                return Index;
            }
        }
    }
    

    }


  • 0
    C

    Ah, I understand! Such a foolish question hahaha. Thank you!


Log in to reply
 

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