Middle-题目3:238. Product of Array Except Self
来源:互联网 发布:linux expect puts 编辑:程序博客网 时间:2024/05/16 12:53
题目原文:
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].
题目大意:
给一个数组nums,输出一个数组output,其中output[i]等于nums数组中除了nums[i]外所有数的乘积。
要求不使用除法,且复杂度O(n),
题目分析:
1. 朴素解法
既然是oj题,AC就好,你说不用除就不用除了?那么问题来了,如果nums[i]是0怎么办?
这时要分两种情况:
(1) nums数组里面有两个以上的0,那么output数组必然全是0.
(2) nums数组里面只有一个0,那么0这一位对应是其他所有非0数的乘积,其他位都是0.
按这个思路,先统计数组里有几个0,作为两种特殊情况。其他的就都乘起来分别算即可。
2. 真的不用除的算法:
考虑output[i]=(nums[0]nums[1]…nums[i-1])(nums[i+1]…*nums[n-1]),那么遍历两次数组,第一轮正向遍历,计算出nums[0]*nums[1]…nums[i-1]的积放到output[i]里面,第二轮反向遍历,计算出nums[i+1]…*nums[n-1]的积再乘进去即可。
源码:(language:java)
1. 朴素解法:
public class Solution { public int[] productExceptSelf(int[] nums) { int product=1,product2=1; int zerocount=0; for(int num:nums) { if(num==0) zerocount++; if(zerocount==2) break; product*=num; product2*=(num==0)?1:num; } if(zerocount==0){ for(int i=0;i<nums.length;i++) nums[i]=product/nums[i]; return nums; } else if(zerocount==1) { int[] array=new int[nums.length]; for(int j=0;j<nums.length;j++) array[j]=(nums[j]==0)?product2:0; return array; } else return new int[nums.length]; }}
- 不用除的巧妙算法:
public class Solution { public int[] productExceptSelf(int[] nums) { int[] res = new int[nums.length]; res[res.length-1] = 1; for(int i=nums.length-2; i>=0; i--) { res[i] = res[i+1] * nums[i+1]; } int left = 1; for(int i=0; i<nums.length; i++) { res[i] *= left; left *= nums[i]; } return res; }}
成绩:
朴素解法:3ms,beats 11.83%,
巧妙解法:2ms,beats 46.07%,众数2ms,53.93%
Cmershen的碎碎念:
Middle前期的很多道题看似简单,但却有很巧妙的算法,应予以注意。
- Middle-题目3: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
- 238. Product of Array Except Self LeetCode
- LeetCode 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- LeetCode *** 238. Product of Array Except Self
- Middle-题目2:260. Single Number III
- Compile Less to CSS with IntelliJ IDEA
- 不死的癌症《股骨头坏死》
- ffmpeg 中av_rescale_rnd 的含义
- 微软源代码管理工具TFS2013安装与使用详细图文教程
- Middle-题目3:238. Product of Array Except Self
- java之构造方法创建JFrame
- 自定义ScrollView解决onScrollChanged()方法不能调用的问题
- Service绑定本类对象的示例
- Scala之隐式转换
- 第五周项目三时间类2
- Middle-题目4:122. Best Time to Buy and Sell Stock II
- Hibernate中的Entity类之间的ManyToMany关联
- 第十/十一周项目四-教师兼干部类