题解 | #未排序数组中累加和为给定值的最长子数组长度#
未排序数组中累加和为给定值的最长子数组长度
https://www.nowcoder.com/practice/36fb0fd3c656480c92b569258a1223d5
#include <iostream> #include <unordered_map> #include <vector> using namespace std; int main() { int n; int target; std::vector<int> nums; int num; std::unordered_map<int, int> umap; // <sum, pos> 值为sum最早出现的pos int sum; int max_len; while (std::cin >> n) { std::cin >> target; nums.resize(n); for (int i = 0; i < n; i++) { std::cin >> num; nums[i] = num; } umap.clear(); umap[0] = -1; // 提前填充的 note sum = 0; max_len = 0; for (int i = 0; i < n; i++) { sum += nums[i]; auto itr = umap.find(sum - target); if (itr != umap.end()) { max_len = std::max(max_len, i - itr->second); } if (umap.find(sum) == umap.end()) { umap[sum] = i; // 第一次出现sum的值加入 } } std::cout << max_len << std::endl; } } // 64 位输出请用 printf("%lld")