Arrays分类算法-ArrayOf Products

博客讨论了三种解决数组产品计算的方法,包括暴力求解、双数组累乘和优化算法。优化后的算法在时间和空间复杂度上都更优,只需O(n)的时间和O(1)的空间即可完成计算。
摘要由CSDN通过智能技术生成
题目要求

在这里插入图片描述
解法一:
非常普通的暴力解法,头铁硬算出每个乘积,然后存入数组,毫无新意。
Time: O(n^2) Space: O(n)
代码:

import java.util.*;

class Program {
  public int[] arrayOfProducts(int[] array) {
    // Write your code here.
		if (array == null || array.length < 2) return array;
		int[] res = new int[array.length];
		for (int i = 0; i < array.length; i++) {
			int temp = i;
			int product = 1;
			for (int j = 0; j < array.length; j++) {
				if (i == j) continue;
				product *= array[j];
			}
			res[i] = product;
		}
    return res;
  }
}

解法二:
创建两个数组,第一个数组存从前到后的累乘结果,第二个数组存从后到前的累乘结果。结果数组将两个数组的结果结合。
Time: O(n) Space: O(1)
代码:

import java.util.*;

class Program {
  public int[] arrayOfProducts(int[] array) {
    // Write your code here.
		if (array.length == 0 || array == null) return new int[] {};
		
		int[] temp1 = new int[array.length];
		temp1[0] = array[0];
		for (int i = 1; i < array.length; i++) {
			temp1[i] = array[i] * temp1[i - 1];  
		}
		
		int[] temp2 = new int[array.length];
		temp2[array.length - 1] = array[array.length - 1];
		int j = array.length - 2;
		for (int i = array.length - 2; i > 0; i--) {
			temp2[i] = temp2[i + 1] * array[j];
			j--;
		}
		
		int[] res = new int[array.length];
		res[0] = temp2[1];
		res[array.length - 1] = temp1[array.length - 2];
		for (int i = 1; i < array.length - 1; i++) {
			res[i] = temp1[i - 1] * temp2[i + 1];
		}
		
		return res;
  }
}

解法三:
思路和第二种解法一样,只是做了一些优化。我们发现得出的的结果并不需要数组全部乘积作为计算参数,因此我们直接将其设置成1,然后用一个临时变量来存上一个数的累乘结果。然后继续计算两数组的数值,最后直接进行计算。
对于本题sample,我们的两个数组是:
temp1{1, 5, 5, 20}
temp2{8, 8, 2, 1}
Time: O(n) Space: O(1)
代码:

import java.util.*;

class Program {
  public int[] arrayOfProducts(int[] array) {
    // Write your code here.
    int[] temp1 = new int[array.length];
	  int left = 1;
		for (int i = 0; i < array.length; i++) {
			temp1[i] = left;
			left *= array[i];
		}
		
		int[] temp2 = new int[array.length];
	  int right = 1;
		for (int i = array.length - 1; i >= 0; i--) {
			temp2[i] = right;
			right *= array[i];
		}
		
		int[] res = new int[array.length];
		for (int i = 0; i < array.length; i++) {
			res[i] = temp1[i] * temp2[i];
		}
		
		return res;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值