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 avector<int>initialized with the two matching indices, e.g.,return {i, j}orreturn vector<int>{i, j}. - Out-of-Bounds Risk: Your initial check
nums[i] + nums[i+1]will crash wheniis the last index of the vector (sincei+1will be beyond the vector's valid range). - Wrong Calculation for
ans1: You wroteans1 = nums[j] == nums[j+1]— this is a boolean comparison, not addition. It should beans1 = nums[i] + nums[j](since you're checking pairs ofnums[i]with every subsequentnums[j]). - Invalid
size()Call:j<size() - iis incorrect; you need to callnums.size()to get the vector's length. Also, the condition should simply bej < nums.size(). - Unwanted
i++in Inner Loop: Incrementingiinside 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 avector<int>with the two indices. For older C standards, you can usereturn 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
jati+1and usingj < 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
相关产品推荐
相关产品推荐

