作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/product-of-array-except-self/description/

题目描述

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

解题方法

两次遍历

当我想了一个用除法做的答案之后就发现题目不允许用除法做233333.

这个题巧妙的地方在于,结果数组不算作空间复杂度里,所以可以用在结果数组中遍历的方式去做。第一次遍历在结果数组里保存每个数字左边的数字乘积,第二个遍历保存的是左边乘积和这个数字右边的乘积的乘积。

所以就得到了出了本身以外的其他元素的乘积。

class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
answer = []
_len = len(nums)
prod = 1
for i in range(_len):
answer.append(prod)
prod *= nums[i]
prod = 1
for i in range(_len - 1, -1, -1):
answer[i] *= prod
prod *= nums[i]
return answer

C++代码如下:

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
const int N = nums.size();
vector<int> res(N, 1);
int prod = 1;
for (int i = 0; i < N; i ++) {
res[i] = prod;
prod *= nums[i];
}
prod = 1;
for (int i = N - 1; i >= 0; i--) {
res[i] *= prod;
prod *= nums[i];
}
return res;
}
};

日期

2018 年 2 月 14 日
2018 年 12 月 14 日 —— 12月过半,2019就要开始

最新文章

  1. word-wrap ,word-break 和white-space 的联系
  2. Web获取客户端物理MAC地址(ocx插件)
  3. GIFT-EMS礼记----青软S2SH(笔记)
  4. [网站公告]3月10日23:00-4:00阿里云SLB升级,会有4-8次连接闪断
  5. BPMN流程图的绘制的注意要点
  6. POJ3126 Prime Path
  7. 程序猿的编程神器 - vim
  8. Axis2 -POJO
  9. linux(CentOS5.8)环境下搭建Radius
  10. MT6592 经验积累
  11. Docker在Linux/Windows上运行NetCore文章系列
  12. mask rcnn
  13. (一) 天猫精灵接入Home Assistant- hass对接天猫精灵
  14. 关于Unity中协程、多线程、线程锁、www网络类的使用
  15. 使用 urllib 设置代理服务
  16. CCCatmullRomBy和CCPointArray
  17. JavaScript学习总结(二十二)——JavaScript屏蔽Backspace键
  18. C#多线程数据分布加载
  19. Python用@property使类方法像属性一样访问
  20. SLIP—串行线路上传输数据报的非标准协议

热门文章

  1. Golang知识点整理
  2. day05文件编辑命令
  3. c学习 - 算法
  4. jdk1.6,1.7,1.8解压版无需安装(64位)
  5. DBMS_RANDOM包详解
  6. java静态方法调用非静态方法
  7. shell脚本实现网站日志分析统计
  8. 【Spring Framework】Spring入门教程(四)注册Bean到IOC容器
  9. 【C/C++】例题3-5 生成元/算法竞赛入门经典/数组与字符串
  10. numpy基础教程--clip函数的使用