Product of Array Except Self
来源:互联网 发布:知乎匿名提问 编辑:程序博客网 时间:2024/05/17 06:19
[题目链接](https://leetcode.com/problems/product-of-array-
except-self/)
错误思路:
设置一个二位数组。d[i][j]是从i到j相乘的结果。当然,[0][last]某些情况是溢出的.然后这样结果中值就是[0][i-1]*[i+1]last。但是提交之后的结果是内存超出,要一个减少空间复杂度的算法。
错误代码
import java.util.Arrays;public class Solution { public static void main(String args[]) { Solution su=new Solution(); int [] result=su.productExceptSelf(new int[]{1,2,3,4}); for(int i=0;i<result.length;i++) { System.out.println(result[i]); } } public int[] productExceptSelf(int[] nums) { int[][] record=new int[nums.length][nums.length]; for(int i=0;i<nums.length;i++) { record[i][i]=nums[i]; } for(int i=0;i<nums.length;i++) { for(int j=i+1;j<nums.length;j++) { record[i][j]=record[i][j-1]*nums[j]; } } int []result=new int[nums.length]; result[0]=record[1][nums.length-1]; result[nums.length-1]=record[0][nums.length-2]; for(int i=1;i<nums.length-1;i++) { result[i]=record[0][i-1]*record[i+1][nums.length-1]; } return result; }}
参照了别人的思路后有一个优美的算法
public class Solution { public int[] productExceptSelf(int[] nums) { int []res=new int [nums.length]; for(int i=0;i<res.length;i++) { res[i]=1; } int left=nums[0],right=nums[nums.length-1]; for(int i=1;i<nums.length;i++) { res[i]=left; left*=nums[i]; } for(int i=nums.length-2;i>=0;i--) { res[i]=right*res[i]; right*=nums[i]; } return res; }}
0 0
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Https原理介绍
- MySql触发器使用讲解
- struts注解(新旧对比)
- Linux - /etc/passwd和/etc/shadow文件结构
- 自定义注解
- Product of Array Except Self
- Android文件上传
- GDB调试程序(一)
- 【QQ机器人开发】茉莉QQ机器人3.X系列插件开发文档
- UVALive - 4452 The Ministers' Major Mess(2-SAT)
- TextView的一些使用
- poj3207Ikki's Story IV - Panda's Trick tarjan缩点
- 零基础学python-1.3 通过idle启动python
- 剑指offer刷题之java实现的栈的压入、弹出序列