question

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

coding

code

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
#include<iostream>
#include<vector>
using namespace std;


class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target);
};

vector<int> Solution::twoSum(vector<int>& nums, int target){
for (int i=0; i<nums.size(); i++){
int other_nums = target -nums[i];
for (int j=i+1; j<nums.size(); j++){ // j start from i+1 ,avoid repeat
if (other_nums == nums[j]){
return {i,j};// when you find and exit immediately
}
}
}
return {}; // no solution return viod;
}

int main() {
vector<int> nums={2,7,11,15};
int target=9;
Solution slover;
vector<int> result = slover.twoSum(nums, target);
cout<< "indices: " << result[0] <<" , " << result[1]<< endl;
return 0;
}

explanation

在 C++ 中,return; 语句的作用是立即终止当前函数的执行,并返回到调用该函数的位置。在代码中,return; 被用于找到解后直接退出整个函数,而不是仅退出循环。以下是详细解释:

  1. return 的作用 终止函数执行:当执行 return; 时,函数会立即结束,后续代码不再运行。 返回控制权:将程序的控制权交还给调用该函数的代码。

  2. 对比:不使用 return 的情况 如果删除 return;,代码会输出所有可能的解:

    1
    2
    3
    4
    if (i != j && other_num == nums[j]) {
    cout << i << "," << j << endl;
    // 没有 return;,继续执行后续循环
    }
    示例输入:

1
nums = [3, 2, 4], target = 6

输出:

1
2
1,2
2,1

  1. vector<int>:这是C++标准库中的一个模板类,表示可以存储多个整数(因为这里指定了<int>)的动态数组。在你的例子中,它同时用作返回类型和参数类型。

  2. twoSum:这是函数的名字。

  3. (vector<int>& nums, int target):这是函数的参数列表。其中:

    • vector<int>& nums 表示第一个参数是一个引用到vector<int>类型的变量,意味着函数将直接操作传入的向量而不是其副本。这样做可以节省内存,并允许函数对原向量做出修改(如果需要的话)。
    • int target 是第二个参数,表示目标和,即你想要在nums中找到的两个数的和。

综上所述,这段代码声明了一个名为twoSum的函数,它接受一个整数向量(通过引用)和一个整数目标值作为输入,然后返回一个整数向量。通常,这个函数的目标是找到nums数组中两个数,使得这两个数的和恰好等于target,并返回这两个数的索引(或者其他形式的结果,具体取决于实现)。不过,具体的实现细节(比如如何找到这两个数)在这个声明中没有给出,需要查看函数体部分才能了解。

problem

你的代码存在多个问题,包括语法错误逻辑错误潜在越界访问。以下是逐行分析和修正:


原始代码

1
2
3
4
5
6
7
8
for (int i=1, i<=nums.length, i++){
other_nums = target - nums[i];
for (int j=1, j<=nums.length, j++){
if (other_nums == nums[j]){
cout<< i "," j << endl;
}
}
}

问题分析与修正

