LeetCode Product of Array Except Self
来源:互联网 发布:360水滴破解软件 编辑:程序博客网 时间:2024/06/05 09:56
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.)
Subscribe to see which companies asked this question
这道题要求除了自己以外的所有其他元素的和,这里的思路是先遍历数组一遍求出所有非0元素的积,并且记录当前数组中0的个数。然后对每个元素检查,如果当前元素等于0并且没有其他元素为0 ,那么积为其他非0元素的积,如果除了当前元素还有其他0,那么积为0;如果当前元素非0但是有其他元素为0的,那么当前元素的积为0;如果当前元素非0而且其他元素也非0,那么就用总积除以当前元素。
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { int total = 1; int co = 0; for(int i= 0;i<nums.size();i++) { if(nums[i] != 0) total *= nums[i]; else ++co; } vector<int> result; for(int i= 0;i<nums.size();i++) { if(nums[i] == 0 && co >1) result.push_back(0); else if(nums[i] == 0 && co == 1) result.push_back(total); else if(nums[i] != 0 && co>0) result.push_back(0); else if(co == 0) result.push_back(total/nums[i]); } return result; }};
0 0
- [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
- Leetcode: Product of Array Except Self
- LeetCode 238: Product of Array Except Self
- LeetCode-Product of Array Except Self
- Leetcode #238 Product of Array Except Self
- 如何使用VC++6.0发布程序(即release版本程序)
- 动态规划---0-1背包问题
- 检查lfs从内核到到第一个进程init是否成功
- Oil Deposits 深度优先搜素油田
- FragmentTabHost的应用
- LeetCode Product of Array Except Self
- java环境下利用blind xxe来列目录和文件读取
- JQuery获取select选中的值
- LeetCode Palindrome Partitioning
- 尼姆博弈(Nimm Game)
- windows下编译sba(sparse bundle adjustment)
- 【我的笔记】Mac电脑的一些操作
- Javascript数组方法(译)
- 使用Callable接口实现多线程