Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to implement the two sum algorithm to find two values in vector that add up to target with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <map>

std::vector<int> twoSum(std::vector<int>& vec, int target) {
    std::map<int,int> mp;
    std::vector<int> vec_result;
    int size = vec.size();
    
    for (int i = 0; i < size; i++) {
        int diff = target - vec[i];
        if (mp.find(diff) != mp.end()) {
            auto result = mp.find(diff);        
            vec_result.push_back(result->second);
            vec_result.push_back(i);
            return vec_result;
        }
        mp.insert(std::make_pair(vec[i], i));
    }
          
    return vec_result;
}

int main() {
    std::vector<int> vec = {1, 5, 7, 6, 4, 3, 2}; 
    std::vector<int> result = twoSum(vec, 9);
    
    for (int i: result) {
        std::cout << i << " ";
    }
}


 
 
 
 
 
/*
run:
 
1 4 
 
*/

 



answered Jul 17, 2023 by avibootz
edited Jul 17, 2023 by avibootz
...