30天Java速成计划:从零基础到能刷算法题!
本文为Java小白量身定制,通过每日2小时的系统学习,带你快速掌握Java基础并具备解决算法问题的能力。坚持30天,你会感谢现在的自己!
📅 学习计划总览
周次 | 学习重点 | 掌握技能 |
---|---|---|
第一周 | Java基础语法 | 变量、流程控制、数组、方法 |
第二周 | 面向对象与核心类 | 类与对象、字符串、集合 |
第三周 | 数据结构与算法基础 | 链表、栈、队列、哈希表 |
第四周 | 算法思维提升 | 二分查找、双指针、动态规划 |
📝 第一周:Java基础语法
Day 1:环境搭建与Hello World
今日重点:搭建开发环境,编写第一个Java程序
public class HelloWorld {public static void main(String[] args) {System.out.println("Hello, World! 🎉");System.out.println("第一天学习Java,加油!");}
}
练习任务:
安装JDK和IntelliJ IDEA
成功运行HelloWorld程序
尝试修改输出内容
Day 2:变量与数据类型
今日重点:理解变量声明和基本数据类型
public class Variables {public static void main(String[] args) {// 基本数据类型int age = 25;double height = 1.75;char grade = 'A';boolean isJavaFun = true;System.out.println("年龄: " + age);System.out.println("身高: " + height + "米");System.out.println("评分: " + grade);System.out.println("Java有趣吗: " + isJavaFun);}
}
Day 3:运算符与表达式
今日重点:掌握各种运算符的使用
public class Operators {public static void main(String[] args) {int a = 10;int b = 3;System.out.println("a + b = " + (a + b)); // 13System.out.println("a - b = " + (a - b)); // 7System.out.println("a * b = " + (a * b)); // 30System.out.println("a / b = " + (a / b)); // 3System.out.println("a % b = " + (a % b)); // 1// 比较运算符System.out.println("a > b: " + (a > b)); // true}
}
Day 4:条件语句
今日重点:掌握if-else和switch语句
import java.util.Scanner;public class Conditionals {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入你的分数: ");int score = scanner.nextInt();if (score >= 90) {System.out.println("优秀!🎊");} else if (score >= 80) {System.out.println("良好!👍");} else if (score >= 60) {System.out.println("及格!✅");} else {System.out.println("需要加油哦!💪");}}
}
Day 5:循环结构
今日重点:掌握for、while循环
public class Loops {public static void main(String[] args) {// for循环打印九九乘法表System.out.println("九九乘法表:");for (int i = 1; i <= 9; i++) {for (int j = 1; j <= i; j++) {System.out.print(j + "×" + i + "=" + (i * j) + "\t");}System.out.println();}// while循环int count = 5;while (count > 0) {System.out.println("倒计时: " + count);count--;}}
}
Day 6:数组
今日重点:数组的声明和使用
import java.util.Arrays;public class ArraysDemo {public static void main(String[] args) {// 数组声明和初始化int[] numbers = {3, 1, 4, 1, 5, 9, 2, 6};// 数组遍历System.out.print("数组元素: ");for (int num : numbers) {System.out.print(num + " ");}// 数组排序Arrays.sort(numbers);System.out.println("\n排序后: " + Arrays.toString(numbers));// 查找最大值int max = numbers[0];for (int num : numbers) {if (num > max) max = num;}System.out.println("最大值: " + max);}
}
Day 7: 方法
今日重点:方法的定义和调用
public class Methods {// 定义方法:计算两个数的和public static int add(int a, int b) {return a + b;}// 定义方法:判断是否为偶数public static boolean isEven(int number) {return number % 2 == 0;}// 递归方法:计算阶乘public static int factorial(int n) {if (n == 0 || n == 1) {return 1;}return n * factorial(n - 1);}public static void main(String[] args) {System.out.println("5 + 3 = " + add(5, 3));System.out.println("8是偶数吗: " + isEven(8));System.out.println("5! = " + factorial(5));}
}
🏗️ 第二周:面向对象编程
Day 8:类与对象
今日重点:理解面向对象的基本概念
java
// 定义学生类
class Student {// 属性(字段)String name;int age;double score;// 构造方法public Student(String name, int age, double score) {this.name = name;this.age = age;this.score = score;}// 方法public void displayInfo() {System.out.println("姓名: " + name);System.out.println("年龄: " + age);System.out.println("成绩: " + score);}public boolean isExcellent() {return score >= 90;}
}public class OOPDemo {public static void main(String[] args) {// 创建对象Student student1 = new Student("张三", 20, 95.5);Student student2 = new Student("李四", 21, 85.0);student1.displayInfo();System.out.println("是否优秀: " + student1.isExcellent());}
}
Day 9:字符串处理
今日重点:掌握String类的常用方法
public class StringDemo {public static void main(String[] args) {String str1 = "Hello";String str2 = "World";// 字符串连接String result = str1 + " " + str2;System.out.println("连接结果: " + result);// 字符串方法System.out.println("长度: " + result.length());System.out.println("转大写: " + result.toUpperCase());System.out.println("转小写: " + result.toLowerCase());System.out.println("包含Hello: " + result.contains("Hello"));System.out.println("替换: " + result.replace("World", "Java"));// 字符串分割String[] words = result.split(" ");System.out.println("分割结果: " + Arrays.toString(words));}
}
Day 10:集合框架
今日重点:掌握ArrayList的使用
import java.util.ArrayList;
import java.util.Collections;public class CollectionDemo {public static void main(String[] args) {// 创建ArrayListArrayList<String> fruits = new ArrayList<>();// 添加元素fruits.add("Apple");fruits.add("Banana");fruits.add("Orange");fruits.add("Mango");System.out.println("原始列表: " + fruits);// 访问元素System.out.println("第一个水果: " + fruits.get(0));// 修改元素fruits.set(1, "Grape");System.out.println("修改后: " + fruits);// 删除元素fruits.remove(2);System.out.println("删除后: " + fruits);// 排序Collections.sort(fruits);System.out.println("排序后: " + fruits);// 遍历System.out.println("所有水果:");for (String fruit : fruits) {System.out.println("- " + fruit);}}
}
Day 11:继承与多态
今日重点:理解继承和多态的概念
// 父类
class Animal {String name;public Animal(String name) {this.name = name;}public void makeSound() {System.out.println("动物发出声音");}public void eat() {System.out.println(name + "正在吃东西");}
}// 子类
class Dog extends Animal {public Dog(String name) {super(name);}@Overridepublic void makeSound() {System.out.println(name + "汪汪叫");}public void fetch() {System.out.println(name + "在接飞盘");}
}class Cat extends Animal {public Cat(String name) {super(name);}@Overridepublic void makeSound() {System.out.println(name + "喵喵叫");}public void climb() {System.out.println(name + "在爬树");}
}public class InheritanceDemo {public static void main(String[] args) {Animal myDog = new Dog("Buddy");Animal myCat = new Cat("Whiskers");myDog.makeSound();myDog.eat();myCat.makeSound();myCat.eat();// 多态示例Animal[] animals = {new Dog("Rex"), new Cat("Mimi")};for (Animal animal : animals) {animal.makeSound(); // 不同的实现}}
}
Day 12:异常处理
今日重点:掌握异常处理机制
import java.util.InputMismatchException;
import java.util.Scanner;public class ExceptionDemo {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);try {System.out.print("请输入第一个数字: ");int num1 = scanner.nextInt();System.out.print("请输入第二个数字: ");int num2 = scanner.nextInt();int result = num1 / num2;System.out.println("结果: " + result);} catch (InputMismatchException e) {System.out.println("错误:请输入有效的整数!");} catch (ArithmeticException e) {System.out.println("错误:不能除以零!");} catch (Exception e) {System.out.println("发生未知错误: " + e.getMessage());} finally {System.out.println("程序执行完毕");scanner.close();}}
}
Day 13:常用工具类
今日重点:掌握Math和Arrays工具类
import java.util.Arrays;
import java.util.Random;public class UtilityDemo {public static void main(String[] args) {// Math类示例System.out.println("π的值: " + Math.PI);System.out.println("2的3次方: " + Math.pow(2, 3));System.out.println("16的平方根: " + Math.sqrt(16));System.out.println("随机数: " + Math.random());// Arrays类示例int[] numbers = new int[10];Random random = new Random();// 填充随机数for (int i = 0; i < numbers.length; i++) {numbers[i] = random.nextInt(100);}System.out.println("原始数组: " + Arrays.toString(numbers));// 排序Arrays.sort(numbers);System.out.println("排序后: " + Arrays.toString(numbers));// 二分查找int key = numbers[5];int index = Arrays.binarySearch(numbers, key);System.out.println("元素 " + key + " 的索引: " + index);// 填充数组int[] filledArray = new int[5];Arrays.fill(filledArray, 7);System.out.println("填充数组: " + Arrays.toString(filledArray));}
}
Day 14:综合练习
今日重点:综合运用本周知识
import java.util.ArrayList;
import java.util.Scanner;class Book {private String title;private String author;private double price;public Book(String title, String author, double price) {this.title = title;this.author = author;this.price = price;}// Getter方法public String getTitle() { return title; }public String getAuthor() { return author; }public double getPrice() { return price; }@Overridepublic String toString() {return String.format("《%s》- %s ¥%.2f", title, author, price);}
}public class BookManager {private ArrayList<Book> books = new ArrayList<>();private Scanner scanner = new Scanner(System.in);public void addBook() {System.out.print("请输入书名: ");String title = scanner.nextLine();System.out.print("请输入作者: ");String author = scanner.nextLine();System.out.print("请输入价格: ");double price = scanner.nextDouble();scanner.nextLine(); // 消耗换行符books.add(new Book(title, author, price));System.out.println("添加成功!");}public void displayBooks() {if (books.isEmpty()) {System.out.println("暂无图书");return;}System.out.println("\n=== 图书列表 ===");for (int i = 0; i < books.size(); i++) {System.out.println((i + 1) + ". " + books.get(i));}}public void run() {while (true) {System.out.println("\n=== 图书管理系统 ===");System.out.println("1. 添加图书");System.out.println("2. 显示图书");System.out.println("3. 退出");System.out.print("请选择操作: ");int choice = scanner.nextInt();scanner.nextLine(); // 消耗换行符switch (choice) {case 1:addBook();break;case 2:displayBooks();break;case 3:System.out.println("谢谢使用!");return;default:System.out.println("无效选择!");}}}public static void main(String[] args) {BookManager manager = new BookManager();manager.run();}
}
🔥 第三周:数据结构与算法
Day 15:链表
今日重点:理解链表的基本操作
// 链表节点定义
class ListNode {int val;ListNode next;ListNode(int val) {this.val = val;this.next = null;}
}// 链表操作
class LinkedList {ListNode head;// 添加节点public void add(int val) {ListNode newNode = new ListNode(val);if (head == null) {head = newNode;} else {ListNode current = head;while (current.next != null) {current = current.next;}current.next = newNode;}}// 显示链表public void display() {ListNode current = head;while (current != null) {System.out.print(current.val + " -> ");current = current.next;}System.out.println("null");}// 反转链表public void reverse() {ListNode prev = null;ListNode current = head;ListNode next = null;while (current != null) {next = current.next;current.next = prev;prev = current;current = next;}head = prev;}
}public class LinkedListDemo {public static void main(String[] args) {LinkedList list = new LinkedList();list.add(1);list.add(2);list.add(3);list.add(4);System.out.println("原始链表:");list.display();System.out.println("反转后:");list.reverse();list.display();}
}
Day 16:栈
今日重点:掌握栈的基本操作
import java.util.Stack;public class StackDemo {public static void main(String[] args) {Stack<Integer> stack = new Stack<>();// 压栈stack.push(10);stack.push(20);stack.push(30);stack.push(40);System.out.println("栈内容: " + stack);System.out.println("栈顶元素: " + stack.peek());System.out.println("栈大小: " + stack.size());// 出栈System.out.println("出栈: " + stack.pop());System.out.println("出栈后: " + stack);// 检查是否为空System.out.println("栈是否为空: " + stack.isEmpty());// 使用栈反转字符串String str = "Hello";Stack<Character> charStack = new Stack<>();for (char c : str.toCharArray()) {charStack.push(c);}StringBuilder reversed = new StringBuilder();while (!charStack.isEmpty()) {reversed.append(charStack.pop());}System.out.println("原始字符串: " + str);System.out.println("反转后: " + reversed.toString());}
}
Day 17:队列
今日重点:掌握队列的基本操作
import java.util.LinkedList;
import java.util.Queue;public class QueueDemo {public static void main(String[] args) {Queue<String> queue = new LinkedList<>();// 入队queue.offer("任务1");queue.offer("任务2");queue.offer("任务3");queue.offer("任务4");System.out.println("队列内容: " + queue);System.out.println("队首元素: " + queue.peek());System.out.println("队列大小: " + queue.size());// 出队while (!queue.isEmpty()) {String task = queue.poll();System.out.println("处理: " + task);System.out.println("剩余任务: " + queue);}// 队列应用:模拟打印机任务Queue<String> printerQueue = new LinkedList<>();printerQueue.offer("文档1.pdf");printerQueue.offer("图片1.jpg");printerQueue.offer("报告.doc");System.out.println("\n打印队列:");while (!printerQueue.isEmpty()) {System.out.println("正在打印: " + printerQueue.poll());}}
}
Day 18:哈希表
今日重点:掌握HashMap的使用
import java.util.HashMap;
import java.util.Map;public class HashMapDemo {public static void main(String[] args) {// 创建HashMapHashMap<String, Integer> studentScores = new HashMap<>();// 添加键值对studentScores.put("张三", 85);studentScores.put("李四", 92);studentScores.put("王五", 78);studentScores.put("赵六", 95);System.out.println("学生成绩: " + studentScores);// 获取值System.out.println("李四的成绩: " + studentScores.get("李四"));// 检查键是否存在System.out.println("包含张三: " + studentScores.containsKey("张三"));// 遍历HashMapSystem.out.println("\n所有学生成绩:");for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());}// 统计单词频率String text = "apple banana apple orange banana apple";String[] words = text.split(" ");HashMap<String, Integer> wordCount = new HashMap<>();for (String word : words) {wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);}System.out.println("\n单词频率: " + wordCount);}
}
Day 19:递归
今日重点:理解递归原理
public class RecursionDemo {// 递归计算阶乘public static int factorial(int n) {if (n == 0 || n == 1) {return 1;}return n * factorial(n - 1);}// 递归计算斐波那契数列public static int fibonacci(int n) {if (n <= 1) {return n;}return fibonacci(n - 1) + fibonacci(n - 2);}// 递归求和public static int sum(int n) {if (n == 1) {return 1;}return n + sum(n - 1);}// 递归打印数组public static void printArray(int[] arr, int index) {if (index == arr.length) {return;}System.out.print(arr[index] + " ");printArray(arr, index + 1);}public static void main(String[] args) {System.out.println("5的阶乘: " + factorial(5));System.out.println("斐波那契第10项: " + fibonacci(10));System.out.println("1到10的和: " + sum(10));int[] numbers = {1, 2, 3, 4, 5};System.out.print("数组元素: ");printArray(numbers, 0);}
}
Day 20:排序算法
今日重点:实现基本排序算法
import java.util.Arrays;public class SortingDemo {// 冒泡排序public static void bubbleSort(int[] arr) {int n = arr.length;for (int i = 0; i < n - 1; i++) {for (int j = 0; j < n - 1 - i; j++) {if (arr[j] > arr[j + 1]) {// 交换int temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}}}// 选择排序public static void selectionSort(int[] arr) {int n = arr.length;for (int i = 0; i < n - 1; i++) {int minIndex = i;for (int j = i + 1; j < n; j++) {if (arr[j] < arr[minIndex]) {minIndex = j;}}// 交换int temp = arr[i];arr[i] = arr[minIndex];arr[minIndex] = temp;}}// 插入排序public static void insertionSort(int[] arr) {int n = arr.length;for (int i = 1; i < n; i++) {int key = arr[i];int j = i - 1;while (j >= 0 && arr[j] > key) {arr[j + 1] = arr[j];j--;}arr[j + 1] = key;}}public static void main(String[] args) {int[] testArray = {64, 34, 25, 12, 22, 11, 90};System.out.println("原始数组: " + Arrays.toString(testArray));// 测试冒泡排序int[] arr1 = testArray.clone();bubbleSort(arr1);System.out.println("冒泡排序: " + Arrays.toString(arr1));// 测试选择排序int[] arr2 = testArray.clone();selectionSort(arr2);System.out.println("选择排序: " + Arrays.toString(arr2));// 测试插入排序int[] arr3 = testArray.clone();insertionSort(arr3);System.out.println("插入排序: " + Arrays.toString(arr3));}
}
Day 21:算法实战
今日重点:解决经典算法问题
import java.util.*;public class AlgorithmPractice {// 两数之和public static int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {int complement = target - nums[i];if (map.containsKey(complement)) {return new int[]{map.get(complement), i};}map.put(nums[i], i);}return new int[0];}// 反转字符串public static String reverseString(String s) {char[] chars = s.toCharArray();int left = 0, right = chars.length - 1;while (left < right) {char temp = chars[left];chars[left] = chars[right];chars[right] = temp;left++;right--;}return new String(chars);}// 判断回文数public static boolean isPalindrome(int x) {if (x < 0) return false;int original = x;int reversed = 0;while (x != 0) {reversed = reversed * 10 + x % 10;x /= 10;}return original == reversed;}// 寻找最大子数组和public static int maxSubArray(int[] nums) {int max = nums[0];int current = nums[0];for (int i = 1; i < nums.length; i++) {current = Math.max(nums[i], current + nums[i]);max = Math.max(max, current);}return max;}public static void main(String[] args) {// 测试两数之和int[] nums = {2, 7, 11, 15};int target = 9;int[] result = twoSum(nums, target);System.out.println("两数之和: " + Arrays.toString(result));// 测试反转字符串String str = "hello";System.out.println("反转字符串: " + reverseString(str));// 测试回文数int num = 12321;System.out.println(num + "是回文数吗: " + isPalindrome(num));// 测试最大子数组和int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};System.out.println("最大子数组和: " + maxSubArray(arr));}
}
🎯 第四周:算法进阶
Day 22:二分查找
public class BinarySearch {// 标准二分查找public static int binarySearch(int[] nums, int target) {int left = 0, right = nums.length - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) {return mid;} else if (nums[mid] < target) {left = mid + 1;} else {right = mid - 1;}}return -1;}// 寻找旋转排序数组中的最小值public static int findMin(int[] nums) {int left = 0, right = nums.length - 1;while (left < right) {int mid = left + (right - left) / 2;if (nums[mid] > nums[right]) {left = mid + 1;} else {right = mid;}}return nums[left];}public static void main(String[] args) {int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15};int target = 7;System.out.println("二分查找 " + target + ": " + binarySearch(sortedArray, target));int[] rotatedArray = {4, 5, 6, 7, 0, 1, 2};System.out.println("旋转数组最小值: " + findMin(rotatedArray));}
}
Day 23:双指针技巧
public class TwoPointers {// 快慢指针:删除排序数组中的重复项public static int removeDuplicates(int[] nums) {if (nums.length == 0) return 0;int slow = 0;for (int fast = 1; fast < nums.length; fast++) {if (nums[fast] != nums[slow]) {slow++;nums[slow] = nums[fast];}}return slow + 1;}// 左右指针:盛最多水的容器public static int maxArea(int[] height) {int left = 0, right = height.length - 1;int maxArea = 0;while (left < right) {int area = Math.min(height[left], height[right]) * (right - left);maxArea = Math.max(maxArea, area);if (height[left] < height[right]) {left++;} else {right--;}}return maxArea;}public static void main(String[] args) {int[] nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};int newLength = removeDuplicates(nums);System.out.println("新数组长度: " + newLength);int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7};System.out.println("最大盛水面积: " + maxArea(height));}
}
Day 24:滑动窗口
import java.util.HashMap;public class SlidingWindow {// 无重复字符的最长子串public static int lengthOfLongestSubstring(String s) {HashMap<Character, Integer> map = new HashMap<>();int maxLength = 0;int left = 0;for (int right = 0; right < s.length(); right++) {char currentChar = s.charAt(right);if (map.containsKey(currentChar)) {left = Math.max(left, map.get(currentChar) + 1);}map.put(currentChar, right);maxLength = Math.max(maxLength, right - left + 1);}return maxLength;}// 最小覆盖子串(简化版)public static String minWindow(String s, String t) {if (s.length() < t.length()) return "";int[] targetCount = new int[128];for (char c : t.toCharArray()) {targetCount[c]++;}int left = 0, right = 0;int count = t.length();int minLength = Integer.MAX_VALUE;int minStart = 0;while (right < s.length()) {if (targetCount[s.charAt(right)] > 0) {count--;}targetCount[s.charAt(right)]--;right++;while (count == 0) {if (right - left < minLength) {minLength = right - left;minStart = left;}targetCount[s.charAt(left)]++;if (targetCount[s.charAt(left)] > 0) {count++;}left++;}}return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength);}public static void main(String[] args) {String s = "abcabcbb";System.out.println("无重复最长子串长度: " + lengthOfLongestSubstring(s));String s2 = "ADOBECODEBANC";String t = "ABC";System.out.println("最小覆盖子串: " + minWindow(s2, t));}
}
Day 25:二叉树
import java.util.*;class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int val) {this.val = val;}
}public class BinaryTree {// 前序遍历public static void preorder(TreeNode root) {if (root == null) return;System.out.print(root.val + " ");preorder(root.left);preorder(root.right);}// 中序遍历public static void inorder(TreeNode root) {if (root == null) return;inorder(root.left);System.out.print(root.val + " ");inorder(root.right);}// 后序遍历public static void postorder(TreeNode root) {if (root == null) return;postorder(root.left);postorder(root.right);System.out.print(root.val + " ");}// 层序遍历public static void levelOrder(TreeNode root) {if (root == null) return;Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int levelSize = queue.size();for (int i = 0; i < levelSize; i++) {TreeNode node = queue.poll();System.out.print(node.val + " ");if (node.left != null) queue.offer(node.left);if (node.right != null) queue.offer(node.right);}System.out.println();}}// 构建示例二叉树public static TreeNode buildSampleTree() {TreeNode root = new TreeNode(1);root.left = new TreeNode(2);root.right = new TreeNode(3);root.left.left = new TreeNode(4);root.left.right = new TreeNode(5);root.right.left = new TreeNode(6);root.right.right = new TreeNode(7);return root;}public static void main(String[] args) {TreeNode root = buildSampleTree();System.out.println("前序遍历:");preorder(root);System.out.println("\n中序遍历:");inorder(root);System.out.println("\n后序遍历:");postorder(root);System.out.println("\n层序遍历:");levelOrder(root);}
}
Day 26:深度优先搜索
import java.util.*;public class DFS {// 全排列public static List<List<Integer>> permute(int[] nums) {List<List<Integer>> result = new ArrayList<>();backtrack(result, new ArrayList<>(), nums);return result;}private static void backtrack(List<List<Integer>> result, List<Integer> temp, int[] nums) {if (temp.size() == nums.length) {result.add(new ArrayList<>(temp));return;}for (int num : nums) {if (temp.contains(num)) continue;temp.add(num);backtrack(result, temp, nums);temp.remove(temp.size() - 1);}}// 组合总和public static List<List<Integer>> combinationSum(int[] candidates, int target) {List<List<Integer>> result = new ArrayList<>();Arrays.sort(candidates);backtrackCombination(result, new ArrayList<>(), candidates, target, 0);return result;}private static void backtrackCombination(List<List<Integer>> result, List<Integer> temp, int[] candidates, int remain, int start) {if (remain < 0) return;if (remain == 0) {result.add(new ArrayList<>(temp));return;}for (int i = start; i < candidates.length; i++) {temp.add(candidates[i]);backtrackCombination(result, temp, candidates, remain - candidates[i], i);temp.remove(temp.size() - 1);}}public static void main(String[] args) {int[] nums = {1, 2, 3};System.out.println("全排列:");List<List<Integer>> permutations = permute(nums);for (List<Integer> perm : permutations) {System.out.println(perm);}int[] candidates = {2, 3, 6, 7};int target = 7;System.out.println("\n组合总和 " + target + ":");List<List<Integer>> combinations = combinationSum(candidates, target);for (List<Integer> comb : combinations) {System.out.println(comb);}}
}
Day 27:动态规划
public class DynamicProgramming {// 斐波那契数列(DP版)public static int fibonacci(int n) {if (n <= 1) return n;int[] dp = new int[n + 1];dp[0] = 0;dp[1] = 1;for (int i = 2; i <= n; i++) {dp[i] = dp[i - 1] + dp[i - 2];}return dp[n];}// 爬楼梯public static int climbStairs(int n) {if (n <= 2) return n;int[] dp = new int[n + 1];dp[1] = 1;dp[2] = 2;for (int i = 3; i <= n; i++) {dp[i] = dp[i - 1] + dp[i - 2];}return dp[n];}// 最长递增子序列public static int lengthOfLIS(int[] nums) {if (nums.length == 0) return 0;int[] dp = new int[nums.length];Arrays.fill(dp, 1);int max = 1;for (int i = 1; i < nums.length; i++) {for (int j = 0; j < i; j++) {if (nums[i] > nums[j]) {dp[i] = Math.max(dp[i], dp[j] + 1);}}max = Math.max(max, dp[i]);}return max;}public static void main(String[] args) {System.out.println("斐波那契第10项: " + fibonacci(10));System.out.println("爬10阶楼梯的方法: " + climbStairs(10));int[] nums = {10, 9, 2, 5, 3, 7, 101, 18};System.out.println("最长递增子序列长度: " + lengthOfLIS(nums));}
}
Day 28:贪心算法
import java.util.Arrays;public class Greedy {// 找零钱问题public static int coinChange(int[] coins, int amount) {Arrays.sort(coins);int count = 0;int index = coins.length - 1;while (amount > 0 && index >= 0) {if (coins[index] <= amount) {count += amount / coins[index];amount %= coins[index];}index--;}return amount == 0 ? count : -1;}// 跳跃游戏public static boolean canJump(int[] nums) {int maxReach = 0;for (int i = 0; i < nums.length; i++) {if (i > maxReach) return false;maxReach = Math.max(maxReach, i + nums[i]);if (maxReach >= nums.length - 1) return true;}return false;}// 买卖股票的最佳时机IIpublic static int maxProfit(int[] prices) {int profit = 0;for (int i = 1; i < prices.length; i++) {if (prices[i] > prices[i - 1]) {profit += prices[i] - prices[i - 1];}}return profit;}public static void main(String[] args) {int[] coins = {1, 2, 5};int amount = 11;System.out.println("找零钱 " + amount + " 需要硬币数: " + coinChange(coins, amount));int[] nums = {2, 3, 1, 1, 4};System.out.println("能否跳到终点: " + canJump(nums));int[] prices = {7, 1, 5, 3, 6, 4};System.out.println("最大利润: " + maxProfit(prices));}
}
Day 29:项目实战
import java.util.*;// 简单的计算器实现
public class Calculator {public static int calculate(String s) {Stack<Integer> stack = new Stack<>();int num = 0;char sign = '+';for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);if (Character.isDigit(c)) {num = num * 10 + (c - '0');}if ((!Character.isDigit(c) && c != ' ') || i == s.length() - 1) {switch (sign) {case '+':stack.push(num);break;case '-':stack.push(-num);break;case '*':stack.push(stack.pop() * num);break;case '/':stack.push(stack.pop() / num);break;}sign = c;num = 0;}}int result = 0;while (!stack.isEmpty()) {result += stack.pop();}return result;}// 单元测试public static void testCalculator() {String[] testCases = {"3+2*2"," 3/2 "," 3+5 / 2 ","1-1+1","2*3+4"};int[] expected = {7, 1, 5, 1, 10};for (int i = 0; i < testCases.length; i++) {int result = calculate(testCases[i]);System.out.println(testCases[i] + " = " + result + " (" + (result == expected[i] ? "✓" : "✗") + ")");}}public static void main(String[] args) {testCalculator();// 交互式计算器Scanner scanner = new Scanner(System.in);System.out.println("\n欢迎使用简单计算器!");System.out.println("输入表达式(支持+ - * /),输入'quit'退出");while (true) {System.out.print("> ");String input = scanner.nextLine().trim();if (input.equalsIgnoreCase("quit")) {System.out.println("再见!");break;}try {int result = calculate(input);System.out.println("结果: " + result);} catch (Exception e) {System.out.println("计算错误,请检查表达式");}}scanner.close();}
}
Day 30:总结与展望
今日重点:复习巩固,制定下一步学习计划
import java.util.*;public class Review {// 综合复习:解决一个中等难度问题public static List<List<Integer>> threeSum(int[] nums) {Arrays.sort(nums);List<List<Integer>> result = new ArrayList<>();for (int i = 0; i < nums.length - 2; i++) {if (i > 0 && nums[i] == nums[i - 1]) continue;int left = i + 1, right = nums.length - 1;while (left < right) {int sum = nums[i] + nums[left] + nums[right];if (sum == 0) {result.add(Arrays.asList(nums[i], nums[left], nums[right]));while (left < right && nums[left] == nums[left + 1]) left++;while (left < right && nums[right] == nums[right - 1]) right--;left++;right--;} else if (sum < 0) {left++;} else {right--;}}}return result;}public static void main(String[] args) {// 测试三数之和int[] nums = {-1, 0, 1, 2, -1, -4};List<List<Integer>> result = threeSum(nums);System.out.println("三数之和结果:");for (List<Integer> triplet : result) {System.out.println(triplet);}// 学习总结System.out.println("\n🎉 恭喜完成30天Java学习!");System.out.println("📚 已掌握技能:");System.out.println(" ✓ Java基础语法");System.out.println(" ✓ 面向对象编程");System.out.println(" ✓ 常用数据结构");System.out.println(" ✓ 基本算法思想");System.out.println(" ✓ 问题解决能力");System.out.println("\n🚀 下一步学习建议:");System.out.println(" 1. 深入学习Java高级特性(泛型、反射、IO等)");System.out.println(" 2. 学习Spring框架");System.out.println(" 3. 掌握数据库操作");System.out.println(" 4. 学习多线程编程");System.out.println(" 5. 参与开源项目");System.out.println("\n💡 保持学习的建议:");System.out.println(" - 每天坚持写代码");System.out.println(" - 参与算法竞赛");System.out.println(" - 阅读优秀源码");System.out.println(" - 写技术博客分享");System.out.println(" - 加入技术社区");}
}
🎯 学习建议与资源
📚 推荐学习资源
书籍:《Java核心技术卷I》、《算法导论》
网站:LeetCode、牛客网、Stack Overflow
视频:B站Java学习路线、慕课网
💡 学习技巧
每日打卡:坚持每天学习2小时
动手实践:所有代码都要亲手敲
及时复习:每周回顾之前的内容
解决问题:遇到错误先自己调试
分享交流:写博客、参与讨论
🚀 后续学习路径
Java进阶:多线程、网络编程、JVM
框架学习:Spring、MyBatis、Spring Boot
数据库:MySQL、Redis、MongoDB
前端基础:HTML、CSS、JavaScript
项目实战:个人博客、电商系统、管理系统
恭喜你完成了30天的Java学习之旅! 🎊
记住,编程学习是一个持续的过程,这30天只是开始。继续保持学习的热情,坚持练习,你一定会成为一名优秀的Java开发者!
如果有任何问题,欢迎在评论区交流讨论! 👇