7-Line C++ Solution Using Multi_set


  • 0

    The idea is simple. We sum all numbers one by one, then count "sum - k". Also, we should decide if current sum equals to k.

    class Solution {
    public:
        int subarraySum(vector<int>& nums, int k) {
            int cnt = 0, sum = 0;
            unordered_multiset<int> mst;
            for (int i: nums) {
                sum += i;
                cnt += mst.count(sum - k) + (sum == k);
                mst.insert(sum);
            }
            return cnt;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.