파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 7. 31. 23:45

https://leetcode.com/problems/range-sum-query-mutable/

 

Range Sum Query - Mutable - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

처음에 좀 navie 하게 풀었다가 TL 남 =_=
솔루션 좀 찾아보니 미리 저장해놓는 방식으로 해결 가능.

class NumArray:

    def __init__(self, nums: List[int]):
        self.nums = nums
        self.s = sum(nums)
        self.l = len(nums)

    def update(self, index: int, val: int) -> None:
        self.s -= self.nums[index]
        self.nums[index] = val
        self.s += self.nums[index]

    def sumRange(self, left: int, right: int) -> int:
        if right - left > self.l // 2:
            ans = sum(self.nums[:left]) + sum(self.nums[right+1:])
            return self.s - ans
        else:
            return sum(self.nums[left: right+1])
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.08.02
Today's Challenge  (0) 2022.08.01
Today's Challenge  (0) 2022.07.30
Today's Challenge  (0) 2022.07.29
Today's Challenge  (0) 2022.07.28
Comments