1. 语法错误
  • 错误for 循环的分隔符错误。
    C++ 中 for 循环的三个部分用分号 ; 分隔,而不是逗号 ,

    修正

    1
    for (int i = 0; i < nums.size(); i++) {  // 分号分隔,索引从0开始

  • 错误cout 语句语法错误。
    输出多个值时需用 << 连接,且语句末尾需要分号 ;

    修正

    1
    cout << i << "," << j << endl;  // 正确语法


2. 数组索引越界
  • 错误:索引从 1 开始,但 C++ 数组/容器的索引从 0 开始。
    若容器大小为 n,有效索引是 0n-1。使用 i <= nums.length 会导致越界。

    修正

    1
    for (int i = 0; i < nums.size(); i++) {  // 索引从0开始,条件用 <


3. 变量未声明类型
  • 错误other_nums 未声明类型。
    C++ 是强类型语言,变量必须显式声明类型。

    修正

    1
    int other_num = target - nums[i];  // 声明为 int


4. 逻辑错误
  • 错误:未处理 i == j 的情况。
    如果允许重复使用同一元素(如 nums = [3], target = 6),则无需处理;但通常题目要求两个不同元素。

    修正

    1
    if (i != j && other_num == nums[j]) {  // 排除相同索引


5. 容器长度获取方式错误
  • 错误nums.length 是无效语法。
    C++ 中:
    • 原生数组需用 sizeof(nums)/sizeof(nums[0])(不推荐)。
    • std::vectorstd::array 需用 nums.size()
    修正
    1
    for (int i = 0; i < nums.size(); i++) {  // 使用 size()

修正后的完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>
using namespace std;

void findTwoSum(const vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
int other_num = target - nums[i];
for (int j = 0; j < nums.size(); j++) {
if (i != j && other_num == nums[j]) { // 确保i和j不同
cout << i << "," << j << endl;
return; // 找到后立即退出
}
}
}
cout << "No solution found." << endl;
}

int main() {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
findTwoSum(nums, target);
return 0;
}

输出

1
0,1

改进建议

  1. 时间复杂度优化
    当前代码时间复杂度为 O(n²),可用哈希表优化到 O(n)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #include <unordered_map>

    void findTwoSumOptimized(const vector<int>& nums, int target) {
    unordered_map<int, int> num_map;
    for (int i = 0; i < nums.size(); i++) {
    int complement = target - nums[i];
    if (num_map.find(complement) != num_map.end()) {
    cout << num_map[complement] << "," << i << endl;
    return;
    }
    num_map[nums[i]] = i;
    }
    cout << "No solution found." << endl;
    }
  2. 边界条件处理

    • 检查输入是否为空。
    • 处理重复解(如要求所有可能的解)。
  3. 返回结果而非直接输出
    函数应返回结果(如 vector<int>),而非直接输出,以提高可重用性。


常见问题总结

问题类型 错误示例 修正后
语法错误 for (int i=1, ...) for (int i=0; ...)
索引越界 i <= nums.length i < nums.size()
变量未声明 other_nums = ... int other_num = ...
逻辑不严谨 允许 i == j 添加 i != j 条件
容器长度获取错误 nums.length nums.size()
函数名大小写不一致:

类内声明的函数名为 TwoSum(首字母大写),但类外定义时也使用 TwoSum,虽然名称一致,但通常成员函数命名建议使用驼峰式(camelCase),例如 twoSum。 更关键的是,你尝试直接通过类名 Solution::TwoSum() 调用非静态成员函数,但非静态函数必须通过对象调用。

非静态成员函数调用错误:

TwoSum 是类的非静态成员函数,必须通过对象调用,而不能直接通过 Solution::TwoSum() 调用。 你的代码存在以下问题:

错误原因 函数名大小写不一致:

类内声明的函数名为 TwoSum(首字母大写),但类外定义时也使用 TwoSum,虽然名称一致,但通常成员函数命名建议使用驼峰式(camelCase),例如 twoSum。 更关键的是,你尝试直接通过类名 Solution::TwoSum() 调用非静态成员函数,但非静态函数必须通过对象调用。 非静态成员函数调用错误: TwoSum 是类的非静态成员函数,必须通过对象调用,而不能直接通过 Solution::TwoSum() 调用。

修正后的代码

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
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
static vector<int> twoSum(vector<int>& nums, int target); // 声明为 static
};

// 统一函数名为 twoSum(驼峰式)
vector<int> Solution::twoSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
int other_num = target - nums[i];
for (int j = i + 1; j < nums.size(); j++) {
if (other_num == nums[j]) {
return {i, j};
}
}
}
return {};
}

int main() {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
vector<int> result = Solution::twoSum(nums, target); // 正确调用静态函数

if (!result.empty()) {
cout << "Indices: " << result[0] << ", " << result[1] << endl;
} else {
cout << "No solution found." << endl;
}

return 0;
}
关键修正说明 将函数声明为 static 在类中声明 twoSum 为静态成员函数,使其可以通过类名直接调用:
1
2
3
4
class Solution {
public:
static vector<int> twoSum(vector<int>& nums, int target);
};
统一函数命名风格 使用 twoSum(首字母小写的驼峰式)而非 TwoSum,符合 C++ 常见风格。

补充结果输出 在 main 函数中检查结果并输出,避免直接忽略返回值。

不使用static函数

若不想使用 static 成员函数,需通过创建类的对象来调用非静态成员函数。以下是修改后的代码: 关键修改说明 移除 static 关键字 在类中将 twoSum 声明为普通成员函数:

1
2
3
4
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target); // 非静态
};

通过对象调用函数 在 main 中创建 Solution 对象,并通过对象调用函数:

1
2
Solution solver; // 创建对象
vector<int> result = solver.twoSum(nums, target); // 正确调用方式