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:多线程
    javascript:正则表达式、一个表单验证的例子
    DOM对象和window对象
    javascript:面向对象和常见内置对象及操作
    如何检查CentOS服务器受到DDOS攻击
    CentOS防SYN攻击
    CentOS服务器简单判断CC攻击的命令
    在VMware中为CentOS配置静态ip并可访问网络
    安全运维之:网络实时流量监测工具iftop
    安全运维之:网络实时流量监测工具iftop
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13220464.html
Copyright © 2011-2022 走看看