-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo238_Array.cs
59 lines (57 loc) · 1.95 KB
/
No238_Array.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode_238
{
//static void Main(string[] args)
//{
// var solution = new Solution();
// while (true)
// {
// //int input = int.Parse(Console.ReadLine());
// //int input2 = int.Parse(Console.ReadLine());
// //int input3 = int.Parse(Console.ReadLine());
// string input = Console.ReadLine();
// //string input2 = Console.ReadLine();
// int[] intArr = input.Split(',').Select(s => int.Parse(s)).ToArray();
// //int input2 = int.Parse(Console.ReadLine());
// var res = solution.ProductExceptSelf(intArr);
// ConsoleX.WriteLine(res);
// }
//}
public class Solution
{
/// <summary>
/// 左右乘积法,算一个数组的乘积可以先慢慢算出左边乘积,在算出右边乘积,这样两次遍历就能计算出所有答案
/// 时间复杂度:O(n)
/// 空间复杂度:O(1)
/// </summary>
/// <param name="nums"></param>
/// <returns></returns>
public int[] ProductExceptSelf(int[] nums)
{
int[] ans = new int[nums.Length];
int leftProduct = 1;
//将左乘积填入答案数组中
for (int i = 0; i < nums.Length; i++)
{
if (i == 0)
ans[0] = 1;
else
{
leftProduct = leftProduct * nums[i - 1];
ans[i] = leftProduct;
}
}
//在把右乘积算出来的同时算出答案
int rightProduct = 1;
for (int i = nums.Length - 1; i >= 0; i--)
{
if (i != nums.Length - 1)
rightProduct = rightProduct * nums[i + 1];
ans[i] = ans[i] * rightProduct;
}
return ans;
}
}
}