美文网首页
LeetCode之Sum of Even Numbers Aft

LeetCode之Sum of Even Numbers Aft

作者: 糕冷羊 | 来源:发表于2019-02-17 16:20 被阅读0次

    问题:
    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.

    Example 1:
    
    Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
    Output: [8,6,2,4]
    Explanation: 
    At the beginning, the array is [1,2,3,4].
    After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
    After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
    After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
    After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
    
    Note:
    
    1. 1 <= A.length <= 10000
    2. -10000 <= A[i] <= 10000
    3. 1 <= queries.length <= 10000
    4. -10000 <= queries[i][0] <= 10000
    5. 0 <= queries[i][1] < A.length
    

    方法:
    先计算所有偶数的和,然后遍历queries,如果A[index]是偶数则先减去,然后A[index]做加处理,然后如果A[index]仍为偶数则加到和中,然后添加到最终结果中,遍历之后输出结果。

    具体实现:

    class SumOfEvenNumbersAfterQueries {
        fun sumEvenAfterQueries(A: IntArray, queries: Array<IntArray>): IntArray {
            val result = mutableListOf<Int>()
            var sum = A.filter { it % 2 == 0 }.sum()
            for (query in queries) {
                val num = query[0]
                val index = query[1]
                if (A[index] % 2 == 0) {
                    sum -= A[index]
                }
                A[index] += num
                if (A[index] % 2 == 0) {
                    sum += A[index]
                }
                result.add(sum)
            }
            return result.toIntArray()
        }
    }
    
    fun main(args: Array<String>) {
        val A = intArrayOf(1, 2, 3, 4)
        val queries = arrayOf(intArrayOf(1, 0), intArrayOf(-3, 1), intArrayOf(-4, 0), intArrayOf(2, 3))
        val sumOfEvenNumbersAfterQueries = SumOfEvenNumbersAfterQueries()
        CommonUtils.printArray(sumOfEvenNumbersAfterQueries.sumEvenAfterQueries(A, queries).toTypedArray())
    }
    

    有问题随时沟通

    具体代码实现可以参考Github

    相关文章

      网友评论

          本文标题:LeetCode之Sum of Even Numbers Aft

          本文链接:https://www.haomeiwen.com/subject/kiigeqtx.html