repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution54.java | data_struct_study/src/array_problem/Solution54.java | package array_problem;
/**
* 螺旋矩阵
*/
public class Solution54 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution151.java | data_struct_study/src/array_problem/Solution151.java | package array_problem;
public class Solution151 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution557.java | data_struct_study/src/array_problem/Solution557.java | package array_problem;
public class Solution557 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution3_3.java | data_struct_study/src/array_problem/Solution3_3.java | package array_problem;
/**
* l 每次可以向前飞跃,而不仅仅是 +1,以确保滑动窗口中不存在重复的字符串,
* 但为了获得这个飞跃值,每次都要遍历一次当前滑动窗口的大小。
*
* 时间换空间:
* 时间复杂度:O(r-l+1) * len(s))
* 空间复杂度:O(1)
*/
public class Solution3_3 {
// 时间换空间的解法:时间复杂度:O(len(s)) * O(r-l+1),空间复杂度:O(1)
public int lengthOfLongestSubstring(String s) {
// 1、初始化滑动窗口:[0,0) 由于后面要使用 s.charAt(r),所以 r 需要从 0 开始 & 记录窗口最大值的变量
int l = 0, r = 0;
int res = 0;
// 2、注意:这里的r不需要+1了
while (r < s.length()) {
// 1)、当前滑动窗口右边界的元素是否在滑动窗口中存在重复元素,
// 有则返回离左边界最近的重复元素下标
int index = findInDuplicate(s, l, r);
// 2)、如果存在重复元素,则更新滑动窗口左边界为重复元素下标+1,以减少可能的冗余遍历(核心)
if (index != -1) {
l = index + 1;
}
// 3)、更新滑动窗口最大值
res = Math.max(res, r - l + 1);
// 4)、滑动窗口右边界+1
r++;
}
return res;
}
/**
* 判读当前窗口新的右边界是否已现在滑动窗口中,有则返回离左边界最近的下标(即飞跃值)
*/
private int findInDuplicate(String s, int l, int r) {
for (int i = l; i < r; i++) {
if (s.charAt(i) == s.charAt(r)) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println((new Solution3_3()).lengthOfLongestSubstring( "abcabcbb" ));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution5.java | data_struct_study/src/array_problem/Solution5.java | package array_problem;
/**
* 最长回文子串:注意要分奇偶情况分别讨论。
*/
public class Solution5 {
public String longestPalindrome(String s) {
if (s==null||s.length()<1) return "";
int maxLen=0, id=-1;
for(int i=0; i<s.length(); i++){
int len1=expand(s,i,i);
int len2=expand(s,i,i+1);
int len=Math.max(len1,len2);
if (len>=maxLen){
maxLen=len;id=i;
}
}
return s.substring(id-(maxLen-1)/2+1, id+maxLen/2);
}
int expand(String s, int l, int r){
while(l>=0&&r<s.length()&&s.charAt(l)==s.charAt(r)){
l--;r++;
}
return r-l+1;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution4.java | data_struct_study/src/array_problem/Solution4.java | package array_problem;
public class Solution4 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution345.java | data_struct_study/src/array_problem/Solution345.java | package array_problem;
//https://leetcode-cn.com/problems/reverse-vowels-of-a-string/:反转字符串中的元音字母
import java.util.Arrays;
import java.util.HashSet;
/**
* 编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
*
* 示例 1:
*
* 输入: "hello"
* 输出: "holle"
* 示例 2:
*
* 输入: "leetcode"
* 输出: "leotcede"
* 说明:
* 元音字母不包含字母"y"。
*
* (元音aeiou)
*/
public class Solution345 {
private final static HashSet<Character> vowels = new HashSet<>(Arrays.asList(
'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'
));
public String reverseVowels(String s) {
if (s == null) {
return null;
}
int i = 0, j = s.length() - 1;
char[] res = new char[s.length()];
while (i <= j) {
char ci = s.charAt(i);
char cj = s.charAt(j);
if (!vowels.contains(ci)) {
res[i++] = ci;
} else if (!vowels.contains(cj)) {
res[j--] = cj;
} else {
res[i++] = cj;
res[j--] = ci;
}
}
return new String(res);
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution209.java | data_struct_study/src/array_problem/Solution209.java | package array_problem;
/**
* 滑动窗口 209:
* 1、什么叫子数组?
* 2、如果没有解怎么办?返回0
* 3、暴力解:遍历所有的连续子数组[i...j],计算其和 sum,验证 sum >= s,时间复杂度 O(n^3)
* 暴力解的问题:大量的重复运算。
* 4、滑动窗口 nums[l...r] 时间 O(n),空间 O(1)
*/
public class Solution209 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution27.java | data_struct_study/src/array_problem/Solution27.java | package array_problem;
//https://leetcode-cn.com/problems/remove-element/:移除元素
/**
* 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
*
* 不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
*
* 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
*
*
*
* 示例 1:
*
* 给定 nums = [3,2,2,3], val = 3,
*
* 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。
*
* 你不需要考虑数组中超出新长度后面的元素。
* 示例 2:
*
* 给定 nums = [0,1,2,2,3,0,4,2], val = 2,
*
* 函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。
*
* 注意这五个元素可为任意顺序。
*
* 你不需要考虑数组中超出新长度后面的元素。
*
*
* 说明:
*
* 为什么返回数值是整数,但输出的答案是数组呢?
*
* 请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。
*
* 你可以想象内部操作如下:
*
* // nums 是以“引用”方式传递的。也就是说,不对实参作任何拷贝
* int len = removeElement(nums, val);
*
* // 在函数里修改输入数组对于调用者是可见的。
* // 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
* for (int i = 0; i < len; i++) {
* print(nums[i]);
* }
*
* 1、如何定义删除?从数组中去除?还是放在数组最后。
* 2、剩余元素的排列是否要保持原有元素的相对顺序。
* 3、是否有空间复杂度的要求。O(1)
*
*/
public class Solution27 {
// public int removeElement(int[] nums, int val) {
//
// }
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution695.java | data_struct_study/src/array_problem/Solution695.java | package array_problem;
public class Solution695 {
private int m, n;
private int[][] d = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int maxAreaOfIsland(int[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
m = grid.length;
n = grid[0].length;
int maxArea = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
maxArea = Math.max(maxArea, dfs(grid, i, j));
}
}
return maxArea;
}
private int dfs(int[][] grid, int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= m || grid[i][j] == 0) {
return 0;
}
// 已经搜索过的设为0,防止重复被搜索
grid[i][j] = 0;
int res = 1;
for (int[] d : d) {
res += dfs(grid, i + d[0], j + d[1]);
}
return res;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution3.java | data_struct_study/src/array_problem/Solution3.java | package array_problem;
/**
* 3:
* 1、字符集?只有字母?数字+字母?ASCLL?
* 2、大小写是否敏感?
*
* 滑动窗口
* 时间复杂度:O(len(s))
* 空间复杂度:O(len(charset))
*/
public class Solution3 {
// 时间复杂度为 O(len(s)),空间复杂度为 O(len(charset))
public int lengthOfLongestSubstring(String s) {
// 1、初始化一个存储ascill字符集的数组
int[] freq = new int[256];
// 2、初始化滑动窗口:[0, -1],窗口大小为0 & 记录滑动窗口最大值的变量
int l = 0, r = -1;
int res = 0;
// 3、当左边界小于字符串长度时,维护滑动窗口
while (l < s.length()) {
// 1)、如果右边界+1小于字符串长度 & 右边界+1的出现频次为0,
// 则将右边界+1,同时将右边界的出现频次+1
if (r + 1 < s.length() && freq[s.charAt(r + 1)] == 0) {
freq[s.charAt(++r)]++;
} else {
// 2)、否则,将左边界的出现频次-1,同时左边界+1
freq[s.charAt(l++)]--;
}
// 3)、更新维护滑动窗口的大小
res = Math.max(res, r - l + 1);
}
return res;
}
public static void main(String[] args) {
System.out.println((new Solution3()).lengthOfLongestSubstring( "abcabcbb" ));
System.out.println((new Solution3()).lengthOfLongestSubstring( "bbbbb" ));
System.out.println((new Solution3()).lengthOfLongestSubstring( "pwwkew" ));
System.out.println((new Solution3()).lengthOfLongestSubstring( "" ));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution88.java | data_struct_study/src/array_problem/Solution88.java | package array_problem;
/**
* 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
* 说明: 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
* 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
*
* 示例:
* 输入:
* nums1 = [1,2,3,0,0,0], m = 3
* nums2 = [2,5,6], n = 3
* 输出: [1,2,2,3,5,6]
*/
public class Solution88 {
// 双指针:为防止元素被覆盖,双指针需从后往前遍历
// 时间复杂度:O(m + n),空间复杂度:O(1)
public void merge(int[] nums1, int m, int[] nums2, int n) {
// 1、初始化数组1、2的指针:指向数组有效尾部 & 合并数组指针指向合并数组有效尾部
int index1 = m - 1, index2 = n - 1;
int indexMerge = m + n - 1;
// 2、当数组1或2的指针有效,即大于等于0时
while (index1 >= 0 || index2 >= 0) {
if (index1 < 0) {
// 3)、如果数组1处的指针小于0,则更新数组1合并指针位置的值为数组2指针处的值,
// 并将数组2的指针和合并指针都-1
nums1[indexMerge--] = nums2[index2--];
} else if (index2 < 0) {
// 4)、否则,更新数组1合并指针位置的值为数组1处指针的值,并将数组1的指针和合并指针都-1
nums1[indexMerge--] = nums1[index1--];
} else if (nums1[index1] > nums2[index2]) {
// 1)、如果数组1的值大于数组2的值,则更新数组1合并指针位置的值为数组1指针处的值,
// 并将数组1的指针和合并指针都-1
nums1[indexMerge--] = nums1[index1--];
} else {
// 2)、否则,更新数组1合并指针位置的值为数组2指针处的值,并将数组2的指针和合并指针都-1
nums1[indexMerge--] = nums2[index2--];
}
}
}
public static void main(String[] args) {
int[] arr1 = new int[]{1, 2, 3, 0, 0, 0};
int[] arr2 = new int[]{2, 5, 6};
new Solution88().merge(arr1, 3, arr2, arr2.length);
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution283.java | data_struct_study/src/array_problem/Solution283.java | package array_problem;
import java.util.ArrayList;
/**
* O(n)
* O(n)
*/
public class Solution283 {
public void moveZeroes(int[] nums) {
ArrayList<Integer> noZeroList = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
noZeroList.add(nums[i]);
}
}
for (int i = 0; i < noZeroList.size(); i++) {
nums[i] = noZeroList.get(i);
}
for (int i = noZeroList.size(); i < nums.length; i++) {
nums[i] = 0;
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution_3.java | data_struct_study/src/array_problem/Solution_3.java | package array_problem;
import java.util.HashSet;
/**
* 原地哈希,把数组中取值在1到n的数放到对应的位置,
* 比如1放到0的位置,2放到1的位置,……n放到n-1的位置,
* 然后遍历重置后的数组,若i下标位置不是i+1,则i+1就是
* 那个最小的正整数,若1到n位置都对的上,说明最小的正整数是n+1。
*
* 所谓原地哈希就是对数组中的元素,直接将其映射(也就是交换)到哈希函数计算出来的数组位置上。
* 本题要找的是第一个缺失的正整数,那么可以使用hash(i) = a[i] - 1这样一个哈希函数,
* 比如对于数组2,3,1,5,-1,原地哈希过程如下:
* 把a[0] = 2交换到第1个位置: 3,2,1,5,-1
* 把a[0] = 3交换到第2个位置:1,2,3,5,-1
* 此时a[0] = 1, a[1] = 2, a[2] = 3,这三个元素都已经映射到了正确的位置上
* 把a[3] = 5交换到第4个位置:1,2,3,-1,5
* 此时a[3] = -1,哈希映射的数组位置(-2)在数组中不存在,因此直接跳过
* 最后a[4] = 5也映射到了正确的位置上,原地哈希完成
* 然后再遍历一遍数组,发现a[3] != 4,也就是说4是第一个缺失的正整数,返回4。
* 对于比较特殊的情况,比如原地哈希后得到的序列是1,2,3,4,5,数组中的元素都
* 满足a[i] = i + 1,那么直接返回len + 1 = 6即可。
* 这样做的时间复杂度是O(n)吗,因为在for循环中存在while循环,所以会有这样的疑问。
* 根据上面的例子我们注意到在a[0]位置完成2次交换后,在a[1]和a[2]位置就不需要进行交换了,
* 也就是说本方法的均摊时间复杂度的确是O(n)。
*/
public class Solution_3 {
/**
* 1、哈希法:时间复杂度O(n),空间复杂度O(n)
*/
public int minNumberdisappered(int[] arr) {
// 1、初始化最小正整数变量为1
int min = 1;
// 2、遍历数组:添加当前元素到set中,当set中包含min时,则min+1
HashSet<Integer> set = new HashSet<>();
for(int value : arr) {
set.add(value);
while (set.contains(min)) {
min++;
}
}
return min;
}
/**
* return the min number
* @param arr int整型一维数组 the array
* @return int整型
*/
public int minNumberdisappered2(int[] arr) {
// 1、原地哈希:遍历数组,只要当前元素的值在数组长度范围内 & 当
// 前元素的值不等于当前元素值-1的下标的值时交换这两个下标元素的值
int n = arr.length;
for(int i = 0; i < n; i++) {
while(arr[i] >= 1 && arr[i] <= n && arr[arr[i] - 1] != arr[i]){
swap(arr, arr[i]-1, i);
}
}
// 2、再遍历一遍数组,如果下标为i的元素的值不是i+1,则说明i+1就是未出现的最小正整数
for(int i = 0; i < n; i++){
if (arr[i] != i + 1){
return i + 1;
}
}
// 3、特殊情况处理,遍历中没有找到,则说明最小正整数就是n+1
return n + 1;
}
private void swap(int[] arr,int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] arr = new int[]{2, 3, 1, 5, -1};
System.out.println(new Solution_3().minNumberdisappered2(arr));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution238.java | data_struct_study/src/array_problem/Solution238.java | package array_problem;
import java.util.Arrays;
/**
* 除自身以外数组的乘积: 对于每一个元素而言,左边的所有元素
* 乘以右边的所有元素就能得到答案。注意,两次循环不能合并!
*/
public class Solution238 {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] product = new int[n];
Arrays.fill(product, 1);
int left = 1;
for (int i = 1; i < n; i++) {
left *= nums[i - 1];
product[i] *= left;
}
int right = 1;
for (int i = n - 2; i >= 0; i--) {
right *= nums[i + 1];
product[i] *= right;
}
return product;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4};
System.out.println(new Solution238().productExceptSelf(nums));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution3_4.java | data_struct_study/src/array_problem/Solution3_4.java | package array_problem;
import java.util.Arrays;
/**
* 3:
* 1、字符集?只有字母?数字+字母?ASCLL?
* 2、大小写是否敏感?
*
* 滑动窗口
* 时间复杂度:O(len(s))
* 空间复杂度:O(len(charset))
*/
public class Solution3_4 {
// 滑动窗口 + 优化:使用记录上一次滑动窗口右边界下标的数组,以实现找到重复元素时左边界的飞跃
// 时间复杂度:O(len(s)) 空间复杂度:O(len(charset))
public int lengthOfLongestSubstring(String s) {
// 1、初始化记录上一次的滑动窗口右边界下标,以实现找到重复元素时左边界的飞跃
int[] last = new int[256];
Arrays.fill(last, -1);
// 2、初始化滑动窗口:[0, -1] & 记录窗口最大值的变量
int l = 0, r = -1;
int res = 0;
// 3、维护滑动窗口
while (r + 1 < s.length()) {
// 1)、右边界+1
r++;
// 2)、如果当前右边界的元素已经出现过,则更新左边界为 左边界 与 右边界元素上次出现的下标+1 两者中的最大值
if (last[s.charAt(r)] != -1) {
l = Math.max(l, last[s.charAt(r)] + 1);
}
// 3)、维护滑动窗口的大小
res = Math.max(res, r - l + 1);
// 4)、保存右边界的下标
last[s.charAt(r)] = r;
}
return res;
}
public static void main(String[] args) {
System.out.println((new Solution3_4()).lengthOfLongestSubstring( "abcabcbb" ));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Main.java | data_struct_study/src/array_problem/Main.java | package array_problem;
/**
* 什么是算法面试?
* 1、不代表能够"正确"回答每一个算法问题,但是合理的思考方向其实更重要,
* 也是正确完成算法面试的前提。
* 2、算法面试优秀并不意味着技术面试优秀,而技术面试优秀也并不意味着能够拿到 Offer。
* 3、把面试的过程看作是和面试官一起探讨一个问题的解决方案。对于问题的
* 细节和应用场景,可以和面试官沟通。而这种沟通本身也是非常重要的,它暗示着
* 你思考问题的方式。
* 4、如果是非常难的问题,对于你的竞争对手来说,也是难的。关键在于你所表达出的解决问题的思路。
* 甚至通过表达解题思路的方向,得出结论:这个问题的解决方案,应该在哪一个领域,我们可以通过查阅
* 或者进一步学习解决问题。
*
* 例如:对于一组数据进行排序?
* 思考:这组数据有什么特征?
* 1)、有没有可能包含有大量重复元素?如果有这种可能的话,三路快排是更好的选择。否则使用普通快排即可。
* 2)、是否大部分数据距离它正确的位置很近?是否近乎有序?如果是这样的话,插入排序是更好的选择。
* 3)、是否数据的取值范围非常有限?比如对学生成绩排序,如果是这样的话,计数排序是更好的选择。
* 4)、是否需要稳定的排序?如果是的话,归并排序是更好地选择。
* 5)、是否是使用链表存储的?如果是的话,归并排序是更好地选择,因为快排非常依赖于数组的随机访问。
* 6)、数据的大小是否可以装载到内存里?不能的话,需要使用外排序。
*
* 如何准备算法面试?
* 在学习和实践做题之间,要掌握平衡。
*
* 如何回答算法面试问题?
* 1、注意题目中的条件,例如:
* 1)、给定一个有序的数组。
* 2)、设计一个 O(nlogn) 的算法。
* 3)、无需考虑额外的空间。
* 4)、数据规模大概是10000。
* 2、当没有思路时:
* 1)、设计几个简单的测试用例,试验一下。
* 2)、不要忽视暴力解法。暴力解法通常是思考的起点。
* 3、优化算法
* 1)、遍历常见的算法思路。
* 2)、遍历常见的数据结构。
* 3)、空间和时间的交互(哈希表)。
* 4、预处理信息(排序)。
* 5、在瓶颈处寻找答案:O(nlogn) + O(n^2)、O(n^3)。
* 6、实际编写问题:
* 1)、极端条件的判断:数组为空?字符串为空?数量为0?指针为 NULL?
* 2)、合理的变量名。
* 3)、注意代码的模块化、复用性。
*
* 一、时间复杂度
* 1、到底什么是大 O?
* n 表示数据规模,O(f(n)) 表示运行算法所需要执行的指令数,和 f(n) 成正比。
* 2、数据规模的概念——如果想在1s之内解决问题:
* 1)、O(n^2) 的算法可以处理大约10^4级别的数据。
* 2)、O(n) 的算法可以处理大约10^8级别的数据。
* 3)、O(nlogn) 的算法可以处理大约10^7级别的数据。
* 3、空间复杂度
* 1)、多开一个辅助的数组:O(n)。
* 2)、多开一个辅助的二维数组:O(n^2)。
* 3)、多开常数空间:O(1)。
* 4)、递归是有空间代价的,递归 n 次,空间复杂度就为 O(n)。
* 4、简单复杂度分析
* 经过几次"除以2"操作后,等于1,此时的算法是对数复杂度的,并且对数复杂度会忽略它的底。
*
* 5、亲自试验自己算法的时间复杂度
* O(log(n)) 与 O(n) 有着本质的差别。
*
* 6、递归算法的复杂度分析
* 1)、不是有递归的函数就是一定是 O(nlogn) 的。
* 2)、递归中进行一次递归调用:递归函数的时间复杂度为 O(T * depth)。
* 3)、递归中进行多次递归调用:画出递归树,计算调用次数。
* 例如2次递归调用:2^0 + ... 2^n = 2^(n+1) - 1 = O(2^n)
* 4)、主定理:归纳了递归函数所计算时间复杂度的所有情况。
*
* 7、均摊时间复杂度分析(Amortized Time Analysis)与 避免复杂度的震荡
* 见 array package
*
* JsonChao的数组核心题库:36题
*/
public class Main {
public static void main(String[] args) {
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution8.java | data_struct_study/src/array_problem/Solution8.java | package array_problem;
public class Solution8 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution16.java | data_struct_study/src/array_problem/Solution16.java | package array_problem;
public class Solution16 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution215.java | data_struct_study/src/array_problem/Solution215.java | package array_problem;
/**
* 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后
* 的第 k 个最大的元素,而不是第 k 个不同的元素。
*
* 示例 1:
* 输入: [3,2,1,5,6,4] 和 k = 2
* 输出: 5
* 示例 2:
*
* 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
* 输出: 4
* 说明:
*
* 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
*
* 1、排序
* O(nlogn)
* O(1)
* 2、堆排序:空间换时间
* O(nlogk)
* O(k)
* 3、利用快排 partition 中,将 pivot 放置在了正确的位置上的性质。
* O(n)
* O(1)
*/
public class Solution215 {
public int findKthLargest(int[] nums, int k) {
// 1、取k为第k个最小的元素 & 初始化窗口左右边界
k = nums.length - k;
int l = 0, r = nums.length - 1;
// 2、当窗口的长度有效,即左边界小于右边界时
while(l < r) {
// 3、利用快排的partition函数找到切分元素对应的位置j,也就是第j个最小的元素
int j = partition(nums, l, r);
// 4、如果找到的第j个最小元素的下标就是目标元素的下标,则break返回元素即可
if (j == k) {
break;
} else if (j < k) {
// 如果小于,则更新窗口左边界为j+1,否则更新窗口右边界为j-1
l = j + 1;
} else {
r = j - 1;
}
}
return nums[k];
}
private int partition(int[] nums, int l, int r) {
// 1)、初始化窗口的左右边界,注意右边界要+1,便于后面复用通用的代码逻辑
int i = l, j = r + 1;
// 2)、取第一个元素为切分元素
int v = nums[l];
// 3)、开启一个while无限循环来找切分元素
while (true) {
// 4)、从左到右找到第一个比切分元素大的元素 & 这个元素小于右边界
while (nums[++i] < v && i < r) ;
// 5)、从右到左找到第一个比切分元素小的元素 & 这个元素大于左边界
while (nums[--j] > v && j > l) ;
// 6)、如果比切分元素大的元素与比切分元素小的元素相遇了,则break
if (i >= j) {
break;
}
// 7)、否则,交互i和j的值
swap(nums, i, j);
}
// 8)、最后,交换l和j的值
swap(nums, l, j);
return j;
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void main(String[] args) {
// [3,2,1,5,6,4] 和 k = 2
int[] nums = new int[]{3, 2, 1, 5, 6, 4};
System.out.println(new Solution215().findKthLargest(nums, 2));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution14.java | data_struct_study/src/array_problem/Solution14.java | package array_problem;
public class Solution14 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution_2.java | data_struct_study/src/array_problem/Solution_2.java | package array_problem;
/**
* 多数投票问题,可以利用 Boyer-Moore 投票算法
* 来解决这个问题,使得时间复杂度为 O(n)。
*
* 使用 cnt 来统计一个元素出现的次数,当遍历到的元素和统计元素相等时,
* 令 cnt++,否则令 cnt--。如果前面查找了 i 个元素,且 cnt == 0,
* 说明前 i 个元素没有 majority,或者有 majority,但是出现的次数
* 少于 i / 2 ,因为如果多于 i / 2 的话 cnt 就一定不会为 0 。
* 此时剩下的 n - i 个元素中,majority 的数目依然多于 (n - i) / 2,
* 因此继续查找就能找出 majority。
*/
public class Solution_2 {
// 1、哈希表:用hashMap统计所有元素出现的次数,时间复杂度O(n), 空间复杂度O(n)
// 2、排序:如果将数组 nums 中的所有元素按照单调递增或单调递减的顺序排序,
// 那么下标为n/2的元素一定是众数。时间复杂度O(nlog(n)),空间复杂度O(logn)(自己实现堆排序O(1))
// 3、Boyer Moore投票算法:时间复杂度O(n), 空间复杂度O(1)
public int majorityElement(int[] nums) {
// 1、初始化出现次数和候选众数
int count = 0;
Integer candidate = null;
// 2、遍历数组
for (int num : nums) {
// 3、如果出现次数为0,则更新当前的候选众数
if (count == 0) {
candidate = num;
}
// 4、然后更新当前候选众数的出现次数:当前元素与候选众数相等,则+1,否则-1
count += (num == candidate) ? 1 : -1;
}
// 5、最后的候选众数就是真正的众数
// 为什么?如果候选众数不是真正的众数,则真正众数会和其它非候选人一起反对,此时候选众数就会下台(count==0),
// 如果候选众数是真正的众数,则真正的众数就会支持,其它非获选人会一起反对,此时候选众数最后一定会当选。
return candidate;
}
public static void main(String[] args) {
int[] nums = new int[]{2,2,1,1,1,2,2};
System.out.println(new Solution_2().majorityElement(nums));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution885.java | data_struct_study/src/array_problem/Solution885.java | package array_problem;
public class Solution885 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution60.java | data_struct_study/src/array_problem/Solution60.java | package array_problem;
public class Solution60 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution75_2.java | data_struct_study/src/array_problem/Solution75_2.java | package array_problem;
/**
* 三路快排的思想
* O(n)
* O(1)
*/
public class Solution75_2 {
public void sortColors(int[] nums) {
// 1、[0, zero] 存储0
int zero = -1;
// 2、[two, nums.length -1] 存储2
int two = nums.length;
// 3、0,2指针往中间靠,最后中间剩下的就是1
// 注意 i < two,遍历的区间会随着尾部2的增多而减小
for (int i = 0; i < two; ) {
if (nums[i] == 1) {
i++;
} else if (nums[i] == 2) {
swap(nums, --two, i);
} else if (nums[i] == 0) {
swap(nums, ++zero, i++);
}
}
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/Solution3_2.java | data_struct_study/src/array_problem/Solution3_2.java | package array_problem;
/**
* 3:
* 1、字符集?只有字母?数字+字母?ASCLL?
* 2、大小写是否敏感?
*
* 滑动窗口
* 时间复杂度:O(len(s))
* 空间复杂度:O(len(charset))
*/
public class Solution3_2 {
// 时间复杂度:O(len(s)),空间复杂度:O(charset)
public int lengthOfLongestSubstring(String s) {
// 1、初始化一个存储ascill字符集的数组用来记录元素的出现频次
int[] freq = new int[256];
// 2、初始化滑动窗口:[0, -1] & 记录窗口最大值的变量
int l = 0, r = -1;
int res = 0;
// 3、维护滑动窗口:左边界小于数组长度 || 右边界+1小于数组长度
// while (l < s.length())
while (r + 1 < s.length()) {
// 1)、如果右边界+1小于数组长度 & 右边界+1的出现频次为0,
// 则将右边界+1,并将其出现频次+1
if (r + 1 < s.length() && freq[s.charAt(r + 1)] == 0) {
freq[s.charAt(++r)]++;
} else {
// 2)、否则,将左边界的出现频次-1,并将左边界+1
freq[s.charAt(l++)]--;
}
// 3)、更新滑动窗口的最大值
res = Math.max(res, r - l + 1);
}
return res;
}
public static void main(String[] args) {
System.out.println((new Solution3_2()).lengthOfLongestSubstring( "abcabcbb" ));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/array_problem/BinarySearch.java | data_struct_study/src/array_problem/BinarySearch.java | package array_problem;
/**
* 二分搜索:[0, n-1] 区间搜索版
*/
public class BinarySearch {
public static int binarySearch(Comparable[] arr, int n, Comparable target){
int l = 0;
int r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid].compareTo(target) == 0) {
return mid;
}
if (arr[mid].compareTo(target) < 0) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return -1;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/red_black_tree/RBTree.java | data_struct_study/src/red_black_tree/RBTree.java | package red_black_tree;
import avl.FileOperation;
import java.util.ArrayList;
/**
* 算法导论中给出的5条红黑树的定义太生硬,并不能让人理解到底什么才是红黑树。
* 而算法4的作者 Robert Sedgewick 是红黑树的发明人之一,而他正是现代计算机科学之父
* Donald Knuth 的弟子,可以挑战下 Donald Knuth 的两大著作:《计算机编程的艺术》
*
* 红黑树与2-3树的等价性。理解了2-3树,对我们理解红黑树与B类树有巨大帮助。
*
* 2-3树:
* 1、满足二分搜索树的基本性质。
* 2、节点可以存放一个元素或两个元素。
* 3、每个节点有2个或者3个孩子——这正是2-3树名称的由来。
* 4、存放一个元素二个孩子的节点称为2节点,存放二个元素三个孩子的节点成为3节点。
* 5、2-3树是一颗绝对平衡(对于任意一个节点来说,左右子树的高度一定是相同的)的数。
*
* 2-3树如何维持绝对的平衡?
* 1、添加节点永远不会添加到一个空节点,而是跟最后的一个叶子节点做融合。
* 2、暂时形成的一层4节点会分裂成两层2节点,暂时形成的两层4节点会分裂成三层2节点。
* 3、生成的新的树中根节点会跟顶部根节点做融合(形成3节点或4节点),以保持绝对平衡。
*
* 红黑树与2-3树的等价性:
* 1、红黑树就是只有一个元素节点的2-3树。
* 2、红黑的连接线表示相连节点原先是同在一个3节点。
* 此时红黑的节点与它相连的黑色父节点一起表示之前的一个3节点。
* 所以所有红黑的节点一定都是向左倾斜的。
* 即3节点的左侧的节点在红黑树中是一个红色的节点。
* 3、2节点的根是黑色的,3节点的右侧节点是红色的,左侧是黑色的。
*
* 红黑树:
* 1、初始化的根节点为红色。
* 2、红黑树是保持"黑平衡"的二叉树,它的本质就是在于2-3树是一个保持绝对平衡的二叉树。
* 由于是"黑平衡",所以严格意义上,不是平衡二叉树。
* 3、最大高度 2logn:即每一个节点都是一个3节点,3节点对应一个黑色与红色连接的树模板。
* 但它的时间复杂度依然是 O(logn)的,虽然比 AVL 树(偏查询)总体性能要慢,但它的重要性在于其添加
* 元素与删除元素相比于 AVL 树来说要快速一些。
*
* 理解了红黑树与2-3树的等价性,我们就可以很容易理解《算法导论》中对于红黑树的5点定义:
* 1、每一个节点可能是红色或黑色。
* 2、根节点是黑色的。
* 3、每一个叶子节点(最后的空节点)一定是黑色的。
* 4、如果一个节点是红色的,那么他的孩子节点一定都是黑色。
* 5、从任意一个节点到叶子节点,经过的黑色节点一定是一样多的。
*
* 它们可以简化为:
* 1、所有节点非红即黑。
* 2、根节点为黑色。
* 3、最后的 NULL 节点为黑。
* 4、红节点的孩子一定为黑。(红色性质)
* 5、黑平衡。(黑色性质)
*
* 对于红黑树,任何不平衡都会在三次旋转内解决。红黑树不仅能和2-3树等价,
* 还和2-4树等价,但是4-node只能以RBR的形状表示。
* 用2-4树去理解《算法导论》中红黑树的实现。
*
* (特殊的红黑树:左倾红黑树)手写红黑树添加节点的逻辑,只要在二分搜索树实现的基础上对添加逻辑进行修改即可:
* 1、永远添加红色节点:Node 构造器中初始化 color 为 RED。
* 2、保持根节点为黑色节点。
* 3、如果红色节点在右侧,需要进行左旋转到左侧。
* (注意:左旋转这个子过程产生的树结构并不一定满足红黑树的性质)
* 4、在2-3树中的2节点添加一个新节点后会进行颜色翻转(flipColors),即根黑子红变为根红子黑。
* 5、如果红色节点在左侧,需要进行右旋转到右侧。
* 6、当前节点表示跟父节点融合在一起时需要设置为红色。
* 7、添加时的最复杂的情况:在2-3树的3节点中添加一个中间值节点,此时需要
* 维护红黑树的逻辑链条——左旋转、右旋转、颜色翻转。而且它的组成过程正符合其它的添加情况,
* 在实现时可以直接复用。red_black_add.png
* 8、红黑树性质的维护时机:和 AVL 树一样,添加节点后回溯向上维护。
* 红黑树的性能总结:
* 1、对于完全随机的数据,普通的二分搜索树即可。
* 但它的缺点在于极端情况下会退化成链表或者是高度不平衡。
* 2、对于查询较多的情况,AVL 树更好。
* 3、而红黑树综合统计性能(综合增删改查所有操作)更优,
* 尤其是添加、删除操作,但是红黑树牺牲了平衡性(2logn 的高度)。
* 4、手写红黑树删除节点的逻辑需要考虑的请求比添加逻辑更复杂,更琐碎,仅适合装逼。
* 右倾红黑树实现?
* 另一种统计性能优秀的树结构:Splay Tree(伸展树),
* 利用了局部性原理——刚被访问的内容下次高概率被再次访问。
*
* 基于红黑树的 Map 和 Set:java.util 中的 TreeMap 和 TreeSet 就是基于红黑树实现的。
* 红黑树的其它实现:查阅算法导论中的红黑树的实现(添加与删除)。
* @param <K>
* @param <V>
*/
public class RBTree<K extends Comparable<K>, V> {
public static final boolean RED = true;
public static final boolean BLACK = false;
private class Node{
public K key;
public V value;
public Node left, right;
public boolean color;
public Node(K key, V value){
this.key = key;
this.value = value;
left = null;
right = null;
color = RED;
}
}
private Node root;
private int size;
public RBTree(){
root = null;
size = 0;
}
/**
* 判断当前节点是否是红色
*
* @param node Node
* @return 当前节点是否是红色
*/
public boolean isRed(Node node) {
if (node == null) {
return BLACK;
}
return node.color;
}
public int getSize(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
/**
* 颜色翻转:在2-3树中的2节点添加一个新节点后会进行颜色翻转(flipColors),即根黑子红变为根红子黑。
*
* @param node 当前子树的根节点
*/
private void flipColors(Node node) {
node.color = RED;
node.left.color = BLACK;
node.right.color = BLACK;
}
/**
* node x
* / \ 右旋转 / \
* x T2 -------> y node
* / \ / \
* y T1 T1 T2
*
* @param node 需要右旋转的节点
* @return 右旋转后的根节点
*/
private Node rightRotate(Node node) {
Node x = node.left;
node.left = x.right;
x.right = node;
x.color = node.color;
// 表示需要融合的元素设置为红色
node.color = RED;
return x;
}
/**
* node x
* / \ 左旋转 / \
* T1 x ---------> node T3
* / \ / \
* T2 T3 T1 T2
*
* @param node 需要左旋转的节点
* @return 左旋转后的新的根节点 x
*/
private Node leftRotate(Node node) {
Node x = node.right;
node.right = x.left;
x.left = node;
// x 节点的颜色需要和原来根节点的颜色保持一致
x.color = node.color;
// 2-3树3节点左侧的节点设置为红色,表示需要融合的元素设置为红色
node.color = RED;
return x;
}
// 向二分搜索树中添加新的元素(key, value)
public void add(K key, V value){
root = add(root, key, value);
// 最终根节点为黑色节点
root.color = BLACK;
}
// 向以node为根的二分搜索树中插入元素(key, value),递归算法
// 返回插入新节点后二分搜索树的根
private Node add(Node node, K key, V value){
if(node == null){
size ++;
// 默认插入红色节点
return new Node(key, value);
}
if(key.compareTo(node.key) < 0)
node.left = add(node.left, key, value);
else if(key.compareTo(node.key) > 0)
node.right = add(node.right, key, value);
else // key.compareTo(node.key) == 0
node.value = value;
// 维护红黑树性质的逻辑链条三步骤
// 1、左旋转情况
if (isRed(node.right) && !isRed(node.left)) {
node = leftRotate(node);
}
// 2、右旋转情况
if (isRed(node.left) && isRed(node.left.left)) {
node = rightRotate(node);
}
// 3、右旋转情况
if (isRed(node.left) && isRed(node.right)) {
flipColors(node);
}
return node;
}
// 返回以node为根节点的二分搜索树中,key所在的节点
private Node getNode(Node node, K key){
if(node == null)
return null;
if(key.equals(node.key))
return node;
else if(key.compareTo(node.key) < 0)
return getNode(node.left, key);
else // if(key.compareTo(node.key) > 0)
return getNode(node.right, key);
}
public boolean contains(K key){
return getNode(root, key) != null;
}
public V get(K key){
Node node = getNode(root, key);
return node == null ? null : node.value;
}
public void set(K key, V newValue){
Node node = getNode(root, key);
if(node == null)
throw new IllegalArgumentException(key + " doesn't exist!");
node.value = newValue;
}
// 返回以node为根的二分搜索树的最小值所在的节点
private Node minimum(Node node){
if(node.left == null)
return node;
return minimum(node.left);
}
// 删除掉以node为根的二分搜索树中的最小节点
// 返回删除节点后新的二分搜索树的根
private Node removeMin(Node node){
if(node.left == null){
Node rightNode = node.right;
node.right = null;
size --;
return rightNode;
}
node.left = removeMin(node.left);
return node;
}
// 从二分搜索树中删除键为key的节点
public V remove(K key){
Node node = getNode(root, key);
if(node != null){
root = remove(root, key);
return node.value;
}
return null;
}
private Node remove(Node node, K key){
if( node == null )
return null;
if( key.compareTo(node.key) < 0 ){
node.left = remove(node.left , key);
return node;
}
else if(key.compareTo(node.key) > 0 ){
node.right = remove(node.right, key);
return node;
}
else{ // key.compareTo(node.key) == 0
// 待删除节点左子树为空的情况
if(node.left == null){
Node rightNode = node.right;
node.right = null;
size --;
return rightNode;
}
// 待删除节点右子树为空的情况
if(node.right == null){
Node leftNode = node.left;
node.left = null;
size --;
return leftNode;
}
// 待删除节点左右子树均不为空的情况
// 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
Node successor = minimum(node.right);
successor.right = removeMin(node.right);
successor.left = node.left;
node.left = node.right = null;
return successor;
}
}
public static void main(String[] args){
System.out.println("Pride and Prejudice");
ArrayList<String> words = new ArrayList<>();
if(FileOperation.readFile("pride-and-prejudice.txt", words)) {
System.out.println("Total words: " + words.size());
RBTree<String, Integer> map = new RBTree<>();
for (String word : words) {
if (map.contains(word))
map.set(word, map.get(word) + 1);
else
map.add(word, 1);
}
System.out.println("Total different words: " + map.getSize());
System.out.println("Frequency of PRIDE: " + map.get("pride"));
System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
}
System.out.println();
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/red_black_tree/Main2.java | data_struct_study/src/red_black_tree/Main2.java | package red_black_tree;
import avl.AVLTree;
import avl.BST;
import java.util.ArrayList;
import java.util.Random;
public class Main2 {
public static void main(String[] args) {
// int n = 20000000;
int n = 20000000;
Random random = new Random(n);
ArrayList<Integer> testData = new ArrayList<>(n);
for(int i = 0 ; i < n ; i ++)
testData.add(random.nextInt(Integer.MAX_VALUE));
// Test BST
long startTime = System.nanoTime();
BST<Integer, Integer> bst = new BST<>();
for (Integer x: testData)
bst.add(x, null);
long endTime = System.nanoTime();
double time = (endTime - startTime) / 1000000000.0;
System.out.println("BST: " + time + " s");
// Test AVL
startTime = System.nanoTime();
AVLTree<Integer, Integer> avl = new AVLTree<>();
for (Integer x: testData)
avl.add(x, null);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("AVL: " + time + " s");
// Test RBTree
startTime = System.nanoTime();
RBTree<Integer, Integer> rbt = new RBTree<>();
for (Integer x: testData)
rbt.add(x, null);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("RBTree: " + time + " s");
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/red_black_tree/Main.java | data_struct_study/src/red_black_tree/Main.java | package red_black_tree;
import avl.AVLTree;
import avl.BST;
import avl.FileOperation;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
System.out.println("Pride and Prejudice");
ArrayList<String> words = new ArrayList<>();
if(FileOperation.readFile("pride-and-prejudice.txt", words)) {
System.out.println("Total words: " + words.size());
// Collections.sort(words);
// Test BST
long startTime = System.nanoTime();
BST<String, Integer> bst = new BST<>();
for (String word : words) {
if (bst.contains(word))
bst.set(word, bst.get(word) + 1);
else
bst.add(word, 1);
}
for(String word: words)
bst.contains(word);
long endTime = System.nanoTime();
double time = (endTime - startTime) / 1000000000.0;
System.out.println("BST: " + time + " s");
// Test AVL
startTime = System.nanoTime();
AVLTree<String, Integer> avl = new AVLTree<>();
for (String word : words) {
if (avl.contains(word))
avl.set(word, avl.get(word) + 1);
else
avl.add(word, 1);
}
for(String word: words)
avl.contains(word);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("AVL: " + time + " s");
// Test RBTree
startTime = System.nanoTime();
RBTree<String, Integer> rbt = new RBTree<>();
for (String word : words) {
if (rbt.contains(word))
rbt.set(word, rbt.get(word) + 1);
else
rbt.add(word, 1);
}
for(String word: words)
rbt.contains(word);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("RBTree: " + time + " s");
}
System.out.println();
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/red_black_tree/Main3.java | data_struct_study/src/red_black_tree/Main3.java | package red_black_tree;
import avl.AVLTree;
import java.util.ArrayList;
import java.util.Random;
public class Main3 {
public static void main(String[] args) {
int n = 20000000;
ArrayList<Integer> testData = new ArrayList<>(n);
for(int i = 0 ; i < n ; i ++)
testData.add(i);
// Test AVL
long startTime = System.nanoTime();
AVLTree<Integer, Integer> avl = new AVLTree<>();
for (Integer x: testData)
avl.add(x, null);
long endTime = System.nanoTime();
double time = (endTime - startTime) / 1000000000.0;
System.out.println("AVL: " + time + " s");
// Test RBTree
startTime = System.nanoTime();
RBTree<Integer, Integer> rbt = new RBTree<>();
for (Integer x: testData)
rbt.add(x, null);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("RBTree: " + time + " s");
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/binary_search_tree/BST.java | data_struct_study/src/binary_search_tree/BST.java | package binary_search_tree;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/**
* 树结构本身是一种天然的的组织结构,用树存储数据能更加高效地搜索。
*
* 二叉树:和链表一样,动态数据结构。
* 1)、对于每一个节点,最多能分成2个节点,即左孩子和右孩子。
* 2)、没有孩子的节点称为叶子节点。
* 3)、每一个孩子节点最多只能有一个父亲节点。
* 4)、二叉树具有天然的递归结构,即每个节点的左右子树都是二叉树。
*
* 注意:一个节点也是二叉树、空也是二叉树。
*
* 二叉树的分类:
* 1)、满二叉树:除了叶子节点外,每个节点都有两个子节点。
*
*
* 二分搜索树:
* 1)、二分搜索树是一个二叉树,且其每一颗子树也是二分搜索树。
* 2)、二分搜索树的每个节点的值大于其左子树的所有节点的值,小于其右子树的所有节点的值。
* 3)、存储的元素必须有可比较性。
* 4)、通常来说,二分搜索树不包含重复元素。如果想包含重复元素的话,只需定义:
* 左子树小于等于节点;或者右子树大于等于节点。注意:数组和链表可以有重复元素。
*
* 什么是遍历操作?
* 1)、遍历就是把所有的节点都访问一遍。
* 2)、访问的原因和业务相关。
* 3)、在线性结构下,遍历是极其容易的,但是在树结构中,遍历会稍微有点难度。
*
* 如何对二叉树进行遍历?
* 对于遍历操作,两颗子树都要顾及。
*
* 前序遍历:最自然和常用的遍历方式。规律:根左右
* 中序遍历:规律:左根右
* 后序遍历:中序遍历的结果就是我们在二叉搜索树中所有数据排序后的结果。规律:左右根。应用:为二分搜索树释放内存。
*
* 心算出二叉搜索树的前中后序遍历:每一个二叉树都会被访问三次,从根节点出发,
* 前序遍历:当一个节点被访问第一次就记录它。
* 中序遍历:当一个节点被访问第二次的时候记录它。
* 后序遍历:当一个节点被访问第三次的时候才记录它。
*
* 前序遍历的非递归实现(深度优先遍历):需要使用栈记录下一步被访问的元素。
* 对于二叉搜索树的非递归实现一般有两种写法:
* 1)、经典教科书写法。
* 2)、完全模拟系统调用栈的写法。
*
* 层序遍历(广度优先遍历):需要使用队列记录当前出队元素的左右子节点。
* 广度优先遍历的意义:
* 1)、在于快速地查询要搜索的元素。
* 2)、更快地找到问题的解。
* 3)、常用于算法设计中——无权图最短路径。
* 4)、联想对比图的深度优先遍历与广度优先遍历。
*
* 从二分搜索树中删除最小值与最大值:
* 往左走的最后一个节点即是存有最小值的节点,往右走的最后一个节点即是存有最大值的节点。
*
* 删除二分搜索树种的任意元素:
* 1)、删除只有左孩子的节点。
* 2)、删除只有右孩子的节点。
* 3)、删除具有左右孩子的节点:
* 1、找到 s = min(d->right)
* s 是 d 的后继(successor)节点,也即 d 的右子树中的最小节点。
* s->right = delMin(d->right)
* s->left = d->left
* 删除 d,s 是新的子树的根。
* 2、找到 p = max(d->left)
* p 是 d 的前驱(predecessor)节点。
*
* 如何高效实现 rank(E 是排名第几的元素)?
* 如何高效实现 select(查找排名第10的元素)?
* 最好的方式是实现一个维护 size 的二分搜索树:
* 给 Node 节点添加新的成员变量 size。
* 维护 depth 的二分搜索树。
* 维护 count 支持重复元素的二分搜索树。
*/
public class BST<E extends Comparable<E>> {
private class Node {
private E e;
private Node left, right;
public Node(E e) {
this.e = e;
this.left = null;
this.right = null;
}
}
private Node root;
private int size;
public BST() {
this.root = null;
this.size = 0;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
/**
* 添加元素
*
* @param e E
*/
public void add(E e) {
root = add(root, e);
}
/**
* 将元素 e 插入到以根节点 root 的二叉树中
*
* @param root Node
* @param e E
* @return 插入元素 e 后的二叉搜索树的根节点
*/
private Node add(Node root, E e) {
if (root == null) {
size++;
return new Node(e);
}
if (root.e.compareTo(e) < 0) {
root.right = add(root.right, e);
} else if (root.e.compareTo(e) > 0) {
root.left = add(root.left, e);
}
return root;
}
/**
* 判断是否包含元素 e
*
* @param e E
* @return 是否包含元素 e
*/
public boolean contains(E e) {
return contains(root, e);
}
/**
* 判断以 root 为根节点的二叉搜索树种是否有元素 e
*
* @param root Node
* @param e E
* @return 以 root 为根节点的二叉搜索树种是否有元素 e
*/
private boolean contains(Node root, E e) {
if (root == null) {
return false;
}
if (e.compareTo(root.e) < 0) {
return contains(root.left, e);
} else if (e.compareTo(root.e) > 0) {
return contains(root.right, e);
} else {
return true;
}
}
/**
* 前序遍历
*/
public void preOrder() {
preOrder(root);
}
/**
* 以根节点 root 的前序遍历
*
* @param root Node
*/
private void preOrder(Node root) {
if (root == null) {
return;
}
System.out.println(root.e);
preOrder(root.left);
preOrder(root.right);
}
/**
* 前序遍历非递归实现,需要借助栈存储下一步要访问的元素
*/
public void preOrderNR() {
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node cur = stack.pop();
System.out.println(cur.e);
if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left != null) {
stack.push(cur.left);
}
}
}
/**
* 中序遍历
*/
public void inOrder() {
inOrder(root);
}
/**
* 以根节点 root 的中序遍历
*
* @param root Node
*/
private void inOrder(Node root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.println(root.e);
inOrder(root.right);
}
/**
* 后序遍历
*/
public void postOrder() {
postOrder(root);
}
/**
* 后序遍历
*
* @param root Node
*/
private void postOrder(Node root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.println(root.e);
}
/**
* 层序遍历
*/
public void levelOrder() {
if (root == null) {
return;
}
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
Node cur = q.remove();
System.out.println(cur.e);
if (cur.left != null) {
q.add(cur.left);
}
if (cur.right != null) {
q.add(cur.right);
}
}
}
/**
* 获取最小值
*
* @return 最小值
*/
public E minValue() {
if (size == 0) {
throw new IllegalArgumentException("BST is empty!");
}
Node ret = minValue(root);
return ret.e;
}
/**
* 递归获取最小值
*
* @param cur 当前的根节点
* @return Node
*/
private Node minValue(Node cur) {
if (cur.left == null) {
return cur;
}
return minValue(cur.left);
}
/**
* 获取最大值
*
* @return 最大值
*/
public E maxValue() {
if (size == 0) {
throw new IllegalArgumentException("BST is empty!");
}
Node ret = maxValue(root);
return ret.e;
}
/**
* 递归获取最大值
*
* @param cur 当前的根节点
* @return Node
*/
private Node maxValue(Node cur) {
if (cur.right == null) {
return cur;
}
return maxValue(cur.right);
}
/**
* 删除最小节点
*
* @return 被删除的最小值
*/
public E removeMinValue() {
E minNode = minValue();
root = removeMinValue(root);
return minNode;
}
/**
* 删除以 cur 为根节点的二叉搜索树中的最小节点
*
* @param cur 当前的根节点
* @return 被删除最小节点后的新的根节点
*/
private Node removeMinValue(Node cur) {
if (cur.left == null) {
Node rightNode = cur.right;
cur.right = null;
size--;
return rightNode;
}
cur.left = removeMinValue(cur.left);
return cur;
}
/**
* 删除最大节点
*
* @return 最大节点
*/
public E removeMaxValue() {
E maxValue = maxValue();
root = removeMaxValue(root);
return maxValue;
}
/**
* 删除以 cur 为根节点的二叉搜索树的最大节点
*
* @param cur 当前的根节点
* @return 删除最大节点后的新的根节点
*/
private Node removeMaxValue(Node cur) {
if (cur.right == null) {
Node leftNode = cur.left;
cur.left = null;
size--;
return leftNode;
}
cur.right = removeMaxValue(cur.right);
return cur;
}
/**
* 删除指定的节点
*
* @param e E
*/
public void remove(E e) {
root = remove(root, e);
}
/**
* 删除以 cur 为根节点中的指定节点
*
* @param cur Node
* @param e E
* @return 删除指定节点后的新的节点
*/
private Node remove(Node cur, E e) {
// 1、处理没有找到要删除的节点时的情况
if (cur == null) {
return null;
}
// 2、处理待删除的节点比当前的根节点 cur 小的情况
if (e.compareTo(cur.e) < 0) {
cur.left = remove(cur.left, e);
return cur;
} else if (e.compareTo(cur.e) > 0) {
// 3、处理待删除的节点比当前的根节点 cur 大的情况
cur.right = remove(cur.right, e);
return cur;
} else { // 4、处理待删除节点为根节点 cur 的情况
// 1)、处理待删除节点左子树为空的情况
if (cur.left == null) {
Node rightNode = cur.right;
cur.right = null;
size--;
return rightNode;
}
// 2)、处理待删除节点右子树为空的情况
if (cur.right == null) {
Node leftNode = cur.left;
cur.left = null;
size--;
return leftNode;
}
// 3)、处理待删除节点左右子树都为空的情况
// 找出待删除节点右子树的最小值
Node processor = minValue(cur.right);
// 将删除了待删除节点右子树的最小值后的新的根节点挂接到 processor 的右子树上
processor.right = removeMinValue(cur.right);
// 将待删除节点的左子树挂接到 processor 的左子树上
processor.left = cur.left;
// 释放游离的对象
cur.left = cur.right = null;
return processor;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
generateBSTString(root, 0, sb);
return sb.toString();
}
/**
* 生成以 root 为根节点的 BST 字符串
*
* @param root Node
* @param deep Deep
* @param sb StringBuilder
*/
private void generateBSTString(Node root, int deep, StringBuilder sb) {
if (root == null) {
sb.append(generateString(deep)).append("null\n");
return;
}
sb.append(generateString(deep)).append(root.e).append("\n");
generateBSTString(root.left, deep + 1, sb);
generateBSTString(root.right, deep + 1, sb);
}
/**
* 生成二叉树深度描述字符串
* -- 表示深度为1
* ---- 表示深度为 2
* 依次类推
*
* @param deep Deep
* @return 二叉树深度描述字符串
*/
private String generateString(int deep) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < deep; i++) {
sb.append("--");
}
return sb.toString();
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/binary_search_tree/Main.java | data_struct_study/src/binary_search_tree/Main.java | package binary_search_tree;
import java.util.ArrayList;
import java.util.Random;
public class Main {
public static void main(String[] args) {
// int[] arr = {5, 3, 8, 2, 9, 7};
// BST<Integer> bst = new BST<>();
// for (int value : arr) {
// bst.add(value);
// }
//
// bst.levelOrder();
// bst.preOrder();
//
// System.out.println();
//
// bst.preOrderNR();
// bst.inOrder();
//
// System.out.println();
//
// bst.postOrder();
// System.out.println();
// System.out.println(bst);
BST<Integer> bst = new BST<>();
Random random = new Random();
int n = 1000;
// test removeMin
for(int i = 0 ; i < n ; i ++)
bst.add(random.nextInt(10000));
ArrayList<Integer> nums = new ArrayList<>();
while(!bst.isEmpty())
nums.add(bst.removeMinValue());
System.out.println(nums);
for(int i = 1 ; i < nums.size() ; i ++)
if(nums.get(i - 1) > nums.get(i))
throw new IllegalArgumentException("Error!");
System.out.println("removeMin test completed.");
// test removeMax
for(int i = 0 ; i < n ; i ++)
bst.add(random.nextInt(10000));
nums = new ArrayList<>();
while(!bst.isEmpty())
nums.add(bst.removeMaxValue());
System.out.println(nums);
for(int i = 1 ; i < nums.size() ; i ++)
if(nums.get(i - 1) < nums.get(i))
throw new IllegalArgumentException("Error!");
System.out.println("removeMax test completed.");
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/heap_and_priority_queue/PriorityQueue.java | data_struct_study/src/heap_and_priority_queue/PriorityQueue.java | package heap_and_priority_queue;
import queue.Queue;
/**
* 用最大堆实现的优先队列
*
* 在 100 万个元素中选取前 100 个元素?
*
* 使用优先队列,维护当前看到的前 100 个元素,需要使用最小堆,也可以使用最大堆(将常规的优先级定义取反即可)
*
* 使用 TreeMap 求频次
*
* @param <E>
*/
public class PriorityQueue<E extends Comparable<E>> implements Queue<E> {
private MaxHeap<E> maxHeap;
public PriorityQueue() {
maxHeap = new MaxHeap<>();
}
@Override
public void enqueue(E e) {
maxHeap.add(e);
}
@Override
public E dequeue() {
return maxHeap.extractMax();
}
@Override
public boolean isEmpty() {
return maxHeap.isEmpty();
}
@Override
public int getSize() {
return maxHeap.getSize();
}
@Override
public E getFront() {
return maxHeap.findMax();
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/heap_and_priority_queue/Solution2.java | data_struct_study/src/heap_and_priority_queue/Solution2.java | package heap_and_priority_queue;
import java.util.PriorityQueue;
import java.util.TreeMap;
/**
* 1、最简单的思路:扫描一遍统计概率,排序找到前k个出现频率最高的元素。时间复杂度:O(nlogn)
* 2、使用优先队列不停地维护我们能找到的前k个出现频率最高的元素。时间复杂度:O(nlogk)
*
* Java 的 PriorityQueue 内部是最小堆
* d 叉堆:d-ary heap
* 常规堆的缺陷:只能看到堆首的元素。
* 索引堆:保存元素与之对应的索引。
* 二项堆
* 斐波那契堆
* 普通队列、优先队列、广义队列
* 栈,也可以理解成是一个队列。
*/
public class Solution2 {
// 时间复杂度:O(nlogk), 空间复杂度:O(n)
public int[] topKFrequent(int[] nums, int k) {
// 1、将所有 元素:出现频次 添加到 TreeMap 中
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int num:nums) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
// 2、使用优先队列维护前 Top k 个元素
PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2) -> map.get(o1) - map.get(o2));
for (int key:map.keySet()) {
if (pq.size() < k) {
pq.add(key);
} else if (map.get(key) > map.get(pq.peek())) {
pq.remove();
pq.add(key);
}
}
// 3、返回保存 Top k 个元素的数组
int[] values = new int[k];
for (int i = values.length - 1; i >= 0; i--) {
values[i] = pq.remove();
}
return values;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/heap_and_priority_queue/MaxHeap.java | data_struct_study/src/heap_and_priority_queue/MaxHeap.java | package heap_and_priority_queue;
import array.Array;
/**
* 向堆中添加元素(上浮,Sift Up) O(logn)
* 从堆中取出最大元素(下沉,Sift Down) O(logn)
*
* replace:取出最大元素后,放入一个新元素。
* 实现1:可以先 extractMax,再 add,两次 O(logn)操作。
* 实现2:可以直接将堆顶元素替换以后 Sift Down,一次 O(logn)操作。
*
* 将 n 个元素插入一个空堆中,算法复杂度为 O(nlogn)。
* heapify(堆化):算法复杂度为 O(n),只需要对所有非叶子节点进行 Sift Down 的操作。
*
* @param <E>
*/
public class MaxHeap<E extends Comparable<E>> {
private final Array<E> array;
public MaxHeap() {
array = new Array<>();
}
public MaxHeap(int capacity) {
array = new Array<>(capacity);
}
/**
* heapify(堆化)
*
* @param arr 静态数组
*/
public MaxHeap(E[] arr) {
array = new Array<>(arr);
if (arr.length != 1) {
for (int i = parent(arr.length - 1); i >= 0; i--) {
siftDown(i);
}
}
}
/**
* 获取堆的大小
*
* @return 堆的大小
*/
public int getSize() {
return array.getSize();
}
/**
* 判断堆是否为空
*
* @return 堆是否为空
*/
public boolean isEmpty() {
return array.isEmpty();
}
/**
* 返回完全二叉树的数组表示中,一个节点的索引它所对应的父亲节点的索引
*
* @param index 某一个节点的索引
* @return 一个节点的索引它所对应的父亲节点的索引
*/
public int parent(int index) {
return (index - 1) / 2;
}
/**
* 返回完全二叉树的数组表示中,一个节点的索引它所对应的左孩子节点的索引
*
* @param index 某一个节点的索引
* @return 一个节点的索引它所对应的左孩子节点的索引
*/
public int leftNode(int index) {
return 2 * index + 1;
}
/**
* 返回完全二叉树的数组表示中,一个节点的索引它所对应的右孩子节点的索引
*
* @param index 某一个节点的索引
* @return 一个节点的索引它所对应的右孩子节点的索引
*/
public int rightNode(int index) {
return 2 * index + 2;
}
/**
* 向堆中添加元素
*
* @param e E
*/
public void add(E e) {
array.addLast(e);
siftUp(array.getSize() - 1);
}
/**
* 堆中元素的上浮
*
* @param k 要上浮元素的 index 下标
*/
private void siftUp(int k) {
while (k > 0 && array.query(parent(k)).compareTo(array.query(k)) < 0) {
array.swap(k, parent(k));
// 重置交换元素后 k 的新 index
k = parent(k);
}
}
/**
* 看堆中的最大元素
*
* @return 堆中的最大元素
*/
public E findMax() {
if (array.getSize() == 0) {
throw new IllegalArgumentException("heap size is 0~");
}
return array.query(0);
}
/**
* 获取堆中最大元素
*
* @return 堆中最大元素
*/
public E extractMax() {
E ret = findMax();
// 1、交换堆顶最大元素与最后一个元素的位置
array.swap(0, array.getSize() - 1);
// 2、删除最后一个元素:堆中最大元素
array.deleteLast();
// 3、下沉
siftDown(0);
return ret;
}
/**
* 堆中元素的下沉
*
* @param k 要下沉的元素 index 下标
*/
private void siftDown(int k) {
// 1)、循环终止条件:当前下沉元素左节点的下标 < 数组的大小
while (leftNode(k) < array.getSize()) {
int j = leftNode(k);
// 2)、如果有右节点,且右节点比左节点大,则 j 更新为右节点的下标
if (j + 1 < array.getSize()
&& array.query(j).compareTo(array.query(j + 1)) < 0) {
j = rightNode(k);
}
// 3)、如果最大孩子节点的值 > 当前节点的值,
// 则交换两者的值并更新下一轮要下沉的元素下标 k
if (array.query(j).compareTo(array.query(k)) <= 0) {
break;
}
array.swap(j, k);
k = j;
}
}
/**
* 替换堆中最大的元素
*
* @param e e
* @return 堆中最大的元素
*/
public E replace(E e) {
E ret = findMax();
array.set(0, e);
siftDown(0);
return ret;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/heap_and_priority_queue/Solution.java | data_struct_study/src/heap_and_priority_queue/Solution.java | package heap_and_priority_queue;
/// 347. Top K Frequent Elements
/// https://leetcode.com/problems/top-k-frequent-elements/description/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;
public class Solution {
private class Array<E> {
private E[] data;
private int size;
// 构造函数,传入数组的容量capacity构造Array
public Array(int capacity){
data = (E[])new Object[capacity];
size = 0;
}
// 无参数的构造函数,默认数组的容量capacity=10
public Array(){
this(10);
}
public Array(E[] arr){
data = (E[])new Object[arr.length];
for(int i = 0 ; i < arr.length ; i ++)
data[i] = arr[i];
size = arr.length;
}
// 获取数组的容量
public int getCapacity(){
return data.length;
}
// 获取数组中的元素个数
public int getSize(){
return size;
}
// 返回数组是否为空
public boolean isEmpty(){
return size == 0;
}
// 在index索引的位置插入一个新元素e
public void add(int index, E e){
if(index < 0 || index > size)
throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size.");
if(size == data.length)
resize(2 * data.length);
for(int i = size - 1; i >= index ; i --)
data[i + 1] = data[i];
data[index] = e;
size ++;
}
// 向所有元素后添加一个新元素
public void addLast(E e){
add(size, e);
}
// 在所有元素前添加一个新元素
public void addFirst(E e){
add(0, e);
}
// 获取index索引位置的元素
public E get(int index){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Get failed. Index is illegal.");
return data[index];
}
// 修改index索引位置的元素为e
public void set(int index, E e){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Set failed. Index is illegal.");
data[index] = e;
}
// 查找数组中是否有元素e
public boolean contains(E e){
for(int i = 0 ; i < size ; i ++){
if(data[i].equals(e))
return true;
}
return false;
}
// 查找数组中元素e所在的索引,如果不存在元素e,则返回-1
public int find(E e){
for(int i = 0 ; i < size ; i ++){
if(data[i].equals(e))
return i;
}
return -1;
}
// 从数组中删除index位置的元素, 返回删除的元素
public E remove(int index){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Remove failed. Index is illegal.");
E ret = data[index];
for(int i = index + 1 ; i < size ; i ++)
data[i - 1] = data[i];
size --;
data[size] = null; // loitering objects != memory leak
if(size == data.length / 4 && data.length / 2 != 0)
resize(data.length / 2);
return ret;
}
// 从数组中删除第一个元素, 返回删除的元素
public E removeFirst(){
return remove(0);
}
// 从数组中删除最后一个元素, 返回删除的元素
public E removeLast(){
return remove(size - 1);
}
// 从数组中删除元素e
public void removeElement(E e){
int index = find(e);
if(index != -1)
remove(index);
}
public void swap(int i, int j){
if(i < 0 || i >= size || j < 0 || j >= size)
throw new IllegalArgumentException("Index is illegal.");
E t = data[i];
data[i] = data[j];
data[j] = t;
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
res.append('[');
for(int i = 0 ; i < size ; i ++){
res.append(data[i]);
if(i != size - 1)
res.append(", ");
}
res.append(']');
return res.toString();
}
// 将数组空间的容量变成newCapacity大小
private void resize(int newCapacity){
E[] newData = (E[])new Object[newCapacity];
for(int i = 0 ; i < size ; i ++)
newData[i] = data[i];
data = newData;
}
}
private class MaxHeap<E extends Comparable<E>> {
private Array<E> data;
public MaxHeap(int capacity){
data = new Array<>(capacity);
}
public MaxHeap(){
data = new Array<>();
}
public MaxHeap(E[] arr){
data = new Array<>(arr);
for(int i = parent(arr.length - 1) ; i >= 0 ; i --)
siftDown(i);
}
// 返回堆中的元素个数
public int size(){
return data.getSize();
}
// 返回一个布尔值, 表示堆中是否为空
public boolean isEmpty(){
return data.isEmpty();
}
// 返回完全二叉树的数组表示中,一个索引所表示的元素的父亲节点的索引
private int parent(int index){
if(index == 0)
throw new IllegalArgumentException("index-0 doesn't have parent.");
return (index - 1) / 2;
}
// 返回完全二叉树的数组表示中,一个索引所表示的元素的左孩子节点的索引
private int leftChild(int index){
return index * 2 + 1;
}
// 返回完全二叉树的数组表示中,一个索引所表示的元素的右孩子节点的索引
private int rightChild(int index){
return index * 2 + 2;
}
// 向堆中添加元素
public void add(E e){
data.addLast(e);
siftUp(data.getSize() - 1);
}
private void siftUp(int k){
while(k > 0 && data.get(parent(k)).compareTo(data.get(k)) < 0 ){
data.swap(k, parent(k));
k = parent(k);
}
}
// 看堆中的最大元素
public E findMax(){
if(data.getSize() == 0)
throw new IllegalArgumentException("Can not findMax when heap is empty.");
return data.get(0);
}
// 取出堆中最大元素
public E extractMax(){
E ret = findMax();
data.swap(0, data.getSize() - 1);
data.removeLast();
siftDown(0);
return ret;
}
private void siftDown(int k){
while(leftChild(k) < data.getSize()){
int j = leftChild(k); // 在此轮循环中,data[k]和data[j]交换位置
if( j + 1 < data.getSize() &&
data.get(j + 1).compareTo(data.get(j)) > 0 )
j ++;
// data[j] 是 leftChild 和 rightChild 中的最大值
if(data.get(k).compareTo(data.get(j)) >= 0 )
break;
data.swap(k, j);
k = j;
}
}
// 取出堆中的最大元素,并且替换成元素e
public E replace(E e){
E ret = findMax();
data.set(0, e);
siftDown(0);
return ret;
}
}
private interface Queue<E> {
int getSize();
boolean isEmpty();
void enqueue(E e);
E dequeue();
E getFront();
}
private class PriorityQueue<E extends Comparable<E>> implements Queue<E> {
private MaxHeap<E> maxHeap;
public PriorityQueue(){
maxHeap = new MaxHeap<>();
}
@Override
public int getSize(){
return maxHeap.size();
}
@Override
public boolean isEmpty(){
return maxHeap.isEmpty();
}
@Override
public E getFront(){
return maxHeap.findMax();
}
@Override
public void enqueue(E e){
maxHeap.add(e);
}
@Override
public E dequeue(){
return maxHeap.extractMax();
}
}
private class Freq implements Comparable<Freq> {
int e, freq;
public Freq(int e, int freq) {
this.e = e;
this.freq = freq;
}
@Override
public int compareTo(Freq anOther) {
if (freq < anOther.freq) {
return 1;
} else if (freq > anOther.freq) {
return -1;
} else {
return 0;
}
}
}
public int[] topKFrequent(int[] nums, int k) {
// 1、求出 nums 数组中各个元素出现的频次
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int num:nums) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
// 2、使用优先队列维护 topK 个元素
PriorityQueue<Freq> queue = new PriorityQueue<>();
for (int key:map.keySet()) {
if (queue.getSize() < k) {
queue.enqueue(new Freq(key, map.get(key)));
} else if (map.get(key) > queue.getFront().freq) {// 重点:优先级 debug 理清思路
queue.dequeue();
queue.enqueue(new Freq(key, map.get(key)));
}
}
// 3、使用 ArrayList 添加 topK 个元素
int[] arr = new int[queue.getSize()];
for (int i = 0; i < arr.length; i++) {
arr[arr.length - i - 1] = queue.dequeue().e;
}
return arr;
}
private static void printList(List<Integer> nums){
for(Integer num: nums)
System.out.print(num + " ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 2, 3};
int k = 2;
System.out.println(Arrays.toString((new Solution()).topKFrequent(nums, k)));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/heap_and_priority_queue/Main.java | data_struct_study/src/heap_and_priority_queue/Main.java | package heap_and_priority_queue;
import java.util.Arrays;
import java.util.Random;
/**
* 普通队列:先进先出,后进后出
* 优先队列:出队顺序和入队顺序无关,和优先级相关
*
* 应用场景:操作系统的任务调度,动态 选择优先级最高的任务进行处理。医生和患者之间的关系。
*
* 优先队列底层实现 入队 出队
* 普通线性结构 O(1) O(n)
* 顺序线性结构 O(n) O(n)
* 堆 O(logn) O(logn)
*
* 堆的基本结构
* 二叉堆:满足特殊性质的二叉树。
* 1、二叉堆是一颗完全二叉树,完全二叉树即把元素顺序一层一层地排列成树的形状。
* 2、堆中每一个元素的值都大于等于它的孩子节点。
*
* 用数组存储二叉树:
* parent = (i - 1) / 2
* leftNode = 2 * i + 1
* rightNode = 2 * i + 2
*
*/
public class Main {
public static void main(String[] args) {
// int n = 1000000;
//
// MaxHeap<Integer> maxHeap = new MaxHeap<>();
// Random random = new Random();
// for(int i = 0 ; i < n ; i ++)
// maxHeap.add(random.nextInt(Integer.MAX_VALUE));
//
// int[] arr = new int[n];
// for(int i = 0 ; i < n ; i ++)
// arr[i] = maxHeap.extractMax();
//
// for(int i = 1 ; i < n ; i ++)
// if(arr[i-1] < arr[i])
// throw new IllegalArgumentException("Error");
//
// System.out.println("Test MaxHeap completed.");
// heapify test
int n = 1000000;
Random random = new Random();
Integer[] testData1 = new Integer[n];
for(int i = 0 ; i < n ; i ++)
testData1[i] = random.nextInt(Integer.MAX_VALUE);
Integer[] testData2 = Arrays.copyOf(testData1, n);
double time1 = testHeap(testData1, false);
System.out.println("Without heapify: " + time1 + " s");
double time2 = testHeap(testData2, true);
System.out.println("With heapify: " + time2 + " s");
}
private static double testHeap(Integer[] testData, boolean isHeapify){
long startTime = System.nanoTime();
MaxHeap<Integer> maxHeap;
if(isHeapify)
maxHeap = new MaxHeap<>(testData);
else{
maxHeap = new MaxHeap<>(testData.length);
for(int num: testData)
maxHeap.add(num);
}
int[] arr = new int[testData.length];
for(int i = 0 ; i < testData.length ; i ++)
arr[i] = maxHeap.extractMax();
for(int i = 1 ; i < testData.length ; i ++)
if(arr[i-1] < arr[i])
throw new IllegalArgumentException("Error");
System.out.println("Test MaxHeap completed.");
long endTime = System.nanoTime();
return (endTime - startTime) / 1000000000.0;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/HeapSort.java | data_struct_study/src/sort_problem/HeapSort.java | package sort_problem;
/**
* 大顶堆实现堆排序:
* 1、构建初始堆,将待排序列构成一个大顶堆:序列对应一个完全二叉树;从最后一个分支结点(n/2)开始,
* 到根(1)为止,依次对每个分支结点进行下沉,以便形成以每个分支结点为根的堆,当最后对树根结点进行
* 调整后,整个树就变成了一个堆。
* 2、将堆顶元素与堆尾元素交换,并从待排序列中移除堆尾元素。
* 3、使用下沉操作下沉堆顶元素以重新构建大顶堆。
* 4、重复2~3,直到待排序列中只剩下一个元素(即堆顶元素)。
*
* 下沉操作:
* 1、仅当当前节点有左子节点时进入while循环体。
* 2、设立下沉后的位置为j,默认为左子节点的位置。
* 3、如果当前节点有右子节点且左子节点小于右子节点时,下沉后的位置j取右子节点的位置(j++)。
* 4、如果当前节点的位置k小于下沉后的位置j时,交换k与j的值,完成这一次的下沉操作。
* 5、更新当前节点的位置为j,如果当前节点还有左子节点则又会进入while循环体进行上述的下沉操作。
*
* 把最大元素和当前堆中数组的最后一个元素交换位置,并且不删除它,
* 那么就可以得到一个从尾到头的递减序列,从正向来看就是一个
* 递增序列,这就是堆排序。
*
* 一个堆的高度为 logN,因此在堆中插入元素和删除最大元素的复杂度都为 logN。
* 对于堆排序,由于要对 N 个节点进行下沉操作,因此复杂度为 NlogN。
* 堆排序是一种原地排序,没有利用额外的空间。
* 现代操作系统很少使用堆排序,因为它无法利用局部性原理进行缓存,
* 也就是数组元素很少和相邻的元素进行比较和交换。
*/
public class HeapSort<T extends Comparable<T>> extends Sort<T> {
/**
* 数组第 0 个位置不能有元素
*/
@Override
public void sort(T[] nums) {
int N = nums.length - 1;
// 1、构建初始堆,将待排序列构成一个大顶堆:
// 序列对应一个完全二叉树;从最后一个分支结点(n/2)开始,
// 到根(1)为止,依次对每个分支结点进行调整(下沉),
// 以便形成以每个分支结点为根的堆,当最后对树根结点进行
// 调整后,整个树就变成了一个堆。
for (int k = N / 2; k >= 1; k--) {
sink(nums, k, N);
}
while (N > 1) {
// 2、将堆顶元素与堆尾元素交换,并从待排序列中移除堆尾元素。
swap(nums, 1, N--);
// 3、使用下沉操作下沉堆顶元素以重新构建大顶堆。
sink(nums, 1, N);
}
}
private void sink(T[] nums, int k, int N) {
// 1)、仅当当前节点有左子节点时进入while循环体。
while (2 * k <= N) {
// 2)、设立下沉后的位置为j,默认为左子节点。
int j = 2 * k;
// 3)、如果当前节点有右子节点且左子节点小于右子节点时,下沉后的位置j取右子节点的位置(j++)。
if (j < N && less(nums, j, j + 1)) {
j++;
}
// 4)、如果当前节点的位置k小于下沉后的位置j时,交换k与j的值,完成这一次的下沉操作。
if (!less(nums, k, j)) {
break;
}
swap(nums, k, j);
// 5)、更新当前节点的位置为j,如果当前节点还有左子节点则又会进入while循环体进行上述的下沉操作。
k = j;
}
}
private boolean less(T[] nums, int i, int j) {
return nums[i].compareTo(nums[j]) < 0;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/Bubble.java | data_struct_study/src/sort_problem/Bubble.java | package sort_problem;
/**
* 从左到右不断交换相邻逆序的元素,在一轮循环之后,可以让未排序的最大元素上浮到右侧。
* 优化:在一轮循环中,如果没有发生交换,那么说明数组已经是有序的,此时可以直接退出。
*/
public class Bubble<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
boolean isSorted = false;
for (int i = N - 1; i > 0 && !isSorted; i--) {
isSorted = true;
for (int j = 0; j < i; j++) {
if (less(nums[j + 1], nums[j])) {
isSorted = false;
swap(nums, j, j + 1);
}
}
}
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/Shell.java | data_struct_study/src/sort_problem/Shell.java | package sort_problem;
/**
* 对于大规模的数组,插入排序很慢,因为它只能交换相邻的元素,每次只能
* 将逆序数量减少 1。希尔排序的出现就是为了解决插入排序的这种局限性,
* 它通过交换不相邻的元素,每次可以将逆序数量减少大于 1。
*
* 希尔排序使用插入排序对间隔 h 的序列进行排序。通过不断减小 h,最后
* 令 h=1,就可以使得整个数组是有序的。
*
* 希尔排序的运行时间达不到平方级别,使用递增序列 1, 4, 13, 40, ...
* 的希尔排序所需要的比较次数不会超过 N 的若干倍乘于递增序列的长度。
* 高级排序算法只会比希尔排序快两倍左右。
*/
public class Shell<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
int h = 1;
while (h < N / 3) {
h = 3 * h + 1; // 1, 4, 13, 40, ...
}
while (h >= 1) {
for (int i = h; i < N; i++) {
for (int j = i; j >= h && less(nums[j], nums[j - h]); j -= h) {
swap(nums, j, j - h);
}
}
h = h / 3;
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/QuickSelection.java | data_struct_study/src/sort_problem/QuickSelection.java | package sort_problem;
/**
* 快速排序的 partition() 方法,会返回一个整数 j 使得 a[l..j-1]
* 小于等于 a[j],且 a[j+1..h] 大于等于 a[j],此时 a[j]
* 就是数组的第 j 大元素。
* 可以利用这个特性找出数组的第 k 个元素。该算法是线性级别的,假设每次
* 能将数组二分,那么比较的总次数为 (N+N/2+N/4+..),直到找到第 k
* 个元素,这个和显然小于 2N。
*/
public class QuickSelection<T extends Comparable<T>> extends Sort<T>{
public T select(T[] nums, int k) {
int l = 0, h = nums.length - 1;
while (h > l) {
int j = partition(nums, l, h);
if (j == k) {
return nums[k];
} else if (j > k) {
h = j - 1;
} else {
l = j + 1;
}
}
return nums[k];
}
private int partition(T[] nums, int l, int h) {
int i = l, j = h + 1;
T v = nums[l];
while (true) {
while (less(nums[++i], v) && i != h) ;
while (less(v, nums[--j]) && j != l) ;
if (i >= j)
break;
swap(nums, i, j);
}
swap(nums, l, j);
return j;
}
@Override
public void sort(T[] nums) {
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/ThreeWayQuickSort.java | data_struct_study/src/sort_problem/ThreeWayQuickSort.java | package sort_problem;
/**
* 快排改进:
* 1、切换到插入排序:
* 因为快速排序在小数组中也会递归调用自己,对于小数组,插入排序比
* 快速排序的性能更好,因此在小数组中可以切换到插入排序。
*
* 2、三数取中:
* 最好的情况下是每次都能取数组的中位数作为切分元素,但是计算中位数
* 的代价很高。一种折中方法是取 3 个元素,并将大小居中的元素作为切分元素。
*
* 3、三向切分:
* 对于有大量重复元素的数组,可以将数组切分为三部分,分别对应小于、等于和大于切分元素。
* 三向切分快速排序对于有大量重复元素的随机数组可以在线性时间内完成排序。
*/
public class ThreeWayQuickSort<T extends Comparable<T>> extends QuickSort<T> {
// @Override
protected void sort(T[] nums, int l, int h) {
if (h <= l) {
return;
}
int lt = l, i = l + 1, gt = h;
T v = nums[l];
while (i <= gt) {
int cmp = nums[i].compareTo(v);
if (cmp < 0) {
swap(nums, lt++, i++);
} else if (cmp > 0) {
swap(nums, i, gt--);
} else {
i++;
}
}
sort(nums, l, lt - 1);
sort(nums, gt + 1, h);
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/MergeSort.java | data_struct_study/src/sort_problem/MergeSort.java | package sort_problem;
/**
* 思路:归并排序的思想是不断地将数组分成两部分,分别进行排序,然后归并起来,
* 归并就是将数组中两个已排序的部分归并成一个。归并排序是稳定性算法。
* 时间复杂度:O(NlogN)
* 空间复杂度:O(N)
*/
public class MergeSort<T extends Comparable<T>> extends Sort<T> {
protected T[] aux;
// 归并方法:归并方法将数组中两个已经排序的部分归并成一个
protected void merge(T[] nums, int l, int m, int h) {
int i = l, j = m + 1;
// 将数据复制到辅助数组
for (int k = l; k <= h; k++) {
aux[k] = nums[k];
}
for (int k = l; k <= h; k++) {
if (i > m) {
nums[k] = aux[j++];
} else if (j > h) {
nums[k] = aux[i++];
} else if (aux[i].compareTo(aux[j]) <= 0) {
nums[k] = aux[i++]; // 先进行这一步,保证稳定性
} else {
nums[k] = aux[j++];
}
}
}
@Override
public void sort(T[] nums) {
// 1、自顶向下归并排序
// 不断地将一个大数组分成两个小数组去求解。
// 因为每次都将问题对半分成两个子问题。
aux = (T[]) new Comparable[nums.length];
sort(nums, 0, nums.length - 1);
// 2、自底向上归并排序
// 先归并那些微型数组,然后成对归并得到的微型数组。
// int N = nums.length;
// aux = (T[]) new Comparable[N];
//
// for (int sz = 1; sz < N; sz += sz) {
// for (int lo = 0; lo < N - sz; lo += sz + sz) {
// merge(nums, lo, lo + sz - 1, Math.min(lo + sz + sz - 1, N - 1));
// }
// }
}
private void sort(T[] nums, int l, int h) {
if (h <= l) {
return;
}
int mid = l + (h - l) / 2;
sort(nums, l, mid);
sort(nums, mid + 1, h);
merge(nums, l, mid, h);
}
public static void main(String[] args) {
Integer[] nums = new Integer[]{3, 5, 1, 2, 4};
new MergeSort<Integer>().sort(nums);
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/QuickSort.java | data_struct_study/src/sort_problem/QuickSort.java | package sort_problem;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* 归并排序将数组分为两个子数组分别排序,并将有序的子数组归并使得整个数组排序;
* 快速排序通过一个切分元素将数组分为两个子数组,左子数组小于等于切分元素,
* 右子数组大于等于切分元素,将这两个子数组排序也就将整个数组排序了。
*
* 快速排序是原地排序,不需要辅助数组,但是递归调用需要辅助栈。
* 快速排序最好的情况下是每次都正好将数组对半分,这样递归调用次数才是最少的。
* 这种情况下比较次数为 CN=2CN/2+N,复杂度为 O(NlogN)。
*
* 最坏的情况下,第一次从最小的元素切分,第二次从第二小的元素切分,如此这般。
* 因此最坏的情况下需要比较 N2/2。
* 为了防止数组最开始就是有序的,需要在进行快速排序时随机打乱数组。
*/
public class QuickSort<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
shuffle(nums);
sort(nums, 0, nums.length - 1);
}
private void sort(T[] nums, int l, int h) {
if (h <= l) {
return;
}
int j = partition(nums, l, h);
sort(nums, l, j - 1);
sort(nums, j + 1, h);
}
private void shuffle(T[] nums) {
List<Comparable> list = Arrays.asList(nums);
Collections.shuffle(list);
list.toArray(nums);
}
// 取 nums[l] 作为切分元素,然后从数组的左端向右扫描直到找到第一个
// 大于等于它的元素,再从数组的右端向左扫描找到第一个小于它的元素,
// 交换这两个元素。不断进行这个过程,就可以保证左指针 i 的左侧元素
// 都不大于切分元素,右指针 j 的右侧元素都不小于切分元素。当两个
// 指针相遇时,将切分元素 nums[l] 和 nums[j] 交换位置。此时的j就是切分元素
private int partition(T[] nums, int l, int h) {
int i = l, j = h + 1;
T v = nums[l];
while (true) {
while (less(nums[++i], v) && i != h) ;
while (less(v, nums[--j]) && j != l) ;
if (i >= j)
break;
swap(nums, i, j);
}
swap(nums, l, j);
return j;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/Selection.java | data_struct_study/src/sort_problem/Selection.java | package sort_problem;
/**
* 从数组中选择最小的元素,将它与数组的第一个元素交换位置。再从数组剩下的元素中
* 选择出最小的元素,将它与数组的第二个元素交换位置。不断进行这样的操作,直到将整个数组排序。
*
* 选择排序需要 ~N2/2 次比较和 ~N 次交换,它的运行时间与输入无关,这个特点
* 使得它对一个已经排序的数组也需要这么多的比较和交换操作。
*/
public class Selection<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
for (int i = 0; i < N - 1; i++) {
int min = i;
for (int j = i + 1; j < N; j++) {
if (less(nums[j], nums[min])) {
min = j;
}
}
swap(nums, i, min);
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/Insertion.java | data_struct_study/src/sort_problem/Insertion.java | package sort_problem;
/**
* 每次都将当前元素插入到左侧已经排序的数组中,使得插入之后左侧数组依然有序。
*
* 对于数组 {3, 5, 2, 4, 1},它具有以下逆序:(3, 2), (3, 1), (5, 2),
* (5, 4), (5, 1), (2, 1), (4, 1),插入排序每次只能交换相邻元素,
* 令逆序数量减少 1,因此插入排序需要交换的次数为逆序数量。
*
* 插入排序的时间复杂度取决于数组的初始顺序,如果数组已经部分有序了,
* 那么逆序较少,需要的交换次数也就较少,时间复杂度较低。
*
* 平均情况下插入排序需要 ~N2/4 比较以及 ~N2/4 次交换;
* 最坏的情况下需要 ~N2/2 比较以及 ~N2/2 次交换,最坏的情况是数组是倒序的;
* 最好的情况下需要 N-1 次比较和 0 次交换,最好的情况就是数组已经有序了。
*/
public class Insertion<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
for (int i = 1; i < N; i++) {
for (int j = i; j > 0 && less(nums[j], nums[j - 1]); j--) {
swap(nums, j, j - 1);
}
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/sort_problem/Sort.java | data_struct_study/src/sort_problem/Sort.java | package sort_problem;
/**
* 待排序的元素需要实现 Java 的 Comparable 接口,该接口有 compareTo() 方法,可以用它来判断两个元素的大小关系。
* 使用辅助函数 less() 和 swap() 来进行比较和交换的操作,使得代码的可读性和可移植性更好。
* 排序算法的成本模型是比较和交换的次数。
*
* 算法 稳定性 时间复杂度 空间复杂度 备注
* 选择排序 × N2 1
* 冒泡排序 √ N2 1
* 插入排序 √ N ~ N2 1 时间复杂度和初始顺序有关
* 希尔排序 × N 的若干倍乘于递增序列的长度 1 改进版插入排序
* 快速排序 × NlogN logN
* 三向切分快速排序 × N ~ NlogN logN 适用于有大量重复主键
* 归并排序 √ NlogN N
* 堆排序 × NlogN 1 无法利用局部性原理
*
* 快速排序是最快的通用排序算法,它的内循环的指令很少,而且它还能利用缓存,
* 因为它总是顺序地访问数据。它的运行时间近似为 ~cNlogN,这里的 c
* 比其它线性对数级别的排序算法都要小。
*
* 使用三向切分快速排序,实际应用中可能出现的某些分布的输入能够达到线性级别,
* 而其它排序算法仍然需要线性对数时间。
*
* Java 主要排序方法为 java.util.Arrays.sort(),对于原始数据类型使用
* 三向切分的快速排序,对于引用类型使用归并排序。
*/
public abstract class Sort<T extends Comparable<T>> {
public abstract void sort(T[] nums);
protected boolean less(T v, T w) {
return v.compareTo(w) < 0;
}
protected void swap(T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/union_find/UnionFind2.java | data_struct_study/src/union_find/UnionFind2.java | package union_find;
public class UnionFind2 implements UF {
/**
* parent[i] 表示第i个元素所属集合中的根节点。
*/
private int[] parent;
public UnionFind2(int size) {
parent = new int[size];
// 每一个元素都是一个单独的集合,也是一棵树的根节点,特征为自己指向自己
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
}
}
@Override
public int getSize() {
return parent.length;
}
private int find(int p) {
if (p < 0 || p >= parent.length) {
throw new IllegalArgumentException("p is out of bound~");
}
// 根节点:parent[p] == p
if (parent[p] != p) {
p = parent[p];
}
return p;
}
@Override
public boolean isConnected(int p, int q) {
return find(p) == find(q);
}
@Override
public void unionElements(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot) {
return;
}
parent[pRoot] = q;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/union_find/UF.java | data_struct_study/src/union_find/UF.java | package union_find;
public interface UF {
int getSize();
boolean isConnected(int p, int q);
void unionElements(int p, int q);
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/union_find/UnionFind1.java | data_struct_study/src/union_find/UnionFind1.java | package union_find;
public class UnionFind1 implements UF {
private int[] id;
public UnionFind1(int size) {
id = new int[size];
for (int i = 0; i < size; i++) {
id[i] = i;
}
}
@Override
public int getSize() {
return id.length;
}
private int find(int p) {
if (p < 0 || p >= id.length) {
throw new IllegalArgumentException("p is out of bound~");
}
return id[p];
}
@Override
public boolean isConnected(int p, int q) {
return find(p) == find(q);
}
@Override
public void unionElements(int p, int q) {
int pID = find(p);
int qID = find(q);
if (pID == qID) {
return;
}
for (int i = 0; i < id.length; i++) {
if (id[i] == pID) {
id[i] = qID;
}
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/union_find/UnionFind4.java | data_struct_study/src/union_find/UnionFind4.java | package union_find;
/**
* 基于 rank(深度排名,并不完全表示数的深度) 的优化,比基于 size 的优化要更合理,合并后得到的 h 在某些情况下要更小。
*/
public class UnionFind4 implements UF {
/**
* parent[i] 表示第i个元素所属集合中的根节点。
*/
private int[] parent;
/**
* sz[i] 表示以i为根的集合的深度
*/
private int[] rank;
public UnionFind4(int size) {
parent = new int[size];
rank = new int[size];
// 每一个元素都是一个单独的集合,也是一棵树的根节点,特征为自己指向自己
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
rank[i] = 1;
}
}
@Override
public int getSize() {
return parent.length;
}
private int find(int p) {
if (p < 0 || p >= parent.length) {
throw new IllegalArgumentException("p is out of bound~");
}
// 根节点:parent[p] == p
if (parent[p] != p) {
p = parent[p];
}
return p;
}
@Override
public boolean isConnected(int p, int q) {
return find(p) == find(q);
}
@Override
public void unionElements(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot) {
return;
}
// 将元素深度低的集合合并到元素深度高的集合上
if (rank[p] < rank[q]) {
parent[pRoot] = qRoot;
} else if (rank[p] > rank[q]){
parent[qRoot] = pRoot;
} else {
parent[qRoot] = pRoot;
rank[pRoot]++;
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/union_find/UnionFind5.java | data_struct_study/src/union_find/UnionFind5.java | package union_find;
/**
* 在 find 方法加上路径压缩。
* 基于 rank(深度排名,并不完全表示数的深度) 的优化,
* 比基于 size 的优化要更合理,合并后得到的 h 在某些情况下要更小。
*/
public class UnionFind5 implements UF {
/**
* parent[i] 表示第i个元素所属集合中的根节点。
*/
private int[] parent;
/**
* sz[i] 表示以i为根的集合的深度
*/
private int[] rank;
public UnionFind5(int size) {
parent = new int[size];
rank = new int[size];
// 每一个元素都是一个单独的集合,也是一棵树的根节点,特征为自己指向自己
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
rank[i] = 1;
}
}
@Override
public int getSize() {
return parent.length;
}
private int find(int p) {
if (p < 0 || p >= parent.length) {
throw new IllegalArgumentException("p is out of bound~");
}
// 根节点:parent[p] == p
if (parent[p] != p) {
// 路径压缩,当前节点的指针指向下下个节点。
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
@Override
public boolean isConnected(int p, int q) {
return find(p) == find(q);
}
@Override
public void unionElements(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot) {
return;
}
// 将元素深度低的集合合并到元素深度高的集合上
if (rank[p] < rank[q]) {
parent[pRoot] = qRoot;
} else if (rank[p] > rank[q]){
parent[qRoot] = pRoot;
} else {
parent[qRoot] = pRoot;
rank[pRoot]++;
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/union_find/UnionFind3.java | data_struct_study/src/union_find/UnionFind3.java | package union_find;
/**
* 基于 size 的优化,避免形成类似链表的结构,导致 O(h)过大。
*/
public class UnionFind3 implements UF {
/**
* parent[i] 表示第i个元素所属集合中的根节点。
*/
private int[] parent;
/**
* sz[i] 表示以i为根的集合中的元素个数
*/
private int[] sz;
public UnionFind3(int size) {
parent = new int[size];
sz = new int[size];
// 每一个元素都是一个单独的集合,也是一棵树的根节点,特征为自己指向自己
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
sz[i] = 1;
}
}
@Override
public int getSize() {
return parent.length;
}
private int find(int p) {
if (p < 0 || p >= parent.length) {
throw new IllegalArgumentException("p is out of bound~");
}
// 根节点:parent[p] == p
if (parent[p] != p) {
p = parent[p];
}
return p;
}
@Override
public boolean isConnected(int p, int q) {
return find(p) == find(q);
}
@Override
public void unionElements(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot) {
return;
}
// 将元素个数少的集合合并到元素个数多的集合上
if (sz[p] < sz[q]) {
parent[pRoot] = qRoot;
sz[qRoot] += sz[pRoot];
} else {
parent[qRoot] = pRoot;
sz[pRoot] += sz[qRoot];
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/union_find/Main.java | data_struct_study/src/union_find/Main.java | package union_find;
/**
* 并查集:由孩子指向父亲,通常用来解决连接问题,最适合合并与查询是相互交替动态进行的请求。
*
* 应用场景:
* 1、网络中节点间的连接状态,网络是一个抽象的概念,用户之间也可以形成网络。
* 2、数学中的集合类实现,求集合中的并集。
*
* 连接问题和路径问题 类比为 堆和顺序表,我们只需要判断它是不是连接的或是最大、最小的元素。
*
* 同一个集合 id 就属于一个集合,就表示是相连的。
*
* Quick Find (使用数组模拟操作并查集的过程):
* find 与 isConnected 时间复杂度 O(1),unionElements 时间复杂度 O(n)。
*
* Quick Union :
* find 与 unionElements 时间复杂度都为 O(h),h 为树的高度。
* 集合编号即为根节点的编号。
*
*/
public class Main {
public static void main(String[] args) {
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/union_find/UnionFind6.java | data_struct_study/src/union_find/UnionFind6.java | package union_find;
/**
* 递归的路径压缩方式,相比非递归的路径压缩性能要稍微差一点。
* 时间复杂度 O(log*n) = { 0 if(n<=1) 1+log*(logn) if(n>1)},可以认作近乎是O(1)级别的。
* 在 find 方法加上路径压缩。
* 基于 rank(深度排名,并不完全表示数的深度) 的优化,
* 比基于 size 的优化要更合理,合并后得到的 h 在某些情况下要更小。
*/
public class UnionFind6 implements UF {
/**
* parent[i] 表示第i个元素所属集合中的根节点。
*/
private int[] parent;
/**
* rank[i] 表示以i为根的集合的深度,在路径压缩的过程中,
* 我们并不会再去更新 rank 的值,因此它并不严格地表示树的深度,
* 而只是作为一个比较值(用于判断将元素深度低的集合合并到元素深度高的集合上)。
*/
private int[] rank;
public UnionFind6(int size) {
parent = new int[size];
rank = new int[size];
// 每一个元素都是一个单独的集合,也是一棵树的根节点,特征为自己指向自己
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
rank[i] = 1;
}
}
@Override
public int getSize() {
return parent.length;
}
private int find(int p) {
if (p < 0 || p >= parent.length) {
throw new IllegalArgumentException("p is out of bound~");
}
// 根节点:parent[p] == p
if (parent[p] != p) {
// 路径压缩,当前节点的指针指向下下个节点。
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
@Override
public boolean isConnected(int p, int q) {
return find(p) == find(q);
}
@Override
public void unionElements(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot) {
return;
}
// 将元素深度低的集合合并到元素深度高的集合上
if (rank[p] < rank[q]) {
parent[pRoot] = qRoot;
} else if (rank[p] > rank[q]){
parent[qRoot] = pRoot;
} else {
parent[qRoot] = pRoot;
rank[pRoot]++;
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution93.java | data_struct_study/src/backstracking_problem/Solution93.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* 递归与回溯
*
* 题目描述:给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
* 有效的 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),
* 整数之间用 '.' 分隔。
*
* 时间复杂度:O(3 ^ SEG_COUNT * ∣s∣)
* 空间复杂度:O(SEG_COUNT)
*/
class Solution93 {
// 1、初始化分段数量 & 返回列表
static final int SEG_COUNT = 4;
List<String> ans = new ArrayList<>();
int[] segments;
public List<String> restoreIpAddresses(String s) {
// 2、初始化分段数组并进行深度优先遍历
segments = new int[SEG_COUNT];
dfs(s, 0, 0);
return ans;
}
public void dfs(String s, int segId, int segStart) {
// 1)、如果找到了 4 段 IP 地址并且遍历完了字符串,那么就是一种答案
if (segId == SEG_COUNT) {
if (segStart == s.length()) {
StringBuilder ipAddr = new StringBuilder();
for (int i = 0; i < SEG_COUNT; ++i) {
ipAddr.append(segments[i]);
if (i != SEG_COUNT - 1) {
ipAddr.append('.');
}
}
ans.add(ipAddr.toString());
}
return;
}
// 2)、如果还没有找到 4 段 IP 地址就已经遍历完了字符串,那么提前回溯
if (segStart == s.length()) {
return;
}
// 3)、异常处理:由于不能有前导零,如果当前数字为 0,那么这一段 IP 地址只能为 0
if (s.charAt(segStart) == '0') {
segments[segId] = 0;
dfs(s, segId + 1, segStart + 1);
}
// 4)、一般情况,枚举每一种可能性并递归
int addr = 0;
for (int segEnd = segStart; segEnd < s.length(); ++segEnd) {
addr = addr * 10 + (s.charAt(segEnd) - '0');
if (addr > 0 && addr <= 0xFF) {
segments[segId] = addr;
dfs(s, segId + 1, segEnd + 1);
} else {
// 当前情况不满足,直接break回到上一层
break;
}
}
}
public static void main(String[] args) {
System.out.println(new Solution93().restoreIpAddresses("25525511135"));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution401.java | data_struct_study/src/backstracking_problem/Solution401.java | package backstracking_problem;
public class Solution401 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/main.java | data_struct_study/src/backstracking_problem/main.java | package backstracking_problem;
/**
* 递归与回溯
*
* JsonChao的递归与回溯核心题库:21题
*/
public class main {
public static void main(String[] args) {
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution200.java | data_struct_study/src/backstracking_problem/Solution200.java | package backstracking_problem;
/**
* O(m * n)
* O(m * n)
* 岛屿数量: 求连通分支个数【dfs】和 【union find】。使用unionfind的原理为:
* 顶点数-最小生成树连线数=连通分支个数。
*/
public class Solution200 {
private int[][] d = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
private int m, n;
private boolean[][] visited;
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int res = 0;
m = grid.length;
n = grid[0].length;
visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1' && !visited[i][j]) {
dfs(grid, i, j);
res++;
}
}
}
return res;
}
// 深度优先遍历当前岛屿占用区域
private void dfs(char[][] grid, int x, int y) {
visited[x][y] = true;
for (int i = 0; i < 4; i++) {
int newX = x + d[i][0];
int newY = y + d[i][1];
if (inArea(newX, newY) && !visited[newX][newY] &&
grid[newX][newY] == '1') {
dfs(grid, newX, newY);
}
}
}
private boolean inArea(int x, int y) {
return x >= 0 && x < m && y >= 0 && y < n;
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution52.java | data_struct_study/src/backstracking_problem/Solution52.java | package backstracking_problem;
/**
* 回溯法时经典人工智能的基础
* 1、剪枝
* 2、快速判断不合法的情况:
* 竖向:col[i] 表示第i列被占用
* 对角线1:dia1[i] 表示第i对角线1被占用—— 2*n-1个 i+j。对角线相加
* 对角线2:dia2[i] 表示第i对角线2被占用—— 2*n-1个 i+j+n-1。对角线相减
*/
public class Solution52 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution51.java | data_struct_study/src/backstracking_problem/Solution51.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* 回溯法是经典人工智能的基础
* 1、剪枝
* 2、快速判断不合法的情况:
* 竖向:col[i] 表示第i列被占用
* 对角线1:dia1[i] 表示第i对角线1被占用—— 2*n-1个 i+j。对角线相加
* 对角线2:dia2[i] 表示第i对角线2被占用—— 2*n-1个 i-j+n-1。对角线相减
* O(n * n)
* O(n)
*/
public class Solution51 {
private boolean[] col;
private boolean[] dia1;
private boolean[] dia2;
private List<List<String>> res;
public List<List<String>> solveNQueens(int n) {
col = new boolean[n];
dia1 = new boolean[2 * n - 1];
dia2 = new boolean[2 * n - 1];
res = new ArrayList<>();
LinkedList<Integer> row = new LinkedList<>();
putQueue(n, 0, row);
return res;
}
// 摆放第 index 行的皇后
private void putQueue(int n, int index, LinkedList<Integer> row) {
if (index == n) {
res.add(generateBroad(n, row));
return;
}
// 尝试将 index 行的皇后摆放在第 i 列
for (int i = 0; i < n; i++) {
if (!col[i] && !dia1[index + i] && !dia2[index - i + n - 1]) {
row.addLast(i);
col[i] = true;
dia1[index + i] = true;
dia2[index - i + n - 1] = true;
putQueue(n , index + 1, row);
col[i] = false;
dia1[index + i] = false;
dia2[index - i + n - 1] = false;
row.removeLast();
}
}
}
private List<String> generateBroad(int n, LinkedList<Integer> row) {
assert row.size() == n;
ArrayList<String> board = new ArrayList<>();
for (int i = 0; i < n; i++) {
char[] charArray = new char[n];
Arrays.fill(charArray, '.');
charArray[row.get(i)] = 'Q';
board.add(new String(charArray));
}
return board;
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution17.java | data_struct_study/src/backstracking_problem/Solution17.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.List;
/**
* 递归与回溯
* 树形问题 17:
* 1、字符串的合法性
* 2、空字符串(null)
* 3、多个解的顺序(无)
* 4、digits 是数字字符串,s(digits) 是digits所能代表的字母字符串,
* s(digital[0...n-1])
* = letter(digital[0]) + letter(digital[1...n-1])
* = letter(digital[0]) + letter(digital[1]) + letter(digital[2...n-1])
* = ...
* 5、递归调用的一个重要特征:要返回——回溯,它是暴力解法的一个主要实现手段。
* 6、3^n = O(2^n)
* O(2^len(s))
* O(len(s)
*/
public class Solution17 {
private String letterMap[] = {
" ", //0
"", //1
"abc", //2
"def", //3
"ghi", //4
"jkl", //5
"mno", //6
"pqrs", //7
"tuv", //8
"wxyz" //9
};
private ArrayList<String> res;
public List<String> letterCombinations(String digits) {
res = new ArrayList<>();
if (digits == null || digits.equals("")) {
return res;
}
findCombinations(digits, 0, "");
return res;
}
private void findCombinations(String digits, int index, String s) {
if (digits.length() == index) {
res.add(s);
return;
}
Character c = digits.charAt(index);
assert c.compareTo('0') >= 0 &&
c.compareTo('9') <= 0 &&
c.compareTo('1') != 0;
String letter = letterMap[c - '0'];
for (int i = 0; i < letter.length(); i++) {
findCombinations(digits, index + 1, s + letter.charAt(i));
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution46.java | data_struct_study/src/backstracking_problem/Solution46.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.List;
/**
* 排列问题
* 时间复杂度:O(n*n!)
* 空间复杂度:O(n)
*/
public class Solution46 {
public List<List<Integer>> permute(int[] nums) {
// 1、创建一个组合嵌套列表 & 组合列表 & 记录已访问元素的数组
List<List<Integer>> permutes = new ArrayList<>();
List<Integer> permuteList = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
// 2、回溯
backtracking(permuteList, permutes, visited, nums);
return permutes;
}
// 1,2,3 => 移除3,2 => 1,3,2 => 移除 2,3,1 => 2,1,3 => ...
private void backtracking(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, int[] nums) {
// 1、如果当前组合等于目标数组长度,则添加到嵌套列表中并返回到上一层
if (permuteList.size() == nums.length) {
permutes.add(new ArrayList<>(permuteList));
return;
}
// 2、遍历已访问数组,如果当前元素没有被访问过,则添加到记录组合列表中,并继续下一层回溯,
// 回溯到底添加完组合列表后,则删除 当前 组合列表中最后一个元素
for (int i = 0; i < visited.length; i++) {
if (!visited[i]) {
visited[i] = true;
permuteList.add(nums[i]);
backtracking(permuteList, permutes, visited, nums);
permuteList.remove(permuteList.size() - 1);
visited[i] = false;
}
}
}
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 3};
new Solution46().permute(nums);
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution90.java | data_struct_study/src/backstracking_problem/Solution90.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution90 {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> subsets = new ArrayList<>();
List<Integer> tempSubset = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
Arrays.sort(nums);
// 统计不同大小的子集
for (int i = 0; i <= nums.length; i++) {
backTracing(0, i, visited, tempSubset, subsets, nums);
}
return subsets;
}
private void backTracing(int start, int size, boolean[] visited, List<Integer> tempSubset, List<List<Integer>> subsets, int[] nums) {
if (tempSubset.size() == size) {
subsets.add(new ArrayList<>(tempSubset));
return;
}
for (int i = start; i < nums.length; i++) {
// 防重处理
if (i != 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
continue;
}
visited[i] = true;
tempSubset.add(nums[i]);
backTracing(i + 1, size, visited, tempSubset, subsets, nums);
tempSubset.remove(tempSubset.size() - 1);
visited[i] = false;
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution78.java | data_struct_study/src/backstracking_problem/Solution78.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.List;
/**
* 子集
*/
public class Solution78 {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> subsets = new ArrayList<>();
List<Integer> tempSubset = new ArrayList<>();
// 统计不同子集的大小
for (int i = 0; i <= nums.length; i++) {
backTracing(0, i, tempSubset, subsets, nums);
}
return subsets;
}
private void backTracing(int start, int size, List<Integer> tempSubset, List<List<Integer>> subsets, int[] nums) {
if (tempSubset.size() == size) {
subsets.add(new ArrayList<>(tempSubset));
return;
}
for (int i = start; i < nums.length; i++) {
tempSubset.add(nums[i]);
backTracing(i + 1, size, tempSubset, subsets, nums);
tempSubset.remove(tempSubset.size() - 1);
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution131.java | data_struct_study/src/backstracking_problem/Solution131.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.List;
/**
* 递归与回溯
*/
public class Solution131 {
public List<List<String>> partition(String s) {
List<List<String>> partitions = new ArrayList<>();
List<String> tempPartition = new ArrayList<>();
backTracing(s, tempPartition, partitions);
return partitions;
}
private void backTracing(String s, List<String> tempPartition, List<List<String>> partitions) {
if (s.length() == 0) {
partitions.add(new ArrayList<>(tempPartition));
return;
}
for (int i = 0; i < s.length(); i++) {
if (isPalindrome(s, 0, i)) {
tempPartition.add(s.substring(0, i + 1));
backTracing(s.substring(i + 1), tempPartition, partitions);
tempPartition.remove(tempPartition.size() - 1);
}
}
}
private boolean isPalindrome(String s, int start, int end) {
while (start < end) {
if (s.charAt(start++) != s.charAt(end--)) {
return false;
}
}
return true;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution417.java | data_struct_study/src/backstracking_problem/Solution417.java | package backstracking_problem;
/**
* floodfill 洪水填充算法——深度优先遍历
*/
public class Solution417 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution216.java | data_struct_study/src/backstracking_problem/Solution216.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.List;
public class Solution216 {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> tempCombination = new ArrayList<>();
backtracking(k, n, 1, tempCombination, combinations);
return combinations;
}
private void backtracking(int k, int n, int start, List<Integer> tempCombination, List<List<Integer>> combinations) {
if (k == 0 && n == 0) {
combinations.add(new ArrayList<>(tempCombination));
return;
}
if (k == 0 || n == 0) {
return;
}
for (int i = start; i <= 9; i++) {
tempCombination.add(i);
backtracking(k - 1, n - i, i + 1, tempCombination, combinations);
tempCombination.remove(tempCombination.size() - 1);
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution47.java | data_struct_study/src/backstracking_problem/Solution47.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 排列问题
* 时间复杂度:O(n*n!)
* 空间复杂度:O(n)
*/
public class Solution47 {
public List<List<Integer>> permuteUnique(int[] nums) {
// 1、创建一个嵌套排列列表 & 排列列表 & 记录已访问元素的数组
List<List<Integer>> permutes = new ArrayList<>();
List<Integer> permuteList = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
// 2、排序数组:保证相同的数字都相邻,然后每次填入的数一定是这个数
// 所在重复数集合中「从左往右第一个未被填过的数字」,
// 为了在后面回溯的时候便于排除重复元素
Arrays.sort(nums);
// 3、回溯
backtracking(permuteList, permutes, visited, nums);
return permutes;
}
private void backtracking(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, int[] nums) {
// 1、如果当前的排列列表达到nums的长度,则添加并返回至上一层
if (permuteList.size() == nums.length) {
permutes.add(permuteList);
return;
}
// 2、遍历记录已访问的数组:不同于组合问题,排列问题首先需要去重,
// 如果当前元素没被访问过,则将其添加到列表中,并继续访问下一层,
// 访问到达添加后排列列表后,则删除当前排列列表中的最后一个元素
for (int i = 0; i < visited.length; i++) {
// 有序数组的去重处理:如果当前元素和前一个元素相等 & 前一个元素没被访问过
if (i != 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
continue;
}
if (!visited[i]) {
visited[i] = true;
permuteList.add(nums[i]);
backtracking(permuteList, permutes, visited, nums);
permuteList.remove(permuteList.size() - 1);
visited[i] = false;
}
}
}
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 3, 2};
new Solution47().permuteUnique(nums);
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution89.java | data_struct_study/src/backstracking_problem/Solution89.java | package backstracking_problem;
public class Solution89 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution39.java | data_struct_study/src/backstracking_problem/Solution39.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.List;
public class Solution39 {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> combinations = new ArrayList<>();
backtracking(new ArrayList<>(), combinations, 0, target, candidates);
return combinations;
}
private void backtracking(ArrayList<Integer> tempCombination, List<List<Integer>> combinations, int start, int target, int[] candidates) {
if (target == 0) {
combinations.add(new ArrayList<>(tempCombination));
return;
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] <= target) {
tempCombination.add(candidates[i]);
backtracking(tempCombination, combinations, i, target - candidates[i], candidates);
tempCombination.remove(tempCombination.size() - 1);
}
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution77.java | data_struct_study/src/backstracking_problem/Solution77.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* 组合问题
* O(n^k)
* O(k)
*/
public class Solution77 {
private ArrayList<List<Integer>> res;
public List<List<Integer>> combine(int n, int k) {
res = new ArrayList<>();
if (n <= 0 || k <= 0 || n < k) {
return res;
}
LinkedList<Integer> c = new LinkedList<>();
generateCombination(n, k, 1, c);
return res;
}
private void generateCombination(int n, int k, int start, LinkedList<Integer> c) {
if (c.size() == k) {
res.add((List<Integer>) c.clone());
return;
}
for (int i = start; i <= n; i++) {
c.addLast(i);
generateCombination(n, k, i + 1, c);
c.removeLast();
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution79.java | data_struct_study/src/backstracking_problem/Solution79.java | package backstracking_problem;
/**
* 二维平面上的回溯法
* O(m*n*m*n)
* O(m*n)
*/
public class Solution79 {
private int m;
private int n;
private int[][] d = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
private boolean[][] visited;
public boolean exist(char[][] board, String word) {
if (board == null || word == null) {
throw new IllegalArgumentException("board and word is null!");
}
m = board.length;
if (m == 0) {
throw new IllegalArgumentException("board length is illegal argument");
}
n = board[0].length;
if (n == 0) {
throw new IllegalArgumentException("board length is illegal argument");
}
visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (searchWord(board, word, 0, i, j)) {
return true;
}
}
}
return false;
}
private boolean searchWord(char[][] board, String word, int index, int startX, int startY) {
if (index == word.length() - 1) {
return word.charAt(index) == board[startX][startY];
}
if (word.charAt(index) == board[startX][startY]) {
visited[startX][startY] = true;
for (int i = 0; i < 4; i++) {
int newX = startX + d[i][0];
int newY = startY + d[i][1];
if (isAccess(newX, newY) && !visited[newX][newY] &&
searchWord(board, word, index + 1, newX, newY)) {
return true;
}
}
visited[startX][startY] = false;
}
return false;
}
private boolean isAccess(int newX, int newY) {
return newX >= 0 && newX < m && newY >= 0 && newY < n;
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution22.java | data_struct_study/src/backstracking_problem/Solution22.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.List;
/**
* 括号生成:【递归】,分只能添加“(”,只能添加“)”,和有可以添加
* “(”又能添加“)”三种情况。注意“)”的个数时时刻刻不能超过“(”。
*/
public class Solution22 {
public List<String> generateParenthesis(int n) {
add("", 0, 0, n);
return list;
}
List<String> list=new ArrayList<>();
void add(String s, int count1, int count2, int n){
if(count1==count2&&count1<n){
s+="(";
add(new String(s), count1+1, count2, n);
}else if (count1==n){
while (count2<n){
s+=")"; count2++;
}
list.add(new String(s));
}else{
add(new String(s+"("), count1+1, count2, n);
add(new String(s+")"), count1, count2+1, n);
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution130.java | data_struct_study/src/backstracking_problem/Solution130.java | package backstracking_problem;
/**
* floodfill 洪水填充算法——深度优先遍历
*/
public class Solution130 {
int[][] d = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int m , n;
public void solve(char[][] board) {
if (board == null || board.length == 0) {
return;
}
m = board.length;
n = board[0].length;
for (int i = 0; i < m; i++) {
dfs(board, i, 0);
dfs(board, i, n - 1);
}
for (int i = 0; i < n; i++) {
dfs(board, 0, i);
dfs(board, m - 1, i);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'T') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
private void dfs(char[][] board, int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') {
return;
}
board[i][j] = 'T';
for (int[] d : d) {
dfs(board, i + d[0], j + d[1]);
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution37.java | data_struct_study/src/backstracking_problem/Solution37.java | package backstracking_problem;
/**
* 回溯法是经典人工智能的基础
* 1、剪枝
* 2、快速判断不合法的情况:
* 竖向:col[i] 表示第i列被占用
* 对角线1:dia1[i] 表示第i对角线1被占用—— 2*n-1个 i+j。对角线相加
* 对角线2:dia2[i] 表示第i对角线2被占用—— 2*n-1个 i+j+n-1。对角线相减
*/
public class Solution37 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution77_2.java | data_struct_study/src/backstracking_problem/Solution77_2.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* 组合问题
* 1、回溯法解决组合问题的优化:剪枝,避免最后的重复运算。
* O(n^k)
* O(k)
*/
public class Solution77_2 {
private ArrayList<List<Integer>> res;
public List<List<Integer>> combine(int n, int k) {
res = new ArrayList<>();
if (n <= 0 || k <= 0 || n < k) {
return res;
}
LinkedList<Integer> c = new LinkedList<>();
generateCombination(n, k, 1, c);
return res;
}
private void generateCombination(int n, int k, int start, LinkedList<Integer> c) {
if (k == c.size()) {
res.add((List<Integer>) c.clone());
return;
}
for (int i = start; i <= n - (k - c.size()) + 1; i++) {
c.addLast(i);
generateCombination(n, k, i + 1, c);
c.removeLast();
}
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/backstracking_problem/Solution40.java | data_struct_study/src/backstracking_problem/Solution40.java | package backstracking_problem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution40 {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> tempCombination = new ArrayList<>();
boolean[] visited = new boolean[candidates.length];
Arrays.sort(candidates);
backtracking(tempCombination, combinations, visited, 0, target, candidates);
return combinations;
}
private void backtracking(List<Integer> tempCombination, List<List<Integer>> combinations, boolean[] visited, int start, int target, int[] candidates) {
if (target == 0) {
combinations.add(new ArrayList<>(tempCombination));
return;
}
for (int i = start; i < candidates.length; i++) {
// 去重处理
if (i != 0 && candidates[i] == candidates[i - 1] && !visited[i - 1]) {
continue;
}
if (candidates[i] <= target) {
visited[i] = true;
tempCombination.add(candidates[i]);
backtracking(tempCombination, combinations, visited, i + 1, target - candidates[i], candidates);
tempCombination.remove(tempCombination.size() - 1);
visited[i] = false;
}
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/trie/WordDictionary.java | data_struct_study/src/trie/WordDictionary.java | package trie;
import java.util.TreeMap;
class WordDictionary {
public class Node {
boolean isWord;
TreeMap<Character, Node> next;
public Node(boolean isWord) {
this.isWord = isWord;
next = new TreeMap<>();
}
public Node() {
this(false);
}
}
Node root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new Node();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (cur.next.get(c) == null) {
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
cur.isWord = true;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return match(root, word, 0);
}
private boolean match(Node cur, String word, int index) {
if (index == word.length()) {
return cur.isWord;
}
char c = word.charAt(index);
if ('.' != c) {
if (cur.next.get(c) == null) {
return false;
}
return match(cur.next.get(c), word, index + 1);
} else {
for (Character character:cur.next.keySet()) {
if (match(cur.next.get(character), word, index + 1)) {
return true;
}
}
return false;
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/ | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/trie/Trie3.java | data_struct_study/src/trie/Trie3.java | package trie;
public class Trie3 {
private class Node{
public boolean isWord;
public Node[] next;
public Node(boolean isWord){
this.isWord = isWord;
next = new Node[26];
}
public Node(){
this(false);
}
}
private Node root;
private int size;
public Trie3(){
root = new Node();
size = 0;
}
// 获得Trie中存储的单词数量
public int getSize(){
return size;
}
// 向Trie中添加一个新的单词word
public void add(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next[c-'a'] == null)
cur.next[c-'a'] = new Node();
cur = cur.next[c-'a'];
}
if(!cur.isWord){
cur.isWord = true;
size ++;
}
}
// 查询单词word是否在Trie中
public boolean contains(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next[c-'a'] == null)
return false;
cur = cur.next[c-'a'];
}
return cur.isWord;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/trie/Trie206.java | data_struct_study/src/trie/Trie206.java | package trie;
import java.util.TreeMap;
class Trie206 {
private class Node {
boolean isWord;
TreeMap<Character, Node> next;
public Node(boolean isWord) {
this.isWord = isWord;
next = new TreeMap<>();
}
public Node() {
this(false);
}
}
private Node root;
/** Initialize your data structure here. */
public Trie206() {
root = new Node();
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (cur.next.get(c) == null) {
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
cur.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (cur.next.get(c) == null) {
return false;
}
cur = cur.next.get(c);
}
return cur.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Node cur = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (cur.next.get(c) == null) {
return false;
}
cur = cur.next.get(c);
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/trie/Trie2.java | data_struct_study/src/trie/Trie2.java | package trie;
import java.util.HashMap;
// 使用HashMap的Trie
public class Trie2 {
private class Node{
public boolean isWord;
public HashMap<Character, Node> next;
public Node(boolean isWord){
this.isWord = isWord;
next = new HashMap<>();
}
public Node(){
this(false);
}
}
private Node root;
private int size;
public Trie2(){
root = new Node();
size = 0;
}
// 获得Trie中存储的单词数量
public int getSize(){
return size;
}
// 向Trie中添加一个新的单词word
public void add(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next.get(c) == null)
cur.next.put(c, new Node());
cur = cur.next.get(c);
}
if(!cur.isWord){
cur.isWord = true;
size ++;
}
}
// 查询单词word是否在Trie中
public boolean contains(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next.get(c) == null)
return false;
cur = cur.next.get(c);
}
return cur.isWord;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/trie/MapSum.java | data_struct_study/src/trie/MapSum.java | package trie;
import java.util.TreeMap;
class MapSum {
public class Node {
public int value;
public TreeMap<Character, Node> next;
public Node(int value) {
this.value = value;
next = new TreeMap<>();
}
public Node() {
this(0);
}
}
Node root;
/** Initialize your data structure here. */
public MapSum() {
root = new Node();
}
public void insert(String key, int val) {
Node cur = root;
for (int i = 0; i < key.length(); i++) {
char c = key.charAt(i);
if (cur.next.get(c) == null) {
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
cur.value = val;
}
public int sum(String prefix) {
Node cur = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (cur.next.get(c) == null) {
return 0;
}
cur = cur.next.get(c);
}
return sum(cur);
}
private int sum(Node cur) {
int res = cur.value;
for(char c:cur.next.keySet()) {
res += sum(cur.next.get(c));
}
return res;
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/trie/Main.java | data_struct_study/src/trie/Main.java | package trie;
import set.BSTSet;
import set.FileOperation;
import java.util.ArrayList;
/**
* Trie:字典树,前缀树,多叉树
*
* 作用:专门为处理字符串而设计的
*
* 字典与 Trie 的比较:
*
* 字典:如果有 n 个条目,使用平衡二叉树查询的复杂度为 O(logn),100万(2^20)的数据量其 logn 大概为 20。
* Trie:查询的时间复杂度为 O(w),w 为查询单词的的长度,大多数单词的长度小于10。
*
* Trie 中每一个节点都有若干个指向下一个节点的指针,考虑不同的语言,不同的情境。
*
* 在我们编写的归并排序和快速排序算法中,对于n比较小的情况,我们会转而使用理论复杂度更高的插入排序去优化。
* 虽然插入排序的理论复杂度比归并排序,快速排序都要高,但是只有在n很大的情况才能显现出来,在n很小的情况下,插入排序更快.
*
* 时间复杂度 BST > TreeMap Trie > HashMap Trie > 数组 Trie
*
*/
public class Main {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<>();
if(FileOperation.readFile("pride-and-prejudice.txt", words) &&
FileOperation.readFile("a-tale-of-two-cities.txt", words)){
// Test BST
long startTime = System.nanoTime();
BSTSet<String> set = new BSTSet<>();
for(String word: words)
set.add(word);
for(String word: words)
set.isContains(word);
long endTime = System.nanoTime();
double time = (endTime - startTime) / 1000000000.0;
System.out.println("Total different words: " + set.getSize());
System.out.println("BSTSet: " + time + " s");
// ---
// Test TreeMap Trie
startTime = System.nanoTime();
Trie trie = new Trie();
for(String word: words)
trie.add(word);
for(String word: words)
trie.contains(word);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("Total different words: " + trie.getSize());
System.out.println("TreeMap Trie: " + time + " s");
// ---
// Test HashMap Trie
startTime = System.nanoTime();
Trie2 trie2 = new Trie2();
for(String word: words)
trie2.add(word);
for(String word: words)
trie2.contains(word);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("Total different words: " + trie.getSize());
System.out.println("HashMap Trie: " + time + " s");
// ---
// Test Array(Map) Trie
startTime = System.nanoTime();
Trie3 trie3 = new Trie3();
for(String word: words)
trie3.add(word);
for(String word: words)
trie3.contains(word);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("Total different words: " + trie.getSize());
System.out.println("Array(Map) Trie: " + time + " s");
}
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/trie/Trie.java | data_struct_study/src/trie/Trie.java | package trie;
import java.util.TreeMap;
/**
* Trie 的删除操作
*
* Trie 的局限性:next 指针是 TreeMap 数据类型,key 值总数最多可以达到26种。
* 改进方式:使用压缩字典树 Compressed Trie
*
* 三分搜索树(Ternary Search Tree):时间换空间。
*
* 后缀树
*
* 子串查询算法:KMP、Boyer-Moore、Rabin-Karp。
*
* 文件压缩实际上也算是一种字符串压缩。
*
* 模式匹配:实现一个正则表达式引擎。
*
* 编译原理:字符串应用很多。
*
* DNA:超长字符串。
*/
public class Trie {
public class Node {
public boolean isWord;
public TreeMap<Character, Node> next;
public Node(boolean isWord) {
this.isWord = isWord;
next = new TreeMap<>();
}
public Node() {
this(false);
}
}
private Node root;
private int size;
public Trie() {
this.root = new Node();
this.size = 0;
}
public int getSize() {
return size;
}
/**
* 向 trie 中添加一个新的单词
*
* @param word 单词
*/
public void add(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
Node node = cur.next.get(c);
if (node == null) {
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
if (!cur.isWord) {
cur.isWord = true;
size++;
}
}
/**
* 判断单词 word 是否包含在 Trie 中
*
* @param word 单词
* @return 单词 word 是否包含在 Trie 中
*/
public boolean contains(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
Node node = cur.next.get(c);
if (node == null) {
return false;
}
cur = cur.next.get(c);
}
return cur.isWord;
}
/**
* 字符集合中是否有 prefix 前缀
*
* @param prefix 字符前缀
* @return 是否有 prefix 前缀
*/
public boolean hasPrefix(String prefix) {
Node cur = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (cur.next.get(c) == null) {
return false;
}
cur = cur.next.get(c);
}
return true;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution213.java | data_struct_study/src/dynamic_problem/Solution213.java | package dynamic_problem;
public class Solution213 {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
if (n == 1) {
return nums[0];
}
return Math.max(tryRob(nums, 0, n - 2), tryRob(nums, 1, n - 1));
}
private int tryRob(int[] nums, int first, int last) {
int pre2 = 0, pre1 = 0;
for (int i = first; i <= last; i++) {
int cur = Math.max(pre1, pre2 + nums[i]);
pre2 = pre1;
pre1 = cur;
}
return pre1;
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution139.java | data_struct_study/src/dynamic_problem/Solution139.java | package dynamic_problem;
import java.util.List;
public class Solution139 {
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= n; i++) {
for(String word:wordDict) {
int len = word.length();
if (len <= i && word.equals(s.substring(i - len, i))) {
dp[i] = dp[i] || dp[i - len];
}
}
}
return dp[n];
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution198_6.java | data_struct_study/src/dynamic_problem/Solution198_6.java | package dynamic_problem;
/**
* DP:优化状态转移
*/
public class Solution198_6 {
public int rob(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int[] memo = new int[n];
memo[n - 1] = nums[n - 1];
for (int i = n - 2; i >= 0; i--) {
memo[i] = Math.max(memo[i + 1], nums[i] + (i + 2 < n ? memo[i - 2] : 0));
}
return memo[0];
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution198_4.java | data_struct_study/src/dynamic_problem/Solution198_4.java | package dynamic_problem;
public class Solution198_4 {
public int rob(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int[] memo = new int[n];
for (int i = 1; i < n; i++) {
for (int j = i; j >= 0; j--) {
memo[i] = Math.max(memo[i], (j - 2) >= 0 ? memo[j - 2] : 0);
}
}
return memo[n - 1];
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution63.java | data_struct_study/src/dynamic_problem/Solution63.java | package dynamic_problem;
public class Solution63 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution120.java | data_struct_study/src/dynamic_problem/Solution120.java | package dynamic_problem;
public class Solution120 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution343_2.java | data_struct_study/src/dynamic_problem/Solution343_2.java | package dynamic_problem;
import array.Array;
import java.util.Arrays;
/**
* 记忆化搜索 + 暴力搜索
* O(n ^ 2)
* O(n)
*/
public class Solution343_2 {
private int[] memo;
public int integerBreak(int n) {
if (n < 1) {
throw new IllegalArgumentException("Illegal argument!");
}
memo = new int[n + 1];
Arrays.fill(memo, -1);
return breakInteger(n);
}
private int breakInteger(int n) {
if (n == 1) {
return 1;
}
if (memo[n] != -1) {
return memo[n];
}
int res = -1;
for (int i = 1; i <= n - 1; i++) {
res = max3(res, i * (n - i), i * breakInteger(n - i));
}
memo[n] = res;
return res;
}
private int max3(int a, int b, int c) {
return Math.max(a, Math.max(b, c));
}
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution509.java | data_struct_study/src/dynamic_problem/Solution509.java | package dynamic_problem;
/**
* 递归
*/
public class Solution509 {
public int fib(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution300_2.java | data_struct_study/src/dynamic_problem/Solution300_2.java | package dynamic_problem;
import java.util.Arrays;
/**
* 记忆化搜索 + DP
* 时间复杂度:O(n ^ 2)
* 空间复杂度:O(n)
*/
public class Solution300_2 {
public int lengthOfLIS(int[] nums) {
// 1、异常处理:如果nums为0,则返回0
int n = nums.length;
if (n == 0) {
return 0;
}
// 2、创建记忆数组并都初始化为-1
int[] memo = new int[n];
Arrays.fill(memo, -1);
// 3、双层遍历:如果下标i处的值大于前面j处的值,则更新memo[i]
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
memo[i] = Math.max(memo[i], 1 + memo[j]);
}
}
}
// 4、再遍历一次计算所有下标处的最大LIS
int res = memo[0];
for (int i = 1; i < n; i++) {
res = Math.max(res, memo[i]);
}
return res;
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution198_3.java | data_struct_study/src/dynamic_problem/Solution198_3.java | package dynamic_problem;
import java.util.Arrays;
/**
* 记忆化搜索
* O(n ^ 2)
* O(n)
*/
public class Solution198_3 {
private int[] memo;
public int rob(int[] nums) {
memo = new int[nums.length];
Arrays.fill(memo, -1);
return tryRob(nums, nums.length - 1);
}
private int tryRob(int[] nums, int index) {
if (index < 0) {
return 0;
}
if (memo[index] != -1) {
return memo[index];
}
int res = 0;
for (int i = 0; i <= index; i++) {
res = Math.max(res, nums[i] + tryRob(nums, i - 2));
}
memo[index] = res;
return res;
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution70_3.java | data_struct_study/src/dynamic_problem/Solution70_3.java | package dynamic_problem;
/**
* 3、Dp + 循环只需记录前两个数的值 => 矩阵快速幂 or 推导公式可以优化时间到 O(logn)
* 时间复杂度:O(n)
* 空间复杂度:O(1)
*/
public class Solution70_3 {
// 3、DP + 循环计算只依赖前两个值即可
// 时间复杂度:O(n), 空间复杂度:O(1)
public int climbStairs(int n) {
// 1、异常处理:n小于0抛出异常
if (n < 0) {
throw new IllegalArgumentException("illegal argument");
}
// 2、如果爬的楼梯是0或1层,则只有1种方式
if (n == 0 || n == 1) {
return 1;
}
// 3、DP + 循环计算只依赖前两个值
int pre = 1, cur = 1;
int next;
for (int i = 2; i <= n; i++) {
next = pre + cur;
pre = cur;
cur = next;
}
return cur;
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution198.java | data_struct_study/src/dynamic_problem/Solution198.java | package dynamic_problem;
import java.util.Arrays;
/**
* 状态的定义和状态转移
* 1、暴力解法:检查所有房子的组合,对每一个组合,检查是否有相邻的房子,如果没有,记录其价值。找最大值。O((2^n)*n)
* 2、注意其中对状态的定义:
* 函数的定义:考虑偷取[x...n-1]范围内的房子。
* 根据对状态的定义,决定状态转移方程:
* f(0) = max{v(0) + f(2), v(1) + f(3) , ... , v(n-3) + f(n-1) ,v(n-2),v(n-1)}
*/
public class Solution198 {
private int[] memo;
public int rob(int[] nums) {
memo = new int[nums.length];
Arrays.fill(memo, -1);
return tryRob(nums, 0);
}
private int tryRob(int[] nums, int index) {
if (index >= nums.length) {
return 0;
}
if (memo[index] != -1) {
return memo[index];
}
int res = 0;
for (int i = index; i < nums.length; i++) {
res = Math.max(res, nums[i] + tryRob(nums, i + 2));
}
memo[index] = res;
return res;
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution509_3.java | data_struct_study/src/dynamic_problem/Solution509_3.java | package dynamic_problem;
import java.util.Arrays;
/**
* 动态规划(DP)+ 记忆化搜索
*/
public class Solution509_3 {
public int fib(int n) {
if (n == 0) {
return 0;
}
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
memo[0] = 0;
memo[1] = 1;
for (int i = 2; i <= n; i++) {
memo[i] = memo[i - 1] + memo[i - 2];
}
return memo[n];
}
} | java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
JsonChao/Awesome-Algorithm-Study | https://github.com/JsonChao/Awesome-Algorithm-Study/blob/f1c886eabf744b69e72a0b0a64b348032b439037/data_struct_study/src/dynamic_problem/Solution354.java | data_struct_study/src/dynamic_problem/Solution354.java | package dynamic_problem;
public class Solution354 {
}
| java | Apache-2.0 | f1c886eabf744b69e72a0b0a64b348032b439037 | 2026-01-05T02:39:40.141219Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.