(java) Product of Array Except Self
2016-02-17 00:42
531 查看
Given an array of n integers where n > 1,
return an array
equal to the product of all the elements of
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.)
思路:如果这个数组中2个及以上的0,那都是0.如果只有1个0,除了出现0的位置不是0外别的位置都是0.如果没有0,那么这个位置就是所有数字的乘积除以这个位置上的数
代码如下(已通过leetcode)
public class Solution {
public int[] productExceptSelf(int[] nums) {
int count0=0;
for(int i=0;i<nums.length;i++)
if(nums[i]==0) count0++;
if(count0>=2) {
for(int i=0;i<nums.length;i++)
nums[i]=0;
} else {
if(count0==1) {
int tempmul=1;
for(int i=0;i<nums.length;i++)
if(nums[i]!=0) tempmul=tempmul*nums[i];
for(int i=0;i<nums.length;i++)
if(nums[i]==0) nums[i]=tempmul;
else nums[i]=0;
} else {
int tempmul=1;
for(int i=0;i<nums.length;i++)
tempmul=tempmul*nums[i];
for(int i=0;i<nums.length;i++)
nums[i]=tempmul/nums[i];
}
}
return nums;
}
}
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.)
思路:如果这个数组中2个及以上的0,那都是0.如果只有1个0,除了出现0的位置不是0外别的位置都是0.如果没有0,那么这个位置就是所有数字的乘积除以这个位置上的数
代码如下(已通过leetcode)
public class Solution {
public int[] productExceptSelf(int[] nums) {
int count0=0;
for(int i=0;i<nums.length;i++)
if(nums[i]==0) count0++;
if(count0>=2) {
for(int i=0;i<nums.length;i++)
nums[i]=0;
} else {
if(count0==1) {
int tempmul=1;
for(int i=0;i<nums.length;i++)
if(nums[i]!=0) tempmul=tempmul*nums[i];
for(int i=0;i<nums.length;i++)
if(nums[i]==0) nums[i]=tempmul;
else nums[i]=0;
} else {
int tempmul=1;
for(int i=0;i<nums.length;i++)
tempmul=tempmul*nums[i];
for(int i=0;i<nums.length;i++)
nums[i]=tempmul/nums[i];
}
}
return nums;
}
}
相关文章推荐
- java学习笔记-类与对象
- JAVA 和 XML --- JAXB 那些事情
- Java RSA 加密解密算法 入门
- java基本命令的使用
- Atitit.jdk java8的语法特性详解 attilax 总结
- Atitit.jdk java8的语法特性详解 attilax 总结
- Atitit.jdk java8的语法特性详解 attilax 总结
- struts2 跳转类型 result type=chain、dispatcher、redirect(redirect-action)
- JavaScipt中栈的实现方法
- javaweb学习总结(四十七)——监听器(Listener)在开发中的应用
- 使用Maven搭建Struts2框架的开发环境
- MyEclipse10搭建Strust2开发环境
- javaweb学习总结(二十七)——jsp简单标签开发案例和打包
- JavaWeb学习总结(十二)——Session
- java基础学习总结——static关键字
- java基础学习总结——多态(动态绑定)
- JavaWeb学习总结(五十)——文件上传和下载
- MyEclipse使用总结——使用MyEclipse打包带源码的jar包
- MyEclipse使用总结——设置MyEclipse开发项目时使用的JDK
- java基础学习总结——对象转型