zoukankan      html  css  js  c++  java
  • 985. Sum of Even Numbers After Queries

    We have an array A of integers, and an array queries of queries.

    For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index].  Then, the answer to the i-th query is the sum of the even values of A.

    (Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)

    Return the answer to all queries.  Your answer array should have answer[i] as the answer to the i-th query.

    有一个数组A,和一个query数组,每次query,会在数组A下标为query[i][1]的地方加上query[i][0],然后统计下偶数的和。

    n2 可以每次query之后重新求一次偶数和

    min(m,n)的方法是一开始就统计好偶数和,然后根据query的值和原始值的加和得到的数的奇偶来判断这个和应该加减多少。

    value = query[i][0], index = query[i][1]

    如果A[index] 是奇数,相加后的数变成偶数了,那就可以给加这个偶数否则就没有变化

    如果A[index]是偶数,相加后的数还是偶数,那就加上这个value,否则减去A[index]

    class Solution(object):
        def sumEvenAfterQueries(self, A, queries):
            """
            :type A: List[int]
            :type queries: List[List[int]]
            :rtype: List[int]
            """
            even_sum = 0
            ans = []
            for value in A:
                if value % 2 == 0:
                    even_sum += value
            for query in queries:
                value = query[0]
                index = query[1]
                if A[index] % 2 == 0:
                    if (A[index] + value) % 2 == 0:
                        even_sum += value
                    else:
                        even_sum -= A[index]
                    A[index] += value
                else:
                    if (A[index] + value) % 2 == 0:
                        even_sum += A[index] + value
                    else:
                        pass
                    A[index] += value
                ans.append(even_sum)
            return ans
  • 相关阅读:
    java实现网络监听
    程序员必须知道FTP命令
    Java进化的尽头
    Oracle逻辑备份与恢复(Data Pump)
    JQuery日期选择器插件date-input
    大型高并发高负载网站的系统架构剖析
    万言万当,不如一默为官之道
    angular.js高级程序设计书本开头配置环境出错,谁能给解答一下
    安装meteor运行基本demo发生错误。
    nodejs 通过 get获取数据修改redis数据
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13220464.html
Copyright © 2011-2022 走看看