C++实现两数之和

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n = nums.size();
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] == target) {
                    return {i, j};
                }
            }
        }
        return {};
    }
};

int main() {
    // 创建一个Solution对象
    Solution solution;

    // 准备测试用例
    vector<int> nums1 = {2, 7, 11, 15};
    int target1 = 9;
    vector<int> expected1 = {0, 1}; // 索引从0开始

    vector<int> nums2 = {3, 2, 4};
    int target2 = 6;
    vector<int> expected2 = {1, 2};

    vector<int> nums3 = {3, 3};
    int target3 = 6;
    vector<int> expected3 = {0, 1};

    // 调用twoSum方法并验证结果
    vector<int> result1 = solution.twoSum(nums1, target1);
    if (result1 == expected1) {
        cout << "Test 1 passed." << endl;
    } else {
        cout << "Test 1 failed. Expected " << "{" << expected1[0] << ", " << expected1[1] << "} but got " << "{" << result1[0] << ", " << result1[1] << "}" << endl;
    }

    vector<int> result2 = solution.twoSum(nums2, target2);
    if (result2 == expected2) {
        cout << "Test 2 passed." << endl;
    } else {
        cout << "Test 2 failed. Expected " << "{" << expected2[0] << ", " << expected2[1] << "} but got " << "{" << result2[0] << ", " << result2[1] << "}" << endl;
    }

    vector<int> result3 = solution.twoSum(nums3, target3);
    if (result3 == expected3) {
        cout << "Test 3 passed." << endl;
    } else {
        cout << "Test 3 failed. Expected " << "{" << expected3[0] << ", " << expected3[1] << "} but got " << "{" << result3[0] << ", " << result3[1] << "}" << endl;
    }

    return 0;
}
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值