一、題目描述
給你一個整數數組?nums
?和一個整數?k
?,請你統計并返回?該數組中和為?k
?的子數組的個數?。
子數組是數組中元素的連續非空序列。
注意:nums中的元素可為負數
輸入:nums = [1,1,1], k = 2
輸出:2輸入:nums = [1,2,3], k = 3
輸出:2
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
二、題目解答
class Solution {
public:int subarraySum(vector<int>& nums, int k) {//假設數組的前綴和為presum[i],那么對于任意兩個下標i,j//如果presum[j]-presum[i] = k//那么從i+1到j的連續子數組合為 k//在遍歷過程中,用哈希表存儲前綴和出現的次數//如果存在哈希表中,那么就count+出現次數 int sum = 0;int count = 0;map <int, int> map_tmp;map_tmp [0] = 1;for (int i = 0; i < nums.size(); i++){sum = sum + nums[i];//有當前前綴和-k的前綴和if (map_tmp.find(sum - k) != map_tmp.end())count += map_tmp[sum - k];//判斷完畢后再加入mapmap_tmp[sum]++;}return count;}
}