My C program failed one test case. Can anybody help me fix this overflow problem?


  • 0
    L

    Here is my code. I tried to convert nums[i] and nums[j] to long but it still failed. I know it's a bad o(n^2), but I really want to solve the overflow problem. Thanks a lot.

    bool containsNearbyAlmostDuplicate(int* nums, int numsSize, int k, int t) {
        int i,j;
        if(numsSize==0 ||k==0)
            return false;
        if(numsSize>k)
        {
            for(i=k;i<numsSize;i++)
            {
                for(j=i-k;j<i;j++)
                {
                    if(abs(nums[i]-nums[j])<=t)
                        return true;
                }
            }
            return false;
        }
        else
        {
            for(i=1;i<numsSize;i++)
            {
                for(j=0;j<i;j++)
                {
                    if(abs(nums[i]-nums[j])<=t)
                        return true;
                }
            }
            return false;
        }   
    }

  • 1
    W

    There is no need to convert nums[i] and nums[j] from int to long. If you have noticed about that the problem is that abs could overflow, you simply use labs instead and will pass.


  • 0
    L

    Thank you so much. I didn't notice that it could be the problem of function... And labs() worked. Thanks again :)


  • 0
    D

    O(n2) have time limit problem for last case, which I met.


Log in to reply
 

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