题解 | #统计每个月兔子的总数#

统计每个月兔子的总数

https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    private static int sum = 1;
    private static int birth1st = 0;
    private static int hasBirth = 0;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n = 0;
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            n = in.nextInt();
        }
        result(n);
        System.out.print(sum);
    }

    private static void result(int n) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(1, 0);
        for (int i = 1; i <= n; i++) {
            addMapValue(map);
            map = birth(map, i);
        }
    }

    private static void addMapValue(Map<Integer, Integer> map) {
        map.forEach((k, v)-> {
            if (v < 3) {
                map.put(k, v + 1);
            }
        });
    }

    private static Map<Integer, Integer> birth(Map<Integer, Integer> map,
            int month) {

        //Map<Integer, Integer> map1 = new HashMap<>();
        List<Integer> keys = new LinkedList<>();
        map.forEach((k, v) -> {
            if (v >= 3) {
                hasBirth += 1;
                keys.add(k);
            }
        });
        if(keys.size() > 0){
            keys.forEach(i -> {
                map.remove(i);
            });
        }

        birth1st += hasBirth;
        for (int i = 1; i <= birth1st; i++) {
            map.put(sum + i, 1);
        }

        hasBirth = 0;
        sum += birth1st;
        return map;
    }
}

优化到炸,勉强过了测试

#努力刷题下#
雪域灰灰刷题笔记 文章被收录于专栏

雪域灰灰刷题笔记

全部评论

相关推荐

09-17 17:09
门头沟学院 Java
雨忄:有人给出过解法,拖晚点去,然后到时候再找其他理由商量,既增加他们的筛人成本,不一定会给你收回offer ,也能占位避免工贼
秋招的嫡长offer
点赞 评论 收藏
分享
刷牛客的我很豁达:你是不是对算法有什么误解,你没手握两篇顶刊顶会,还想搞算法岗,有顶刊顶会在算法岗算才入门
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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