跳转至

3701. 计算交替和

题目描述

给你一个整数数组 nums

交替和 定义为:将 nums 中偶数下标位置的元素 相加 减去 奇数下标位置的元素。即:nums[0] - nums[1] + nums[2] - nums[3]...

返回表示 nums 的交替和的整数。

 

示例 1:

输入: nums = [1,3,5,7]

输出: -4

解释:

  • 偶数下标位置的元素是 nums[0] = 1nums[2] = 5,因为 0 和 2 是偶数。
  • 奇数下标位置的元素是 nums[1] = 3nums[3] = 7,因为 1 和 3 是奇数。
  • 交替和为 nums[0] - nums[1] + nums[2] - nums[3] = 1 - 3 + 5 - 7 = -4

示例 2:

输入: nums = [100]

输出: 100

解释:

  • 唯一的偶数下标位置的元素是 nums[0] = 100,因为 0 是偶数。
  • 没有奇数下标位置的元素。
  • 交替和为 nums[0] = 100

 

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

解法

方法一:模拟

我们可以直接遍历数组 \(\textit{nums}\),对于每个下标 \(i\),如果 \(i\) 是偶数,则将 \(\textit{nums}[i]\) 加到答案中,否则将 \(\textit{nums}[i]\) 减去。

最后返回答案即可。

时间复杂度 \(O(n)\),其中 \(n\) 是数组 \(\textit{nums}\) 的长度。空间复杂度 \(O(1)\)

1
2
3
class Solution:
    def alternatingSum(self, nums: List[int]) -> int:
        return sum(nums[0::2]) - sum(nums[1::2])
1
2
3
4
5
6
7
8
9
class Solution {
    public int alternatingSum(int[] nums) {
        int ans = 0;
        for (int i = 0; i < nums.length; ++i) {
            ans += (i % 2 == 0 ? nums[i] : -nums[i]);
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
public:
    int alternatingSum(vector<int>& nums) {
        int ans = 0;
        for (int i = 0; i < nums.size(); ++i) {
            ans += (i % 2 == 0 ? nums[i] : -nums[i]);
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func alternatingSum(nums []int) (ans int) {
    for i, x := range nums {
        if i%2 == 0 {
            ans += x
        } else {
            ans -= x
        }
    }
    return
}
1
2
3
4
5
6
7
function alternatingSum(nums: number[]): number {
    let ans: number = 0;
    for (let i = 0; i < nums.length; ++i) {
        ans += i % 2 === 0 ? nums[i] : -nums[i];
    }
    return ans;
}

评论