class Solution { public: int subarraySum(vector<int>& nums, int k) { int cur = 0, res = 0; unordered_map<int, int> um; // 注意這裏前綴和多了一個0,防止漏掉數組的前綴和恰好等於k的狀況 um[0] = 1; for (int num : nums) { cur += num; res += um.find(cur - k) == um.end() ? 0 : um[cur - k]; ++um[cur]; } return res; } };
分析:數組