Output Limit Exceeded, what's wrong with this code ?


  • 0
    T

    class Solution { public:
    vector<int> twoSum(vector<int> &numbers, int target) {
    vector<int> index(2);
    int len = numbers.size();
    int a = 0, b = 1;
    while (1) {
    while(target != numbers[a] + numbers[b]) {
    cout<<a<<" "<<b<<"\n";
    b++;
    if (b == len) {
    a++;
    b = a+1;
    }

            }
            if (target == numbers[a] + numbers[b]) {
                index[0] = a+1;
                index[1] = b+1;
                return index;
            }
        }
    } };
    

    I just want to try solving this by force, but the code just can't be accepted, which I think it goes well in my IDE, or is there any bug ?

    any suggestion is appreciated. thanks!


  • 0
    C

    No bug.

    But you code to solve this problem is not the best,it takes too long time.

    O(N^2) may not pass the time limit.

    Try to use hashing.


  • 0
    N

    try sort struct {value,index} type.


Log in to reply
 

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