mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 05:24:07 +00:00
day 16: 238-product-of-array-except-self
This commit is contained in:
parent
3de8ed3745
commit
b634dfae36
10
238-product-of-array-except-self/driver.cpp
Normal file
10
238-product-of-array-except-self/driver.cpp
Normal file
@ -0,0 +1,10 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<int> nums{1, 2, 3, 4};
|
||||
vector<int> answer{24, 12, 8, 6};
|
||||
Solution soln;
|
||||
cout << "Found products correctly? " << soln.test(nums, answer) << endl;
|
||||
return 0;
|
||||
}
|
||||
35
238-product-of-array-except-self/soln.cpp
Normal file
35
238-product-of-array-except-self/soln.cpp
Normal file
@ -0,0 +1,35 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
vector<int> Solution::productExceptSelf(vector<int> &nums)
|
||||
{
|
||||
int n = nums.size();
|
||||
vector<int> pres(n);
|
||||
vector<int> sufs(n);
|
||||
vector<int> result(n);
|
||||
// calculate prefixes starting from second
|
||||
int cur = 1;
|
||||
for (int i = 1; i < n; i++)
|
||||
{
|
||||
pres[i] = cur * nums[i - 1];
|
||||
cur = pres[i];
|
||||
}
|
||||
// calculate suffixes starting from second last
|
||||
cur = 1;
|
||||
for (int j = n - 2; j >= 0; j--)
|
||||
{
|
||||
sufs[j] = cur * nums[j + 1];
|
||||
cur = sufs[j];
|
||||
}
|
||||
|
||||
result[0] = sufs[0];
|
||||
result[n - 1] = pres[n - 1];
|
||||
for (int i = 1; i < n - 1; i++)
|
||||
{
|
||||
result[i] = pres[i] * sufs[i];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool Solution::test(vector<int>& nums, vector<int>& answer) {
|
||||
return productExceptSelf(nums) == answer;
|
||||
}
|
||||
7
238-product-of-array-except-self/soln.hpp
Normal file
7
238-product-of-array-except-self/soln.hpp
Normal file
@ -0,0 +1,7 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
class Solution {
|
||||
public:
|
||||
vector<int> productExceptSelf(vector<int>& nums);
|
||||
bool test(vector<int>& nums, vector<int>& answer);
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user