Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5397877

Browse files
two_pointer: 238
1 parent 52cbdd9 commit 5397877

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* @lc app=leetcode.cn id=238 lang=cpp
3+
*
4+
* [238] 除自身以外数组的乘积
5+
*
6+
* https://leetcode.cn/problems/product-of-array-except-self/description/
7+
*
8+
* algorithms
9+
* Medium (74.80%)
10+
* Likes: 1457
11+
* Dislikes: 0
12+
* Total Accepted: 270.8K
13+
* Total Submissions: 362K
14+
* Testcase Example: '[1,2,3,4]'
15+
*
16+
* 给你一个整数数组 nums,返回
17+
* 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。
18+
*
19+
* 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位
20+
* 整数范围内。
21+
*
22+
* 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
23+
*
24+
*
25+
*
26+
* 示例 1:
27+
*
28+
*
29+
* 输入: nums = [1,2,3,4]
30+
* 输出: [24,12,8,6]
31+
*
32+
*
33+
* 示例 2:
34+
*
35+
*
36+
* 输入: nums = [-1,1,0,-3,3]
37+
* 输出: [0,0,9,0,0]
38+
*
39+
*
40+
*
41+
*
42+
* 提示:
43+
*
44+
*
45+
* 2 <= nums.length <= 10^5
46+
* -30 <= nums[i] <= 30
47+
* 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内
48+
*
49+
*
50+
*
51+
*
52+
* 进阶:你可以在 O(1) 的额外空间复杂度内完成这个题目吗?(
53+
* 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
54+
*
55+
*/
56+
57+
#include <vector>
58+
using namespace std;
59+
60+
// @lc code=start
61+
class Solution {
62+
public:
63+
// 左右两个数组,分别代表当前元素左侧乘积和右侧乘积,两者想乘即为当前位置结果
64+
vector<int> productExceptSelf(vector<int> &nums) {
65+
int n = nums.size();
66+
if (nums.empty()) {
67+
return vector<int>();
68+
}
69+
vector<int> left(n), right(n);
70+
left[0] = 1, right[n - 1] = 1;
71+
for (int i = 1; i < n; i++) {
72+
left[i] = left[i - 1] * nums[i - 1];
73+
}
74+
for (int i = n - 2; i >= 0; i--) {
75+
right[i] = right[i + 1] * nums[i + 1];
76+
}
77+
78+
vector<int> ret(n);
79+
for (int i = 0; i < n; i++) {
80+
ret[i] = left[i] * right[i];
81+
}
82+
return ret;
83+
}
84+
};
85+
// @lc code=end

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /