- 238. 除自身以外数组的乘积 中等
- 560. 和为 K 的子数组 中等

解法1: 左右乘积列表

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int length = nums.size()
// L 和 R 分别表示左右两侧的乘积列表
vector<int> L(length, 0), R(length, 0)
vector<int> answer(length)
// L[i] 为索引 i 左侧所有元素的乘积
// 对于索引为 '0' 的元素,因为左侧没有元素,所以 L[0] = 1
L[0] = 1
for (int i = 1
L[i] = nums[i - 1] * L[i - 1]
}
// R[i] 为索引 i 右侧所有元素的乘积
// 对于索引为 'length-1' 的元素,因为右侧没有元素,所以 R[length-1] = 1
R[length - 1] = 1
for (int i = length - 2
R[i] = nums[i + 1] * R[i + 1]
}
// 对于索引 i,除 nums[i] 之外其余各元素的乘积就是左侧所有元素的乘积乘以右侧所有元素的乘积
for (int i = 0
answer[i] = L[i] * R[i]
}
return answer
}
}
- 时间复杂度: O(N), 其中 N 指的是数组
nums 的大小。预处理 L 和 R 数组以及最后的遍历计算都是 O(N) 的时间复杂度
- 空间复杂度: O(N), - 其中 N 指的是数组
nums 的大小。使用了 L 和 R 数组去构造答案,L 和 R 数组的长度为数组 nums 的大小
解法2: 空间复杂度O(1)
- 这种方法的唯一变化就是我们没有构造 R 数组。而是用一个遍历来跟踪右边元素的乘积。并更新数组 answer[i]=answer[i]∗R。然后 R 更新为 R=R∗nums[i],其中变量 R 表示的就是索引右侧数字的乘积。
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int length = nums.size()
vector<int> answer(length)
// answer[i] 表示索引 i 左侧所有元素的乘积
// 因为索引为 '0' 的元素左侧没有元素, 所以 answer[0] = 1
answer[0] = 1
for (int i = 1
answer[i] = nums[i - 1] * answer[i - 1]
}
// R 为右侧所有元素的乘积
// 刚开始右边没有元素,所以 R = 1
int R = 1
for (int i = length - 1
// 对于索引 i,左边的乘积为 answer[i],右边的乘积为 R
answer[i] = answer[i] * R
// R 需要包含右边所有的乘积,所以计算下一个结果时需要将当前值乘到 R 上
R *= nums[i]
}
return answer
}
}
- 时间复杂度: O(N), 其中 N 指的是数组
nums 的大小。预处理 L 和 R 数组以及最后的遍历计算都是 O(N) 的时间复杂度
- 空间复杂度: O(1), 输出数组不算进空间复杂度中,因此我们只需要常数的空间存放变量

解法1: 前缀和+哈希表优化

class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> mp;
mp[0] = 1;
int count = 0;
int pre = 0;
for (auto& x : nums) {
pre += x;
if (mp.find(pre - k) != mp.end()) {
count += mp[pre - k];
}
mp[pre]++;
}
return count;
}
};
- 时间复杂度: O(N), 其中 n 为数组的长度。我们遍历数组的时间复杂度为 O(n),中间利用哈希表查询删除的复杂度均为 O(1),因此总时间复杂度为 O(n)。
- 空间复杂度: O(1), 其中 n 为数组的长度。哈希表在最坏情况下可能有 n 个不同的键值,因此需要 O(n) 的空间复杂度