[leetcode] 238. Product of Array Except Self
2015-12-15 10:08
471 查看
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.)
这道题是计算数组中除当前数字之外其他数字的乘积,题目难度为Medium。
题目限定了时间复杂度为O(n),双层遍历不能使用,同时不能用除法,因而用总乘积除以每个数字的方法也不能使用。求除了当前数字之外其他数字的乘积,我们可以把问题分解为左右两部分,分别求出左边和右边数字的乘积,然后把两个乘积相乘就得到了结果。具体代码:
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.)
这道题是计算数组中除当前数字之外其他数字的乘积,题目难度为Medium。
题目限定了时间复杂度为O(n),双层遍历不能使用,同时不能用除法,因而用总乘积除以每个数字的方法也不能使用。求除了当前数字之外其他数字的乘积,我们可以把问题分解为左右两部分,分别求出左边和右边数字的乘积,然后把两个乘积相乘就得到了结果。具体代码:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> output(nums.size(), 1); int right = 1; for(int i=1; i<nums.size(); i++) { output[i] = output[i-1] * nums[i-1]; } for(int i=nums.size()-1; i>=0; i--) { output[i] *= right; right *= nums[i]; } return output; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解