LeetCode *** 238. Product of Array Except Self
来源:互联网 发布:单词社交网络 mp4 编辑:程序博客网 时间:2024/05/01 09:33
题目:
Given an array of n integers where n > 1, nums
, return an arrayoutput
such that output[i]
is equal to the product of all the elements ofnums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
分析:
既然是除了自己以外的数的积,那么把所有的数相乘即可。
但是考虑到数组中可能有0的存在,那么需要把没有0,有1一个0,有多个0的情况分别写出。同时将所有不为0的数相乘即可。
代码:
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { int total=1,numOfZero=0,now; for(int i=0;i<nums.size();++i){ if(nums[i]==0)numOfZero++; else total*=nums[i]; } vector<int> res; if(numOfZero){ if(numOfZero==1){ for(int i=0;i<nums.size();++i){ if(nums[i]!=0)res.push_back(0); else res.push_back(total); } } else { for(int i=0;i<nums.size();++i){ res.push_back(0); } } } else { for(int i=0;i<nums.size();++i){ res.push_back(total/nums[i]); } } return res; }};
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
- 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
- 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
- RabbitMQ消息队列(七):适用于云计算集群的远程调用(RPC)
- poj2367
- 2048游戏python版
- hihoCoder[Offer收割]编程练习赛3题目解析
- 2010年山东省第一届ACM大学生程序设计竞赛:Hello World!
- LeetCode *** 238. Product of Array Except Self
- 【Java】分析JAVA应用CPU占用过高的问题
- 采用Memcached实现分布式Session
- binder
- RabbitMQ消息队列的小伙伴(八): ProtoBuf(Google Protocol Buffer)
- 【bzoj2124】等差子序列 权值线段树维护hash
- 《Android第一行代码》学习笔记
- 自顶向下的归并排序和自底向上的归并排序
- HashMap、ConcurrentHashMap、HashTable、HashSet