题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int[] sMs = new int[n];
int[] sXs = new int[n];
HashSet<Integer> set = new HashSet<>();
//关键点就是set必须手动添加一个元素,从而进入循环,添加元素。
set.add(0);
// 砝码种类
for (int i = 0; i < n; i++) {
sMs[i] = sc.nextInt();
}
// 砝码个数
for (int i = 0; i < n; i++) {
sXs[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
HashSet<Integer> setTemp = new HashSet<>();
set.stream().forEach(aaa->setTemp.add(aaa));
//每个砝码的个数,关键步骤,只要有砝码,至少为1个
for (int j = 1; j <= sXs[i]; j++) {
for (Object ob : setTemp.toArray()) {
set.add(((Integer)ob).intValue() + sMs[i] * j);
}
}
}
//for (Object ob : set.toArray()) {
// System.out.println(((Integer)ob).intValue());
//}
System.out.println(set.size());
}
}
}
查看24道真题和解析