Product of Array Except Self

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.)

就是用减法实现除法。

注意零的处理。

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int size = nums.size();
vector<int> ret(size, );
long long product = ;
int countZero = ;
int ind = -; // 0-index for(int i = ; i < size; i ++)
{
if(nums[i] == )
{
countZero ++;
ind = i;
}
} //special case for 0
if(countZero == )
{//no zero
for(int i = ; i < size; i ++)
product *= nums[i];
for(int i = ; i < size; i ++)
ret[i] = mydivide(product, nums[i]);
}
else if(countZero == )
{//1 zero
for(int i = ; 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 = ;
if((product < ) ^ (divisor < ))
sign = -;
if(product < )
product = -product;
if(divisor < )
divisor = -divisor;
//to here, product and divisor are positive
int ret = ;
while(true)
{
int part = ; //part quotient
int num = divisor;
while(product > num)
{
num <<= ;
part <<= ;
}
if(product == num)
{
ret += part;
return sign * ret;
}
else
{
num >>= ;
part >>= ;
ret += part;
product -= num;
}
}
}
};

最新文章

  1. 推荐两本学习linux的经典书籍
  2. [JavaScript]JS由来
  3. FFmpeg-20160418-snapshot-bin
  4. (二)关于ajax那些事
  5. 【转】Solr5.3.1定时增量添加索引和重做索引
  6. PHP 如何阻止用户上传成人照片或者裸照
  7. 问题-WIN7 ..\Bin\InitCC32.exe&quot;.进程无法访问(拒绝访问)
  8. 通过GWT RPC实现客户端与服务器端的交互
  9. CENTOS elasticsearch plugin install:Failed: SSLException[java.security.ProviderException,解决
  10. SQL server抽疯后修改sa密码无法成功的处理办法
  11. 从零开始PHP学习 - 第三天
  12. java 读取excel(Map结构)xls
  13. Mybatis学习(5)高级映射
  14. vim命令替换操作
  15. C语言的split功能
  16. Hibernate(7)关联关系_单向1对n
  17. Java ee第六周作业
  18. Poj2386 Lake Counting (DFS)
  19. 前端--vue框架
  20. beego 初体验 - orm - 增删改查

热门文章

  1. 小丸工具箱FAQ
  2. [转]使用tee记录mysql client 所有的操作,十个节省时间的mysql命令
  3. Codeforces 449C Jzzhu and Apples 贪心 (看题解)
  4. 6-10 下落的树叶 uva699
  5. linux 之 汇编语言 的mov和movl sub 和subl add 和addl 的区别??
  6. Redis持久化(persistence)
  7. 《Android进阶之光》--RxJava实现RxBus
  8. Web侦察工具HTTrack (爬取整站)
  9. [漏洞分析]thinkphp 5.1.25 insert、insetAll、update方法注入
  10. FTP 其他设置