Solve this using C++ code

Write a solution in any language to the following: Given a large list of integers (more than 1 000 000 values) find how many ways there are of selecting two of them that add up to 0

Showing Answers 1 - 3 of 3 Answers

Jin Hyuk Cho

  • Feb 3rd, 2016
 

Working example

Code
  1. #include <iostream>

  2. #include <vector>

  3. #include <algorithm>

  4. // clone array

  5. // sort numbers

  6.     sort(numbers.begin(), numbers.end());

  7.    

  8.     // front and back

  9. // result

  10. // non-unique number support

  Was this answer useful?  Yes

dada

  • Feb 6th, 2016
 

This solution is O(n)

Code
  1. #include <iostream>

  2. #include <vector>

  3. #include <limits>

  4. #include <algorithm>

  5. #include <random>

  6. #define MAX_NUM 10000

  7. //input data

  8.  

  9.         // fill input data with some random numbers

  10. // poscount[i] will have the count of occurances of number i

  11. // negcount[i] will have the count of occurances of number -i

  12.  

  13.         // go through input data and populate poscount and negcount

  14. // number of pairs formed of negative and positive numbers of same value will be minimum of pos and neg values

  15. "Number of pairs of numbers whose sum is 0 is: "

  Was this answer useful?  Yes

Jin Hyuk Cho

  • Feb 8th, 2016
 

O(n) solution

Code
  1. #include <iostream>

  2. #include <string>

  3. #include <vector>

  4. #include <queue>

  5. #include <set>

  6. #include <locale>         // std::locale, std::isdigit

  7. #include <sstream>

  8. #include <algorithm>

  9. #include <iterator>

  10. #include <map>

  11. // construct occurance map

  12. // iterate over the occurance map

  13. // cout << count.first << "=" << count.second << endl;

  14. // complement found

  15.                 // complements count * numbers count

  16. /**

  17.  * Main executable

  18.  */

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions