238. Product of Array Except Self
题目分析
Given an array nums
of n integers where n > 1, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input:[1,2,3,4]
Output:[24,12,8,6]
Note: Please solve it without division and in O(n).
思路
最初思路:仔细读题后发现,这道题就是要输出一个数组,该shuz数组第i个元素就等于给定元素除了第i个元素外的其他元素的乘积。并且要求时间复杂度为O(n),除了结果集不能够使用其他额外的空间
public class Solution {
public static void main(String[] args) {
int[] nums = new int[] {0,4,0};
nums = productExceptSelf(nums);
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
public static int[] productExceptSelf(int[] nums) {
int Products = 1;
int CountZreo = 0;
for (int i = 0; i < nums.length; i++) {
if(nums[i]!=0) {
Products *= nums[i];
}
else {
CountZreo++;
}
}
int[] result = new int[nums.length];
for (int i = 0; i < result.length; i++) {
if(CountZreo == 0) {
result[i] = Products/nums[i];
}else if (CountZreo ==1 ) {
if(nums[i] ==0)
result[i] = Products;
else
result[i] = 0;
}else {
result[i] = 0;
}
}
return result;
}
}
大神的代码
class Solution {
public int[] productExceptSelf(int[] nums) {
int [] arr = new int[nums.length];
arr[0] = 1;
for(int i =1;i<nums.length;i++) {
arr[i] = nums[i-1]*arr[i-1];
}
int right =1;
for(int i =nums.length-1;i>=0;i--) {
arr[i]*=right;
right = right * nums[i];
}
return arr;
}
}
遇到的问题
1.在计算结果时,由于考虑不周到。遇到了两次错误,因为按照我的代码方法,给定数组中0出现的不同次数会影响结果集的输出不同,一开始没有考虑给定数组中全为0的状况,第二次又没有考虑给定数组中不是全为0,但0的个数也大于1的情况。所以我的这种思路需要先计算出原始数组中0的个数。根据不同的0的个数,输出不同的结果集。思路相对麻烦,要分情况写。
对比思考
1.这里看大神的解法,他将原数组遍历两遍,第一遍从左往右循环计算该位置所有左边的数的乘积,第二遍从右往左循环计算该位置所有右边的数的乘积。这样就完成了除了本身外的所有数的乘积的计算,思路巧妙!
2.虽然两种解法的时间复杂度都是O(n)且满足题目要求,但是大神的代码思路巧妙容易理解,我的代码则比较冗杂!