238. Product of Array Except Self
来源:互联网 发布:化妆品采购数据分析 编辑:程序博客网 时间:2024/06/06 12:49
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 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.)
这道题最初解决的时候我的想法是统计数组中0的个数,思想很简单,也容易理解,直接上代码,代码如下:
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
int count = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0){
count++;
}
}
if(count > 1){
for(int i = 0; i < nums.length; i++){
result[i] = 0;
}
return result;
}else if(count == 1){
int temp = 1;
for(int i = 0; i < nums.length; i++){
if(nums[i] != 0){
temp *= nums[i];
}
}
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0){
result[i] = temp;
}else{
result[i] = 0;
}
}
return result;
}else{
int temp = 1;
for(int i = 0; i < nums.length; i++){
temp *= nums[i];
}
for(int i = 0; i < nums.length; i++){
result[i] = temp / nums[i];
}
return result;
}
}
}
但是这样写不够美观整洁,时间复杂度与空间复杂度都是最优的,但是代码太多让人不舒服,后来找到一种更好的方法,代码如下:
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
for(int i = 0; i < result.length; i++){
result[i] = 1;
}
int start = 1;
for(int i = 0; i < nums.length; i++){
result[i] *= start;
start = start * nums[i];
}
int end = 1;
for(int i = nums.length - 1; i >= 0; i--){
result[i] *= end;
end = end * nums[i];
}
return result;
}
}这样看起来就比较简洁,解决问题的办法不止一种,我们要根据情况选择最适合的方法。
- [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
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- LeetCode *** 238. Product of Array Except Self
- LeetCode 238. Product of Array Except Self
- java 串口数据问题:如何将byte转为无符号数
- 【问题解决】前台AJAX请求向Java后台传时+号变为空格—其他特殊字符解析出错也可参考解决
- 将对象类型转换为xml用到XStream.jar报错
- (HDU 5723)Abandoned country <最小生成树 + 树上所有两点之间的距离的期望> 多校训练1
- hdu—1081
- 238. Product of Array Except Self
- 编译QtE出现qbytearray.cpp:52:18: fatal error: zlib.h: No such file or directory
- 利用RFM模型做电商客户价值分析
- JavaScript深入理解之原型
- C++关键字(1)--const
- vs2010 编译 levmar 2.6,(Levenberg-Marquardt)
- 程序CPU使用率探讨
- 数据结构-----最大堆的实现
- android studio那些不为人知的秘密