题目链接:https://leetcode.com/problems/product-of-array-except-self/

238. Product of Array Except Self

My Submissions

Question
Total Accepted: 36393 Total
Submissions: 87262 Difficulty: Medium

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.)

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview?

 

Yes

 

No

Discuss

    给出一个数组,要求计算一个新数组。数组里全部的元素都是除了自己以外的元素乘积。而且要求不许用除法。

    《编程之美》上的一道原题。创建两个辅助数组。一个保存全部左边元素乘积的结果。一个保存全部右边元素乘积的结果。借助这两个数组,一次遍历就能够得到结果。

    我的AC代码

public class ProductofArrayExceptSelf {

	public static void main(String[] args) {
int[] a = { 1, 2, 3, 4 };
System.out.print(Arrays.toString((productExceptSelf(a))));
} public static int[] productExceptSelf(int[] nums) {
int len = nums.length;
int[] r = new int[len]; int[] left = new int[len];
int[] right = new int[len];
left[0] = nums[0];
for (int i = 1; i < len; i++) {
left[i] = left[i - 1] * nums[i];
}
right[len - 1] = nums[len - 1];
for (int i = len - 2; i >= 0; i--) {
right[i] = right[i + 1] * nums[i];
} r[0] = right[1];
r[len - 1] = left[len - 2];
for (int i = 1; i < len - 1; i++) {
r[i] = left[i - 1] * right[i + 1];
}
return r;
}
}

最新文章

  1. ASP.NET Aries 2.0 发布(原来的源码SVN已关闭,开源源码已迁移到GitHub)
  2. [Hadoop] Hadoop学习历程 [持续更新中…]
  3. JS技术大全(防止复制,粘贴等)
  4. 批量运行R包
  5. 【枚举】bzoj3391 [Usaco2004 Dec]Tree Cutting网络破坏
  6. 用python简单处理图片(5):图像直方图
  7. maven打的jars项目,log4j不会输出日志
  8. SqlServer 中如何查看某一个Sql语句是复用了执行计划,还是重新生成了执行计划
  9. android发送/接收Json包含中文的处理
  10. linux scp ssh命令不用输入密码
  11. android从网络获取图片
  12. Balanced Binary Tree --Leetcode C++
  13. Android:刚6瓶啤酒4两56度白酒下肚,竟然20分钟做了一手机版站点 !
  14. D3.js:饼状图的制作
  15. Lambda应用场景和使用实例
  16. 011.Adding Search to an ASP.NET Core MVC app --【给程序添加搜索功能】
  17. 《算法导论》Chapter 4 Divide-and-Conquer的学习笔记
  18. From CORBA technology To Thrift technology
  19. Delphi的关键字
  20. linux 几个命令

热门文章

  1. MySQL安装详细图解整理
  2. 8. 博客系统| 富文本编辑框和基于bs4模块防御xss攻击
  3. TNS:listener does not currently know of service requested in connect descriptor错误改正
  4. POJ - 3080 Blue Jeans 【KMP+暴力】(最大公共字串)
  5. HDU 2222 Keywords Search (AC自动机)(模板题)
  6. 利用zabbix监控oracle数据库
  7. epoll使用详解
  8. Windows 7 Boot Updater 如何使用
  9. #1075 : 开锁魔法III
  10. E: Unable to locate package openjdk-8-jdk 及java version 切换