标签:利用 code turn cto equals find 双层 一个 who
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2 Output: 2
Note:
方法1:双层遍历
。。。
方法2:利用哈希表加一点数学推导
class Solution { public: int subarraySum(vector<int>& nums, int k) { int n = nums.size(); if (n == 0) return 0; unordered_map<int, int>sum_fre; sum_fre[0] = 1; int sum = 0; int res = 0; for (auto num: nums) { sum += num; // k = sum[0, j] - sum[0, i - 1] ===> sum[0, j] - k 其中i-1 < j; // 遍历一遍,将所有的sum[0, j]存起来。若在哈希表中发现之前有满足上边式子的,则得到一个满足要求的连续序列 if (sum_fre.find(sum - k) != sum_fre.end()) res += sum_fre[sum - k]; sum_fre[sum]++; } return res; } };
标签:利用 code turn cto equals find 双层 一个 who
原文地址:https://www.cnblogs.com/qiang-wei/p/12271492.html