238. Product of Array Except Self
来源:互联网 发布:知党规 行敬畏 编辑:程序博客网 时间:2024/04/30 08:38
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].
tip:不能用除法、时间复杂度要求O(n)(这样遍历数组的方法也不行了)
想了好久都没想到O(n)的方法,最后还是用了除法,在有0的情况下还有另外处理,比较复杂,代码如下,仅供忽略
public class Solution { public int[] productExceptSelf(int[] nums) { int[] results = new int[nums.length]; int product = 1; int zeroPos = 0; for(int i = 0;i<nums.length;i++) { product *= nums[i]; if(nums[i] == 0) { zeroPos = i; } } if(product == 0) { for(int i = 0;i<results.length;i++) { results[i] = 0; } product = 1; for(int i = 0;i<nums.length;i++) { if(i == zeroPos) { continue; } product *= nums[i]; } results[zeroPos] = product; } else { for(int i = 0;i<nums.length;i++) { results[i] = product/nums[i]; } } return results; }}
正确解法
思路:result[i]的一种求法是:可以先依次乘i的右边各个元素,再乘i的左边各个元素
如题目中的[1,2,3,4],result[1] = 3 * 4 * 1 = 12
public class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length; int result[] = new int[n]; result[n-1] = 1; for(int i = n-2;i>=0;i--) { result[i] = result[i+1] * nums[i+1]; } int left = 1; for(int i = 0;i<n;i++) { result[i] = result[i] * left; left = left * 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
- ORACLE的redo文件在不同机器上存储是否使用big-endian还是little-endian的问题
- 单片机程序下载,LED灯
- ImageLoader的各种格式DisplayImageOptions 的设置
- matlab ubuntu linux 出现 libGL error
- 适配android 7的自定义相机的预览及拍照
- 238. Product of Array Except Self
- Laravel学习:路由、视图、控制器工作流程(2)
- integer综合分析
- linux海量文件数量的发布
- sql中where和on的区别
- MySQL账号权限建议
- 集成腾讯随心播1.8.4代码流程分析
- php通过ssh2扩展控制linux,模拟阿里云web控制台
- SylixOS网卡驱动框架