题解 | #和为K的连续子数组#
和为K的连续子数组
http://www.nowcoder.com/practice/704c8388a82e42e58b7f5751ec943a11
class Solution {
public:
/**
* max length of the subarray sum = k
* @param arr int整型vector the array
* @param k int整型 target
* @return int整型
*/
int maxlenEqualK(vector<int>& arr, int k) {
// write code here
int res = 0;
int n = arr.size();
// hash表记录前缀和(1:int)的下标(2:int)
unordered_map<int, int> mp;
// 当前缀和为0,下标为-1
mp[0] = -1;
int temp = 0;
// 初始化
for(int i = 0; i < n; i++) {
temp += arr[i];
if(mp.find(temp - k) != mp.end()) {
res = max(res, i - mp[temp - k]);
}
if(mp.find(temp) == mp.end()) {
mp[temp] = i;
}
}
return res;
}
};