Accepted by using C++. welcome any suggestions.


  • 0
    S

    I think it would be some help to those who not been accepted.

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
           map<int, int> mymap;
           // inset to map
           for (int i = 0; i < numbers.size(); ++i) {
               mymap[numbers[i]] = i+1;
           }
    
           vector<int> result;
           for (int i = 0; i < numbers.size(); ++i) {
               int a = numbers[i];
               int b = target - a;
               map<int, int>::iterator map_it = mymap.begin();
               map_it = mymap.find(b);
               if (map_it != mymap.end()) {
                   // find the right answer
                   int index1 = i+1;
                   int index2 = map_it->second;
                   // make sure the answer in the right order
                   if (index1 < index2) {
                       result.push_back(index1);
                       result.push_back(index2);
                   } else if(index1 > index2) {
                       result.push_back(index2);
                       result.push_back(index2);
                   } else {
                       // this is an except.
                       // because all the numbers are different,
                       // and the answer is a pair of different
                       // index not the same one.
                       continue;
                   }
                   break;
               }
           }
           return result;
        }
    };

  • 0
    J

    I don't think your submission is absolutely right. Because when two or more integers have same value( like [0,1,2,3,1,0,0],and target number is 0), using this data structure (that is map) can not reach the request of this question.


  • 0
    S

    This problem says "You may assume that each input would have exactly one solution." But your sequence has three answers.


  • 0
    L

    There is a test case like [0,3,4,0] and target number is 0.
    And when there are two same value in the sequence, map will discard the other one, does it right?


  • 0
    L

    sorry, this is my first here, so it should be a comment...


  • 0
    S

    no matter. thanks for your question. In fact, I used a little tip. index1 < index2, the map only store the bigger index. so I got index1 form vector, and index2 from the map. so the result will be right.


  • 0
    L

    got it, thanks!


Log in to reply
 

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