Swift solution - Prefix Sum & HashMap


  • 0
    class Solution {
        func subarraySum(_ nums: [Int], _ k: Int) -> Int {
            var sum = 0
            var result = 0
            var preSum = [0: 1]
            
            for i in 0..<nums.count {
                sum += nums[i]
                if preSum.keys.contains(sum - k) {
                    result += preSum[sum - k]!
                }
                if let item = preSum[sum] {
                    preSum[sum] = item + 1
                } else {
                    preSum[sum] = 1
                }
            }
            
            return result
        }
    }
    

Log in to reply
 

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