LeetCode 985

HJ seo·2022년 9월 21일
0

Coding Test(Python)

목록 보기
30/45

문제 링크

잡담.

최근에 벼르고 벼뤘던 코딩테스트 오픈카톡을 들어가게 되었다. 정말 그냥 들어가면 되는 방이더라.
들어가서 백준을 제외한 이런저런 코딩테스트 준비를 할 수 있는 사이트들이 보여서 LeetCdoe를 한번 풀어봤다.
백준과 다르게
1. 채점결과에 정답을 맞췄을 때 시간, 메모리가 얼마나 들었는지 알려주는 기능이 좋더라.
2. 문제가 어떤 식으로 작동하면 되는지 initial code를 짜기 매우 쉽게 설명을 풀어서 써놓았다.

문제 설명.

※백준과 같이 어떤 스토리가 있는 문제가 아니라 정말 문제 설명만 있기 때문에 설명은 복붙으로 채운다.

You are given an integer array nums and an array queries where queries[i] = [vali, indexi].

For each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums.

Return an integer array answer where answer[i] is the answer to the ith query.

  • example input
nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
  • output
[8,6,2,4]
  • description
At the beginning, the array is [1,2,3,4].
After adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.

풀이 설명.

문제를 보고 거의 바로 풀이가 떠올랐기 때문에 그 방법을 먼저 간단히 적으려고 한다.
처음에 array에 있는 짝수들의 합even_sum을 구한다. 그 이후 각각의 쿼리에 따라 수가 짝수에서 홀수로 변하는지, 짝수가 그대로 짝수로 유지되거나 홀수가 짝수로 변하는지에 따라 even_sum의 값을 재조정해주고, array의 값 역시 바꿔준다.
answer list에 값을 넣어주는 것으로 end.

풀이 코드.

class Solution:
    def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
        leng = len(nums)
        even_sum = 0
        for i in range(leng):
            if nums[i]%2 == 0:
                even_sum += nums[i]
        
        answer = [0 for _ in range(leng)]
        
        for i in range(leng):
            x,y = queries[i]
            z = nums[y]
            if z%2 and x%2:
                even_sum += z+x
            elif z%2 == 0 and x%2 == 0:
                even_sum += x
            elif z%2 == 0 and x%2:
                even_sum -= z
                
            nums[y] += x
            
            answer[i] = even_sum
            
        return answer
profile
다양한 분야에 관심이 많은 초보 개발자 입니다.

0개의 댓글