leetCode-Product of Array Except Self
来源:互联网 发布:apache base64 maven 编辑:程序博客网 时间:2024/06/06 02:35
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.)
My Solution:
class Solution {//主要思想就是求出所有数的乘积,遍历数组,除以nums[i]就可以了,只不过有两种特殊情况,一种是数组中有一个元素为0,那么可以将其他元素赋为0,0元素为其他元素乘积,如果数组中为0的元素多于1,那么直接返回0数组 public int[] productExceptSelf(int[] nums) { int len = nums.length; int[] result = new int[len]; int m = 1; int zeroCount = 0; int index = 0; for(int i = 0;i < len;i++){ if(nums[i] != 0){ m *= nums[i]; }else{ zeroCount++; index = i; } } if(zeroCount != 0){ if(zeroCount == 1){ for(int i = 0;i < len;i++){ if(i == index){ result[i] = m; }else{ result[i] = 0; } } } return result; } for(int i = 0;i < len;i++){ result[i] = m / nums[i]; } return result; }}
Better Solution:
//第一遍遍历,product[i]对应i之前的所有元素乘积,第二遍逆序遍历,product[i]补上之前缺少的部分class Solution { public int[] productExceptSelf(int[] nums) { int[] products = new int[nums.length]; int num = 1; for (int i = 0; i < nums.length; i++) { products[i] = num; num *= nums[i]; } num = 1; for (int i = nums.length - 1; i >= 0; i--) { products[i] *= num; num *= nums[i]; } return products; }}
阅读全文
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
- C socket 发送HTTP简单介绍
- App发生崩溃保存崩溃日志在本地,并发送邮件给开发人员
- Java泛型获取T class的解决方法(异步请求代码的优化)
- Maven WEB 项目使用ProGuard进行混淆,最佳解决方案
- 11.Python
- leetCode-Product of Array Except Self
- 什么是数据结构?
- linux add user/ delete user
- 迈开机器学习的第一步
- Material Design设计技巧
- 分布式 tensorflow
- 【贪心算法】背包问题 C++
- qt 开发遇到的坑
- Bagging和Boosting概念以及区别