小米Java后端开发笔试 2023/9/2 16:00-17:30


样例输出: 9.0

//通过67%
public class Main2 {
    public static void main(String args[]) throws Exception {
        Scanner cin=new Scanner(System.in);
        int a = cin.nextInt();
        String s=cin.next();
        String[] b=s.split(",");
        int n=b.length;
        int min=Integer.MAX_VALUE;
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<n;i++){
            String[] c=b[i].split(":");
            if("".equals(c[0])||"".equals(c[1]))continue;
            int aa=Integer.parseInt(c[0]);
            int bb=Integer.parseInt(c[1]);
            int cc=Math.abs(aa-a);
            map.put(cc,bb);
            min=Math.min(cc,min);
        }
        double res=0;
        int count=0;
        for(Integer key:map.keySet()){
            if(key==min){
                res+=map.get(key);
                count++;
            }
        }
        double ans=res/count;
        System.out.println(String.format("%.1f",ans));
    }
}

第二题

样例输出: 13
提示:
在样例中,手机至少需要有13mAh的初始电量,在运行任务2后剩余电量11mAh、运行任务1后剩余电量10mAh、运行任务3后剩余7mAh.

//通过率67%
public class Main3 {
    public static void main(String args[]) throws Exception {
        Scanner cin=new Scanner(System.in);
        //  int a = cin.nextInt();
        String s=cin.next();
        String[] b=s.split(",");
        int n=b.length;
        int[][] res=new int[n][2];
        for(int i=0;i<n;i++){
            String[] c=b[i].split(":");
            if("".equals(c[0])||"".equals(c[1]))continue;
            int aa=Integer.parseInt(c[0]);
            int bb=Integer.parseInt(c[1]);
            res[i][0]=aa;
            res[i][1]=bb;
        }
        Arrays.sort(res,(k,l)->l[1]-k[1]);
        int ans=0,pre=0;
        for (int i = 0; i < n; i++) {
            int left=res[i][0];
            int right=res[i][1];
            if(left>right){
                ans=-1;
                break;
            }
            if(pre<right){
                ans+=right-pre;
                pre=right;
            }
            pre-=left;
        }
        System.out.println(ans);
    }
}

  目录