LeetCode 30 days Challenge - Day 15
本系列將對LeetCode新推出的30天算法挑戰進行總結記錄,旨在記錄學習成果、方便未來查閱,同時望爲廣大網友提供幫助。
Product of Array Except Self
Given an array nums
of n integers where n > 1, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It’s guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
Solution
題目要求分析:給定一個整型數組,對每個元素,計算整個數組除了該元素以外的其他元素乘積。
解法:
本題直觀考慮是很簡單的,然而,題目中提出了兩個要求:1. 不能使用除法;2. 使用常量空間(除返回數組)。
因此,必須充分利用返回數組來解決問題。以下對基本思想進行說明:
- 從左往右遍歷nums,在返回數組中,位置 i 處的元素值爲
原數組中 i 左邊的所有元素乘積
; - 從右往左遍歷nums,用一個變量suffix記錄
原數組中當前位置右邊的所有元素乘積
,並更新返回數組。
實際上,返回數組中每個元素的計算,是由“原數組中該位置左邊的元素乘積”乘“原數組中該位置右邊的元素乘積”得到的,巧妙地避開了自己。
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> res(nums.size(), 1);
for (int i = 1; i<nums.size(); i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int suffix = 1;
for (int i = nums.size()-1; i>=0; i--) {
res[i] = res[i] * suffix;
suffix *= nums[i];
}
return res;
}
傳送門:Product of Array Except Self
2020/4 Karl