【LeetCode】238. Product of Array Except Self
2015-07-25 11:34
316 查看
Product of Array Except Self
Given an array of n integers where n > 1,
Solve it without division and in O(n).
For example, given
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.)
就是用减法实现除法。
注意零的处理。
Given an array of n integers where n > 1,
nums, return an array
outputsuch that
output[i]is equal to the product of all the elements of
numsexcept
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.)
就是用减法实现除法。
注意零的处理。
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int size = nums.size(); vector<int> ret(size, 0); long long product = 1; int countZero = 0; int ind = -1; // 0-index for(int i = 0; i < size; i ++) { if(nums[i] == 0) { countZero ++; ind = i; } } //special case for 0 if(countZero == 0) {//no zero for(int i = 0; i < size; i ++) product *= nums[i]; for(int i = 0; i < size; i ++) ret[i] = mydivide(product, nums[i]); } else if(countZero == 1) {//1 zero for(int i = 0; i < size; i ++) { if(i != ind) product *= nums[i]; } ret[ind] = product; //others are 0s } else {//2 or more zeros ; //all 0s } return ret; } int mydivide(long long product, int divisor) {// guaranteed that divisor is not 0 int sign = 1; if((product < 0) ^ (divisor < 0)) sign = -1; if(product < 0) product = -product; if(divisor < 0) divisor = -divisor; //to here, product and divisor are positive int ret = 0; while(true) { int part = 1; //part quotient 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; } } } };
相关文章推荐
- HDU 1258 Sum It Up
- 根据像素画圆
- hdoj.5289 Assignment【单调队列】 2015/07/25
- A计划(bfs)
- 去掉标题栏、信息栏和实现全屏
- sublime常用快捷键
- Linux下的网络配置命令
- MPlayer-ww 增加边看边剪切功能+生成高质量GIF功能
- Java Servlet与Applet、CGI、JSP的比较
- 1019. General Palindromic Number (20)
- nyoj-20-吝啬的国度(深搜)
- 开机自动开启小键盘灯
- WPS 文字排版 标题回车后标题号自动增加
- css的作业
- 在netbean里面无法启动tomcat
- nyoj91 阶乘之和
- 查询区间内不同数字的个数 lydsy1878
- 新浪微博,腾讯微博mysql数据库主表猜想
- 关于cocos2dx如何通过jni进行c++与java的交互
- cocos2dx Android签名总结