Can anyone help me? I am getting runtime error when the input is too large and I don't know how to fix it


  • -3
    M

    This is my code:

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            
            int index1, index2, j;
            j = 1;
            vector<int> solution(2);
            
            for (int i=0; i<=numbers.size(); i++) {
                if (numbers[i] + numbers[i+j] == target) {
                    index1 = i + 1;
                    index2 = j + 1;
                    solution.push_back(index1);
                    solution.push_back(index2);
                    return solution;
                }
                else {
                    j++;
                }
            }
        }
    };

  • 2
    W

    i think your code is only to test index likes <1,2>, <2,4>……
    so you should to use two circles to do this job. However if you use two circles,you will get time limited error.
    i think hash is the way to solve this problem,


  • 0
    M

    Hi! Yes, I used two loops before but I got a time error, so I changed the code this way... I will try hashing! Thanks!


  • 0
    U

    your code looks like can't solve input like {1,4,5,6} target: 7
    because i and j are next to each other


  • 0
    M

    Thanks for your help!! I have to review this code.


Log in to reply
 

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