标签:ext ++ element example 序列 size put not nbsp
Given an array of n integers where n > 1,
nums
, return an arrayoutput
such thatoutput[i]
is equal to the product of all the elements ofnums
exceptnums[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.)
题目要求不能使用除法,空间复杂度为O(1),时间复杂度为O(n)。
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int n = nums.size(); if (n <= 1) return nums; vector<int> res(n); res[0] = 1; for (int i = 1; i <= n - 1; ++i) res[i] = res[i - 1] * nums[i - 1]; int post_product = 1; for (int i = n-2; i >= 0; --i) { // 注意起始位置 post_product *= nums[i+1]; res[i] *= post_product; } return res; } };
238. Product of Array Except Self
标签:ext ++ element example 序列 size put not nbsp
原文地址:http://www.cnblogs.com/naivecoder/p/6964755.html