LeetCode 238. Product of Array Except Self (Medium)
来源:互联网 发布:什么数据库管理系统 编辑:程序博客网 时间:2024/06/02 03:16
题目描述:
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).
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.)
Example:
Given [1,2,3,4], return [24,12,8,6].
题目大意:给出一个数组,为每一个元素算出除了它本身以外其余元素的积。
思路:两次遍历,第一次从左到右算出每个元素左边所有元素的积,第二次从右到左算出结果。
c++代码:
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> ans(nums.size(), 1); for (int i = 1; i < nums.size(); i++) { ans[i] = ans[i - 1] * nums[i - 1]; } int base = 1; for (int i = nums.size() - 1; i >= 0; i--) { ans[i] = base * ans[i]; base = base * nums[i]; } return ans; }};
阅读全文
0 0
- Leetcode 238. Product of Array Except Self (Medium) (cpp)
- LeetCode 238. Product of Array Except Self (Medium)
- 238. Product of Array Except Self #Medium
- 【Medium】238. Product of Array Except Self
- [Leetcode 238, Medium] Product of Array Except Self
- 【Leetcode-Medium-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
- 238. Product of Array Except Self LeetCode
- 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
- php的PDO连接数据库(一)
- go环境搭建
- PostgreSQL hook机制编写插件限制超级用户权限
- C++中explicit关键字的使用
- Android.mk 文件语法详解
- LeetCode 238. Product of Array Except Self (Medium)
- 基于CAS思想的java并发AtomicBoolean实例详解
- CSDN防止粘贴代码乱码的方式--方便自己用
- JVM 菜鸟进阶高手之路十一(eden survivor分配问题)
- JavaScript怎么上传图片
- 第一天
- 基本的bash shell命令
- Geoserver的CORS问题解决
- java this的用法及注意点