LeetCode-Sum of Even Numbers After Queries

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/88546101

Description:
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 <= A.length <= 10000
  • -10000 <= A[i] <= 10000
  • 1 <= queries.length <= 10000
  • -10000 <= queries[i][0] <= 10000
  • 0 <= queries[i][1] < A.length

题意:给定一个整数数组A和一个查询数组queries,对于queries中的每一次查询,先执行对A中的A[index]处的值加上val( i n d e x = q u e i r e s [ i ] [ 1 ] v a l = q u e r i e s [ i ] [ 0 ] i [ 0 , q u e r i e s . l e n g t h 1 ] index = queires[i][1], val = queries[i][0],i \in[0, queries.length - 1] ),之后求A中所有偶数的和的值;

解法:因为每一次的操作仅仅只对A中的一个元素进行值的操作,所以我们可以在此操作之前先求得初始时A中所有偶数的和为even;之后,对查询数组的每一个操作,假设此时要操作的位置为i,有下面几种情况

  • 如果A[i]为奇数 && queries[i][0]为奇数,那么进行累加之后A[i]的值必定为偶数,此时even的值需要加上A[i]和queries[i][0];
  • 如果A[i]为奇数 && queries[i][0]为偶数,那么进行累加之后A[i]的值仍然为奇数,此时even的值不变;
  • 如果A[i]为偶数 && queries[i][0]为偶数,那么进行累加之后A[i]的值仍然为偶数,此时even的值需要加上queries[i][0];
  • 如果A[i]为偶数 && queries[i][0]为奇数,那么进行累加之后A[i]的值为奇数,此时even的值需要减去A[i]和queries[i][0];
Java
class Solution {
    public int[] sumEvenAfterQueries(int[] A, int[][] queries) {
        int[] res = new int[queries.length];
        int even = 0;
        int ind = 0;
        for (int a: A) {
            even = a % 2 == 0 ? even + a : even;
        }
        for (int[] query: queries) {
            if (Math.abs(A[query[1]]) % 2 == 1 && Math.abs(query[0]) % 2 == 1) {
                even += query[0] + A[query[1]];
            } else if (A[query[1]] % 2 == 0) {
                if (query[0] % 2 == 0) {
                    even += query[0];
                } else {
                    even -= A[query[1]];
                }
            }
            A[query[1]] += query[0];
            res[ind++] = even;
        }

        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/88546101