题目
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.)
思路
对于i = 5 时 result[5] = (nums[0] * nums[1] * nums[2] * nums[3] * nums[4] ) * (nums[6] nums[7] * nums[8] * nums[9] * nums[10])
从上面开始看出对于第i个,我们只要知道它左边的连续乘积 和 它右边的连续乘积 就OK了。
代码
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int size = nums.size();
vector<int> result(size,0);
vector<int> left(size,0);
vector<int> right(size,0);
int leftNum = 1,rightNum = 1;
for(int i = 0;i < size;++i){
left[i] = leftNum;
right[size-i-1] = rightNum;
leftNum *= nums[i];
rightNum *= nums[size-i-1];
}
for(int i = 0;i < size;++i){
result[i] = left[i] * right[i];
}
return result;
}
};
int main(){
Solution s;
vector<int> vec = {1,2};
vector<int> result = s.productExceptSelf(vec);
int size = result.size();
for(int i = 0;i < size;++i){
cout<<result[i]<<" ";
}
return 0;
}
运行时间
<script type="text/javascript">
$(function () {
$('pre.prettyprint code').each(function () {
var lines = $(this).text().split('\n').length;
var $numbering = $('<ul/>').addClass('pre-numbering').hide();
$(this).addClass('has-numbering').parent().append($numbering);
for (i = 1; i <= lines; i++) {
$numbering.append($('<li/>').text(i));
};
$numbering.fadeIn(1700);
});
});
</script>
分享到:
相关推荐
思路:题目中说不能用除法;用暴力,会超时。 为了计算 除第i个元素的乘积,可以将数组分为三个部分:1…i-1; i; i+1…n (注:这里的i代表序号,不是数组下标) output[i] = a * b[被乘数a:代表前i-1个数的乘积...
用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现...
JVM 基础 JAVA 并发 JVM 性能调优 LeetCode 算法 .......
My Solutions to Leetcode Database problems. 我的 Leetcode 数据.zip
Leetcode 题解.pdf
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101.zip
LeetCode 后端.zip
Leetcode101.zip
刷leetcode总结.md
Recording personal Java, Python, JavaScript solutions for Leetcode problems. 记录个人 Java, Python, JavaScript 的Leetcode题解.zip
原创:leetcode 111. 二叉树的最小深度记住:最小深度和最大深度方法不同。* Definition for a binary tree node.in
原创:leetcode 107. 二叉树的层次遍历 II【队列】* Definition for a binary tree node.
原创:leetcode 5. 最长回文子串//寻找以i-1,i为中点偶数长度的回文//寻找以i为中心的奇数长度的回文。
My Solutions to Leetcode problems. All solutions support C
原创:leetcode 22.括号生成【回溯】对待这种问题,千万别暴力搜索,那样太笨了。但是这个方法是最容易理解的//回溯法 (后面的括号) 不可以大于 (前面
leetcode-editor,在ide中做leetcode练习,支持leetcode.com和leetcode-cn.com,以满足练习的基本需求。理论上支持:intellij idea phpstorm webstorm pycharm rubymine appcode clion goland datagrip rider mps ...
LeetCode674. 最长连续递增序列674. 最长连续递增序列解题思路:记录每次递增序列的长度,max存储最大长度// 递增序列更新最大长度} else
LeetCode746.使用最小花费爬楼梯746. 使用最小花费爬楼梯解题思路:动态规划当前楼梯最小值=Math.min(前一步最小值,前两步最小值)简化 mi