题目:
给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
示例:
输入: [1,2,3,4]
输出: [24,12,8,6]
题解:
方法一:乘积 = 当前数左边的乘积 * 当前数右边的乘积
import java.util.*;
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
int k = 1;
for(int i = 0; i < res.length; i++){
res[i] = k;
k = k * nums[i]; // 此时数组存储的是除去当前元素左边的元素乘积
}
k = 1;
for(int i = res.length - 1; i >= 0; i--){
res[i] = res[i] * k; // k为该数右边的乘积。
k = k * nums[i]; // 此时数组等于左边的 * 该数右边的。
}
return res;
}
}
public class Main {
public static void main(String[] args) {
int[] nums = {2,4,1,3,5};
Solution p = new Solution();
int[] b = p.productExceptSelf(nums);
System.out.println("输出结果"+ Arrays.toString(b));
}
}
方法二:暴力(超时)
import java.util.*;
class Solution {
public int[] productExceptSelf(int[] nums) {
int tempMul;
int temp;
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
tempMul = 1;
temp = nums[i];
nums[i] = 1;
for (int j = 0; j < nums.length; j++) {
tempMul = tempMul * nums[j];
}
res[i] = tempMul;
nums[i] = temp;
}
return res;
}
}
public class Main {
public static void main(String[] args) {
int[] nums = {1,2,3,4};
Solution p = new Solution();
int[] b = p.productExceptSelf(nums);
System.out.println("输出结果"+ Arrays.toString(b));
}
}