LeetCode -- Product of Array Except Self
来源:互联网 发布:怎么当淘宝客服 编辑:程序博客网 时间:2024/05/22 13:21
题目描述:
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].
输入数组Nums,返回一个数组output,要求output[i]为,nums[0]...nums[i-1],nums[i+1]....nums[n]的乘积。
思路:
1.区分是否包含0的情况,存0的索引。
2.考虑越界的情况
实现代码:
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].
输入数组Nums,返回一个数组output,要求output[i]为,nums[0]...nums[i-1],nums[i+1]....nums[n]的乘积。
思路:
1.区分是否包含0的情况,存0的索引。
2.考虑越界的情况
实现代码:
public class Solution { public int[] ProductExceptSelf(int[] nums) { if(nums == null || nums.Length == 1){return nums;}var output = new int[nums.Length];var zeroIndexes = new List<int>();for(var i =0 ;i < nums.Length; i++){ if(nums[i] == 0){ zeroIndexes.Add(i); } output[i] = 0;}if(zeroIndexes.Count > 1){ return output;}else if(zeroIndexes.Count == 1){ var s = 1; for(var i =0 ;i < nums.Length ;i++){ if(i == zeroIndexes[0]){ continue; } s *= nums[i]; } output[zeroIndexes[0]] = s; return output;}else{ output[0] = 1; for(var i = 1;i < nums.Length; i++){output[0] *= nums[i];}for(var i = 1; i < nums.Length; i++){ try{output[i] = output[0] * nums [0] % nums[i] == 0 ? output[0] * nums[0] / nums[i] : nums[i] * output[0]/ nums[0];}catch(System.OverflowException ex){output[i] = 0;}}}return output; }}
0 0
- [leetcode][array] Product of Array Except Self
- 【LeetCode】237 Product of Array Except Self
- #leetcode#Product of Array Except Self
- leetcode 238: Product of Array Except Self
- [leetcode] 238.Product of Array Except Self
- [leetcode] Product of Array Except Self
- LeetCode Product of Array Except Self
- leetCode(43):Product of Array Except Self
- LeetCode Product of Array Except Self
- 【leetcode】Product of Array Except Self
- 【leetcode】Product of Array Except Self
- leetcode: Product of Array Except Self
- [leetcode] Product of Array Except Self
- [LeetCode] Product of Array Except Self
- Leetcode: Product of Array Except Self
- LeetCode 238: Product of Array Except Self
- LeetCode-Product of Array Except Self
- Leetcode #238 Product of Array Except Self
- LeetCode -- Permutations II
- URL传递参数长度限制
- android studio 导入eclipse的项目
- ToolBar基本使用方法
- Eclipse中如何修改SVN的地址
- LeetCode -- Product of Array Except Self
- Mysql 相关 记录
- Android开发网上的一些重要知识点
- LeetCode -- Remove Duplicates From Sorted Array 2
- vs 中大括号之间垂直虚线显示
- 创业之中一些重要的事
- return特点
- diff()差分
- LeetCode -- Reverse Bits