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

  • 0

    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";
    if (b == len) {
    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

    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

    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.