Advent Of Code 是老哥Eric从2015年开始的兴趣项目。每年 12 月 1 号准时开始,每天都会解锁一道题,只有第一道题提交正确答案后会显示当天的第二题。和其他OJ不同,AoC只关心最后的答案,并不强求时间复杂度或者执行时间和执行内存。(换言之,只要你电脑够好或者足够有耐心,你完全可以暴力解题)AoC的题目背景一般都很好玩,这也让AoC做题的过程更放松。博主这两年都有在玩。一般前面的题比较简单,越往后越难。但是随着 AI 能力越来越强,相信解题成功率今年也会挺高的。今年刚好从第一天开始做题,在博客这里记录一下。另咱也不是啥OJ大神,玩AoC纯属娱乐,不追求最优的解法,图个和大伙儿共乐~
题目链接 Advent of Code 2026 · Day 1
按 AoC 的要求,这里不转载原题,题目内容请前往官网查看。
Part 1 解题思路 第一题其实就一句话:What do you get if you multiply together the three IDs which appear most often?
经常打Leetcode的童鞋们会直接一激灵,这不是LC347 Top K Frequent Elements 吗?就是最后要乘一下。
所以第一题的Java解法就很简单,直接HashMap记录一下ID出现的次数,然后List按照value排个降序,再去取前三个key相乘就行了。代码如下:
Java 源码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class Q1 { public static void main (String[] args) { HashMap<Integer, Integer> map = new HashMap <>(); try (BufferedReader br = new BufferedReader (new FileReader ("input.txt" ))) { String line; while ((line = br.readLine()) != null ) { int num = Integer.parseInt(line); map.put(num, map.getOrDefault(num, 0 ) + 1 ); } List<Map.Entry<Integer, Integer>> list = new ArrayList <>(map.entrySet()); list.sort((a, b) -> b.getValue().compareTo(a.getValue())); long res = 1 ; for (int i = 0 ; i < 3 ; i++) { res *= (long ) list.get(i).getKey(); } System.out.println(res); } catch (IOException e) { e.printStackTrace(); } } }
Part 2 解题思路 类似地,第二题也是一句话:What do you get if you multiply together the three IDs which appear least often?
所以这里稍加改动,升序排列再取前三个相乘就行了。代码如下:
Java 源码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class Q2 { public static void main (String[] args) { HashMap<Integer, Integer> map = new HashMap <>(); try (BufferedReader br = new BufferedReader (new FileReader ("input.txt" ))) { String line; while ((line = br.readLine()) != null ) { int num = Integer.parseInt(line); map.put(num, map.getOrDefault(num, 0 ) + 1 ); } List<Map.Entry<Integer, Integer>> list = new ArrayList <>(map.entrySet()); list.sort((a, b) -> a.getValue().compareTo(b.getValue())); long res = 1 ; for (int i = 0 ; i < 3 ; i++) { res *= (long ) list.get(i).getKey(); } System.out.println(res); } catch (IOException e) { e.printStackTrace(); } } }
Copyright Notice The original puzzles belong to Advent of Code. All solutions and explanations in this article are my own work.
https://adventofcode.com/2026/about