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

36 lines
1.0 KiB
Java
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}