【Leetcode】Product of Array Except Self
来源:互联网 发布:贸易企业运营数据分析 编辑:程序博客网 时间:2024/04/28 16:14
题目链接:https://leetcode.com/problems/product-of-array-except-self/
题目:
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]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
思路:
1、规避除法。用两个数组描述元素左、右边乘积,结果就是该元素左右乘积之积。空间复杂度为O(n)
2、在上述思路基础上减少数组的使用,用result代替右边的乘积,再用一个常数表示元素左边乘积。
算法1:
public int[] productExceptSelf(int[] nums) {int right[] = new int[nums.length]; //元素右边乘积int left[] = new int[nums.length];//int result[] = new int[nums.length];for (int i = nums.length - 1; i >= 0; i--) {if (i == nums.length - 1) {right[i] = 1;} else {right[i] = right[i + 1] * nums[i + 1];}}for (int i = 0; i < nums.length; i++) {if (i == 0) {left[i] = 1;} else {left[i] = left[i - 1] * nums[i - 1];}}for (int i = 0; i < nums.length; i++) {result[i] = right[i] * left[i];}return result;}
算法2:
public int[] productExceptSelf(int[] nums) {int result[] = new int[nums.length];for (int i = nums.length - 1; i >= 0; i--) { //元素右边乘积if (i == nums.length - 1) {result[i] = 1;} else {result[i] = result[i + 1] * nums[i + 1];}}int left = 0;//左边乘积for (int i = 0; i < nums.length; i++) {if (i == 0) {left = 1;} else {left= left * nums[i - 1];result[i] = result[i] * left;}}return result;}
0 0
- [leetcode][array] Product of Array Except Self
- 【LeetCode】237 Product of Array Except Self
- #leetcode#Product of Array Except Self
- leetcode 238: Product of Array Except Self
- [leetcode] 238.Product of Array Except Self
- [leetcode] Product of Array Except Self
- LeetCode Product of Array Except Self
- leetCode(43):Product of Array Except Self
- LeetCode Product of Array Except Self
- 【leetcode】Product of Array Except Self
- 【leetcode】Product of Array Except Self
- leetcode: Product of Array Except Self
- [leetcode] Product of Array Except Self
- [LeetCode] Product of Array Except Self
- Leetcode: Product of Array Except Self
- LeetCode 238: Product of Array Except Self
- LeetCode-Product of Array Except Self
- Leetcode #238 Product of Array Except Self
- HAXM is working and emulator runs in fast virt mode
- Mvc 入门
- OpenGLES: gl_Position设置
- javaSE(21)(适配器设计模式)
- 立体视频视差图的几种计算方法
- 【Leetcode】Product of Array Except Self
- stl之pair,map,vector区别
- IOS_图片轮播器实现
- Android动画效果生动有趣的通知NiftyNotification(Android Toast替代品)
- Oracle 分区表和普通表查询效率分析对比
- js跨域说明及跨域的几个方式
- centos升级默认python2.6.6到2.7.9版本
- Android自定义控件系列之应用篇——圆形进度条
- mac idea