Pretty easy O(n) Solution


  • 1
    public class Solution {
        public int SubarraySum(int[] nums, int k)
            {
                if (nums == null) return 0;
                int sum = 0; int count = 0;
                Dictionary<int, int> map = new Dictionary<int, int>();
                map.Add(0, 1);
                for (int i = 0; i < nums.Length; i++)
                {
                    sum += nums[i];
                    if (map.ContainsKey(sum - k))
                        count += map[sum - k];
                    AddorUpdateDict(map, sum);
                }
                return count;
            }
            void AddorUpdateDict(Dictionary<int, int> map, int sum)
            {
                if (map.ContainsKey(sum))
                    map[sum]++;
                else
                    map.Add(sum, 1);
            }
    }
    

Log in to reply
 

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