为什么不能简单的这样做呢。显示结果是输入[3,2,4],6 输出却为2,2


  • -34
    S

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

        }
    }
    return 0;
    

    }


  • 9
    C

    请用英文提问。

    Please ask your question in English.

    Your problem is, the index array will only exist in this function. Once this function terminates, values in the array may change.

    A quick fix is, instead of "int index[2]", try "static int index[2]".

    Your solution runs in time (O(N^2)), which is sufficient to pass the test cases, but still there are faster algorithms.


  • 0
    S

    I am sorry for that.Thank you for your remind and answer.


  • 0
    C

    You're very Welcome.


  • 0
    K

    The inner loop of your code should ignore index i - add one condition (i != j) in your if statement.


Log in to reply
 

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