思路:
参考了https://leetcode-cn.com/problems/ways-to-make-a-fair-array/solution/shuang-bai-zheng-fu-jiao-ti-qian-zhui-he-by-letian/,这个方法非常清晰简洁。当遇到涉及奇数下标和与偶数下标和的问题时,奇偶交替前缀和可能是一种比较好的处理方式。
实现:
1 class Solution 2 { 3 public: 4 int waysToMakeFair(vector<int>& nums) 5 { 6 int n = nums.size(); 7 vector<int> s(n + 1, 0); 8 for (int i = 1; i <= n; i++) 9 { 10 if (i & 1) s[i] = s[i - 1] + nums[i - 1]; 11 else s[i] = s[i - 1] - nums[i - 1]; 12 } 13 int res = 0; 14 for (int i = 1; i <= n; i++) 15 { 16 if (s[i - 1] == s[n] - s[i]) res++; 17 } 18 return res; 19 } 20 }