LeetCode之Sum of Even Numbers After Queries(Kotlin)

嘟囔發表於2019-02-17

問題: 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

相關文章