C++实现基于文件输入的twoSum问题,如何优化内存占用?
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 longbecause your input numbers can be up to 999,999,998—subtracting one from a large target could cause integer overflow if usingint. - 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

