You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode两数之和(C++暴力解法):返回数组索引编译报错求助

Fixing Your Two Sum Brute-force Solution in C++

First, let's tackle the immediate error you're seeing: the return statement syntax is wrong. In C++, you can't return an array like nums[] {i,i+1}. Instead, you need to construct a vector<int> directly with the indices you found.

Key Issues in Your Code

Let's break down all the problems in your current code:

  • Incorrect Return Syntax: return nums[] {i,i+1} is invalid C++ syntax. To return the indices, you should return a vector<int> initialized with the two matching indices, e.g., return {i, j} or return vector<int>{i, j}.
  • Out-of-Bounds Risk: Your initial check nums[i] + nums[i+1] will crash when i is the last index of the vector (since i+1 will be beyond the vector's valid range).
  • Wrong Calculation for ans1: You wrote ans1 = nums[j] == nums[j+1] — this is a boolean comparison, not addition. It should be ans1 = nums[i] + nums[j] (since you're checking pairs of nums[i] with every subsequent nums[j]).
  • Invalid size() Call: j<size() - i is incorrect; you need to call nums.size() to get the vector's length. Also, the condition should simply be j < nums.size().
  • Unwanted i++ in Inner Loop: Incrementing i inside the inner loop will mess up the outer loop's iteration, causing you to skip elements and miss potential pairs.

Corrected Brute-force Code

Here's the fixed version of your code that works correctly:

#include <vector>
using namespace std;

vector<int> twoSum(vector<int>& nums, int target) {
    // Iterate through each element in the vector
    for (int i = 0; i < nums.size(); i++) {
        // Check every element that comes after the current i to avoid duplicate pairs
        for (int j = i + 1; j < nums.size(); j++) {
            // Check if the current pair adds up to the target
            if (nums[i] + nums[j] == target) {
                // Return the indices as a properly constructed vector
                return {i, j};
            }
        }
    }
    // According to LeetCode's problem statement, there's always a valid solution,
    // but we include this fallback to satisfy the compiler's requirement for a return value
    return {};
}

Explanation of the Fixes

  • Return Statement: We use return {i, j} (a C11+ feature) to directly initialize and return a vector<int> with the two indices. For older C standards, you can use return vector<int>{i, j} instead.
  • Brute-force Logic: The nested loops ensure we check every unique pair exactly once (no duplicate checks like (i,j) and (j,i)), which is the standard brute-force approach for this problem.
  • No Out-of-Bounds Access: By starting j at i+1 and using j < nums.size(), we never access elements outside the vector's valid range.

Bonus Note (Optional)

While you mentioned you can't use map or hash tables right now, once you're comfortable with those data structures, you can optimize this solution to O(n) time complexity by storing elements and their indices in a hash map as you iterate through the vector.

内容的提问来源于stack exchange,提问作者salvador-soto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:22:54