-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathID238ProductOfArrayExceptSelf.java
102 lines (95 loc) · 2.98 KB
/
ID238ProductOfArrayExceptSelf.java
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* @Author: yuran
* @Date: 2024-09-01 18:28:41
* @LastEditTime: 2024-09-08 19:43:18
* @描述:
*/
package leetcode.editor.cn;
public class ID238ProductOfArrayExceptSelf {
public static void main(String[] args) {
Solution solution = new ID238ProductOfArrayExceptSelf().new Solution();
StringBuilder builder = new StringBuilder();
// 执行测试
int[] arr = {1, 2, 3, 4, 5};
int[] ints = solution.productExceptSelf(arr);
System.out.println(builder);
}
// leetcode submit region begin(Prohibit modification and deletion)
class Solution {
/**
* 描述:
* 1.不使用除法
* 2.O(n)时间复杂度
* Date 2024/8/29
*
* @param nums
* @return int[]
*/
public int[] productExceptSelf1(int[] nums) {
int len = nums.length;
int[] answer = new int[len];
// i=(i-1)*(i+1)
// 左边
int[] left = new int[len];
left[0] = 1;
for (int i = 1; i < len; i++) {
left[i] = left[i - 1] * nums[i - 1];
if (left[i] == 0) break;
}
// 右边
int[] right = new int[len];
right[len - 1] = 1;
for (int i = len - 2; i >= 0; i--) {
right[i] = right[i + 1] * nums[i + 1];
if (right[i] == 0) break;
}
// ans=left*right
for (int i = 0; i < len; i++) {
answer[i] = left[i] * right[i];
}
return answer;
}
/**
* 描述:空间优化版本
*/
public int[] productExceptSelf(int[] nums) {
int len = nums.length;
// i=(i-1)*(i+1)
// 左边
int[] left = new int[len];
left[0] = 1;
for (int i = 1; i < len; i++) {
left[i] = left[i - 1] * nums[i - 1];
if (left[i] == 0) break;
}
// 右边
int[] right = new int[len];
right[len - 1] = 1;
for (int i = len - 2; i >= 0; i--) {
right[i] = right[i + 1] * nums[i + 1];
if (right[i] == 0) break;
}
// ans=left*right
for (int i = 0; i < len; i++) {
left[i] = left[i] * right[i];
}
return left;
}
}
// leetcode submit region end(Prohibit modification and deletion)
public int[] productExceptSelf(int[] nums) {
int len = nums.length;
int[] answer = new int[len];
// O(N²)的时间复杂度——超时了
for (int i = 0; i < len; i++) {
answer[i] = 1;
// 模运算
int j = (i + 1) % len;
while (j != i) {
answer[i] = answer[i] * nums[j];
j = (j + 1) % len; // 下标所以不可以是len
}
}
return answer;
}
}