1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00
LeetCode/cs/product-of-array-except-self.cs
Matej Focko 15bd5cb743
cs: add «238. Product of Array Except Self»
Signed-off-by: Matej Focko <mfocko@redhat.com>
2024-03-15 17:28:55 +01:00

28 lines
721 B
C#

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;
}
}