238. Product of Array Except Self
来源:互联网 发布:下周主要财经数据 编辑:程序博客网 时间:2024/05/28 11:30
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.)
public class Solution { public int[] productExceptSelf(int[] nums) { int[] result = new int[nums.length]; if(nums == null || nums.length == 0){ return result; } result[result.length-1] = 1;//把最右边的数设为1 for(int i= result.length-2; i>=0; i--){ result[i] = result[i+1]*nums[i+1]; }//从右往左扫一遍,逐步相乘,这样到最左边的时候就是除了nums[0]和nums[nums.length-1]以外所有数的乘积 int leftSum = 1; for(int i=0; i<nums.length; i++){ result[i] *= leftSum; leftSum *= nums[i]; //再从左往右扫一遍即可 } return result; }}
阅读全文
0 0
- [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
- LeetCode 238. Product of Array Except Self
- Java面向对象的六原则法则
- WebGL基础简明教程1-简介
- a标签怎么去下划线以及实现点击前和点击后不变色
- 求两个链表的第一个公共结点各种情况及三种思路分析
- java 可变参数方法不支持多个可变参数以及多种类型的替代方法
- 238. Product of Array Except Self
- Cassandra 3.0 的新特性介绍: 物化视图
- js 面对对象编程
- okhttp网络框架的https协议之忽略证书验证的登录实例
- C# 内存单位计算 源码
- WebGL基础简明教程2-基础知识
- group by 与order by
- appcan移动开发中uexBaiduMap插件的悬浮效果
- 【php中的curl】php中curl的详细解说