LeetCode/com/zerroi/leetcode/ThreeNine/ProductExceptSelf.java

36 lines
1.0 KiB
Java
Raw Permalink Normal View History

2024-03-10 20:15:29 +08:00
package com.zerroi.leetcode.ThreeNine;
public class ProductExceptSelf {
public static void main(String[] args) {
SolutionFirst solutionFirst = new SolutionFirst();
int[] ints = solutionFirst.productExceptSelf(new int[]{1, 2, 3, 4});
}
}
/*
给你一个整数数组 nums返回 数组 answer 其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积
题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 整数范围内
不要使用除法且在 O(n) 时间复杂度内完成此题
*/
class SolutionFirst {
public int[] productExceptSelf(int[] nums) {
int length = nums.length;
int[] res = new int[length];
int temp = 1;
for (int i = 0; i < length; i++) {
res[i] = temp;
temp = temp * nums[i];
}
int a = 1;
for (int i = length - 1; i >= 0; i--) {
res[i] = res[i] * a;
a = a * nums[i];
}
return res;
}
}