Why my code always have Runtime Error,but answer is correct.Please Help.


  • 0
    P
    typedef struct _NODE
     {
         int index[2];
     }NODE;
     int find_max(int *num,int numSize)
     {
         int i = 0;
         int maxNum=num[0];
         for (i=1;i<numSize;i++)
         {
             if(maxNum < num[i])
                maxNum = num[i];
         }
         return maxNum;
     }
     int find_min(int *num,int numSize)
     {
         int i = 0;
         int minNum=num[0];
         for (i=1;i<numSize;i++)
         {
             if(minNum > num[i])
                minNum = num[i];
         }
         return minNum;
     }
    int* twoSum(int* nums, int numsSize, int target) {
        int i = 0;
        int maxNum,minNum;
        int *answer ;
        int dst = 0;
        maxNum = find_max(nums,numsSize);
        minNum = find_min(nums,numsSize);
        
        NODE *node_pos,*node_neg ;
        if(minNum < 0)
            node_neg = calloc((-1)*minNum ,sizeof(NODE));
        node_pos = calloc(maxNum ,sizeof(NODE));
        answer = calloc(2,sizeof(int));
        for(i=0;i<numsSize;i++)
        {
            if(nums[i]>=0)
            {
                if(node_pos[nums[i]].index[0])
                    node_pos[nums[i]].index[1] = i+1;
                else
                    node_pos[nums[i]].index[0] = i+1;
            }
            else
            {
                
                if(node_neg[(-1)*nums[i]].index[0])
                    node_neg[(-1)*nums[i]].index[1] = i+1;
                else
                    node_neg[(-1)*nums[i]].index[0] = i+1;
            }
        }
        
        for(i=0;i<numsSize;i++)
        {
            dst = target-nums[i];
            //printf("dst %d\n",dst);
            if(dst >=0)
            {
                if(dst > maxNum)
                    continue;
                if(node_pos[dst].index[0])
                {
                    
                    answer[0]=i+1;
                    if(target == nums[i]*2)
                        answer[1]=node_pos[dst].index[1];
                    else
                        answer[1]=node_pos[dst].index[0];
                    //printf("find\n");
                    break;
                }
                
            }
            else
            {
                if(dst < minNum)
                    continue;
                if(node_neg[(-1)*dst].index[0])
                {
                    answer[0]=i+1;
                    if(target == nums[i]*2)
                        answer[1]=node_neg[(-1)*dst].index[1];
                    else
                        answer[1]=node_neg[(-1)*dst].index[0];
                    break;
                }
            }
            
        }
        printf("answer %d %d",answer[0],answer[1]);
        return answer;
        
    }

Log in to reply
 

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