zoukankan      html  css  js  c++  java
  • 985. 查询后的偶数和

     

     

    代码一:暴力超时。

    class Solution(object):
        # 暴力超时
        def sumEvenAfterQueries(self, A, queries):
            """
            :type A: List[int]
            :type queries: List[List[int]]
            :rtype: List[int]
            """
            ans = []
            for i in range(len(A)):
                A[queries[i][1]] += queries[i][0]
                temp = 0
                for j in range(len(A)):
                    if A[j] % 2 == 0:
                        temp += A[j]
                ans.append(temp)
            return ans
    
    
    if __name__ == '__main__':
        solution = Solution()
        print(solution.sumEvenAfterQueries(A=[1, 2, 3, 4], queries=[[1, 0], [-3, 1], [-4, 0], [2, 3]]))

    代码二:

     1 class Solution(object):
     2     def sumEvenAfterQueries(self, A, queries):
     3         """
     4         :type A: List[int]
     5         :type queries: List[List[int]]
     6         :rtype: List[int]
     7         """
     8         # 返回值
     9         ans = []
    10         # 统计原list中偶数元素的和
    11         temp = 0
    12         for i in range(len(A)):
    13             if A[i] % 2 == 0:
    14                 temp += A[i]
    15         for j in range(len(A)):
    16             val = queries[j][0]
    17             index = queries[j][1]
    18             # 若将要改变的元素是偶数,则要从和中减掉
    19             if A[index] % 2 == 0:
    20                 temp -= A[index]
    21             # 改变元素
    22             A[index] += val
    23             # 若改变以后是偶数,则要加到和中
    24             if A[index] % 2 == 0:
    25                 temp += A[index]
    26             ans.append(temp)
    27         return ans
    28 
    29 
    30 if __name__ == '__main__':
    31     solution = Solution()
    32     print(solution.sumEvenAfterQueries(A=[1, 2, 3, 4], queries=[[1, 0], [-3, 1], [-4, 0], [2, 3]]))
  • 相关阅读:
    关于jstl.jar引用问题及解决方法
    React 解析/ 第二节 使用 Reac
    NOde.js的安装和简介
    JACOB调用控件函数
    Linux 常用命令
    webService接口发布失败问题
    CommonsMultipartFile---用Spring实现文件上传
    验证签名(章)是否有效的方法
    新起点,新征程
    使用C#正则表达式获取必应每日图片地址
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12800304.html
Copyright © 2011-2022 走看看