問(wèn)題:
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
大意:
給出一個(gè)有n(n>1)個(gè)整數(shù)的數(shù)組nums,返回一個(gè)output數(shù)組,output[i]等于除了nums[i]外其余所有元素的乘積。
不使用除法且在O(n)時(shí)間內(nèi)完成。
比如,給出 [1,2,3,4],返回 [24,12,8,6]。
進(jìn)階:
你能使用固定的空間復(fù)雜度嗎?(注意:output數(shù)組不算做額外的空間。)
思路:
如果用除法就簡(jiǎn)單了,直接全部乘起來(lái),然后每個(gè)位置對(duì)應(yīng)除以nums[i]的元素就可以了。
不用除法的話,我們要用兩次遍歷,先正著遍歷一遍,在結(jié)果數(shù)組上每個(gè)元素都算到累乘至nums數(shù)組中對(duì)應(yīng)位置的前面所有的元素,比如第三個(gè)元素的值為nums中前連個(gè)元素的乘積。
第二次遍歷,反著遍歷,用一個(gè)變量記錄從后到前的累乘,同時(shí)結(jié)果數(shù)組中乘以這個(gè)變量。
這樣對(duì)每一個(gè)位置來(lái)說(shuō),其剛好在第一次遍歷中取得了它前面所有元素的乘積,第二次遍歷中又乘以了它后面所有元素的乘積,唯獨(dú)不算它自己在內(nèi)。
代碼(Java):
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
for (int i = 0; i < result.length; i++) result[i] = 1;
for (int i = 1; i < nums.length; i++) {// 先正著來(lái)一遍,只乘到前一個(gè)元素
result[i] = result[i-1] * nums[i-1];
}
int behind = 1;
for (int i = nums.length-1; i >= 0; i--) {// 再倒著來(lái)一遍,乘以后面的數(shù)
result[i] = result[i] * behind;
behind = behind * nums[i];
}
return result;
}
}
合集:https://github.com/Cloudox/LeetCode-Record