Why this solution does not work, fail only one test case


  • 0
    P

    14 / 15 test cases passed.
    Status: Wrong Answer
    Submitted: 0 minutes ago
    Input: [3,2,4], 6
    Output: 1, 1
    Expected: 2, 3

    class Solution {
    public:
    vector<int> twoSum(vector<int> &numbers, int target) {
    vector<int> result;
    map<int, int> hashmap;
    for (int i = 0; i < numbers.size(); i++) {
    hashmap[numbers[i]] = i;
    }
    for (int j = 0; j < numbers.size(); j++) {
    if (hashmap.find(target - numbers[j]) != hashmap.end()) {
    cout << "works";
    result.push_back(j + 1);
    result.push_back(hashmap[target - numbers[j]] + 1);
    break;
    }
    }
    return result;
    }
    };


  • 1
    B

    Well the reason is that you put all the elements in the map upfront. You need to put an element number[i] in the hash-map only after you have already searched for (target-number[i]) in the map.


  • 1
    T

    You need to take care of fake repeated elements.
    6 = 3 + 3, while only one 3 here.


  • 0
    P

    Thank you very much


  • 0
    P

    Thank you very much


Log in to reply
 

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