Product of Array Except Self
2015-07-16 10:30
218 查看
问题描述
Given an array of n integers where n > 1,
Solve it without division and in O(n).
For example, given
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. 使用辅助空间
为方便理解,使用两个与输入数组同等大小的辅助数组,
首先,从前到后扫描数组,一个数组[i]存储的是除了当前元素外的所有前面元素的乘积;
然后,从后到前扫描数组,另一个数组[i]存储的是除了当前元素外的所有后面元素的乘积。
最后将这两个数组的对应位置的元素相乘即可。
优化后可以省略一个数组和一遍扫描。
程序
Given an array of n integers where n > 1,
nums, return an array
outputsuch that
output[i]is equal to the product of all the elements of
numsexcept
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. 使用辅助空间
为方便理解,使用两个与输入数组同等大小的辅助数组,
首先,从前到后扫描数组,一个数组[i]存储的是除了当前元素外的所有前面元素的乘积;
然后,从后到前扫描数组,另一个数组[i]存储的是除了当前元素外的所有后面元素的乘积。
最后将这两个数组的对应位置的元素相乘即可。
优化后可以省略一个数组和一遍扫描。
程序
public class Solution { public int[] productExceptSelf(int[] nums) { if (nums == null) { return null; } int len = nums.length; int[] res = new int[len]; int[] tmp = new int[len]; tmp[0] = 1; res[0] = 1; for (int i = 1; i < len; i++) { tmp[i] = tmp[i - 1] * nums[i - 1]; res[i] = tmp[i]; } tmp[len - 1] = 1; for (int i = len - 2; i >= 0; i--) { tmp[i] = tmp[i + 1] * nums[i + 1]; res[i] *= tmp[i]; } return res; } }
相关文章推荐
- 一个手写的 http client
- 【Struts2九】类型转换器
- php导出mysql
- Java,php,python,js 定义字符串
- 修改grub解决计算机启动报错:ERROR 17
- 带环单链表及单链表的相交
- IBM刀片概念
- 磁盘分区 partition table
- 银行系统第一版
- C# Programming Study #2
- 关于DownloadManager的一些问题
- 20150716,微软7月15日发布14个安全补丁
- static_cast、dynamic_cast、reinterpret_cast和const_cast之间的区别
- 学习笔记之Myeclipse学习笔记(二)_MyEclipse跟踪调试
- 【js】带按钮的js弹出框
- 遥感图像存储格式BSQ/BIL/BIP的理解
- [Android] ImageView.ScaleType设置图解
- linux更换阿里云的源的shell脚本
- 【struts2八】利用token防止表单重复提交
- python 字典的setdefault方法