LeetCode刷题记录——第985题(查询后的偶数和)

版权声明:此BLOG为个人BLOG,内容均来自原创及互连网转载。最终目的为记录自己需要的内容或自己的学习感悟,不涉及商业用途,转载请附上原博客。 https://blog.csdn.net/bulo1025/article/details/88926376

题目描述

给出一个整数数组 A 和一个查询数组 queries。

对于第 i 次查询,有 val = queries[i][0], index = queries[i][1],我们会把 val 加到 A[index] 上。然后,第 i 次查询的答案是 A 中偶数值的和。

(此处给定的 index = queries[i][1] 是从 0 开始的索引,每次查询都会永久修改数组 A。)

返回所有查询的答案。你的答案应当以数组 answer 给出,answer[i] 为第 i 次查询的答案。

示例:

输入:A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
输出:[8,6,2,4]
解释:
开始时,数组为 [1,2,3,4]。
将 1 加到 A[0] 上之后,数组为 [2,2,3,4],偶数值之和为 2 + 2 + 4 = 8。
将 -3 加到 A[1] 上之后,数组为 [2,-1,3,4],偶数值之和为 2 + 4 = 6。
将 -4 加到 A[0] 上之后,数组为 [-2,-1,3,4],偶数值之和为 -2 + 4 = 2。
将 2 加到 A[3] 上之后,数组为 [-2,-1,3,6],偶数值之和为 -2 + 6 = 4。

题目描述

  • 构造sumofeven函数,计算偶数的和
  • 根据三种情况判断是否需要加减

代码示例

class Solution(object):
    def sumEvenAfterQueries(self, A, queries):
        """
        :type A: List[int]
        :type queries: List[List[int]]
        :rtype: List[int]
        """
        sumofeven = sum(i for i in A if i%2 == 0)
        res = []
        for item in queries:
            index = item[1]
            value =item[0]
            newvalue = A[index] + value
            # 先是偶数,加了之后还是偶数
            if A[index]%2 == 0 and newvalue%2 == 0:
                sumofeven += value
            # 先是偶数,加了之后变成奇数
            if A[index]%2 == 0 and newvalue%2 != 0:
                sumofeven -= A[index]
            # 先是奇数,加了之后变成偶数
            if A[index]%2 != 0 and newvalue%2 == 0:
                sumofeven += newvalue
            res.append(sumofeven)
            A[index] = newvalue
        return res

2019年3月31日 于燕南

猜你喜欢

转载自blog.csdn.net/bulo1025/article/details/88926376