Leetcode题解 238. Product of Array Except Self
来源:互联网 发布:ssm log4j sql 编辑:程序博客网 时间:2024/06/05 03:31
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
注意泄题加粗部分,不用除法,解法一用除法来做,注意元素可能为0的情况。
public class Solution { public int[] productExceptSelf(int[] nums) { int res=1; int zeroCount=0; for(int i=0;i<nums.length;i++){ if(nums[i]!=0){ res*=nums[i]; }else{ zeroCount++; } } int[] result=new int[nums.length]; if(zeroCount>1) return result; else if(zeroCount==1){ for(int i=0;i<nums.length;i++){ if(nums[i]==0){ result[i]=res; }else{ result[i]=0; } } return result; }else{ for(int i=0;i<nums.length;i++){ result[i]=res/nums[i]; } return result; } }}
解法二:(不用除法。分别计算每个元素的左边部分和右边部分的所有元素的乘积即为最终结果)
public class Solution { public int[] productExceptSelf(int[] nums) { int len=nums.length; int[] res=new int[len]; res[len-1]=1; for(int i=len-2;i>=0;i--){ res[i]=res[i+1]*nums[i+1]; } int left=1; for(int i=0;i<len;i++){ res[i]*=left; left*=nums[i]; } return res; }}
0 0
- LeetCode题解:Product of Array Except Self
- Leetcode题解 238. Product of Array Except Self
- LeetCode 238. Product of Array Except Self 题解(C++)
- [leetcode] 238.Product of Array Except Self
- [LeetCode]238.Product of Array Except Self
- [leetcode] 238. Product of Array Except Self
- Leetcode 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self LeetCode
- LeetCode 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- LeetCode *** 238. Product of Array Except Self
- LeetCode 238. Product of Array Except Self
- 【leetcode】238. Product of Array Except Self
- leetcode-238. Product of Array Except Self
- Leetcode 238. Product of Array Except Self
- 【leetcode】238. Product of Array Except Self
- LeetCode- 238. Product of Array Except Self
- 暑假留校学习生活
- 动态规划专题
- 进程管理和调度
- 《leetCode》:Shortest Palindrome
- BZOJ 3037 创世纪
- Leetcode题解 238. Product of Array Except Self
- Spring Boot 基于Maven 基础Pom.xml文件
- 对RBTree的总结
- 树莓派安装mplayer
- codeforces 362 div2D Puzzles
- 算法复习之快排(C++版)
- UVA10152ShellSort
- LPC1788入门手记
- 锁 互斥量 信号量