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

C++实现基于文件输入的twoSum问题,如何优化内存占用?

Optimizing Memory Usage for Your TwoSum C++ Solution

Hey there! Let's walk through some key tweaks to slash the memory footprint of your twoSum implementation. The original code has a few places where it uses more memory than necessary—here's how to fix them:

1. Skip Loading the Entire File Into a String

Your current code reads the whole input file into a single source string before parsing, which wastes memory especially if the input is large. Instead, read the first line directly as the target, then process the second line's number sequence on the fly without storing the entire file.

2. Don't Store the Entire Number Sequence

Storing all numbers in a vector<int> uses O(n) memory upfront. You can check for the valid pair as you read each number—no need to keep every number in memory. This cuts memory usage significantly, especially for huge datasets.

3. Use unordered_set Instead of unordered_map

Since you only need to check if a complement exists (not track its index), an unordered_set is sufficient. It stores just values instead of key-value pairs, saving a bit of memory compared to unordered_map.

Optimized Code Implementation

Here's the revised code incorporating all these changes:

#include <iostream>
#include <fstream>
#include <unordered_set>
#include <string>
using namespace std;

int main() {
    ifstream f1("input.txt");
    if (!f1.is_open()) {
        // Handle file open error if needed
        return 1;
    }

    long long target;
    // Read target directly from first line (use long long to avoid overflow)
    f1 >> target;
    f1.ignore(); // Skip the newline after target

    unordered_set<long long> complements;
    bool flag = false;
    long long num;
    // Read numbers one by one and check immediately
    while (f1 >> num) {
        if (complements.count(num)) {
            flag = true;
            break;
        }
        // Calculate and store the complement we need to look for later
        long long complement = target - num;
        complements.insert(complement);
    }

    f1.close();

    ofstream f2("output.txt");
    f2 << (flag ? "1" : "0");
    f2.close();

    return 0;
}

Additional Notes:

  • Overflow Prevention: I switched to long long because your input numbers can be up to 999,999,998—subtracting one from a large target could cause integer overflow if using int.
  • Early Termination: As soon as we find a valid pair, we break out of the loop immediately, saving both time and memory.
  • Minimal Storage: We only store the complements we need to check against, not the entire input sequence or file.

内容的提问来源于stack exchange,提问作者hikkers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:33:11