Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 0 additions & 41 deletions leetcode/0001-two-sum/test.cpp

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
#include <unordered_map>
#include <vector>

class Solution {
public:
std::vector<int> twoSum(const std::vector<int> &nums, int target) {
// 方法1:哈希表
struct Solution {
static std::vector<int> twoSum(const std::vector<int> &nums, int target) {
std::unordered_map<int, int> hash;
for (std::size_t i{0}; i < nums.size(); ++i) {
auto it{hash.find(nums[i])};
Expand Down
47 changes: 47 additions & 0 deletions leetcode/0001/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include "test.hpp"
#include "solution.hpp"

using namespace testing;
namespace {
using SolutionList = std::tuple<Solution>;
struct TestCase {
TestCase(const YAML::Node &node) {
Decode(node["input"]["nums"], input.nums);
Decode(node["input"]["target"], input.target);
Decode(node["expected"], expected);
}
struct {
std::vector<int> nums;
int target;
} input;
std::vector<int> expected;
};

template <typename Solution>
void Expect(const std::vector<int> &nums, const int target, const std::vector<int> &expected) {
// 检查约束条件
ASSERT_THAT(nums.size(), AllOf(Ge(2), Le(10000))); // 2 <= nums.length <= 10^4
ASSERT_THAT(nums, Each(AllOf(Ge(-1000000000), Le(1000000000)))); // -10^9 <= nums[i] <= 10^9
ASSERT_THAT(target, AllOf(Ge(-1000000000), Le(1000000000))); // -10^9 <= target <= 10^9
// Only one valid answer exists
// TODO(resserops): 补充检查

// 验证目标函数
Solution solution;
auto res{solution.twoSum(nums, target)};
ASSERT_EQ(2, res.size());
if (res[0] > res[1]) {
std::swap(res[0], res[1]);
}
EXPECT_EQ(res, expected);
}

template <typename Solution>
void Expect(const TestCase &tc) {
Expect<Solution>(tc.input.nums, tc.input.target, tc.expected);
}

TEST_Y(LeetCode1, Example1);
TEST_Y(LeetCode1, Example2);
TEST_Y(LeetCode1, Example3);
} // namespace
17 changes: 17 additions & 0 deletions leetcode/0001/test_suite.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
example1:
input:
nums: [2,7,11,15]
target: 9
expected: [0,1]

example2:
input:
nums: [3,2,4]
target: 6
expected: [1,2]

example3:
input:
nums: [3,3]
target: 6
expected: [0,1]
1 change: 1 addition & 0 deletions leetcode/0001/title.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
two-sum