大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

28 lines
550 B

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int subarraySum(vector<int>& nums, int k) {
  4. unordered_map<int, int> mp;
  5. mp[0] = 1;
  6. int count = 0, pre = 0;
  7. for (auto& x:nums) {
  8. pre += x;
  9. if (mp.find(pre - k) != mp.end()) {
  10. count += mp[pre - k];
  11. }
  12. mp[pre]++;
  13. }
  14. return count;
  15. }
  16. int main() {
  17. int n;
  18. cin >> n;
  19. vector<int> nums(n);
  20. for(int i = 0; i < n; i++){
  21. cin >> nums[i];
  22. }
  23. int k;
  24. cin >> k;
  25. cout << subarraySum(nums, k) << endl;
  26. return 0;
  27. }