题解 | #统计每个月兔子的总数#
统计每个月兔子的总数
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; } }
优化到炸,勉强过了测试
雪域灰灰刷题笔记 文章被收录于专栏
雪域灰灰刷题笔记