题解 | #称砝码#

称砝码

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

看了别人的题解思路,才想出通过全部用例的逻辑的,自己原来的方法想破了脑袋也还是只能通过6/20的用例。。。😂😂

import java.util.*;
import java.lang.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int n = Integer.parseInt(in.nextLine());
            String m[] = in.nextLine().split(" ");
            String x[] = in.nextLine().split(" ");
            ArrayList<Integer> fl = new ArrayList<>();//用于存放铺展开来的砝码组
            //将每个砝码,无论是否重量一样,都装进fl中
            for(int i=0;i<n;i++){
                int mi = Integer.parseInt(m[i]);
                int xi = Integer.parseInt(x[i]);
                for(int j=0;j<xi;j++){
                    fl.add(mi);
                }               
            }

            /*逐个加入砝码,每加一个,都取出hs中已经存在的所有重量场景分别加该砝码重量后生成新的重量场景添加的hs中,
			例如第0个砝码有0,m0,下一个砝码加进去后就会是0,m0,0+m1,m0+m1,再下一个是0,m0,0+m1,m0+m1,0+m2,m0+m2,0+m1+m2,m0+m1+m2...,
			若重量有重复,Hashset会自动去重。*/
            HashSet<Integer> hs=new HashSet<>();
            hs.add(0);
            for(int k=0;k<fl.size();k++){
                Object[] ol = hs.stream().toArray();
                int hl = hs.size();
                for(int h=0;h<hl;h++){
                    hs.add((int)ol[h]+fl.get(k));
                }
            }
            System.out.println(hs.size());
        }
    }
}

全部评论

相关推荐

码农索隆:想看offer细节
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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