描述
给定一个整数数组A。
定义B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
, 计算B的时候请不要使用除法。请输出B。
样例
样例 1
输入: A = [1, 2, 3]
输出: [6, 3, 2]
解析:B[0] = A[1] * A[2] = 6; B[1] = A[0] * A[2] = 3; B[2] = A[0] * A[1] = 2
样例 2
输入: A = [2, 4, 6]
输出: [24, 12, 8]
话不多说,很简单,直接上代码
import java.util.ArrayList;
import java.util.List;
public class ProductExcludeItself {
public static void main(String[] args) {
List<Integer> list=new ArrayList<>();
list.add(2);
list.add(4);
list.add(6);
List<Long> result=new ArrayList<>();
result=productExcludeItself(list);
for (int i = 0; i <result.size() ; i++) {
System.out.print(result.get(i)+" ");
}
}
public static List<Long> productExcludeItself(List<Integer> nums) {
// write your code here
List<Long> result=new ArrayList<>();
for (int i = 0; i <nums.size() ; i++) {
long temp=1;
for (int j = 0; j <nums.size() ; j++) {
if (i==j){
continue;
}else {
temp = temp * nums.get(j);
}
}
result.add(temp);
}
return result;
}
}