leetcode Product of Array Except Self 生成除自己之外的数组
来源:互联网 发布:优化9蒙古入侵 编辑:程序博客网 时间:2024/06/05 06:13
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].
题意:给定一个数组,在每个位置生成其他位置相乘得到的值。
思路:定义一个值记录0的个数,一个值记录除0外元素的乘积。
时间复杂度O(n),空间复杂度O(1)。
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { int temp = 1, zeroCount = 0; for (auto ele : nums) { if (ele) temp *= ele; else zeroCount++; } if(zeroCount == 0) for (int i = 0; i < nums.size(); ++i) nums[i] = temp / nums[i]; else for (int i = 0; i < nums.size(); ++i) { if (nums[i]) nums[i] = 0; else if (zeroCount == 1) nums[i] = temp; else nums[i] = 0; } return nums; }};
阅读全文
0 0
- leetcode Product of Array Except Self 生成除自己之外的数组
- 238. 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:238. Product of Array Except Self(除自身外的乘积)
- Product of Array Except Self 数组除自身的所有乘积
- [leetcode][array] Product of Array Except Self
- leetcode 238. 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
- numpy 切片操作
- 实验二 线性表综合实验(单链表)
- C++常用小知识点总结
- java List 排序 Collections.sort() 对 List 排序
- ACM算法:迪杰斯特拉最短路径
- leetcode Product of Array Except Self 生成除自己之外的数组
- [CODE【VS】]江哥的DP题d
- 1. STM32F10X-架构
- linux 命令小结
- python 爬虫爬取所有上市公司公告信息(一)
- SpringBoot24-spingboot数据访问-声明式事务
- 新建一个Maven Web项目jsp出现错误(关于Tomcat服务器)
- Java并发编程 07 Executors框架
- 通过 TensorFlow 进行的机器学习 如何帮助可口可乐实现移动购买凭证