leetcode刷题日记——Product of Array Except Self
来源:互联网 发布:淘宝考试答题器 编辑:程序博客网 时间:2024/04/30 16:41
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).
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
问题分析:题目目的就是将数组对应位置的元素换位剩余位置元素的乘积。拿到此题不要固定思维,不要去想怎么从当前元素来获取其他剩余元素,而应该想到的是先将所有元素的乘积获取到,然后在除掉对应位置的元素即可。这里涉及到除法,就需要判断元素是否为零,为零的元素需要单独考虑,实际分类看如下代码:
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { int sum=1,count=0; for(int i=0;i<nums.size();i++){ if(nums[i]!=0) sum*=nums[i]; else count++; } for(int i=0;i<nums.size();i++){ if(count==0) nums[i]=sum/nums[i]; else if(count==1){ if(nums[i]==0) nums[i]=sum; else nums[i]=0; } else{ nums[i]=0; } } return nums; }};
0 0
- leetcode刷题日记——Product of Array Except Self
- leetcode——Product of Array Except Self
- Product of Array Except Self —— Leetcode
- LeetCode——Product of Array Except Self
- [leetcode][array] Product of Array Except Self
- 【LeetCode】237 Product of Array Except Self
- #leetcode#Product of Array Except Self
- leetcode 238: Product of Array Except Self
- [leetcode] 238.Product of Array Except Self
- [leetcode] Product of Array Except Self
- LeetCode Product of Array Except Self
- leetCode(43):Product of Array Except Self
- LeetCode Product of Array Except Self
- 【leetcode】Product of Array Except Self
- 【leetcode】Product of Array Except Self
- leetcode: Product of Array Except Self
- [leetcode] Product of Array Except Self
- [LeetCode] Product of Array Except Self
- C语言运算符的优先级和结合性
- jQuery中的动画
- dateutil和pytz的安装
- BZOJ3212 A Simple Problem with Integers
- 13、提升Android UI流畅度的建议
- leetcode刷题日记——Product of Array Except Self
- Qt遇到奇怪的问题--FTH
- bzoj3994 约数个数和 数论&莫比乌斯反演
- 杂记<一>
- [腾讯云]数据盘分区以及格式化
- 用GitHub构建个人Maven仓库
- Hbase过滤器
- Spark:环境搭建
- 杭电acm1232