leetcode记录:难度简单:985. Sum of Even Numbers After Queries(计算数组与2维数组查询后的值)

题目出处:https://leetcode.com/problems/sum-of-even-numbers-after-queries/

题目描述:

我们有一个数组一个整数数组,一个查询的数组查询。对于第i个查询val =查询[i][0], index =查询[i][1],我们将val添加到[index]中。然后,第i个查询的答案是a的偶数的和(这里,给定的index = queries[i][1]是一个基于0的索引,每个查询都永久性地修改数组a)。返回所有查询的答案。您的答案数组应该有answer[i]作为第i个查询的答案。

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.

思路:

就对应查询,判断计算就行了,因为循环条件只有一个就是全部加完,所以可以用for循环,比较简单,没什么好讲的,因为我不喜欢直接操作原数组,所以我用let B=A.map((x)=>{return x});复制了一个新的,直接操作原数组,可能会更快

/**
 * @param {number[]} A
 * @param {number[][]} queries
 * @return {number[]}
 */
let sumEvenAfterQueries = function(A, queries) {
    //新建一个B,数据与A同,不直接操作A
    let B=A.map((x)=>{return x});
    //储存每次操作完成后的结果
    let result = [];

    //循环相加,index要操作的下标,digit是对应下标的值
    let len = queries.length;
    for(let i = 0;i<len;i++){
        // console.log(A[i]);
        //计算 adding后的数组
        let index = queries[i][1];
        let digit = queries[i][0];
        B[index]=B[index]+digit;

        //找到数组中的偶数,计算结果,并推进result数组中
        let count = 0;
        for(let j=0;j<len;j++){
            if(B[j]%2 ===0){
                count+=B[j]
            }
        }
        result.push(count)
    }
    return result
};

let A=[1,2,3,4],queries = [[1,0],[-3,1],[-4,0],[2,3]];
console.log(sumEvenAfterQueries(A, queries));

猜你喜欢

转载自blog.csdn.net/weixin_42273637/article/details/87855725