leetcode 238. Product of Array Except Self
来源:互联网 发布:虚拟机网络nat 编辑:程序博客网 时间:2024/05/13 09:56
Given an array of n integers where n > 1, nums
, return an arrayoutput
such that output[i]
is equal to the product of all the elements ofnums
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.)
Subscribe to see which companies asked this question
思路:注意分情况讨论,数组里面没有0,一个0,两个以上0都是不一样的情况。
public class Solution {
public int[] productExceptSelf(int[] nums) {
//test if overflow
if(nums.length == 2){
int temp = nums[0];
nums[0] = nums[1];
nums[1] = temp;
return nums;
}
int tProduct = 1;
int zcount = 0;
boolean firstZ = true;
for(int num : nums){
if(num == 0 && firstZ == true){
firstZ = false;
zcount++;
continue;
}
if(num == 0){
zcount++;
}
tProduct *= num;
}
for(int i = 0; i < nums.length; ++i){
if(zcount > 1){
nums[i] = 0;
}else if(zcount == 1){
if(nums[i] != 0){
nums[i] = 0;
}else{
nums[i] = tProduct;
}
}else if(zcount == 0){
nums[i] = tProduct/nums[i];
}
}
return nums;
}
}
- [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
- [ jQuery ] jquery 闭包浅析!
- [Go语言]我的第二个Go语言程序
- Mysql与Oracle的50个区别
- 二维变换矩阵的坐标变换,逆矩阵,角度的实现
- Java Web中cookie和session详解
- leetcode 238. Product of Array Except Self
- Swift 必备开发库 (高级篇) 一
- listview属性之android:layout_width
- js之2016.7.21字符串处理之替换 ,计数长度和符号,分隔
- Bootstrap中的模态框遇到点击选项跳转后模态框不显示的问题
- Restaurant Testing Round #12 B
- Android 4.4Eclipse项目中使用RecyclerView
- linux 常用命令 用法总结
- poj2632 Crashing Robots