-
Notifications
You must be signed in to change notification settings - Fork 1
/
twoSum.cpp
68 lines (57 loc) · 1.47 KB
/
twoSum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// https://leetcode.com/problems/two-sum/
//
// Status: Accepted
// Runtime: 8ms
// Score: 97.83%
//
#include <iostream>
#include <map>
#include <vector>
#include <gtest/gtest.h>
#include "args.h"
#include "macros.h"
using namespace std;
// class definition comes from leetcode
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
std::map<int, int> map;
std::map<int, int>::iterator it;
for (int i=0; i<(int)nums.size(); i++) {
int remainder = target - nums[i];
it = map.find(remainder);
if (it != map.end() ) {
return vector<int>{ map[remainder], i};
}
map[nums[i]] = i;
}
throw "No solution found";
}
};
TEST(TwoSumsTest, CorrectSample)
{
vector<int> nums = {2, 7, 11, 15};
int target = 9;
vector<int> correct = {0, 1};
Solution solution;
try {
ASSERT_EQ(solution.twoSum(nums, target), correct);
} catch (...) {
cout << "TwoSumsTest.CorrectSample:: Caught exception \"" << "\"\n";
}
}
TEST(TwoSumsTest, NoSolution)
{
vector<int> nums = {2, 7, 11, 15};
int target = 95;
bool exceptionThrown = false;
vector<int> ignoreAnswer;
try {
Solution solution;
ignoreAnswer = solution.twoSum(nums, target);
} catch (...) {
exceptionThrown = true;
}
ASSERT_EQ(exceptionThrown, true);
}