Leetcode 238. Product of Array Except Self
来源:互联网 发布:投标施工组织设计软件 编辑:程序博客网 时间:2024/05/16 15:48
题意较为简单,即得到一组数据中除任意一元素外所有元素的积(难点为不能用到除法)。较为简单的可以想到用减法来代替除法,即每次用被除数减去除数的X倍,X从一开始累加,等到被除数为0时X的值就是商。但这种办法过于复杂会超时,可令X又逐渐增长优化为2的指数倍增长,利用循环来得到结果。例如:27 / 3, 27 - 3 , 27-2*3 ,....., 27-8*3=3, 3 - 3=0; 则x=8+1=9.
代码如下:
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { int m=1; int count=0; vector<int> s; for(int i=0;i<nums.size();i++) { m=m*nums[i]; if(nums[i]==0) count++; } if(count>=2) { for(int i=0;i<nums.size();i++) s.push_back(0); } else if(count==1) { for(int i=0;i<nums.size();i++) { if(nums[i]!=0) s.push_back(0); else { int temp=1; for(int j=0;j<nums.size();j++) { if(nums[j]!=0) temp=temp*nums[j]; } s.push_back(temp); } } } else { for(int i=0;i<nums.size();i++) { int temp=div(m,nums[i]); s.push_back(temp); } } return s; } int div(long long product, int divisor) { int sign = 1; if((product < 0) ^ (divisor < 0)) sign = -1; if(product < 0) product = -product; if(divisor < 0) divisor = -divisor; int ret = 0; while(true) { int part = 1; int num = divisor; while(product > num) { num <<= 1; part <<= 1; } if(product == num) { ret += part; return sign * ret; } else { num >>= 1; part >>= 1; ret += part; product -= num; } } }};
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
- android仿小米时钟
- Spring 零配置
- String's interface
- 【BZOJ 2326】【HNOI 2011】数学作业【矩阵乘法】
- leetcode-459-Repeated Substring Pattern
- Leetcode 238. Product of Array Except Self
- 子查询in 为何不能用order by
- Project Euler 013 Large sum
- CSS属性之定位属性详解
- 基于H5的图片上传解析
- 1029.Median (25)
- JavaScript中this指向
- wustoj1938格子游戏
- Spring中利用JDBC模板完成SQLServer数据库(MySQL一样)各种操作