题解 | #构建乘积数组#
构建乘积数组
http://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46
1.python 解法:构建两个函数,主函数轮询每一个元素并调用子函数,子函数用于构建每一个元素的乘积。得益于python的列表解析式,整个解法相对简洁
# -*- coding:utf-8 -*- class Solution: def multiply(self, A): # write code here res_lst = [] [res_lst.append(self.sp_mutil(A, index, A[0])) for index in range(len(A))] return res_lst def sp_mutil(self, lst, index, res): for i in range(1, len(lst)): if i != index: res *= lst[i] return res
2.java解法:同python。大括号和分号真的很麻烦且没必要
import java.util.ArrayList; public class Solution { public int[] multiply(int[] A) { int[] res = new int[A.length]; for(int i=0; i<A.length; i++){ res[i] = sp_mutil(A, i, A[0]); } return res; } private int sp_mutil(int[] lst, int index, int res){ for(int i=0; i<lst.length;i++){ if(i!=index){ res *= lst[i]; } } return res; } }
package main /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param A int整型一维数组 * @return int整型一维数组 */ func multiply( A []int ) []int { // write code here var B = make([]int, len(A)) for i,_ := range(A){ temp := A[i] B[i] = 1 A[i] = 1 for k,_ := range(A){ B[i] *= A[k] } A[i] = temp } return B }