-
PrefixSum_Leetcode_303. Range Sum Query - Immutable [swift]알고리즘/알고리즘 문제풀이 2025. 3. 13. 17:51
https://leetcode.com/problems/range-sum-query-immutable/description/
정답코드
아무 생각 없이 nums만 저장하고 method에서 더해서 반환했더니
35ms가 나왔다. (0ms가 나와야함)
PrefixSum 문제라는걸 상기하고 다시 풀어서 0ms로 해결
더보기더보기class NumArray { var nums: [Int] var sums: [Int] init(_ nums: [Int]) { self.nums = nums var cur = 0 var sums = [Int](repeating: 0, count: nums.count) for i in 0..<nums.count { cur += nums[i] sums[i] = cur } self.sums = sums } func sumRange(_ left: Int, _ right: Int) -> Int { if left > 0 { return sums[right] - sums[left - 1] } else if right > 0 { return sums[right] } else { return sums[0] } } // func sumRange(_ left: Int, _ right: Int) -> Int { // let ranged = nums[left...right] // return ranged.reduce(0,{$0 + $1}) // } }
'알고리즘 > 알고리즘 문제풀이' 카테고리의 다른 글
dijkstra_Programmers_배달 [swift] (0) 2025.03.25 PrefixSum_Leetcode_2381. Shifting Letters II [swift] (0) 2025.03.24 PrefixSum_Leetcode_238. Product of Array Except Self [swift] (0) 2025.03.13 PrefixSum_Leetcode_1248. Count Number of Nice Subarrays [swift] (0) 2025.03.11 PrefixSum_Leetcode_523. Continuous Subarray Sum [swift] (0) 2025.03.11