cs: add «238. Product of Array Except Self»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
4763cdbdda
commit
15bd5cb743
1 changed files with 28 additions and 0 deletions
28
cs/product-of-array-except-self.cs
Normal file
28
cs/product-of-array-except-self.cs
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
public class Solution {
|
||||||
|
private int Get(int[] products, int idx) {
|
||||||
|
if (idx < 0 || idx >= products.Length) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
return products[idx];
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] ProductExceptSelf(int[] nums) {
|
||||||
|
var left = new int[nums.Length];
|
||||||
|
var right = new int[nums.Length];
|
||||||
|
|
||||||
|
for (var i = 0; i < nums.Length; ++i) {
|
||||||
|
left[i] = nums[i] * Get(left, i - 1);
|
||||||
|
|
||||||
|
int j = nums.Length - i - 1;
|
||||||
|
right[j] = nums[j] * Get(right, j + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = new int[nums.Length];
|
||||||
|
|
||||||
|
for (var i = 0; i < nums.Length; ++i) {
|
||||||
|
result[i] = Get(left, i - 1) * Get(right, i + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue