在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note:
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。 示例: 给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 说明:
132ms 1 class NumArray { 2 let sum: [Int] 3 init(_ nums: [Int]) { 4 var s = 0 5 var sum = [0] 6 for n in nums { 7 s += n 8 sum.append(s) 9 } 10 self.sum = sum 11 } 12 13 func sumRange(_ i: Int, _ j: Int) -> Int { 14 return sum[j + 1] - sum[i] 15 } 16 } 132ms 1 class NumArray { 2 3 let _nums : [Int] 4 var sums : [Int] 5 6 init(_ nums: [Int]) { 7 _nums = nums 8 9 sums = [Int]() 10 if nums.isEmpty { 11 return 12 } 13 sums.append(_nums[0]) 14 for i in 1..<nums.count { 15 sums.append(sums[i-1] + _nums[i]) 16 } 17 18 } 19 20 @inline(__always) func sumRange(_ i: Int, _ j: Int) -> Int { 21 if i == 0 { 22 return sums[j] 23 } 24 return sums[j]-sums[i-1] 25 } 26 } 27 28 /** 29 * Your NumArray object will be instantiated and called as such: 30 * let obj = NumArray(nums) 31 * let ret_1: Int = obj.sumRange(i, j) 32 */ 33 172ms 1 class NumArray { 2 3 private var sums: [Int] = [] 4 5 init(_ nums: [Int]) { 6 guard !nums.isEmpty else { 7 return 8 } 9 10 var sums = Array(repeating: 0, count: nums.count) 11 sums[0] = nums[0] 12 for index in 1..<nums.count { 13 let num = nums[index] 14 sums[index] = sums[index - 1] + num 15 } 16 17 self.sums = sums 18 } 19 20 func sumRange(_ i: Int, _ j: Int) -> Int { 21 if i == 0 { 22 return sums[j] 23 } else { 24 return sums[j] - sums[i - 1] 25 } 26 } 27 } 2444ms 1 class NumArray { 2 let nums: [Int] 3 4 init(_ nums: [Int]) { 5 self.nums = nums 6 } 7 8 func sumRange(_ i: Int, _ j: Int) -> Int 9 { 10 var sum = 0 11 for index in i...j 12 { 13 sum += nums[index] 14 } 15 return sum 16 } 17 } 3328ms 1 class NumArray { 2 3 var nums: [Int] 4 5 init(_ nums: [Int]) { 6 self.nums = nums 7 } 8 9 func sumRange(_ i: Int, _ j: Int) -> Int { 10 11 guard i <= j && i < nums.count else { 12 return 0 13 } 14 15 let i = i < 0 ? 0 : i 16 let j = j < nums.count ? j : nums.count-1 17 18 var sum = 0 19 for k in i...j { 20 sum += nums[k] 21 } 22 23 return sum 24 } 25 }
|
请发表评论