题解 | #称砝码#

称砝码

https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int num = in.nextInt();
            int[] typeHeight = new int[num];
            int[] numHeight = new int[num];
            for (int i = 0; i < num; i++) {
                typeHeight[i] = in.nextInt();
            }
            for (int i = 0; i < num; i++) {
                numHeight[i] = in.nextInt();
            }
            HashSet<Integer> hashSet = new HashSet<>();

            hashSet.add(0);
            //遍历所有砝码
            for (int i = 0; i < num; i++) {
                //得到每种砝码的重量和数量
                int weight = typeHeight[i];
                int number = numHeight[i];
                HashSet<Integer> temp = new HashSet<>();
                for (int j = 1; j <= number; j++) {
                    //将当前同种类砝码进行叠加,每次叠加都与之前所称重量数进行对比,有新的就加入到集合中
                    for (Integer w : hashSet) {
                        temp.add(w + weight * j);
                    }
                }
                hashSet.addAll(temp);
            }
            System.out.println(hashSet.size());
        }
    }
}

全部评论

相关推荐

在笔试的大西瓜很矫健:校招数分不用想了,这经历和学历都不够用,大厂更别想,初筛都过不了,说点不好听的小厂数分都进不去(小厂也是假数分),要两个对口实习+3个项目(或者3+2),而且要有含金量才能补一点你的学历劣势。 建议刷实习,社招找数分,校招看运气,能入行业就行,可以运营转数分
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务