题意
- 给一个数组, 计算不包含nums[i]的数组的乘积,
方法
- 记录数组中零的数量和索引
代码
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
bool zero_idx[100024];
int zero_nums = 0;
memset(zero_idx, 0, sizeof(zero_idx));
int product_all = 1, N = nums.size();
for (int i = 0; i < N; i++) {
if (nums[i] == 0) {
zero_idx[i] = true;
zero_nums++;
continue;
}
product_all *= nums[i];
}
vector<int> ans;
for (int i = 0; i < N; i++) {
if (zero_nums > 1) {
ans.push_back(0);
}
else if (zero_idx[i] == true || zero_nums == 0) {
int product_res = product_all;
if (nums[i]) product_res /= nums[i];
ans.push_back(product_res);
}
else ans.push_back(0);
}
return ans;
}
};
标签:product,idx,nums,int,Self,Except,Product,zero,ans
From: https://www.cnblogs.com/Figure_at_a_Window/p/16751309.html