Leetcode 238 - Product of Array Except Self(递推)
来源:互联网 发布:linux复制命令 编辑:程序博客网 时间:2024/05/02 02:08
题意
给定一个数组a[],对于其中的每一个元素x,求数组中所有数相乘并除以该元素x的结果。并且不能使用除法。
思路
算法1
我们维护一个l[i]和r[i]数组,分别代表从左往右乘到元素
那么,对于我们要求的结果
算法2
我们需要想办法去优化一下空间,其实从我们上面的式子
那么我们只需要从左往右遍历一遍得到
代码
//algorithm 1class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> l(nums.size(), 0); vector<int> r(nums.size(), 0); vector<int> ans(nums.size(), 0); for (int i = 0; i < nums.size(); i++) l[i] = i ? l[i - 1] * nums[i] : nums[i]; for (int i = nums.size() - 1; i >= 0; i--) r[i] = i == nums.size() - 1 ? nums[i] : r[i + 1] * nums[i]; for (int i = 0; i < nums.size(); i++) ans[i] = (i == 0 ? 1 : l[i - 1]) * (i == nums.size() - 1 ? 1 : r[i + 1]); return ans; }};//algorithm 2class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> ans(nums.size(), 0); int l = 1, r = 1; for (int i = 0; i < nums.size(); i++) { ans[i] = l; l *= nums[i]; } for (int j = nums.size() - 1; j >= 0; j--) { ans[j] *= r; r *= nums[j]; } return ans; }};
0 0
- Leetcode 238 - Product of Array Except Self(递推)
- leetcode 238: Product of Array Except Self
- LeetCode 238: Product of Array Except Self
- Leetcode #238 Product of Array Except Self
- Leetcode 238 Product of Array Except Self
- [leetcode 238]Product of Array Except Self
- LeetCode(238)Product of Array Except Self
- leetcode 238: Product of Array Except Self
- Leetcode #238 Product of Array Except Self
- [LeetCode 238] Product of Array Except Self
- leetcode 238:Product of Array Except Self
- Product of Array Except Self - LeetCode 238
- LeetCode 238 Product of Array Except Self
- 【LEETCODE】238-Product of Array Except Self
- LeetCode 238:Product of Array Except Self
- leetcode 238 Product of Array Except Self
- leetcode 238: Product of Array Except Self
- [LeetCode 238] Product of Array Except Self
- 剑指:反转链表
- 给校园招聘中应聘嵌入式程序员的几点建议
- socket通信 简单的客户端和服务器的通信 服务器的代码
- 前端模块化方案的比较(webpack/require.js/seajs/browserify
- Mybatis-Spring 的高级配置 (SqlSessionFactoryBean)
- Leetcode 238 - Product of Array Except Self(递推)
- unable to access 'https://github.com/CocoaPods/Specs.git/': SSLRead() return error -9806
- Python入门(一):整数、浮点数和布尔值的运算
- 如何监控一个Activity加载完毕(完成渲染)-onWindowFocusChanged
- 工具类:检查数据库表是否存在某一列
- idea快捷键
- HTML元素及属性(二)
- HDU 1005 Number Sequence(循环节) *
- WCF通过配置文件搭建—— 一起嗨