当前位置: 首页 > 后端技术 > Java

LeetCode-238-Productofarraysothersthanitself

时间:2023-04-02 01:34:31 Java

arraysproductofarraysotherthanitself题目描述:给定一个长度为n的整数数组nums,其中n>1,返回输出数组output,其中output[i]等于nums中除nums[i]之外的所有元素的乘积。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:数组遍历的大致思路是遍历数组两次,分别计算前缀乘积和后缀乘积,过程中将它们相乘。具体过程如下:首先声明一个与原数组大小相同的数组,用于暂存累加值然后从前向后遍历数组,记录每个位置的前缀累加积;然后从后向前遍历数组,计算每个位置的后缀累积,再与上一次遍历得到的前缀累积相乘。可获得相应仓位的非自累计产品。最后,返回这个临时数组作为结果。importjava.util.Arrays;publicclassLeetCode_238{publicstaticint[]productExceptSelf(int[]nums){intlen=nums.length;int[]temp=newint[len];两者都初始化为1Arrays.fill(temp,1);//计算前缀和乘积temp[i]表示第i个数之前所有数的乘积for(inti=1;i=0;i--){//当前数的乘积结果等于前缀和后缀与temp[i]=temp[i]*subfixS;//更新后缀和subfixS*=nums[i];}返回温度;}publicstaticvoidmain(String[]args){int[]nums=newint[]{1,2,3,4};//测试用例,预期输出:[24,12,8,6]for(inti:productExceptSelf(nums)){System.out.print(i+"");}}}【每日留言】也许我不是最好的,但我是最努力的。