LeetCode238——除自身以外数组的乘积
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/product-of-array-except-self/description/
题目描述:
知识点:数组
思路一:暴力**法
时间复杂度是O(n ^ 2),其中n是数组的长度。空间复杂度是O(1)。
JAVA代码:
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
int temp = 1;
for (int j = 0; j < nums.length; j++) {
if(j != i){
temp *= nums[j];
}
}
result[i] = temp;
}
return result;
}
}
LeetCode解题报告:
思路二:左右遍历两次
时间复杂度是O(n),其中n是数组的长度。空间复杂度是O(1)。
JAVA代码:
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
result[0] = 1;
for (int i = 1; i < nums.length; i++) {
result[i] = result[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = nums.length - 1; i >= 0; i--) {
result[i] *= right;
right *= nums[i];
}
return result;
}
}
LeetCode解题报告: