Swift solution - Prefix Sum


  • 0
    class NumArray {
        
        let prefixSum: [Int]
        
        init(_ nums: [Int]) {
            var prefixSum = [Int](repeatElement(0, count: nums.count - 1))
            
            for i in 1..<nums.count {
                prefixSum[i] = prefixSum[i - 1] + nums[i]
            }
            
            self.prefixSum = prefixSum
        }
        
        func sumRange(_ i: Int, _ j: Int) -> Int {
            if i == 0 {
                return prefixSum[j]
            }
            
            return prefixSum[j] - prefixSum[i - 1]
        }
        
        
    }
    

Log in to reply
 

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