diff --git a/codes/code_links.json b/codes/code_links.json new file mode 100644 index 000000000..163abf156 --- /dev/null +++ b/codes/code_links.json @@ -0,0 +1,6319 @@ +{ + "chapter_appendix": {}, + "chapter_array_and_linkedlist": { + "[file]{array}-[class]{}-[func]{random_access}": { + "python": [ + "[class]{}-[func]{random_access}" + ], + "cpp": [ + "[class]{}-[func]{randomAccess}" + ], + "java": [ + "[class]{array}-[func]{randomAccess}" + ], + "csharp": [ + "[class]{array}-[func]{RandomAccess}" + ], + "go": [ + "[class]{}-[func]{randomAccess}" + ], + "swift": [ + "[class]{}-[func]{randomAccess}" + ], + "javascript": [ + "[class]{}-[func]{randomAccess}" + ], + "typescript": [ + "[class]{}-[func]{randomAccess}" + ], + "dart": [ + "[class]{}-[func]{randomAccess}" + ], + "rust": [ + "[class]{}-[func]{random_access}" + ], + "c": [ + "[class]{}-[func]{randomAccess}" + ], + "kotlin": [ + "[class]{}-[func]{randomAccess}" + ], + "ruby": [ + "[class]{}-[func]{random_access}" + ], + "zig": [ + "[class]{}-[func]{randomAccess}" + ] + }, + "[file]{array}-[class]{}-[func]{insert}": { + "python": [ + "[class]{}-[func]{insert}" + ], + "cpp": [ + "[class]{}-[func]{insert}" + ], + "java": [ + "[class]{array}-[func]{insert}" + ], + "csharp": [ + "[class]{array}-[func]{Insert}" + ], + "go": [ + "[class]{}-[func]{insert}" + ], + "swift": [ + "[class]{}-[func]{insert}" + ], + "javascript": [ + "[class]{}-[func]{insert}" + ], + "typescript": [ + "[class]{}-[func]{insert}" + ], + "dart": [ + "[class]{}-[func]{insert}" + ], + "rust": [ + "[class]{}-[func]{insert}" + ], + "c": [ + "[class]{}-[func]{insert}" + ], + "kotlin": [ + "[class]{}-[func]{insert}" + ], + "ruby": [ + "[class]{}-[func]{insert}" + ], + "zig": [ + "[class]{}-[func]{insert}" + ] + }, + "[file]{array}-[class]{}-[func]{remove}": { + "python": [ + "[class]{}-[func]{remove}" + ], + "cpp": [ + "[class]{}-[func]{remove}" + ], + "java": [ + "[class]{array}-[func]{remove}" + ], + "csharp": [ + "[class]{array}-[func]{Remove}" + ], + "go": [ + "[class]{}-[func]{remove}" + ], + "swift": [ + "[class]{}-[func]{remove}" + ], + "javascript": [ + "[class]{}-[func]{remove}" + ], + "typescript": [ + "[class]{}-[func]{remove}" + ], + "dart": [ + "[class]{}-[func]{remove}" + ], + "rust": [ + "[class]{}-[func]{remove}" + ], + "c": [ + "[class]{}-[func]{removeItem}" + ], + "kotlin": [ + "[class]{}-[func]{remove}" + ], + "ruby": [ + "[class]{}-[func]{remove}" + ], + "zig": [ + "[class]{}-[func]{remove}" + ] + }, + "[file]{array}-[class]{}-[func]{traverse}": { + "python": [ + "[class]{}-[func]{traverse}" + ], + "cpp": [ + "[class]{}-[func]{traverse}" + ], + "java": [ + "[class]{array}-[func]{traverse}" + ], + "csharp": [ + "[class]{array}-[func]{Traverse}" + ], + "go": [ + "[class]{}-[func]{traverse}" + ], + "swift": [ + "[class]{}-[func]{traverse}" + ], + "javascript": [ + "[class]{}-[func]{traverse}" + ], + "typescript": [ + "[class]{}-[func]{traverse}" + ], + "dart": [ + "[class]{}-[func]{traverse}" + ], + "rust": [ + "[class]{}-[func]{traverse}" + ], + "c": [ + "[class]{}-[func]{traverse}" + ], + "kotlin": [ + "[class]{}-[func]{traverse}" + ], + "ruby": [ + "[class]{}-[func]{traverse}" + ], + "zig": [ + "[class]{}-[func]{traverse}" + ] + }, + "[file]{array}-[class]{}-[func]{find}": { + "python": [ + "[class]{}-[func]{find}" + ], + "cpp": [ + "[class]{}-[func]{find}" + ], + "java": [ + "[class]{array}-[func]{find}" + ], + "csharp": [ + "[class]{array}-[func]{Find}" + ], + "go": [ + "[class]{}-[func]{find}" + ], + "swift": [ + "[class]{}-[func]{find}" + ], + "javascript": [ + "[class]{}-[func]{find}" + ], + "typescript": [ + "[class]{}-[func]{find}" + ], + "dart": [ + "[class]{}-[func]{find}" + ], + "rust": [ + "[class]{}-[func]{find}" + ], + "c": [ + "[class]{}-[func]{find}" + ], + "kotlin": [ + "[class]{}-[func]{find}" + ], + "ruby": [ + "[class]{}-[func]{find}" + ], + "zig": [ + "[class]{}-[func]{find}" + ] + }, + "[file]{array}-[class]{}-[func]{extend}": { + "python": [ + "[class]{}-[func]{extend}" + ], + "cpp": [ + "[class]{}-[func]{extend}" + ], + "java": [ + "[class]{array}-[func]{extend}" + ], + "csharp": [ + "[class]{array}-[func]{Extend}" + ], + "go": [ + "[class]{}-[func]{extend}" + ], + "swift": [ + "[class]{}-[func]{extend}" + ], + "javascript": [ + "[class]{}-[func]{extend}" + ], + "typescript": [ + "[class]{}-[func]{extend}" + ], + "dart": [ + "[class]{}-[func]{extend}" + ], + "rust": [ + "[class]{}-[func]{extend}" + ], + "c": [ + "[class]{}-[func]{extend}" + ], + "kotlin": [ + "[class]{}-[func]{extend}" + ], + "ruby": [ + "[class]{}-[func]{extend}" + ], + "zig": [ + "[class]{}-[func]{extend}" + ] + }, + "[file]{linked_list}-[class]{}-[func]{insert}": { + "python": [ + "[class]{}-[func]{insert}" + ], + "cpp": [ + "[class]{}-[func]{insert}" + ], + "java": [ + "[class]{linked_list}-[func]{insert}" + ], + "csharp": [ + "[class]{linked_list}-[func]{Insert}" + ], + "go": [ + "[class]{}-[func]{insertNode}" + ], + "swift": [ + "[class]{}-[func]{insert}" + ], + "javascript": [ + "[class]{}-[func]{insert}" + ], + "typescript": [ + "[class]{}-[func]{insert}" + ], + "dart": [ + "[class]{}-[func]{insert}" + ], + "rust": [ + "[class]{}-[func]{insert}" + ], + "c": [ + "[class]{}-[func]{insert}" + ], + "kotlin": [ + "[class]{}-[func]{insert}" + ], + "ruby": [ + "[class]{}-[func]{insert}" + ], + "zig": [ + "[class]{}-[func]{insert}" + ] + }, + "[file]{linked_list}-[class]{}-[func]{remove}": { + "python": [ + "[class]{}-[func]{remove}" + ], + "cpp": [ + "[class]{}-[func]{remove}" + ], + "java": [ + "[class]{linked_list}-[func]{remove}" + ], + "csharp": [ + "[class]{linked_list}-[func]{Remove}" + ], + "go": [ + "[class]{}-[func]{removeItem}" + ], + "swift": [ + "[class]{}-[func]{remove}" + ], + "javascript": [ + "[class]{}-[func]{remove}" + ], + "typescript": [ + "[class]{}-[func]{remove}" + ], + "dart": [ + "[class]{}-[func]{remove}" + ], + "rust": [ + "[class]{}-[func]{remove}" + ], + "c": [ + "[class]{}-[func]{removeItem}" + ], + "kotlin": [ + "[class]{}-[func]{remove}" + ], + "ruby": [ + "[class]{}-[func]{remove}" + ], + "zig": [ + "[class]{}-[func]{remove}" + ] + }, + "[file]{linked_list}-[class]{}-[func]{access}": { + "python": [ + "[class]{}-[func]{access}" + ], + "cpp": [ + "[class]{}-[func]{access}" + ], + "java": [ + "[class]{linked_list}-[func]{access}" + ], + "csharp": [ + "[class]{linked_list}-[func]{Access}" + ], + "go": [ + "[class]{}-[func]{access}" + ], + "swift": [ + "[class]{}-[func]{access}" + ], + "javascript": [ + "[class]{}-[func]{access}" + ], + "typescript": [ + "[class]{}-[func]{access}" + ], + "dart": [ + "[class]{}-[func]{access}" + ], + "rust": [ + "[class]{}-[func]{access}" + ], + "c": [ + "[class]{}-[func]{access}" + ], + "kotlin": [ + "[class]{}-[func]{access}" + ], + "ruby": [ + "[class]{}-[func]{access}" + ], + "zig": [ + "[class]{}-[func]{access}" + ] + }, + "[file]{linked_list}-[class]{}-[func]{find}": { + "python": [ + "[class]{}-[func]{find}" + ], + "cpp": [ + "[class]{}-[func]{find}" + ], + "java": [ + "[class]{linked_list}-[func]{find}" + ], + "csharp": [ + "[class]{linked_list}-[func]{Find}" + ], + "go": [ + "[class]{}-[func]{findNode}" + ], + "swift": [ + "[class]{}-[func]{find}" + ], + "javascript": [ + "[class]{}-[func]{find}" + ], + "typescript": [ + "[class]{}-[func]{find}" + ], + "dart": [ + "[class]{}-[func]{find}" + ], + "rust": [ + "[class]{}-[func]{find}" + ], + "c": [ + "[class]{}-[func]{find}" + ], + "kotlin": [ + "[class]{}-[func]{find}" + ], + "ruby": [ + "[class]{}-[func]{find}" + ], + "zig": [ + "[class]{}-[func]{find}" + ] + }, + "[file]{my_list}-[class]{my_list}-[func]{}": { + "python": [ + "[class]{MyList}-[func]{}" + ], + "cpp": [ + "[class]{MyList}-[func]{}" + ], + "java": [ + "[class]{MyList}-[func]{}" + ], + "csharp": [ + "[class]{MyList}-[func]{}" + ], + "go": [ + "[class]{myList}-[func]{}" + ], + "swift": [ + "[class]{MyList}-[func]{}" + ], + "javascript": [ + "[class]{MyList}-[func]{}" + ], + "typescript": [ + "[class]{MyList}-[func]{}" + ], + "dart": [ + "[class]{MyList}-[func]{}" + ], + "rust": [ + "[class]{MyList}-[func]{}" + ], + "c": [ + "[class]{MyList}-[func]{}" + ], + "kotlin": [ + "[class]{MyList}-[func]{}" + ], + "ruby": [ + "[class]{MyList}-[func]{}" + ], + "zig": [ + "[class]{MyList}-[func]{}" + ] + } + }, + "chapter_backtracking": { + "[file]{preorder_traversal_i_compact}-[class]{}-[func]{pre_order}": { + "python": [ + "[class]{}-[func]{pre_order}" + ], + "cpp": [ + "[class]{}-[func]{preOrder}" + ], + "java": [ + "[class]{preorder_traversal_i_compact}-[func]{preOrder}" + ], + "csharp": [ + "[class]{preorder_traversal_i_compact}-[func]{PreOrder}" + ], + "go": [ + "[class]{}-[func]{preOrderI}" + ], + "swift": [ + "[class]{}-[func]{preOrder}" + ], + "javascript": [ + "[class]{}-[func]{preOrder}" + ], + "typescript": [ + "[class]{}-[func]{preOrder}" + ], + "dart": [ + "[class]{}-[func]{preOrder}" + ], + "rust": [ + "[class]{}-[func]{pre_order}" + ], + "c": [ + "[class]{}-[func]{preOrder}" + ], + "kotlin": [ + "[class]{}-[func]{preOrder}" + ], + "ruby": [ + "[class]{}-[func]{pre_order}" + ] + }, + "[file]{preorder_traversal_ii_compact}-[class]{}-[func]{pre_order}": { + "python": [ + "[class]{}-[func]{pre_order}" + ], + "cpp": [ + "[class]{}-[func]{preOrder}" + ], + "java": [ + "[class]{preorder_traversal_ii_compact}-[func]{preOrder}" + ], + "csharp": [ + "[class]{preorder_traversal_ii_compact}-[func]{PreOrder}" + ], + "go": [ + "[class]{}-[func]{preOrderII}" + ], + "swift": [ + "[class]{}-[func]{preOrder}" + ], + "javascript": [ + "[class]{}-[func]{preOrder}" + ], + "typescript": [ + "[class]{}-[func]{preOrder}" + ], + "dart": [ + "[class]{}-[func]{preOrder}" + ], + "rust": [ + "[class]{}-[func]{pre_order}" + ], + "c": [ + "[class]{}-[func]{preOrder}" + ], + "kotlin": [ + "[class]{}-[func]{preOrder}" + ], + "ruby": [ + "[class]{}-[func]{pre_order}" + ] + }, + "[file]{preorder_traversal_iii_compact}-[class]{}-[func]{pre_order}": { + "python": [ + "[class]{}-[func]{pre_order}" + ], + "cpp": [ + "[class]{}-[func]{preOrder}" + ], + "java": [ + "[class]{preorder_traversal_iii_compact}-[func]{preOrder}" + ], + "csharp": [ + "[class]{preorder_traversal_iii_compact}-[func]{PreOrder}" + ], + "go": [ + "[class]{}-[func]{preOrderIII}" + ], + "swift": [ + "[class]{}-[func]{preOrder}" + ], + "javascript": [ + "[class]{}-[func]{preOrder}" + ], + "typescript": [ + "[class]{}-[func]{preOrder}" + ], + "dart": [ + "[class]{}-[func]{preOrder}" + ], + "rust": [ + "[class]{}-[func]{pre_order}" + ], + "c": [ + "[class]{}-[func]{preOrder}" + ], + "kotlin": [ + "[class]{}-[func]{preOrder}" + ], + "ruby": [ + "[class]{}-[func]{pre_order}" + ] + }, + "[file]{preorder_traversal_iii_template}-[class]{}-[func]{backtrack}": { + "python": [ + "[class]{}-[func]{is_solution}", + "[class]{}-[func]{record_solution}", + "[class]{}-[func]{is_valid}", + "[class]{}-[func]{make_choice}", + "[class]{}-[func]{undo_choice}", + "[class]{}-[func]{backtrack}" + ], + "cpp": [ + "[class]{}-[func]{isSolution}", + "[class]{}-[func]{recordSolution}", + "[class]{}-[func]{isValid}", + "[class]{}-[func]{makeChoice}", + "[class]{}-[func]{undoChoice}", + "[class]{}-[func]{backtrack}" + ], + "java": [ + "[class]{preorder_traversal_iii_template}-[func]{isSolution}", + "[class]{preorder_traversal_iii_template}-[func]{recordSolution}", + "[class]{preorder_traversal_iii_template}-[func]{isValid}", + "[class]{preorder_traversal_iii_template}-[func]{makeChoice}", + "[class]{preorder_traversal_iii_template}-[func]{undoChoice}", + "[class]{preorder_traversal_iii_template}-[func]{backtrack}" + ], + "csharp": [ + "[class]{preorder_traversal_iii_template}-[func]{IsSolution}", + "[class]{preorder_traversal_iii_template}-[func]{RecordSolution}", + "[class]{preorder_traversal_iii_template}-[func]{IsValid}", + "[class]{preorder_traversal_iii_template}-[func]{MakeChoice}", + "[class]{preorder_traversal_iii_template}-[func]{UndoChoice}", + "[class]{preorder_traversal_iii_template}-[func]{Backtrack}" + ], + "go": [ + "[class]{}-[func]{isSolution}", + "[class]{}-[func]{recordSolution}", + "[class]{}-[func]{isValid}", + "[class]{}-[func]{makeChoice}", + "[class]{}-[func]{undoChoice}", + "[class]{}-[func]{backtrackIII}" + ], + "swift": [ + "[class]{}-[func]{isSolution}", + "[class]{}-[func]{recordSolution}", + "[class]{}-[func]{isValid}", + "[class]{}-[func]{makeChoice}", + "[class]{}-[func]{undoChoice}", + "[class]{}-[func]{backtrack}" + ], + "javascript": [ + "[class]{}-[func]{isSolution}", + "[class]{}-[func]{recordSolution}", + "[class]{}-[func]{isValid}", + "[class]{}-[func]{makeChoice}", + "[class]{}-[func]{undoChoice}", + "[class]{}-[func]{backtrack}" + ], + "typescript": [ + "[class]{}-[func]{isSolution}", + "[class]{}-[func]{recordSolution}", + "[class]{}-[func]{isValid}", + "[class]{}-[func]{makeChoice}", + "[class]{}-[func]{undoChoice}", + "[class]{}-[func]{backtrack}" + ], + "dart": [ + "[class]{}-[func]{isSolution}", + "[class]{}-[func]{recordSolution}", + "[class]{}-[func]{isValid}", + "[class]{}-[func]{makeChoice}", + "[class]{}-[func]{undoChoice}", + "[class]{}-[func]{backtrack}" + ], + "rust": [ + "[class]{}-[func]{is_solution}", + "[class]{}-[func]{record_solution}", + "[class]{}-[func]{is_valid}", + "[class]{}-[func]{make_choice}", + "[class]{}-[func]{undo_choice}", + "[class]{}-[func]{backtrack}" + ], + "c": [ + "[class]{}-[func]{isSolution}", + "[class]{}-[func]{recordSolution}", + "[class]{}-[func]{isValid}", + "[class]{}-[func]{makeChoice}", + "[class]{}-[func]{undoChoice}", + "[class]{}-[func]{backtrack}" + ], + "kotlin": [ + "[class]{}-[func]{isSolution}", + "[class]{}-[func]{recordSolution}", + "[class]{}-[func]{isValid}", + "[class]{}-[func]{makeChoice}", + "[class]{}-[func]{undoChoice}", + "[class]{}-[func]{backtrack}" + ], + "ruby": [ + "[class]{}-[func]{is_solution}", + "[class]{}-[func]{record_solution}", + "[class]{}-[func]{is_valid}", + "[class]{}-[func]{make_choice}", + "[class]{}-[func]{undo_choice}", + "[class]{}-[func]{backtrack}" + ] + }, + "[file]{n_queens}-[class]{}-[func]{n_queens}": { + "python": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{n_queens}" + ], + "cpp": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{nQueens}" + ], + "java": [ + "[class]{n_queens}-[func]{backtrack}", + "[class]{n_queens}-[func]{nQueens}" + ], + "csharp": [ + "[class]{n_queens}-[func]{Backtrack}", + "[class]{n_queens}-[func]{NQueens}" + ], + "go": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{nQueens}" + ], + "swift": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{nQueens}" + ], + "javascript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{nQueens}" + ], + "typescript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{nQueens}" + ], + "dart": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{nQueens}" + ], + "rust": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{n_queens}" + ], + "c": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{nQueens}" + ], + "kotlin": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{nQueens}" + ], + "ruby": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{n_queens}" + ] + }, + "[file]{permutations_i}-[class]{}-[func]{permutations_i}": { + "python": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutations_i}" + ], + "cpp": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsI}" + ], + "java": [ + "[class]{permutations_i}-[func]{backtrack}", + "[class]{permutations_i}-[func]{permutationsI}" + ], + "csharp": [ + "[class]{permutations_i}-[func]{Backtrack}", + "[class]{permutations_i}-[func]{PermutationsI}" + ], + "go": [ + "[class]{}-[func]{backtrackI}", + "[class]{}-[func]{permutationsI}" + ], + "swift": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsI}" + ], + "javascript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsI}" + ], + "typescript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsI}" + ], + "dart": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsI}" + ], + "rust": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutations_i}" + ], + "c": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsI}" + ], + "kotlin": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsI}" + ], + "ruby": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutations_i}" + ] + }, + "[file]{permutations_ii}-[class]{}-[func]{permutations_ii}": { + "python": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutations_ii}" + ], + "cpp": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsII}" + ], + "java": [ + "[class]{permutations_ii}-[func]{backtrack}", + "[class]{permutations_ii}-[func]{permutationsII}" + ], + "csharp": [ + "[class]{permutations_ii}-[func]{Backtrack}", + "[class]{permutations_ii}-[func]{PermutationsII}" + ], + "go": [ + "[class]{}-[func]{backtrackII}", + "[class]{}-[func]{permutationsII}" + ], + "swift": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsII}" + ], + "javascript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsII}" + ], + "typescript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsII}" + ], + "dart": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsII}" + ], + "rust": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutations_ii}" + ], + "c": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsII}" + ], + "kotlin": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutationsII}" + ], + "ruby": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{permutations_ii}" + ] + }, + "[file]{subset_sum_i_naive}-[class]{}-[func]{subset_sum_i_naive}": { + "python": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subset_sum_i_naive}" + ], + "cpp": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumINaive}" + ], + "java": [ + "[class]{subset_sum_i_naive}-[func]{backtrack}", + "[class]{subset_sum_i_naive}-[func]{subsetSumINaive}" + ], + "csharp": [ + "[class]{subset_sum_i_naive}-[func]{Backtrack}", + "[class]{subset_sum_i_naive}-[func]{SubsetSumINaive}" + ], + "go": [ + "[class]{}-[func]{backtrackSubsetSumINaive}", + "[class]{}-[func]{subsetSumINaive}" + ], + "swift": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumINaive}" + ], + "javascript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumINaive}" + ], + "typescript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumINaive}" + ], + "dart": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumINaive}" + ], + "rust": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subset_sum_i_naive}" + ], + "c": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumINaive}" + ], + "kotlin": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumINaive}" + ], + "ruby": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subset_sum_i_naive}" + ] + }, + "[file]{subset_sum_i}-[class]{}-[func]{subset_sum_i}": { + "python": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subset_sum_i}" + ], + "cpp": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumI}" + ], + "java": [ + "[class]{subset_sum_i}-[func]{backtrack}", + "[class]{subset_sum_i}-[func]{subsetSumI}" + ], + "csharp": [ + "[class]{subset_sum_i}-[func]{Backtrack}", + "[class]{subset_sum_i}-[func]{SubsetSumI}" + ], + "go": [ + "[class]{}-[func]{backtrackSubsetSumI}", + "[class]{}-[func]{subsetSumI}" + ], + "swift": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumI}" + ], + "javascript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumI}" + ], + "typescript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumI}" + ], + "dart": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumI}" + ], + "rust": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subset_sum_i}" + ], + "c": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumI}" + ], + "kotlin": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumI}" + ], + "ruby": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subset_sum_i}" + ] + }, + "[file]{subset_sum_ii}-[class]{}-[func]{subset_sum_ii}": { + "python": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subset_sum_ii}" + ], + "cpp": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumII}" + ], + "java": [ + "[class]{subset_sum_ii}-[func]{backtrack}", + "[class]{subset_sum_ii}-[func]{subsetSumII}" + ], + "csharp": [ + "[class]{subset_sum_ii}-[func]{Backtrack}", + "[class]{subset_sum_ii}-[func]{SubsetSumII}" + ], + "go": [ + "[class]{}-[func]{backtrackSubsetSumII}", + "[class]{}-[func]{subsetSumII}" + ], + "swift": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumII}" + ], + "javascript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumII}" + ], + "typescript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumII}" + ], + "dart": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumII}" + ], + "rust": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subset_sum_ii}" + ], + "c": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumII}" + ], + "kotlin": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subsetSumII}" + ], + "ruby": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{subset_sum_ii}" + ] + } + }, + "chapter_computational_complexity": { + "[file]{complexity_exercises}-[class]{}-[func]{sum_iter}": { + "python": [ + "[class]{}-[func]{sum_iter}", + "[class]{}-[func]{sum_recur}" + ], + "cpp": [ + "[class]{}-[func]{sumIter}", + "[class]{}-[func]{sumRecur}" + ], + "java": [ + "[class]{complexity_exercises}-[func]{sumIter}", + "[class]{complexity_exercises}-[func]{sumRecur}" + ], + "csharp": [ + "[class]{complexity_exercises}-[func]{SumIter}", + "[class]{complexity_exercises}-[func]{SumRecur}" + ], + "go": [ + "[class]{}-[func]{sumIter}", + "[class]{}-[func]{sumRecur}" + ], + "swift": [ + "[class]{}-[func]{sumIter}", + "[class]{}-[func]{sumRecur}" + ], + "javascript": [ + "[class]{}-[func]{sumIter}", + "[class]{}-[func]{sumRecur}" + ], + "typescript": [ + "[class]{}-[func]{sumIter}", + "[class]{}-[func]{sumRecur}" + ], + "dart": [ + "[class]{}-[func]{sumIter}", + "[class]{}-[func]{sumRecur}" + ], + "rust": [ + "[class]{}-[func]{sum_iter}", + "[class]{}-[func]{sum_recur}" + ], + "c": [ + "[class]{}-[func]{sumIter}", + "[class]{}-[func]{sumRecur}" + ], + "kotlin": [ + "[class]{}-[func]{sumIter}", + "[class]{}-[func]{sumRecur}" + ], + "ruby": [ + "[class]{}-[func]{sum_iter}", + "[class]{}-[func]{sum_recur}" + ] + }, + "[file]{complexity_exercises}-[class]{}-[func]{linear_loop}": { + "python": [ + "[class]{}-[func]{linear_loop}", + "[class]{}-[func]{quadratic_loop}", + "[class]{}-[func]{logarithmic_loop}" + ], + "cpp": [ + "[class]{}-[func]{linearLoop}", + "[class]{}-[func]{quadraticLoop}", + "[class]{}-[func]{logarithmicLoop}" + ], + "java": [ + "[class]{complexity_exercises}-[func]{linearLoop}", + "[class]{complexity_exercises}-[func]{quadraticLoop}", + "[class]{complexity_exercises}-[func]{logarithmicLoop}" + ], + "csharp": [ + "[class]{complexity_exercises}-[func]{LinearLoop}", + "[class]{complexity_exercises}-[func]{QuadraticLoop}", + "[class]{complexity_exercises}-[func]{LogarithmicLoop}" + ], + "go": [ + "[class]{}-[func]{linearLoop}", + "[class]{}-[func]{quadraticLoop}", + "[class]{}-[func]{logarithmicLoop}" + ], + "swift": [ + "[class]{}-[func]{linearLoop}", + "[class]{}-[func]{quadraticLoop}", + "[class]{}-[func]{logarithmicLoop}" + ], + "javascript": [ + "[class]{}-[func]{linearLoop}", + "[class]{}-[func]{quadraticLoop}", + "[class]{}-[func]{logarithmicLoop}" + ], + "typescript": [ + "[class]{}-[func]{linearLoop}", + "[class]{}-[func]{quadraticLoop}", + "[class]{}-[func]{logarithmicLoop}" + ], + "dart": [ + "[class]{}-[func]{linearLoop}", + "[class]{}-[func]{quadraticLoop}", + "[class]{}-[func]{logarithmicLoop}" + ], + "rust": [ + "[class]{}-[func]{linear_loop}", + "[class]{}-[func]{quadratic_loop}", + "[class]{}-[func]{logarithmic_loop}" + ], + "c": [ + "[class]{}-[func]{linearLoop}", + "[class]{}-[func]{quadraticLoop}", + "[class]{}-[func]{logarithmicLoop}" + ], + "kotlin": [ + "[class]{}-[func]{linearLoop}", + "[class]{}-[func]{quadraticLoop}", + "[class]{}-[func]{logarithmicLoop}" + ], + "ruby": [ + "[class]{}-[func]{linear_loop}", + "[class]{}-[func]{quadratic_loop}", + "[class]{}-[func]{logarithmic_loop}" + ] + }, + "[file]{iteration}-[class]{}-[func]{for_loop}": { + "python": [ + "[class]{}-[func]{for_loop}" + ], + "cpp": [ + "[class]{}-[func]{forLoop}" + ], + "java": [ + "[class]{iteration}-[func]{forLoop}" + ], + "csharp": [ + "[class]{iteration}-[func]{ForLoop}" + ], + "go": [ + "[class]{}-[func]{forLoop}" + ], + "swift": [ + "[class]{}-[func]{forLoop}" + ], + "javascript": [ + "[class]{}-[func]{forLoop}" + ], + "typescript": [ + "[class]{}-[func]{forLoop}" + ], + "dart": [ + "[class]{}-[func]{forLoop}" + ], + "rust": [ + "[class]{}-[func]{for_loop}" + ], + "c": [ + "[class]{}-[func]{forLoop}" + ], + "kotlin": [ + "[class]{}-[func]{forLoop}" + ], + "ruby": [ + "[class]{}-[func]{for_loop}" + ], + "zig": [ + "[class]{}-[func]{forLoop}" + ] + }, + "[file]{iteration}-[class]{}-[func]{while_loop}": { + "python": [ + "[class]{}-[func]{while_loop}" + ], + "cpp": [ + "[class]{}-[func]{whileLoop}" + ], + "java": [ + "[class]{iteration}-[func]{whileLoop}" + ], + "csharp": [ + "[class]{iteration}-[func]{WhileLoop}" + ], + "go": [ + "[class]{}-[func]{whileLoop}" + ], + "swift": [ + "[class]{}-[func]{whileLoop}" + ], + "javascript": [ + "[class]{}-[func]{whileLoop}" + ], + "typescript": [ + "[class]{}-[func]{whileLoop}" + ], + "dart": [ + "[class]{}-[func]{whileLoop}" + ], + "rust": [ + "[class]{}-[func]{while_loop}" + ], + "c": [ + "[class]{}-[func]{whileLoop}" + ], + "kotlin": [ + "[class]{}-[func]{whileLoop}" + ], + "ruby": [ + "[class]{}-[func]{while_loop}" + ], + "zig": [ + "[class]{}-[func]{whileLoop}" + ] + }, + "[file]{iteration}-[class]{}-[func]{while_loop_ii}": { + "python": [ + "[class]{}-[func]{while_loop_ii}" + ], + "cpp": [ + "[class]{}-[func]{whileLoopII}" + ], + "java": [ + "[class]{iteration}-[func]{whileLoopII}" + ], + "csharp": [ + "[class]{iteration}-[func]{WhileLoopII}" + ], + "go": [ + "[class]{}-[func]{whileLoopII}" + ], + "swift": [ + "[class]{}-[func]{whileLoopII}" + ], + "javascript": [ + "[class]{}-[func]{whileLoopII}" + ], + "typescript": [ + "[class]{}-[func]{whileLoopII}" + ], + "dart": [ + "[class]{}-[func]{whileLoopII}" + ], + "rust": [ + "[class]{}-[func]{while_loop_ii}" + ], + "c": [ + "[class]{}-[func]{whileLoopII}" + ], + "kotlin": [ + "[class]{}-[func]{whileLoopII}" + ], + "ruby": [ + "[class]{}-[func]{while_loop_ii}" + ], + "zig": [ + "[class]{}-[func]{whileLoopII}" + ] + }, + "[file]{iteration}-[class]{}-[func]{nested_for_loop}": { + "python": [ + "[class]{}-[func]{nested_for_loop}" + ], + "cpp": [ + "[class]{}-[func]{nestedForLoop}" + ], + "java": [ + "[class]{iteration}-[func]{nestedForLoop}" + ], + "csharp": [ + "[class]{iteration}-[func]{NestedForLoop}" + ], + "go": [ + "[class]{}-[func]{nestedForLoop}" + ], + "swift": [ + "[class]{}-[func]{nestedForLoop}" + ], + "javascript": [ + "[class]{}-[func]{nestedForLoop}" + ], + "typescript": [ + "[class]{}-[func]{nestedForLoop}" + ], + "dart": [ + "[class]{}-[func]{nestedForLoop}" + ], + "rust": [ + "[class]{}-[func]{nested_for_loop}" + ], + "c": [ + "[class]{}-[func]{nestedForLoop}" + ], + "kotlin": [ + "[class]{}-[func]{nestedForLoop}" + ], + "ruby": [ + "[class]{}-[func]{nested_for_loop}" + ], + "zig": [ + "[class]{}-[func]{nestedForLoop}" + ] + }, + "[file]{recursion}-[class]{}-[func]{recur}": { + "python": [ + "[class]{}-[func]{recur}" + ], + "cpp": [ + "[class]{}-[func]{recur}" + ], + "java": [ + "[class]{recursion}-[func]{recur}" + ], + "csharp": [ + "[class]{recursion}-[func]{Recur}" + ], + "go": [ + "[class]{}-[func]{recur}" + ], + "swift": [ + "[class]{}-[func]{recur}" + ], + "javascript": [ + "[class]{}-[func]{recur}" + ], + "typescript": [ + "[class]{}-[func]{recur}" + ], + "dart": [ + "[class]{}-[func]{recur}" + ], + "rust": [ + "[class]{}-[func]{recur}" + ], + "c": [ + "[class]{}-[func]{recur}" + ], + "kotlin": [ + "[class]{}-[func]{recur}" + ], + "ruby": [ + "[class]{}-[func]{recur}" + ], + "zig": [ + "[class]{}-[func]{recur}" + ] + }, + "[file]{recursion}-[class]{}-[func]{tail_recur}": { + "python": [ + "[class]{}-[func]{tail_recur}" + ], + "cpp": [ + "[class]{}-[func]{tailRecur}" + ], + "java": [ + "[class]{recursion}-[func]{tailRecur}" + ], + "csharp": [ + "[class]{recursion}-[func]{TailRecur}" + ], + "go": [ + "[class]{}-[func]{tailRecur}" + ], + "swift": [ + "[class]{}-[func]{tailRecur}" + ], + "javascript": [ + "[class]{}-[func]{tailRecur}" + ], + "typescript": [ + "[class]{}-[func]{tailRecur}" + ], + "dart": [ + "[class]{}-[func]{tailRecur}" + ], + "rust": [ + "[class]{}-[func]{tail_recur}" + ], + "c": [ + "[class]{}-[func]{tailRecur}" + ], + "kotlin": [ + "[class]{}-[func]{tailRecur}" + ], + "ruby": [ + "[class]{}-[func]{tail_recur}" + ], + "zig": [ + "[class]{}-[func]{tailRecur}" + ] + }, + "[file]{recursion}-[class]{}-[func]{fib}": { + "python": [ + "[class]{}-[func]{fib}" + ], + "cpp": [ + "[class]{}-[func]{fib}" + ], + "java": [ + "[class]{recursion}-[func]{fib}" + ], + "csharp": [ + "[class]{recursion}-[func]{Fib}" + ], + "go": [ + "[class]{}-[func]{fib}" + ], + "swift": [ + "[class]{}-[func]{fib}" + ], + "javascript": [ + "[class]{}-[func]{fib}" + ], + "typescript": [ + "[class]{}-[func]{fib}" + ], + "dart": [ + "[class]{}-[func]{fib}" + ], + "rust": [ + "[class]{}-[func]{fib}" + ], + "c": [ + "[class]{}-[func]{fib}" + ], + "kotlin": [ + "[class]{}-[func]{fib}" + ], + "ruby": [ + "[class]{}-[func]{fib}" + ], + "zig": [ + "[class]{}-[func]{fib}" + ] + }, + "[file]{recursion}-[class]{}-[func]{for_loop_recur}": { + "python": [ + "[class]{}-[func]{for_loop_recur}" + ], + "cpp": [ + "[class]{}-[func]{forLoopRecur}" + ], + "java": [ + "[class]{recursion}-[func]{forLoopRecur}" + ], + "csharp": [ + "[class]{recursion}-[func]{ForLoopRecur}" + ], + "go": [ + "[class]{}-[func]{forLoopRecur}" + ], + "swift": [ + "[class]{}-[func]{forLoopRecur}" + ], + "javascript": [ + "[class]{}-[func]{forLoopRecur}" + ], + "typescript": [ + "[class]{}-[func]{forLoopRecur}" + ], + "dart": [ + "[class]{}-[func]{forLoopRecur}" + ], + "rust": [ + "[class]{}-[func]{for_loop_recur}" + ], + "c": [ + "[class]{}-[func]{forLoopRecur}" + ], + "kotlin": [ + "[class]{}-[func]{forLoopRecur}" + ], + "ruby": [ + "[class]{}-[func]{for_loop_recur}" + ], + "zig": [ + "[class]{}-[func]{forLoopRecur}" + ] + }, + "[file]{space_complexity}-[class]{}-[func]{constant}": { + "python": [ + "[class]{}-[func]{function}", + "[class]{}-[func]{constant}" + ], + "cpp": [ + "[class]{}-[func]{func}", + "[class]{}-[func]{constant}" + ], + "java": [ + "[class]{space_complexity}-[func]{function}", + "[class]{space_complexity}-[func]{constant}" + ], + "csharp": [ + "[class]{space_complexity}-[func]{Function}", + "[class]{space_complexity}-[func]{Constant}" + ], + "go": [ + "[class]{}-[func]{function}", + "[class]{}-[func]{spaceConstant}" + ], + "swift": [ + "[class]{}-[func]{function}", + "[class]{}-[func]{constant}" + ], + "javascript": [ + "[class]{}-[func]{constFunc}", + "[class]{}-[func]{constant}" + ], + "typescript": [ + "[class]{}-[func]{constFunc}", + "[class]{}-[func]{constant}" + ], + "dart": [ + "[class]{}-[func]{function}", + "[class]{}-[func]{constant}" + ], + "rust": [ + "[class]{}-[func]{function}", + "[class]{}-[func]{constant}" + ], + "c": [ + "[class]{}-[func]{func}", + "[class]{}-[func]{constant}" + ], + "kotlin": [ + "[class]{}-[func]{function}", + "[class]{}-[func]{constant}" + ], + "ruby": [ + "[class]{}-[func]{function}", + "[class]{}-[func]{constant}" + ], + "zig": [ + "[class]{}-[func]{function}", + "[class]{}-[func]{constant}" + ] + }, + "[file]{space_complexity}-[class]{}-[func]{linear}": { + "python": [ + "[class]{}-[func]{linear}" + ], + "cpp": [ + "[class]{}-[func]{linear}" + ], + "java": [ + "[class]{space_complexity}-[func]{linear}" + ], + "csharp": [ + "[class]{space_complexity}-[func]{Linear}" + ], + "go": [ + "[class]{}-[func]{spaceLinear}" + ], + "swift": [ + "[class]{}-[func]{linear}" + ], + "javascript": [ + "[class]{}-[func]{linear}" + ], + "typescript": [ + "[class]{}-[func]{linear}" + ], + "dart": [ + "[class]{}-[func]{linear}" + ], + "rust": [ + "[class]{}-[func]{linear}" + ], + "c": [ + "[class]{HashTable}-[func]{}", + "[class]{}-[func]{linear}" + ], + "kotlin": [ + "[class]{}-[func]{linear}" + ], + "ruby": [ + "[class]{}-[func]{linear}" + ], + "zig": [ + "[class]{}-[func]{linear}" + ] + }, + "[file]{space_complexity}-[class]{}-[func]{linear_recur}": { + "python": [ + "[class]{}-[func]{linear_recur}" + ], + "cpp": [ + "[class]{}-[func]{linearRecur}" + ], + "java": [ + "[class]{space_complexity}-[func]{linearRecur}" + ], + "csharp": [ + "[class]{space_complexity}-[func]{LinearRecur}" + ], + "go": [ + "[class]{}-[func]{spaceLinearRecur}" + ], + "swift": [ + "[class]{}-[func]{linearRecur}" + ], + "javascript": [ + "[class]{}-[func]{linearRecur}" + ], + "typescript": [ + "[class]{}-[func]{linearRecur}" + ], + "dart": [ + "[class]{}-[func]{linearRecur}" + ], + "rust": [ + "[class]{}-[func]{linear_recur}" + ], + "c": [ + "[class]{}-[func]{linearRecur}" + ], + "kotlin": [ + "[class]{}-[func]{linearRecur}" + ], + "ruby": [ + "[class]{}-[func]{linear_recur}" + ], + "zig": [ + "[class]{}-[func]{linearRecur}" + ] + }, + "[file]{space_complexity}-[class]{}-[func]{quadratic}": { + "python": [ + "[class]{}-[func]{quadratic}" + ], + "cpp": [ + "[class]{}-[func]{quadratic}" + ], + "java": [ + "[class]{space_complexity}-[func]{quadratic}" + ], + "csharp": [ + "[class]{space_complexity}-[func]{Quadratic}" + ], + "go": [ + "[class]{}-[func]{spaceQuadratic}" + ], + "swift": [ + "[class]{}-[func]{quadratic}" + ], + "javascript": [ + "[class]{}-[func]{quadratic}" + ], + "typescript": [ + "[class]{}-[func]{quadratic}" + ], + "dart": [ + "[class]{}-[func]{quadratic}" + ], + "rust": [ + "[class]{}-[func]{quadratic}" + ], + "c": [ + "[class]{}-[func]{quadratic}" + ], + "kotlin": [ + "[class]{}-[func]{quadratic}" + ], + "ruby": [ + "[class]{}-[func]{quadratic}" + ], + "zig": [ + "[class]{}-[func]{quadratic}" + ] + }, + "[file]{space_complexity}-[class]{}-[func]{quadratic_recur}": { + "python": [ + "[class]{}-[func]{quadratic_recur}" + ], + "cpp": [ + "[class]{}-[func]{quadraticRecur}" + ], + "java": [ + "[class]{space_complexity}-[func]{quadraticRecur}" + ], + "csharp": [ + "[class]{space_complexity}-[func]{QuadraticRecur}" + ], + "go": [ + "[class]{}-[func]{spaceQuadraticRecur}" + ], + "swift": [ + "[class]{}-[func]{quadraticRecur}" + ], + "javascript": [ + "[class]{}-[func]{quadraticRecur}" + ], + "typescript": [ + "[class]{}-[func]{quadraticRecur}" + ], + "dart": [ + "[class]{}-[func]{quadraticRecur}" + ], + "rust": [ + "[class]{}-[func]{quadratic_recur}" + ], + "c": [ + "[class]{}-[func]{quadraticRecur}" + ], + "kotlin": [ + "[class]{}-[func]{quadraticRecur}" + ], + "ruby": [ + "[class]{}-[func]{quadratic_recur}" + ], + "zig": [ + "[class]{}-[func]{quadraticRecur}" + ] + }, + "[file]{space_complexity}-[class]{}-[func]{build_tree}": { + "python": [ + "[class]{}-[func]{build_tree}" + ], + "cpp": [ + "[class]{}-[func]{buildTree}" + ], + "java": [ + "[class]{space_complexity}-[func]{buildTree}" + ], + "csharp": [ + "[class]{space_complexity}-[func]{BuildTree}" + ], + "go": [ + "[class]{}-[func]{buildTree}" + ], + "swift": [ + "[class]{}-[func]{buildTree}" + ], + "javascript": [ + "[class]{}-[func]{buildTree}" + ], + "typescript": [ + "[class]{}-[func]{buildTree}" + ], + "dart": [ + "[class]{}-[func]{buildTree}" + ], + "rust": [ + "[class]{}-[func]{build_tree}" + ], + "c": [ + "[class]{}-[func]{buildTree}" + ], + "kotlin": [ + "[class]{}-[func]{buildTree}" + ], + "ruby": [ + "[class]{}-[func]{build_tree}" + ], + "zig": [ + "[class]{}-[func]{buildTree}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{constant}": { + "python": [ + "[class]{}-[func]{constant}" + ], + "cpp": [ + "[class]{}-[func]{constant}" + ], + "java": [ + "[class]{time_complexity}-[func]{constant}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{Constant}" + ], + "go": [ + "[class]{}-[func]{constant}" + ], + "swift": [ + "[class]{}-[func]{constant}" + ], + "javascript": [ + "[class]{}-[func]{constant}" + ], + "typescript": [ + "[class]{}-[func]{constant}" + ], + "dart": [ + "[class]{}-[func]{constant}" + ], + "rust": [ + "[class]{}-[func]{constant}" + ], + "c": [ + "[class]{}-[func]{constant}" + ], + "kotlin": [ + "[class]{}-[func]{constant}" + ], + "ruby": [ + "[class]{}-[func]{constant}" + ], + "zig": [ + "[class]{}-[func]{constant}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{linear}": { + "python": [ + "[class]{}-[func]{linear}" + ], + "cpp": [ + "[class]{}-[func]{linear}" + ], + "java": [ + "[class]{time_complexity}-[func]{linear}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{Linear}" + ], + "go": [ + "[class]{}-[func]{linear}" + ], + "swift": [ + "[class]{}-[func]{linear}" + ], + "javascript": [ + "[class]{}-[func]{linear}" + ], + "typescript": [ + "[class]{}-[func]{linear}" + ], + "dart": [ + "[class]{}-[func]{linear}" + ], + "rust": [ + "[class]{}-[func]{linear}" + ], + "c": [ + "[class]{}-[func]{linear}" + ], + "kotlin": [ + "[class]{}-[func]{linear}" + ], + "ruby": [ + "[class]{}-[func]{linear}" + ], + "zig": [ + "[class]{}-[func]{linear}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{array_traversal}": { + "python": [ + "[class]{}-[func]{array_traversal}" + ], + "cpp": [ + "[class]{}-[func]{arrayTraversal}" + ], + "java": [ + "[class]{time_complexity}-[func]{arrayTraversal}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{ArrayTraversal}" + ], + "go": [ + "[class]{}-[func]{arrayTraversal}" + ], + "swift": [ + "[class]{}-[func]{arrayTraversal}" + ], + "javascript": [ + "[class]{}-[func]{arrayTraversal}" + ], + "typescript": [ + "[class]{}-[func]{arrayTraversal}" + ], + "dart": [ + "[class]{}-[func]{arrayTraversal}" + ], + "rust": [ + "[class]{}-[func]{array_traversal}" + ], + "c": [ + "[class]{}-[func]{arrayTraversal}" + ], + "kotlin": [ + "[class]{}-[func]{arrayTraversal}" + ], + "ruby": [ + "[class]{}-[func]{array_traversal}" + ], + "zig": [ + "[class]{}-[func]{arrayTraversal}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{quadratic}": { + "python": [ + "[class]{}-[func]{quadratic}" + ], + "cpp": [ + "[class]{}-[func]{quadratic}" + ], + "java": [ + "[class]{time_complexity}-[func]{quadratic}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{Quadratic}" + ], + "go": [ + "[class]{}-[func]{quadratic}" + ], + "swift": [ + "[class]{}-[func]{quadratic}" + ], + "javascript": [ + "[class]{}-[func]{quadratic}" + ], + "typescript": [ + "[class]{}-[func]{quadratic}" + ], + "dart": [ + "[class]{}-[func]{quadratic}" + ], + "rust": [ + "[class]{}-[func]{quadratic}" + ], + "c": [ + "[class]{}-[func]{quadratic}" + ], + "kotlin": [ + "[class]{}-[func]{quadratic}" + ], + "ruby": [ + "[class]{}-[func]{quadratic}" + ], + "zig": [ + "[class]{}-[func]{quadratic}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{bubble_sort}": { + "python": [ + "[class]{}-[func]{bubble_sort}" + ], + "cpp": [ + "[class]{}-[func]{bubbleSort}" + ], + "java": [ + "[class]{time_complexity}-[func]{bubbleSort}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{BubbleSort}" + ], + "go": [ + "[class]{}-[func]{bubbleSort}" + ], + "swift": [ + "[class]{}-[func]{bubbleSort}" + ], + "javascript": [ + "[class]{}-[func]{bubbleSort}" + ], + "typescript": [ + "[class]{}-[func]{bubbleSort}" + ], + "dart": [ + "[class]{}-[func]{bubbleSort}" + ], + "rust": [ + "[class]{}-[func]{bubble_sort}" + ], + "c": [ + "[class]{}-[func]{bubbleSort}" + ], + "kotlin": [ + "[class]{}-[func]{bubbleSort}" + ], + "ruby": [ + "[class]{}-[func]{bubble_sort}" + ], + "zig": [ + "[class]{}-[func]{bubbleSort}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{exponential}": { + "python": [ + "[class]{}-[func]{exponential}" + ], + "cpp": [ + "[class]{}-[func]{exponential}" + ], + "java": [ + "[class]{time_complexity}-[func]{exponential}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{Exponential}" + ], + "go": [ + "[class]{}-[func]{exponential}" + ], + "swift": [ + "[class]{}-[func]{exponential}" + ], + "javascript": [ + "[class]{}-[func]{exponential}" + ], + "typescript": [ + "[class]{}-[func]{exponential}" + ], + "dart": [ + "[class]{}-[func]{exponential}" + ], + "rust": [ + "[class]{}-[func]{exponential}" + ], + "c": [ + "[class]{}-[func]{exponential}" + ], + "kotlin": [ + "[class]{}-[func]{exponential}" + ], + "ruby": [ + "[class]{}-[func]{exponential}" + ], + "zig": [ + "[class]{}-[func]{exponential}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{exp_recur}": { + "python": [ + "[class]{}-[func]{exp_recur}" + ], + "cpp": [ + "[class]{}-[func]{expRecur}" + ], + "java": [ + "[class]{time_complexity}-[func]{expRecur}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{ExpRecur}" + ], + "go": [ + "[class]{}-[func]{expRecur}" + ], + "swift": [ + "[class]{}-[func]{expRecur}" + ], + "javascript": [ + "[class]{}-[func]{expRecur}" + ], + "typescript": [ + "[class]{}-[func]{expRecur}" + ], + "dart": [ + "[class]{}-[func]{expRecur}" + ], + "rust": [ + "[class]{}-[func]{exp_recur}" + ], + "c": [ + "[class]{}-[func]{expRecur}" + ], + "kotlin": [ + "[class]{}-[func]{expRecur}" + ], + "ruby": [ + "[class]{}-[func]{exp_recur}" + ], + "zig": [ + "[class]{}-[func]{expRecur}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{logarithmic}": { + "python": [ + "[class]{}-[func]{logarithmic}" + ], + "cpp": [ + "[class]{}-[func]{logarithmic}" + ], + "java": [ + "[class]{time_complexity}-[func]{logarithmic}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{Logarithmic}" + ], + "go": [ + "[class]{}-[func]{logarithmic}" + ], + "swift": [ + "[class]{}-[func]{logarithmic}" + ], + "javascript": [ + "[class]{}-[func]{logarithmic}" + ], + "typescript": [ + "[class]{}-[func]{logarithmic}" + ], + "dart": [ + "[class]{}-[func]{logarithmic}" + ], + "rust": [ + "[class]{}-[func]{logarithmic}" + ], + "c": [ + "[class]{}-[func]{logarithmic}" + ], + "kotlin": [ + "[class]{}-[func]{logarithmic}" + ], + "ruby": [ + "[class]{}-[func]{logarithmic}" + ], + "zig": [ + "[class]{}-[func]{logarithmic}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{log_recur}": { + "python": [ + "[class]{}-[func]{log_recur}" + ], + "cpp": [ + "[class]{}-[func]{logRecur}" + ], + "java": [ + "[class]{time_complexity}-[func]{logRecur}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{LogRecur}" + ], + "go": [ + "[class]{}-[func]{logRecur}" + ], + "swift": [ + "[class]{}-[func]{logRecur}" + ], + "javascript": [ + "[class]{}-[func]{logRecur}" + ], + "typescript": [ + "[class]{}-[func]{logRecur}" + ], + "dart": [ + "[class]{}-[func]{logRecur}" + ], + "rust": [ + "[class]{}-[func]{log_recur}" + ], + "c": [ + "[class]{}-[func]{logRecur}" + ], + "kotlin": [ + "[class]{}-[func]{logRecur}" + ], + "ruby": [ + "[class]{}-[func]{log_recur}" + ], + "zig": [ + "[class]{}-[func]{logRecur}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{linear_log_recur}": { + "python": [ + "[class]{}-[func]{linear_log_recur}" + ], + "cpp": [ + "[class]{}-[func]{linearLogRecur}" + ], + "java": [ + "[class]{time_complexity}-[func]{linearLogRecur}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{LinearLogRecur}" + ], + "go": [ + "[class]{}-[func]{linearLogRecur}" + ], + "swift": [ + "[class]{}-[func]{linearLogRecur}" + ], + "javascript": [ + "[class]{}-[func]{linearLogRecur}" + ], + "typescript": [ + "[class]{}-[func]{linearLogRecur}" + ], + "dart": [ + "[class]{}-[func]{linearLogRecur}" + ], + "rust": [ + "[class]{}-[func]{linear_log_recur}" + ], + "c": [ + "[class]{}-[func]{linearLogRecur}" + ], + "kotlin": [ + "[class]{}-[func]{linearLogRecur}" + ], + "ruby": [ + "[class]{}-[func]{linear_log_recur}" + ], + "zig": [ + "[class]{}-[func]{linearLogRecur}" + ] + }, + "[file]{time_complexity}-[class]{}-[func]{factorial_recur}": { + "python": [ + "[class]{}-[func]{factorial_recur}" + ], + "cpp": [ + "[class]{}-[func]{factorialRecur}" + ], + "java": [ + "[class]{time_complexity}-[func]{factorialRecur}" + ], + "csharp": [ + "[class]{time_complexity}-[func]{FactorialRecur}" + ], + "go": [ + "[class]{}-[func]{factorialRecur}" + ], + "swift": [ + "[class]{}-[func]{factorialRecur}" + ], + "javascript": [ + "[class]{}-[func]{factorialRecur}" + ], + "typescript": [ + "[class]{}-[func]{factorialRecur}" + ], + "dart": [ + "[class]{}-[func]{factorialRecur}" + ], + "rust": [ + "[class]{}-[func]{factorial_recur}" + ], + "c": [ + "[class]{}-[func]{factorialRecur}" + ], + "kotlin": [ + "[class]{}-[func]{factorialRecur}" + ], + "ruby": [ + "[class]{}-[func]{factorial_recur}" + ], + "zig": [ + "[class]{}-[func]{factorialRecur}" + ] + }, + "[file]{worst_best_time_complexity}-[class]{}-[func]{find_one}": { + "python": [ + "[class]{}-[func]{random_numbers}", + "[class]{}-[func]{find_one}" + ], + "cpp": [ + "[class]{}-[func]{randomNumbers}", + "[class]{}-[func]{findOne}" + ], + "java": [ + "[class]{worst_best_time_complexity}-[func]{randomNumbers}", + "[class]{worst_best_time_complexity}-[func]{findOne}" + ], + "csharp": [ + "[class]{worst_best_time_complexity}-[func]{RandomNumbers}", + "[class]{worst_best_time_complexity}-[func]{FindOne}" + ], + "go": [ + "[class]{}-[func]{randomNumbers}", + "[class]{}-[func]{findOne}" + ], + "swift": [ + "[class]{}-[func]{randomNumbers}", + "[class]{}-[func]{findOne}" + ], + "javascript": [ + "[class]{}-[func]{randomNumbers}", + "[class]{}-[func]{findOne}" + ], + "typescript": [ + "[class]{}-[func]{randomNumbers}", + "[class]{}-[func]{findOne}" + ], + "dart": [ + "[class]{}-[func]{randomNumbers}", + "[class]{}-[func]{findOne}" + ], + "rust": [ + "[class]{}-[func]{random_numbers}", + "[class]{}-[func]{find_one}" + ], + "c": [ + "[class]{}-[func]{randomNumbers}", + "[class]{}-[func]{findOne}" + ], + "kotlin": [ + "[class]{}-[func]{randomNumbers}", + "[class]{}-[func]{findOne}" + ], + "ruby": [ + "[class]{}-[func]{random_numbers}", + "[class]{}-[func]{find_one}" + ], + "zig": [ + "[class]{}-[func]{randomNumbers}", + "[class]{}-[func]{findOne}" + ] + } + }, + "chapter_data_structure": {}, + "chapter_divide_and_conquer": { + "[file]{fast_power}-[class]{}-[func]{fast_pow}": { + "python": [ + "[class]{}-[func]{fast_pow}" + ], + "cpp": [ + "[class]{}-[func]{fastPow}" + ], + "java": [ + "[class]{fast_power}-[func]{fastPow}" + ], + "csharp": [ + "[class]{fast_power}-[func]{FastPow}" + ], + "go": [ + "[class]{}-[func]{fastPow}" + ], + "swift": [ + "[class]{}-[func]{fastPow}" + ], + "javascript": [ + "[class]{}-[func]{fastPow}" + ], + "typescript": [ + "[class]{}-[func]{fastPow}" + ], + "dart": [ + "[class]{}-[func]{fastPow}" + ], + "rust": [ + "[class]{}-[func]{fast_pow}" + ], + "c": [ + "[class]{}-[func]{fastPow}" + ], + "kotlin": [ + "[class]{}-[func]{fastPow}" + ], + "ruby": [ + "[class]{}-[func]{fast_pow}" + ] + }, + "[file]{binary_search_recur}-[class]{}-[func]{binary_search}": { + "python": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binary_search}" + ], + "cpp": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binarySearch}" + ], + "java": [ + "[class]{binary_search_recur}-[func]{dfs}", + "[class]{binary_search_recur}-[func]{binarySearch}" + ], + "csharp": [ + "[class]{binary_search_recur}-[func]{DFS}", + "[class]{binary_search_recur}-[func]{BinarySearch}" + ], + "go": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binarySearch}" + ], + "swift": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binarySearch}" + ], + "javascript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binarySearch}" + ], + "typescript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binarySearch}" + ], + "dart": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binarySearch}" + ], + "rust": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binary_search}" + ], + "c": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binarySearch}" + ], + "kotlin": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binarySearch}" + ], + "ruby": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{binary_search}" + ] + }, + "[file]{build_tree}-[class]{}-[func]{build_tree}": { + "python": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{build_tree}" + ], + "cpp": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{buildTree}" + ], + "java": [ + "[class]{build_tree}-[func]{dfs}", + "[class]{build_tree}-[func]{buildTree}" + ], + "csharp": [ + "[class]{build_tree}-[func]{DFS}", + "[class]{build_tree}-[func]{BuildTree}" + ], + "go": [ + "[class]{}-[func]{dfsBuildTree}", + "[class]{}-[func]{buildTree}" + ], + "swift": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{buildTree}" + ], + "javascript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{buildTree}" + ], + "typescript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{buildTree}" + ], + "dart": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{buildTree}" + ], + "rust": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{build_tree}" + ], + "c": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{buildTree}" + ], + "kotlin": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{buildTree}" + ], + "ruby": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{build_tree}" + ] + }, + "[file]{hanota}-[class]{}-[func]{solve_hanota}": { + "python": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solve_hanota}" + ], + "cpp": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solveHanota}" + ], + "java": [ + "[class]{hanota}-[func]{move}", + "[class]{hanota}-[func]{dfs}", + "[class]{hanota}-[func]{solveHanota}" + ], + "csharp": [ + "[class]{hanota}-[func]{Move}", + "[class]{hanota}-[func]{DFS}", + "[class]{hanota}-[func]{SolveHanota}" + ], + "go": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfsHanota}", + "[class]{}-[func]{solveHanota}" + ], + "swift": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solveHanota}" + ], + "javascript": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solveHanota}" + ], + "typescript": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solveHanota}" + ], + "dart": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solveHanota}" + ], + "rust": [ + "[class]{}-[func]{move_pan}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solve_hanota}" + ], + "c": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solveHanota}" + ], + "kotlin": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solveHanota}" + ], + "ruby": [ + "[class]{}-[func]{move}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{solve_hanota}" + ] + } + }, + "chapter_dynamic_programming": { + "[file]{min_cost_climbing_stairs_dp}-[class]{}-[func]{min_cost_climbing_stairs_dp}": { + "python": [ + "[class]{}-[func]{min_cost_climbing_stairs_dp}" + ], + "cpp": [ + "[class]{}-[func]{minCostClimbingStairsDP}" + ], + "java": [ + "[class]{min_cost_climbing_stairs_dp}-[func]{minCostClimbingStairsDP}" + ], + "csharp": [ + "[class]{min_cost_climbing_stairs_dp}-[func]{MinCostClimbingStairsDP}" + ], + "go": [ + "[class]{}-[func]{minCostClimbingStairsDP}" + ], + "swift": [ + "[class]{}-[func]{minCostClimbingStairsDP}" + ], + "javascript": [ + "[class]{}-[func]{minCostClimbingStairsDP}" + ], + "typescript": [ + "[class]{}-[func]{minCostClimbingStairsDP}" + ], + "dart": [ + "[class]{}-[func]{minCostClimbingStairsDP}" + ], + "rust": [ + "[class]{}-[func]{min_cost_climbing_stairs_dp}" + ], + "c": [ + "[class]{}-[func]{minCostClimbingStairsDP}" + ], + "kotlin": [ + "[class]{}-[func]{minCostClimbingStairsDP}" + ], + "ruby": [ + "[class]{}-[func]{min_cost_climbing_stairs_dp}" + ] + }, + "[file]{min_cost_climbing_stairs_dp}-[class]{}-[func]{min_cost_climbing_stairs_dp_comp}": { + "python": [ + "[class]{}-[func]{min_cost_climbing_stairs_dp_comp}" + ], + "cpp": [ + "[class]{}-[func]{minCostClimbingStairsDPComp}" + ], + "java": [ + "[class]{min_cost_climbing_stairs_dp}-[func]{minCostClimbingStairsDPComp}" + ], + "csharp": [ + "[class]{min_cost_climbing_stairs_dp}-[func]{MinCostClimbingStairsDPComp}" + ], + "go": [ + "[class]{}-[func]{minCostClimbingStairsDPComp}" + ], + "swift": [ + "[class]{}-[func]{minCostClimbingStairsDPComp}" + ], + "javascript": [ + "[class]{}-[func]{minCostClimbingStairsDPComp}" + ], + "typescript": [ + "[class]{}-[func]{minCostClimbingStairsDPComp}" + ], + "dart": [ + "[class]{}-[func]{minCostClimbingStairsDPComp}" + ], + "rust": [ + "[class]{}-[func]{min_cost_climbing_stairs_dp_comp}" + ], + "c": [ + "[class]{}-[func]{minCostClimbingStairsDPComp}" + ], + "kotlin": [ + "[class]{}-[func]{minCostClimbingStairsDPComp}" + ], + "ruby": [ + "[class]{}-[func]{min_cost_climbing_stairs_dp_comp}" + ] + }, + "[file]{climbing_stairs_constraint_dp}-[class]{}-[func]{climbing_stairs_constraint_dp}": { + "python": [ + "[class]{}-[func]{climbing_stairs_constraint_dp}" + ], + "cpp": [ + "[class]{}-[func]{climbingStairsConstraintDP}" + ], + "java": [ + "[class]{climbing_stairs_constraint_dp}-[func]{climbingStairsConstraintDP}" + ], + "csharp": [ + "[class]{climbing_stairs_constraint_dp}-[func]{ClimbingStairsConstraintDP}" + ], + "go": [ + "[class]{}-[func]{climbingStairsConstraintDP}" + ], + "swift": [ + "[class]{}-[func]{climbingStairsConstraintDP}" + ], + "javascript": [ + "[class]{}-[func]{climbingStairsConstraintDP}" + ], + "typescript": [ + "[class]{}-[func]{climbingStairsConstraintDP}" + ], + "dart": [ + "[class]{}-[func]{climbingStairsConstraintDP}" + ], + "rust": [ + "[class]{}-[func]{climbing_stairs_constraint_dp}" + ], + "c": [ + "[class]{}-[func]{climbingStairsConstraintDP}" + ], + "kotlin": [ + "[class]{}-[func]{climbingStairsConstraintDP}" + ], + "ruby": [ + "[class]{}-[func]{climbing_stairs_constraint_dp}" + ] + }, + "[file]{min_path_sum}-[class]{}-[func]{min_path_sum_dfs}": { + "python": [ + "[class]{}-[func]{min_path_sum_dfs}" + ], + "cpp": [ + "[class]{}-[func]{minPathSumDFS}" + ], + "java": [ + "[class]{min_path_sum}-[func]{minPathSumDFS}" + ], + "csharp": [ + "[class]{min_path_sum}-[func]{MinPathSumDFS}" + ], + "go": [ + "[class]{}-[func]{minPathSumDFS}" + ], + "swift": [ + "[class]{}-[func]{minPathSumDFS}" + ], + "javascript": [ + "[class]{}-[func]{minPathSumDFS}" + ], + "typescript": [ + "[class]{}-[func]{minPathSumDFS}" + ], + "dart": [ + "[class]{}-[func]{minPathSumDFS}" + ], + "rust": [ + "[class]{}-[func]{min_path_sum_dfs}" + ], + "c": [ + "[class]{}-[func]{minPathSumDFS}" + ], + "kotlin": [ + "[class]{}-[func]{minPathSumDFS}" + ], + "ruby": [ + "[class]{}-[func]{min_path_sum_dfs}" + ] + }, + "[file]{min_path_sum}-[class]{}-[func]{min_path_sum_dfs_mem}": { + "python": [ + "[class]{}-[func]{min_path_sum_dfs_mem}" + ], + "cpp": [ + "[class]{}-[func]{minPathSumDFSMem}" + ], + "java": [ + "[class]{min_path_sum}-[func]{minPathSumDFSMem}" + ], + "csharp": [ + "[class]{min_path_sum}-[func]{MinPathSumDFSMem}" + ], + "go": [ + "[class]{}-[func]{minPathSumDFSMem}" + ], + "swift": [ + "[class]{}-[func]{minPathSumDFSMem}" + ], + "javascript": [ + "[class]{}-[func]{minPathSumDFSMem}" + ], + "typescript": [ + "[class]{}-[func]{minPathSumDFSMem}" + ], + "dart": [ + "[class]{}-[func]{minPathSumDFSMem}" + ], + "rust": [ + "[class]{}-[func]{min_path_sum_dfs_mem}" + ], + "c": [ + "[class]{}-[func]{minPathSumDFSMem}" + ], + "kotlin": [ + "[class]{}-[func]{minPathSumDFSMem}" + ], + "ruby": [ + "[class]{}-[func]{min_path_sum_dfs_mem}" + ] + }, + "[file]{min_path_sum}-[class]{}-[func]{min_path_sum_dp}": { + "python": [ + "[class]{}-[func]{min_path_sum_dp}" + ], + "cpp": [ + "[class]{}-[func]{minPathSumDP}" + ], + "java": [ + "[class]{min_path_sum}-[func]{minPathSumDP}" + ], + "csharp": [ + "[class]{min_path_sum}-[func]{MinPathSumDP}" + ], + "go": [ + "[class]{}-[func]{minPathSumDP}" + ], + "swift": [ + "[class]{}-[func]{minPathSumDP}" + ], + "javascript": [ + "[class]{}-[func]{minPathSumDP}" + ], + "typescript": [ + "[class]{}-[func]{minPathSumDP}" + ], + "dart": [ + "[class]{}-[func]{minPathSumDP}" + ], + "rust": [ + "[class]{}-[func]{min_path_sum_dp}" + ], + "c": [ + "[class]{}-[func]{minPathSumDP}" + ], + "kotlin": [ + "[class]{}-[func]{minPathSumDP}" + ], + "ruby": [ + "[class]{}-[func]{min_path_sum_dp}" + ] + }, + "[file]{min_path_sum}-[class]{}-[func]{min_path_sum_dp_comp}": { + "python": [ + "[class]{}-[func]{min_path_sum_dp_comp}" + ], + "cpp": [ + "[class]{}-[func]{minPathSumDPComp}" + ], + "java": [ + "[class]{min_path_sum}-[func]{minPathSumDPComp}" + ], + "csharp": [ + "[class]{min_path_sum}-[func]{MinPathSumDPComp}" + ], + "go": [ + "[class]{}-[func]{minPathSumDPComp}" + ], + "swift": [ + "[class]{}-[func]{minPathSumDPComp}" + ], + "javascript": [ + "[class]{}-[func]{minPathSumDPComp}" + ], + "typescript": [ + "[class]{}-[func]{minPathSumDPComp}" + ], + "dart": [ + "[class]{}-[func]{minPathSumDPComp}" + ], + "rust": [ + "[class]{}-[func]{min_path_sum_dp_comp}" + ], + "c": [ + "[class]{}-[func]{minPathSumDPComp}" + ], + "kotlin": [ + "[class]{}-[func]{minPathSumDPComp}" + ], + "ruby": [ + "[class]{}-[func]{min_path_sum_dp_comp}" + ] + }, + "[file]{edit_distance}-[class]{}-[func]{edit_distance_dp}": { + "python": [ + "[class]{}-[func]{edit_distance_dp}" + ], + "cpp": [ + "[class]{}-[func]{editDistanceDP}" + ], + "java": [ + "[class]{edit_distance}-[func]{editDistanceDP}" + ], + "csharp": [ + "[class]{edit_distance}-[func]{EditDistanceDP}" + ], + "go": [ + "[class]{}-[func]{editDistanceDP}" + ], + "swift": [ + "[class]{}-[func]{editDistanceDP}" + ], + "javascript": [ + "[class]{}-[func]{editDistanceDP}" + ], + "typescript": [ + "[class]{}-[func]{editDistanceDP}" + ], + "dart": [ + "[class]{}-[func]{editDistanceDP}" + ], + "rust": [ + "[class]{}-[func]{edit_distance_dp}" + ], + "c": [ + "[class]{}-[func]{editDistanceDP}" + ], + "kotlin": [ + "[class]{}-[func]{editDistanceDP}" + ], + "ruby": [ + "[class]{}-[func]{edit_distance_dp}" + ] + }, + "[file]{edit_distance}-[class]{}-[func]{edit_distance_dp_comp}": { + "python": [ + "[class]{}-[func]{edit_distance_dp_comp}" + ], + "cpp": [ + "[class]{}-[func]{editDistanceDPComp}" + ], + "java": [ + "[class]{edit_distance}-[func]{editDistanceDPComp}" + ], + "csharp": [ + "[class]{edit_distance}-[func]{EditDistanceDPComp}" + ], + "go": [ + "[class]{}-[func]{editDistanceDPComp}" + ], + "swift": [ + "[class]{}-[func]{editDistanceDPComp}" + ], + "javascript": [ + "[class]{}-[func]{editDistanceDPComp}" + ], + "typescript": [ + "[class]{}-[func]{editDistanceDPComp}" + ], + "dart": [ + "[class]{}-[func]{editDistanceDPComp}" + ], + "rust": [ + "[class]{}-[func]{edit_distance_dp_comp}" + ], + "c": [ + "[class]{}-[func]{editDistanceDPComp}" + ], + "kotlin": [ + "[class]{}-[func]{editDistanceDPComp}" + ], + "ruby": [ + "[class]{}-[func]{edit_distance_dp_comp}" + ] + }, + "[file]{climbing_stairs_backtrack}-[class]{}-[func]{climbing_stairs_backtrack}": { + "python": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbing_stairs_backtrack}" + ], + "cpp": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbingStairsBacktrack}" + ], + "java": [ + "[class]{climbing_stairs_backtrack}-[func]{backtrack}", + "[class]{climbing_stairs_backtrack}-[func]{climbingStairsBacktrack}" + ], + "csharp": [ + "[class]{climbing_stairs_backtrack}-[func]{Backtrack}", + "[class]{climbing_stairs_backtrack}-[func]{ClimbingStairsBacktrack}" + ], + "go": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbingStairsBacktrack}" + ], + "swift": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbingStairsBacktrack}" + ], + "javascript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbingStairsBacktrack}" + ], + "typescript": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbingStairsBacktrack}" + ], + "dart": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbingStairsBacktrack}" + ], + "rust": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbing_stairs_backtrack}" + ], + "c": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbingStairsBacktrack}" + ], + "kotlin": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbingStairsBacktrack}" + ], + "ruby": [ + "[class]{}-[func]{backtrack}", + "[class]{}-[func]{climbing_stairs_backtrack}" + ] + }, + "[file]{climbing_stairs_dfs}-[class]{}-[func]{climbing_stairs_dfs}": { + "python": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbing_stairs_dfs}" + ], + "cpp": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFS}" + ], + "java": [ + "[class]{climbing_stairs_dfs}-[func]{dfs}", + "[class]{climbing_stairs_dfs}-[func]{climbingStairsDFS}" + ], + "csharp": [ + "[class]{climbing_stairs_dfs}-[func]{DFS}", + "[class]{climbing_stairs_dfs}-[func]{ClimbingStairsDFS}" + ], + "go": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFS}" + ], + "swift": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFS}" + ], + "javascript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFS}" + ], + "typescript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFS}" + ], + "dart": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFS}" + ], + "rust": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbing_stairs_dfs}" + ], + "c": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFS}" + ], + "kotlin": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFS}" + ], + "ruby": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbing_stairs_dfs}" + ] + }, + "[file]{climbing_stairs_dfs_mem}-[class]{}-[func]{climbing_stairs_dfs_mem}": { + "python": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbing_stairs_dfs_mem}" + ], + "cpp": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFSMem}" + ], + "java": [ + "[class]{climbing_stairs_dfs_mem}-[func]{dfs}", + "[class]{climbing_stairs_dfs_mem}-[func]{climbingStairsDFSMem}" + ], + "csharp": [ + "[class]{climbing_stairs_dfs_mem}-[func]{DFS}", + "[class]{climbing_stairs_dfs_mem}-[func]{ClimbingStairsDFSMem}" + ], + "go": [ + "[class]{}-[func]{dfsMem}", + "[class]{}-[func]{climbingStairsDFSMem}" + ], + "swift": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFSMem}" + ], + "javascript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFSMem}" + ], + "typescript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFSMem}" + ], + "dart": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFSMem}" + ], + "rust": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbing_stairs_dfs_mem}" + ], + "c": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFSMem}" + ], + "kotlin": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbingStairsDFSMem}" + ], + "ruby": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{climbing_stairs_dfs_mem}" + ] + }, + "[file]{climbing_stairs_dp}-[class]{}-[func]{climbing_stairs_dp}": { + "python": [ + "[class]{}-[func]{climbing_stairs_dp}" + ], + "cpp": [ + "[class]{}-[func]{climbingStairsDP}" + ], + "java": [ + "[class]{climbing_stairs_dp}-[func]{climbingStairsDP}" + ], + "csharp": [ + "[class]{climbing_stairs_dp}-[func]{ClimbingStairsDP}" + ], + "go": [ + "[class]{}-[func]{climbingStairsDP}" + ], + "swift": [ + "[class]{}-[func]{climbingStairsDP}" + ], + "javascript": [ + "[class]{}-[func]{climbingStairsDP}" + ], + "typescript": [ + "[class]{}-[func]{climbingStairsDP}" + ], + "dart": [ + "[class]{}-[func]{climbingStairsDP}" + ], + "rust": [ + "[class]{}-[func]{climbing_stairs_dp}" + ], + "c": [ + "[class]{}-[func]{climbingStairsDP}" + ], + "kotlin": [ + "[class]{}-[func]{climbingStairsDP}" + ], + "ruby": [ + "[class]{}-[func]{climbing_stairs_dp}" + ] + }, + "[file]{climbing_stairs_dp}-[class]{}-[func]{climbing_stairs_dp_comp}": { + "python": [ + "[class]{}-[func]{climbing_stairs_dp_comp}" + ], + "cpp": [ + "[class]{}-[func]{climbingStairsDPComp}" + ], + "java": [ + "[class]{climbing_stairs_dp}-[func]{climbingStairsDPComp}" + ], + "csharp": [ + "[class]{climbing_stairs_dp}-[func]{ClimbingStairsDPComp}" + ], + "go": [ + "[class]{}-[func]{climbingStairsDPComp}" + ], + "swift": [ + "[class]{}-[func]{climbingStairsDPComp}" + ], + "javascript": [ + "[class]{}-[func]{climbingStairsDPComp}" + ], + "typescript": [ + "[class]{}-[func]{climbingStairsDPComp}" + ], + "dart": [ + "[class]{}-[func]{climbingStairsDPComp}" + ], + "rust": [ + "[class]{}-[func]{climbing_stairs_dp_comp}" + ], + "c": [ + "[class]{}-[func]{climbingStairsDPComp}" + ], + "kotlin": [ + "[class]{}-[func]{climbingStairsDPComp}" + ], + "ruby": [ + "[class]{}-[func]{climbing_stairs_dp_comp}" + ] + }, + "[file]{knapsack}-[class]{}-[func]{knapsack_dfs}": { + "python": [ + "[class]{}-[func]{knapsack_dfs}" + ], + "cpp": [ + "[class]{}-[func]{knapsackDFS}" + ], + "java": [ + "[class]{knapsack}-[func]{knapsackDFS}" + ], + "csharp": [ + "[class]{knapsack}-[func]{KnapsackDFS}" + ], + "go": [ + "[class]{}-[func]{knapsackDFS}" + ], + "swift": [ + "[class]{}-[func]{knapsackDFS}" + ], + "javascript": [ + "[class]{}-[func]{knapsackDFS}" + ], + "typescript": [ + "[class]{}-[func]{knapsackDFS}" + ], + "dart": [ + "[class]{}-[func]{knapsackDFS}" + ], + "rust": [ + "[class]{}-[func]{knapsack_dfs}" + ], + "c": [ + "[class]{}-[func]{knapsackDFS}" + ], + "kotlin": [ + "[class]{}-[func]{knapsackDFS}" + ], + "ruby": [ + "[class]{}-[func]{knapsack_dfs}" + ] + }, + "[file]{knapsack}-[class]{}-[func]{knapsack_dfs_mem}": { + "python": [ + "[class]{}-[func]{knapsack_dfs_mem}" + ], + "cpp": [ + "[class]{}-[func]{knapsackDFSMem}" + ], + "java": [ + "[class]{knapsack}-[func]{knapsackDFSMem}" + ], + "csharp": [ + "[class]{knapsack}-[func]{KnapsackDFSMem}" + ], + "go": [ + "[class]{}-[func]{knapsackDFSMem}" + ], + "swift": [ + "[class]{}-[func]{knapsackDFSMem}" + ], + "javascript": [ + "[class]{}-[func]{knapsackDFSMem}" + ], + "typescript": [ + "[class]{}-[func]{knapsackDFSMem}" + ], + "dart": [ + "[class]{}-[func]{knapsackDFSMem}" + ], + "rust": [ + "[class]{}-[func]{knapsack_dfs_mem}" + ], + "c": [ + "[class]{}-[func]{knapsackDFSMem}" + ], + "kotlin": [ + "[class]{}-[func]{knapsackDFSMem}" + ], + "ruby": [ + "[class]{}-[func]{knapsack_dfs_mem}" + ] + }, + "[file]{knapsack}-[class]{}-[func]{knapsack_dp}": { + "python": [ + "[class]{}-[func]{knapsack_dp}" + ], + "cpp": [ + "[class]{}-[func]{knapsackDP}" + ], + "java": [ + "[class]{knapsack}-[func]{knapsackDP}" + ], + "csharp": [ + "[class]{knapsack}-[func]{KnapsackDP}" + ], + "go": [ + "[class]{}-[func]{knapsackDP}" + ], + "swift": [ + "[class]{}-[func]{knapsackDP}" + ], + "javascript": [ + "[class]{}-[func]{knapsackDP}" + ], + "typescript": [ + "[class]{}-[func]{knapsackDP}" + ], + "dart": [ + "[class]{}-[func]{knapsackDP}" + ], + "rust": [ + "[class]{}-[func]{knapsack_dp}" + ], + "c": [ + "[class]{}-[func]{knapsackDP}" + ], + "kotlin": [ + "[class]{}-[func]{knapsackDP}" + ], + "ruby": [ + "[class]{}-[func]{knapsack_dp}" + ] + }, + "[file]{knapsack}-[class]{}-[func]{knapsack_dp_comp}": { + "python": [ + "[class]{}-[func]{knapsack_dp_comp}" + ], + "cpp": [ + "[class]{}-[func]{knapsackDPComp}" + ], + "java": [ + "[class]{knapsack}-[func]{knapsackDPComp}" + ], + "csharp": [ + "[class]{knapsack}-[func]{KnapsackDPComp}" + ], + "go": [ + "[class]{}-[func]{knapsackDPComp}" + ], + "swift": [ + "[class]{}-[func]{knapsackDPComp}" + ], + "javascript": [ + "[class]{}-[func]{knapsackDPComp}" + ], + "typescript": [ + "[class]{}-[func]{knapsackDPComp}" + ], + "dart": [ + "[class]{}-[func]{knapsackDPComp}" + ], + "rust": [ + "[class]{}-[func]{knapsack_dp_comp}" + ], + "c": [ + "[class]{}-[func]{knapsackDPComp}" + ], + "kotlin": [ + "[class]{}-[func]{knapsackDPComp}" + ], + "ruby": [ + "[class]{}-[func]{knapsack_dp_comp}" + ] + }, + "[file]{unbounded_knapsack}-[class]{}-[func]{unbounded_knapsack_dp}": { + "python": [ + "[class]{}-[func]{unbounded_knapsack_dp}" + ], + "cpp": [ + "[class]{}-[func]{unboundedKnapsackDP}" + ], + "java": [ + "[class]{unbounded_knapsack}-[func]{unboundedKnapsackDP}" + ], + "csharp": [ + "[class]{unbounded_knapsack}-[func]{UnboundedKnapsackDP}" + ], + "go": [ + "[class]{}-[func]{unboundedKnapsackDP}" + ], + "swift": [ + "[class]{}-[func]{unboundedKnapsackDP}" + ], + "javascript": [ + "[class]{}-[func]{unboundedKnapsackDP}" + ], + "typescript": [ + "[class]{}-[func]{unboundedKnapsackDP}" + ], + "dart": [ + "[class]{}-[func]{unboundedKnapsackDP}" + ], + "rust": [ + "[class]{}-[func]{unbounded_knapsack_dp}" + ], + "c": [ + "[class]{}-[func]{unboundedKnapsackDP}" + ], + "kotlin": [ + "[class]{}-[func]{unboundedKnapsackDP}" + ], + "ruby": [ + "[class]{}-[func]{unbounded_knapsack_dp}" + ] + }, + "[file]{unbounded_knapsack}-[class]{}-[func]{unbounded_knapsack_dp_comp}": { + "python": [ + "[class]{}-[func]{unbounded_knapsack_dp_comp}" + ], + "cpp": [ + "[class]{}-[func]{unboundedKnapsackDPComp}" + ], + "java": [ + "[class]{unbounded_knapsack}-[func]{unboundedKnapsackDPComp}" + ], + "csharp": [ + "[class]{unbounded_knapsack}-[func]{UnboundedKnapsackDPComp}" + ], + "go": [ + "[class]{}-[func]{unboundedKnapsackDPComp}" + ], + "swift": [ + "[class]{}-[func]{unboundedKnapsackDPComp}" + ], + "javascript": [ + "[class]{}-[func]{unboundedKnapsackDPComp}" + ], + "typescript": [ + "[class]{}-[func]{unboundedKnapsackDPComp}" + ], + "dart": [ + "[class]{}-[func]{unboundedKnapsackDPComp}" + ], + "rust": [ + "[class]{}-[func]{unbounded_knapsack_dp_comp}" + ], + "c": [ + "[class]{}-[func]{unboundedKnapsackDPComp}" + ], + "kotlin": [ + "[class]{}-[func]{unboundedKnapsackDPComp}" + ], + "ruby": [ + "[class]{}-[func]{unbounded_knapsack_dp_comp}" + ] + }, + "[file]{coin_change}-[class]{}-[func]{coin_change_dp}": { + "python": [ + "[class]{}-[func]{coin_change_dp}" + ], + "cpp": [ + "[class]{}-[func]{coinChangeDP}" + ], + "java": [ + "[class]{coin_change}-[func]{coinChangeDP}" + ], + "csharp": [ + "[class]{coin_change}-[func]{CoinChangeDP}" + ], + "go": [ + "[class]{}-[func]{coinChangeDP}" + ], + "swift": [ + "[class]{}-[func]{coinChangeDP}" + ], + "javascript": [ + "[class]{}-[func]{coinChangeDP}" + ], + "typescript": [ + "[class]{}-[func]{coinChangeDP}" + ], + "dart": [ + "[class]{}-[func]{coinChangeDP}" + ], + "rust": [ + "[class]{}-[func]{coin_change_dp}" + ], + "c": [ + "[class]{}-[func]{coinChangeDP}" + ], + "kotlin": [ + "[class]{}-[func]{coinChangeDP}" + ], + "ruby": [ + "[class]{}-[func]{coin_change_dp}" + ] + }, + "[file]{coin_change}-[class]{}-[func]{coin_change_dp_comp}": { + "python": [ + "[class]{}-[func]{coin_change_dp_comp}" + ], + "cpp": [ + "[class]{}-[func]{coinChangeDPComp}" + ], + "java": [ + "[class]{coin_change}-[func]{coinChangeDPComp}" + ], + "csharp": [ + "[class]{coin_change}-[func]{CoinChangeDPComp}" + ], + "go": [ + "[class]{}-[func]{coinChangeDPComp}" + ], + "swift": [ + "[class]{}-[func]{coinChangeDPComp}" + ], + "javascript": [ + "[class]{}-[func]{coinChangeDPComp}" + ], + "typescript": [ + "[class]{}-[func]{coinChangeDPComp}" + ], + "dart": [ + "[class]{}-[func]{coinChangeDPComp}" + ], + "rust": [ + "[class]{}-[func]{coin_change_dp_comp}" + ], + "c": [ + "[class]{}-[func]{coinChangeDPComp}" + ], + "kotlin": [ + "[class]{}-[func]{coinChangeDPComp}" + ], + "ruby": [ + "[class]{}-[func]{coin_change_dp_comp}" + ] + }, + "[file]{coin_change_ii}-[class]{}-[func]{coin_change_ii_dp}": { + "python": [ + "[class]{}-[func]{coin_change_ii_dp}" + ], + "cpp": [ + "[class]{}-[func]{coinChangeIIDP}" + ], + "java": [ + "[class]{coin_change_ii}-[func]{coinChangeIIDP}" + ], + "csharp": [ + "[class]{coin_change_ii}-[func]{CoinChangeIIDP}" + ], + "go": [ + "[class]{}-[func]{coinChangeIIDP}" + ], + "swift": [ + "[class]{}-[func]{coinChangeIIDP}" + ], + "javascript": [ + "[class]{}-[func]{coinChangeIIDP}" + ], + "typescript": [ + "[class]{}-[func]{coinChangeIIDP}" + ], + "dart": [ + "[class]{}-[func]{coinChangeIIDP}" + ], + "rust": [ + "[class]{}-[func]{coin_change_ii_dp}" + ], + "c": [ + "[class]{}-[func]{coinChangeIIDP}" + ], + "kotlin": [ + "[class]{}-[func]{coinChangeIIDP}" + ], + "ruby": [ + "[class]{}-[func]{coin_change_ii_dp}" + ] + }, + "[file]{coin_change_ii}-[class]{}-[func]{coin_change_ii_dp_comp}": { + "python": [ + "[class]{}-[func]{coin_change_ii_dp_comp}" + ], + "cpp": [ + "[class]{}-[func]{coinChangeIIDPComp}" + ], + "java": [ + "[class]{coin_change_ii}-[func]{coinChangeIIDPComp}" + ], + "csharp": [ + "[class]{coin_change_ii}-[func]{CoinChangeIIDPComp}" + ], + "go": [ + "[class]{}-[func]{coinChangeIIDPComp}" + ], + "swift": [ + "[class]{}-[func]{coinChangeIIDPComp}" + ], + "javascript": [ + "[class]{}-[func]{coinChangeIIDPComp}" + ], + "typescript": [ + "[class]{}-[func]{coinChangeIIDPComp}" + ], + "dart": [ + "[class]{}-[func]{coinChangeIIDPComp}" + ], + "rust": [ + "[class]{}-[func]{coin_change_ii_dp_comp}" + ], + "c": [ + "[class]{}-[func]{coinChangeIIDPComp}" + ], + "kotlin": [ + "[class]{}-[func]{coinChangeIIDPComp}" + ], + "ruby": [ + "[class]{}-[func]{coin_change_ii_dp_comp}" + ] + } + }, + "chapter_graph": { + "[file]{graph_adjacency_matrix}-[class]{graph_adj_mat}-[func]{}": { + "python": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "cpp": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "java": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "csharp": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "go": [ + "[class]{graphAdjMat}-[func]{}" + ], + "swift": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "javascript": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "typescript": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "dart": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "rust": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "c": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "kotlin": [ + "[class]{GraphAdjMat}-[func]{}" + ], + "ruby": [ + "[class]{GraphAdjMat}-[func]{}" + ] + }, + "[file]{graph_adjacency_list}-[class]{graph_adj_list}-[func]{}": { + "python": [ + "[class]{GraphAdjList}-[func]{}" + ], + "cpp": [ + "[class]{GraphAdjList}-[func]{}" + ], + "java": [ + "[class]{GraphAdjList}-[func]{}" + ], + "csharp": [ + "[class]{GraphAdjList}-[func]{}" + ], + "go": [ + "[class]{graphAdjList}-[func]{}" + ], + "swift": [ + "[class]{GraphAdjList}-[func]{}" + ], + "javascript": [ + "[class]{GraphAdjList}-[func]{}" + ], + "typescript": [ + "[class]{GraphAdjList}-[func]{}" + ], + "dart": [ + "[class]{GraphAdjList}-[func]{}" + ], + "rust": [ + "[class]{GraphAdjList}-[func]{}" + ], + "c": [ + "[class]{AdjListNode}-[func]{}", + "[class]{GraphAdjList}-[func]{}" + ], + "kotlin": [ + "[class]{GraphAdjList}-[func]{}" + ], + "ruby": [ + "[class]{GraphAdjList}-[func]{}" + ] + }, + "[file]{graph_bfs}-[class]{}-[func]{graph_bfs}": { + "python": [ + "[class]{}-[func]{graph_bfs}" + ], + "cpp": [ + "[class]{}-[func]{graphBFS}" + ], + "java": [ + "[class]{graph_bfs}-[func]{graphBFS}" + ], + "csharp": [ + "[class]{graph_bfs}-[func]{GraphBFS}" + ], + "go": [ + "[class]{}-[func]{graphBFS}" + ], + "swift": [ + "[class]{}-[func]{graphBFS}" + ], + "javascript": [ + "[class]{}-[func]{graphBFS}" + ], + "typescript": [ + "[class]{}-[func]{graphBFS}" + ], + "dart": [ + "[class]{}-[func]{graphBFS}" + ], + "rust": [ + "[class]{}-[func]{graph_bfs}" + ], + "c": [ + "[class]{Queue}-[func]{}", + "[class]{}-[func]{isVisited}", + "[class]{}-[func]{graphBFS}" + ], + "kotlin": [ + "[class]{}-[func]{graphBFS}" + ], + "ruby": [ + "[class]{}-[func]{graph_bfs}" + ] + }, + "[file]{graph_dfs}-[class]{}-[func]{graph_dfs}": { + "python": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graph_dfs}" + ], + "cpp": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graphDFS}" + ], + "java": [ + "[class]{graph_dfs}-[func]{dfs}", + "[class]{graph_dfs}-[func]{graphDFS}" + ], + "csharp": [ + "[class]{graph_dfs}-[func]{DFS}", + "[class]{graph_dfs}-[func]{GraphDFS}" + ], + "go": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graphDFS}" + ], + "swift": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graphDFS}" + ], + "javascript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graphDFS}" + ], + "typescript": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graphDFS}" + ], + "dart": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graphDFS}" + ], + "rust": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graph_dfs}" + ], + "c": [ + "[class]{}-[func]{isVisited}", + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graphDFS}" + ], + "kotlin": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graphDFS}" + ], + "ruby": [ + "[class]{}-[func]{dfs}", + "[class]{}-[func]{graph_dfs}" + ] + } + }, + "chapter_greedy": { + "[file]{fractional_knapsack}-[class]{}-[func]{fractional_knapsack}": { + "python": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractional_knapsack}" + ], + "cpp": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractionalKnapsack}" + ], + "java": [ + "[class]{Item}-[func]{}", + "[class]{fractional_knapsack}-[func]{fractionalKnapsack}" + ], + "csharp": [ + "[class]{Item}-[func]{}", + "[class]{fractional_knapsack}-[func]{FractionalKnapsack}" + ], + "go": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractionalKnapsack}" + ], + "swift": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractionalKnapsack}" + ], + "javascript": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractionalKnapsack}" + ], + "typescript": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractionalKnapsack}" + ], + "dart": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractionalKnapsack}" + ], + "rust": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractional_knapsack}" + ], + "c": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractionalKnapsack}" + ], + "kotlin": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractionalKnapsack}" + ], + "ruby": [ + "[class]{Item}-[func]{}", + "[class]{}-[func]{fractional_knapsack}" + ] + }, + "[file]{coin_change_greedy}-[class]{}-[func]{coin_change_greedy}": { + "python": [ + "[class]{}-[func]{coin_change_greedy}" + ], + "cpp": [ + "[class]{}-[func]{coinChangeGreedy}" + ], + "java": [ + "[class]{coin_change_greedy}-[func]{coinChangeGreedy}" + ], + "csharp": [ + "[class]{coin_change_greedy}-[func]{CoinChangeGreedy}" + ], + "go": [ + "[class]{}-[func]{coinChangeGreedy}" + ], + "swift": [ + "[class]{}-[func]{coinChangeGreedy}" + ], + "javascript": [ + "[class]{}-[func]{coinChangeGreedy}" + ], + "typescript": [ + "[class]{}-[func]{coinChangeGreedy}" + ], + "dart": [ + "[class]{}-[func]{coinChangeGreedy}" + ], + "rust": [ + "[class]{}-[func]{coin_change_greedy}" + ], + "c": [ + "[class]{}-[func]{coinChangeGreedy}" + ], + "kotlin": [ + "[class]{}-[func]{coinChangeGreedy}" + ], + "ruby": [ + "[class]{}-[func]{coin_change_greedy}" + ] + }, + "[file]{max_capacity}-[class]{}-[func]{max_capacity}": { + "python": [ + "[class]{}-[func]{max_capacity}" + ], + "cpp": [ + "[class]{}-[func]{maxCapacity}" + ], + "java": [ + "[class]{max_capacity}-[func]{maxCapacity}" + ], + "csharp": [ + "[class]{max_capacity}-[func]{MaxCapacity}" + ], + "go": [ + "[class]{}-[func]{maxCapacity}" + ], + "swift": [ + "[class]{}-[func]{maxCapacity}" + ], + "javascript": [ + "[class]{}-[func]{maxCapacity}" + ], + "typescript": [ + "[class]{}-[func]{maxCapacity}" + ], + "dart": [ + "[class]{}-[func]{maxCapacity}" + ], + "rust": [ + "[class]{}-[func]{max_capacity}" + ], + "c": [ + "[class]{}-[func]{maxCapacity}" + ], + "kotlin": [ + "[class]{}-[func]{maxCapacity}" + ], + "ruby": [ + "[class]{}-[func]{max_capacity}" + ] + }, + "[file]{max_product_cutting}-[class]{}-[func]{max_product_cutting}": { + "python": [ + "[class]{}-[func]{max_product_cutting}" + ], + "cpp": [ + "[class]{}-[func]{maxProductCutting}" + ], + "java": [ + "[class]{max_product_cutting}-[func]{maxProductCutting}" + ], + "csharp": [ + "[class]{max_product_cutting}-[func]{MaxProductCutting}" + ], + "go": [ + "[class]{}-[func]{maxProductCutting}" + ], + "swift": [ + "[class]{}-[func]{maxProductCutting}" + ], + "javascript": [ + "[class]{}-[func]{maxProductCutting}" + ], + "typescript": [ + "[class]{}-[func]{maxProductCutting}" + ], + "dart": [ + "[class]{}-[func]{maxProductCutting}" + ], + "rust": [ + "[class]{}-[func]{max_product_cutting}" + ], + "c": [ + "[class]{}-[func]{maxProductCutting}" + ], + "kotlin": [ + "[class]{}-[func]{maxProductCutting}" + ], + "ruby": [ + "[class]{}-[func]{max_product_cutting}" + ] + } + }, + "chapter_hashing": { + "[file]{simple_hash}-[class]{}-[func]{rot_hash}": { + "python": [ + "[class]{}-[func]{add_hash}", + "[class]{}-[func]{mul_hash}", + "[class]{}-[func]{xor_hash}", + "[class]{}-[func]{rot_hash}" + ], + "cpp": [ + "[class]{}-[func]{addHash}", + "[class]{}-[func]{mulHash}", + "[class]{}-[func]{xorHash}", + "[class]{}-[func]{rotHash}" + ], + "java": [ + "[class]{simple_hash}-[func]{addHash}", + "[class]{simple_hash}-[func]{mulHash}", + "[class]{simple_hash}-[func]{xorHash}", + "[class]{simple_hash}-[func]{rotHash}" + ], + "csharp": [ + "[class]{simple_hash}-[func]{AddHash}", + "[class]{simple_hash}-[func]{MulHash}", + "[class]{simple_hash}-[func]{XorHash}", + "[class]{simple_hash}-[func]{RotHash}" + ], + "go": [ + "[class]{}-[func]{addHash}", + "[class]{}-[func]{mulHash}", + "[class]{}-[func]{xorHash}", + "[class]{}-[func]{rotHash}" + ], + "swift": [ + "[class]{}-[func]{addHash}", + "[class]{}-[func]{mulHash}", + "[class]{}-[func]{xorHash}", + "[class]{}-[func]{rotHash}" + ], + "javascript": [ + "[class]{}-[func]{addHash}", + "[class]{}-[func]{mulHash}", + "[class]{}-[func]{xorHash}", + "[class]{}-[func]{rotHash}" + ], + "typescript": [ + "[class]{}-[func]{addHash}", + "[class]{}-[func]{mulHash}", + "[class]{}-[func]{xorHash}", + "[class]{}-[func]{rotHash}" + ], + "dart": [ + "[class]{}-[func]{addHash}", + "[class]{}-[func]{mulHash}", + "[class]{}-[func]{xorHash}", + "[class]{}-[func]{rotHash}" + ], + "rust": [ + "[class]{}-[func]{add_hash}", + "[class]{}-[func]{mul_hash}", + "[class]{}-[func]{xor_hash}", + "[class]{}-[func]{rot_hash}" + ], + "c": [ + "[class]{}-[func]{addHash}", + "[class]{}-[func]{mulHash}", + "[class]{}-[func]{xorHash}", + "[class]{}-[func]{rotHash}" + ], + "kotlin": [ + "[class]{}-[func]{addHash}", + "[class]{}-[func]{mulHash}", + "[class]{}-[func]{xorHash}", + "[class]{}-[func]{rotHash}" + ], + "ruby": [ + "[class]{}-[func]{add_hash}", + "[class]{}-[func]{mul_hash}", + "[class]{}-[func]{xor_hash}", + "[class]{}-[func]{rot_hash}" + ] + }, + "[file]{hash_map_chaining}-[class]{hash_map_chaining}-[func]{}": { + "python": [ + "[class]{HashMapChaining}-[func]{}" + ], + "cpp": [ + "[class]{HashMapChaining}-[func]{}" + ], + "java": [ + "[class]{HashMapChaining}-[func]{}" + ], + "csharp": [ + "[class]{HashMapChaining}-[func]{}" + ], + "go": [ + "[class]{hashMapChaining}-[func]{}" + ], + "swift": [ + "[class]{HashMapChaining}-[func]{}" + ], + "javascript": [ + "[class]{HashMapChaining}-[func]{}" + ], + "typescript": [ + "[class]{HashMapChaining}-[func]{}" + ], + "dart": [ + "[class]{HashMapChaining}-[func]{}" + ], + "rust": [ + "[class]{HashMapChaining}-[func]{}" + ], + "c": [ + "[class]{Node}-[func]{}", + "[class]{HashMapChaining}-[func]{}" + ], + "kotlin": [ + "[class]{HashMapChaining}-[func]{}" + ], + "ruby": [ + "[class]{HashMapChaining}-[func]{}" + ] + }, + "[file]{hash_map_open_addressing}-[class]{hash_map_open_addressing}-[func]{}": { + "python": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "cpp": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "java": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "csharp": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "go": [ + "[class]{hashMapOpenAddressing}-[func]{}" + ], + "swift": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "javascript": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "typescript": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "dart": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "rust": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "c": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "kotlin": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ], + "ruby": [ + "[class]{HashMapOpenAddressing}-[func]{}" + ] + }, + "[file]{array_hash_map}-[class]{array_hash_map}-[func]{}": { + "python": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "cpp": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "java": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "csharp": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "go": [ + "[class]{pair}-[func]{}", + "[class]{arrayHashMap}-[func]{}" + ], + "swift": [ + "[file]{utils/Pair.swift}-[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "javascript": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "typescript": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "dart": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "rust": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "c": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "kotlin": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ], + "ruby": [ + "[class]{Pair}-[func]{}", + "[class]{ArrayHashMap}-[func]{}" + ] + } + }, + "chapter_heap": { + "[file]{my_heap}-[class]{max_heap}-[func]{__init__}": { + "python": [ + "[class]{MaxHeap}-[func]{__init__}" + ], + "cpp": [ + "[class]{MaxHeap}-[func]{MaxHeap}" + ], + "java": [ + "[class]{MaxHeap}-[func]{MaxHeap}" + ], + "csharp": [ + "[class]{MaxHeap}-[func]{MaxHeap}" + ], + "go": [ + "[class]{maxHeap}-[func]{newMaxHeap}" + ], + "swift": [ + "[class]{MaxHeap}-[func]{init}" + ], + "javascript": [ + "[class]{MaxHeap}-[func]{constructor}" + ], + "typescript": [ + "[class]{MaxHeap}-[func]{constructor}" + ], + "dart": [ + "[class]{MaxHeap}-[func]{MaxHeap}" + ], + "rust": [ + "[class]{MaxHeap}-[func]{new}" + ], + "c": [ + "[class]{MaxHeap}-[func]{newMaxHeap}" + ], + "kotlin": [ + "[class]{MaxHeap}-[func]{}" + ], + "ruby": [ + "[class]{MaxHeap}-[func]{initialize}" + ] + }, + "[file]{my_heap}-[class]{max_heap}-[func]{parent}": { + "python": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ], + "cpp": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ], + "java": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ], + "csharp": [ + "[class]{MaxHeap}-[func]{Left}", + "[class]{MaxHeap}-[func]{Right}", + "[class]{MaxHeap}-[func]{Parent}" + ], + "go": [ + "[class]{maxHeap}-[func]{left}", + "[class]{maxHeap}-[func]{right}", + "[class]{maxHeap}-[func]{parent}" + ], + "swift": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ], + "javascript": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ], + "typescript": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ], + "dart": [ + "[class]{MaxHeap}-[func]{_left}", + "[class]{MaxHeap}-[func]{_right}", + "[class]{MaxHeap}-[func]{_parent}" + ], + "rust": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ], + "c": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ], + "kotlin": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ], + "ruby": [ + "[class]{MaxHeap}-[func]{left}", + "[class]{MaxHeap}-[func]{right}", + "[class]{MaxHeap}-[func]{parent}" + ] + }, + "[file]{my_heap}-[class]{max_heap}-[func]{peek}": { + "python": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "cpp": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "java": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "csharp": [ + "[class]{MaxHeap}-[func]{Peek}" + ], + "go": [ + "[class]{maxHeap}-[func]{peek}" + ], + "swift": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "javascript": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "typescript": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "dart": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "rust": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "c": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "kotlin": [ + "[class]{MaxHeap}-[func]{peek}" + ], + "ruby": [ + "[class]{MaxHeap}-[func]{peek}" + ] + }, + "[file]{my_heap}-[class]{max_heap}-[func]{sift_up}": { + "python": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{sift_up}" + ], + "cpp": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{siftUp}" + ], + "java": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{siftUp}" + ], + "csharp": [ + "[class]{MaxHeap}-[func]{Push}", + "[class]{MaxHeap}-[func]{SiftUp}" + ], + "go": [ + "[class]{maxHeap}-[func]{push}", + "[class]{maxHeap}-[func]{siftUp}" + ], + "swift": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{siftUp}" + ], + "javascript": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{siftUp}" + ], + "typescript": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{siftUp}" + ], + "dart": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{siftUp}" + ], + "rust": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{sift_up}" + ], + "c": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{siftUp}" + ], + "kotlin": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{siftUp}" + ], + "ruby": [ + "[class]{MaxHeap}-[func]{push}", + "[class]{MaxHeap}-[func]{sift_up}" + ] + }, + "[file]{my_heap}-[class]{max_heap}-[func]{sift_down}": { + "python": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{sift_down}" + ], + "cpp": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{siftDown}" + ], + "java": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{siftDown}" + ], + "csharp": [ + "[class]{MaxHeap}-[func]{Pop}", + "[class]{MaxHeap}-[func]{SiftDown}" + ], + "go": [ + "[class]{maxHeap}-[func]{pop}", + "[class]{maxHeap}-[func]{siftDown}" + ], + "swift": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{siftDown}" + ], + "javascript": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{siftDown}" + ], + "typescript": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{siftDown}" + ], + "dart": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{siftDown}" + ], + "rust": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{sift_down}" + ], + "c": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{siftDown}" + ], + "kotlin": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{siftDown}" + ], + "ruby": [ + "[class]{MaxHeap}-[func]{pop}", + "[class]{MaxHeap}-[func]{sift_down}" + ] + }, + "[file]{top_k}-[class]{}-[func]{top_k_heap}": { + "python": [ + "[class]{}-[func]{top_k_heap}" + ], + "cpp": [ + "[class]{}-[func]{topKHeap}" + ], + "java": [ + "[class]{top_k}-[func]{topKHeap}" + ], + "csharp": [ + "[class]{top_k}-[func]{TopKHeap}" + ], + "go": [ + "[class]{}-[func]{topKHeap}" + ], + "swift": [ + "[class]{}-[func]{topKHeap}" + ], + "javascript": [ + "[class]{}-[func]{pushMinHeap}", + "[class]{}-[func]{popMinHeap}", + "[class]{}-[func]{peekMinHeap}", + "[class]{}-[func]{getMinHeap}", + "[class]{}-[func]{topKHeap}" + ], + "typescript": [ + "[class]{}-[func]{pushMinHeap}", + "[class]{}-[func]{popMinHeap}", + "[class]{}-[func]{peekMinHeap}", + "[class]{}-[func]{getMinHeap}", + "[class]{}-[func]{topKHeap}" + ], + "dart": [ + "[class]{}-[func]{topKHeap}" + ], + "rust": [ + "[class]{}-[func]{top_k_heap}" + ], + "c": [ + "[class]{}-[func]{pushMinHeap}", + "[class]{}-[func]{popMinHeap}", + "[class]{}-[func]{peekMinHeap}", + "[class]{}-[func]{getMinHeap}", + "[class]{}-[func]{topKHeap}" + ], + "kotlin": [ + "[class]{}-[func]{topKHeap}" + ], + "ruby": [ + "[class]{}-[func]{top_k_heap}" + ] + } + }, + "chapter_introduction": {}, + "chapter_preface": {}, + "chapter_reference": {}, + "chapter_searching": { + "[file]{binary_search}-[class]{}-[func]{binary_search}": { + "python": [ + "[class]{}-[func]{binary_search}" + ], + "cpp": [ + "[class]{}-[func]{binarySearch}" + ], + "java": [ + "[class]{binary_search}-[func]{binarySearch}" + ], + "csharp": [ + "[class]{binary_search}-[func]{BinarySearch}" + ], + "go": [ + "[class]{}-[func]{binarySearch}" + ], + "swift": [ + "[class]{}-[func]{binarySearch}" + ], + "javascript": [ + "[class]{}-[func]{binarySearch}" + ], + "typescript": [ + "[class]{}-[func]{binarySearch}" + ], + "dart": [ + "[class]{}-[func]{binarySearch}" + ], + "rust": [ + "[class]{}-[func]{binary_search}" + ], + "c": [ + "[class]{}-[func]{binarySearch}" + ], + "kotlin": [ + "[class]{}-[func]{binarySearch}" + ], + "ruby": [ + "[class]{}-[func]{binary_search}" + ] + }, + "[file]{binary_search}-[class]{}-[func]{binary_search_lcro}": { + "python": [ + "[class]{}-[func]{binary_search_lcro}" + ], + "cpp": [ + "[class]{}-[func]{binarySearchLCRO}" + ], + "java": [ + "[class]{binary_search}-[func]{binarySearchLCRO}" + ], + "csharp": [ + "[class]{binary_search}-[func]{BinarySearchLCRO}" + ], + "go": [ + "[class]{}-[func]{binarySearchLCRO}" + ], + "swift": [ + "[class]{}-[func]{binarySearchLCRO}" + ], + "javascript": [ + "[class]{}-[func]{binarySearchLCRO}" + ], + "typescript": [ + "[class]{}-[func]{binarySearchLCRO}" + ], + "dart": [ + "[class]{}-[func]{binarySearchLCRO}" + ], + "rust": [ + "[class]{}-[func]{binary_search_lcro}" + ], + "c": [ + "[class]{}-[func]{binarySearchLCRO}" + ], + "kotlin": [ + "[class]{}-[func]{binarySearchLCRO}" + ], + "ruby": [ + "[class]{}-[func]{binary_search_lcro}" + ] + }, + "[file]{binary_search_edge}-[class]{}-[func]{binary_search_left_edge}": { + "python": [ + "[class]{}-[func]{binary_search_left_edge}" + ], + "cpp": [ + "[class]{}-[func]{binarySearchLeftEdge}" + ], + "java": [ + "[class]{binary_search_edge}-[func]{binarySearchLeftEdge}" + ], + "csharp": [ + "[class]{binary_search_edge}-[func]{BinarySearchLeftEdge}" + ], + "go": [ + "[class]{}-[func]{binarySearchLeftEdge}" + ], + "swift": [ + "[class]{}-[func]{binarySearchLeftEdge}" + ], + "javascript": [ + "[class]{}-[func]{binarySearchLeftEdge}" + ], + "typescript": [ + "[class]{}-[func]{binarySearchLeftEdge}" + ], + "dart": [ + "[class]{}-[func]{binarySearchLeftEdge}" + ], + "rust": [ + "[class]{}-[func]{binary_search_left_edge}" + ], + "c": [ + "[class]{}-[func]{binarySearchLeftEdge}" + ], + "kotlin": [ + "[class]{}-[func]{binarySearchLeftEdge}" + ], + "ruby": [ + "[class]{}-[func]{binary_search_left_edge}" + ] + }, + "[file]{binary_search_edge}-[class]{}-[func]{binary_search_right_edge}": { + "python": [ + "[class]{}-[func]{binary_search_right_edge}" + ], + "cpp": [ + "[class]{}-[func]{binarySearchRightEdge}" + ], + "java": [ + "[class]{binary_search_edge}-[func]{binarySearchRightEdge}" + ], + "csharp": [ + "[class]{binary_search_edge}-[func]{BinarySearchRightEdge}" + ], + "go": [ + "[class]{}-[func]{binarySearchRightEdge}" + ], + "swift": [ + "[class]{}-[func]{binarySearchRightEdge}" + ], + "javascript": [ + "[class]{}-[func]{binarySearchRightEdge}" + ], + "typescript": [ + "[class]{}-[func]{binarySearchRightEdge}" + ], + "dart": [ + "[class]{}-[func]{binarySearchRightEdge}" + ], + "rust": [ + "[class]{}-[func]{binary_search_right_edge}" + ], + "c": [ + "[class]{}-[func]{binarySearchRightEdge}" + ], + "kotlin": [ + "[class]{}-[func]{binarySearchRightEdge}" + ], + "ruby": [ + "[class]{}-[func]{binary_search_right_edge}" + ] + }, + "[file]{binary_search_insertion}-[class]{}-[func]{binary_search_insertion_simple}": { + "python": [ + "[class]{}-[func]{binary_search_insertion_simple}" + ], + "cpp": [ + "[class]{}-[func]{binarySearchInsertionSimple}" + ], + "java": [ + "[class]{binary_search_insertion}-[func]{binarySearchInsertionSimple}" + ], + "csharp": [ + "[class]{binary_search_insertion}-[func]{BinarySearchInsertionSimple}" + ], + "go": [ + "[class]{}-[func]{binarySearchInsertionSimple}" + ], + "swift": [ + "[class]{}-[func]{binarySearchInsertionSimple}" + ], + "javascript": [ + "[class]{}-[func]{binarySearchInsertionSimple}" + ], + "typescript": [ + "[class]{}-[func]{binarySearchInsertionSimple}" + ], + "dart": [ + "[class]{}-[func]{binarySearchInsertionSimple}" + ], + "rust": [ + "[class]{}-[func]{binary_search_insertion_simple}" + ], + "c": [ + "[class]{}-[func]{binarySearchInsertionSimple}" + ], + "kotlin": [ + "[class]{}-[func]{binarySearchInsertionSimple}" + ], + "ruby": [ + "[class]{}-[func]{binary_search_insertion_simple}" + ] + }, + "[file]{binary_search_insertion}-[class]{}-[func]{binary_search_insertion}": { + "python": [ + "[class]{}-[func]{binary_search_insertion}" + ], + "cpp": [ + "[class]{}-[func]{binarySearchInsertion}" + ], + "java": [ + "[class]{binary_search_insertion}-[func]{binarySearchInsertion}" + ], + "csharp": [ + "[class]{binary_search_insertion}-[func]{BinarySearchInsertion}" + ], + "go": [ + "[class]{}-[func]{binarySearchInsertion}" + ], + "swift": [ + "[class]{}-[func]{binarySearchInsertion}" + ], + "javascript": [ + "[class]{}-[func]{binarySearchInsertion}" + ], + "typescript": [ + "[class]{}-[func]{binarySearchInsertion}" + ], + "dart": [ + "[class]{}-[func]{binarySearchInsertion}" + ], + "rust": [ + "[class]{}-[func]{binary_search_insertion}" + ], + "c": [ + "[class]{}-[func]{binarySearchInsertion}" + ], + "kotlin": [ + "[class]{}-[func]{binarySearchInsertion}" + ], + "ruby": [ + "[class]{}-[func]{binary_search_insertion}" + ] + }, + "[file]{two_sum}-[class]{}-[func]{two_sum_brute_force}": { + "python": [ + "[class]{}-[func]{two_sum_brute_force}" + ], + "cpp": [ + "[class]{}-[func]{twoSumBruteForce}" + ], + "java": [ + "[class]{two_sum}-[func]{twoSumBruteForce}" + ], + "csharp": [ + "[class]{two_sum}-[func]{TwoSumBruteForce}" + ], + "go": [ + "[class]{}-[func]{twoSumBruteForce}" + ], + "swift": [ + "[class]{}-[func]{twoSumBruteForce}" + ], + "javascript": [ + "[class]{}-[func]{twoSumBruteForce}" + ], + "typescript": [ + "[class]{}-[func]{twoSumBruteForce}" + ], + "dart": [ + "[class]{}-[func]{twoSumBruteForce}" + ], + "rust": [ + "[class]{}-[func]{two_sum_brute_force}" + ], + "c": [ + "[class]{}-[func]{twoSumBruteForce}" + ], + "kotlin": [ + "[class]{}-[func]{twoSumBruteForce}" + ], + "ruby": [ + "[class]{}-[func]{two_sum_brute_force}" + ] + }, + "[file]{two_sum}-[class]{}-[func]{two_sum_hash_table}": { + "python": [ + "[class]{}-[func]{two_sum_hash_table}" + ], + "cpp": [ + "[class]{}-[func]{twoSumHashTable}" + ], + "java": [ + "[class]{two_sum}-[func]{twoSumHashTable}" + ], + "csharp": [ + "[class]{two_sum}-[func]{TwoSumHashTable}" + ], + "go": [ + "[class]{}-[func]{twoSumHashTable}" + ], + "swift": [ + "[class]{}-[func]{twoSumHashTable}" + ], + "javascript": [ + "[class]{}-[func]{twoSumHashTable}" + ], + "typescript": [ + "[class]{}-[func]{twoSumHashTable}" + ], + "dart": [ + "[class]{}-[func]{twoSumHashTable}" + ], + "rust": [ + "[class]{}-[func]{two_sum_hash_table}" + ], + "c": [ + "[class]{HashTable}-[func]{}", + "[class]{}-[func]{twoSumHashTable}" + ], + "kotlin": [ + "[class]{}-[func]{twoSumHashTable}" + ], + "ruby": [ + "[class]{}-[func]{two_sum_hash_table}" + ] + } + }, + "chapter_sorting": { + "[file]{bubble_sort}-[class]{}-[func]{bubble_sort}": { + "python": [ + "[class]{}-[func]{bubble_sort}" + ], + "cpp": [ + "[class]{}-[func]{bubbleSort}" + ], + "java": [ + "[class]{bubble_sort}-[func]{bubbleSort}" + ], + "csharp": [ + "[class]{bubble_sort}-[func]{BubbleSort}" + ], + "go": [ + "[class]{}-[func]{bubbleSort}" + ], + "swift": [ + "[class]{}-[func]{bubbleSort}" + ], + "javascript": [ + "[class]{}-[func]{bubbleSort}" + ], + "typescript": [ + "[class]{}-[func]{bubbleSort}" + ], + "dart": [ + "[class]{}-[func]{bubbleSort}" + ], + "rust": [ + "[class]{}-[func]{bubble_sort}" + ], + "c": [ + "[class]{}-[func]{bubbleSort}" + ], + "kotlin": [ + "[class]{}-[func]{bubbleSort}" + ], + "ruby": [ + "[class]{}-[func]{bubble_sort}" + ] + }, + "[file]{bubble_sort}-[class]{}-[func]{bubble_sort_with_flag}": { + "python": [ + "[class]{}-[func]{bubble_sort_with_flag}" + ], + "cpp": [ + "[class]{}-[func]{bubbleSortWithFlag}" + ], + "java": [ + "[class]{bubble_sort}-[func]{bubbleSortWithFlag}" + ], + "csharp": [ + "[class]{bubble_sort}-[func]{BubbleSortWithFlag}" + ], + "go": [ + "[class]{}-[func]{bubbleSortWithFlag}" + ], + "swift": [ + "[class]{}-[func]{bubbleSortWithFlag}" + ], + "javascript": [ + "[class]{}-[func]{bubbleSortWithFlag}" + ], + "typescript": [ + "[class]{}-[func]{bubbleSortWithFlag}" + ], + "dart": [ + "[class]{}-[func]{bubbleSortWithFlag}" + ], + "rust": [ + "[class]{}-[func]{bubble_sort_with_flag}" + ], + "c": [ + "[class]{}-[func]{bubbleSortWithFlag}" + ], + "kotlin": [ + "[class]{}-[func]{bubbleSortWithFlag}" + ], + "ruby": [ + "[class]{}-[func]{bubble_sort_with_flag}" + ] + }, + "[file]{bucket_sort}-[class]{}-[func]{bucket_sort}": { + "python": [ + "[class]{}-[func]{bucket_sort}" + ], + "cpp": [ + "[class]{}-[func]{bucketSort}" + ], + "java": [ + "[class]{bucket_sort}-[func]{bucketSort}" + ], + "csharp": [ + "[class]{bucket_sort}-[func]{BucketSort}" + ], + "go": [ + "[class]{}-[func]{bucketSort}" + ], + "swift": [ + "[class]{}-[func]{bucketSort}" + ], + "javascript": [ + "[class]{}-[func]{bucketSort}" + ], + "typescript": [ + "[class]{}-[func]{bucketSort}" + ], + "dart": [ + "[class]{}-[func]{bucketSort}" + ], + "rust": [ + "[class]{}-[func]{bucket_sort}" + ], + "c": [ + "[class]{}-[func]{bucketSort}" + ], + "kotlin": [ + "[class]{}-[func]{bucketSort}" + ], + "ruby": [ + "[class]{}-[func]{bucket_sort}" + ] + }, + "[file]{counting_sort}-[class]{}-[func]{counting_sort_naive}": { + "python": [ + "[class]{}-[func]{counting_sort_naive}" + ], + "cpp": [ + "[class]{}-[func]{countingSortNaive}" + ], + "java": [ + "[class]{counting_sort}-[func]{countingSortNaive}" + ], + "csharp": [ + "[class]{counting_sort}-[func]{CountingSortNaive}" + ], + "go": [ + "[class]{}-[func]{countingSortNaive}" + ], + "swift": [ + "[class]{}-[func]{countingSortNaive}" + ], + "javascript": [ + "[class]{}-[func]{countingSortNaive}" + ], + "typescript": [ + "[class]{}-[func]{countingSortNaive}" + ], + "dart": [ + "[class]{}-[func]{countingSortNaive}" + ], + "rust": [ + "[class]{}-[func]{counting_sort_naive}" + ], + "c": [ + "[class]{}-[func]{countingSortNaive}" + ], + "kotlin": [ + "[class]{}-[func]{countingSortNaive}" + ], + "ruby": [ + "[class]{}-[func]{counting_sort_naive}" + ] + }, + "[file]{counting_sort}-[class]{}-[func]{counting_sort}": { + "python": [ + "[class]{}-[func]{counting_sort}" + ], + "cpp": [ + "[class]{}-[func]{countingSort}" + ], + "java": [ + "[class]{counting_sort}-[func]{countingSort}" + ], + "csharp": [ + "[class]{counting_sort}-[func]{CountingSort}" + ], + "go": [ + "[class]{}-[func]{countingSort}" + ], + "swift": [ + "[class]{}-[func]{countingSort}" + ], + "javascript": [ + "[class]{}-[func]{countingSort}" + ], + "typescript": [ + "[class]{}-[func]{countingSort}" + ], + "dart": [ + "[class]{}-[func]{countingSort}" + ], + "rust": [ + "[class]{}-[func]{counting_sort}" + ], + "c": [ + "[class]{}-[func]{countingSort}" + ], + "kotlin": [ + "[class]{}-[func]{countingSort}" + ], + "ruby": [ + "[class]{}-[func]{counting_sort}" + ] + }, + "[file]{heap_sort}-[class]{}-[func]{heap_sort}": { + "python": [ + "[class]{}-[func]{sift_down}", + "[class]{}-[func]{heap_sort}" + ], + "cpp": [ + "[class]{}-[func]{siftDown}", + "[class]{}-[func]{heapSort}" + ], + "java": [ + "[class]{heap_sort}-[func]{siftDown}", + "[class]{heap_sort}-[func]{heapSort}" + ], + "csharp": [ + "[class]{heap_sort}-[func]{SiftDown}", + "[class]{heap_sort}-[func]{HeapSort}" + ], + "go": [ + "[class]{}-[func]{siftDown}", + "[class]{}-[func]{heapSort}" + ], + "swift": [ + "[class]{}-[func]{siftDown}", + "[class]{}-[func]{heapSort}" + ], + "javascript": [ + "[class]{}-[func]{siftDown}", + "[class]{}-[func]{heapSort}" + ], + "typescript": [ + "[class]{}-[func]{siftDown}", + "[class]{}-[func]{heapSort}" + ], + "dart": [ + "[class]{}-[func]{siftDown}", + "[class]{}-[func]{heapSort}" + ], + "rust": [ + "[class]{}-[func]{sift_down}", + "[class]{}-[func]{heap_sort}" + ], + "c": [ + "[class]{}-[func]{siftDown}", + "[class]{}-[func]{heapSort}" + ], + "kotlin": [ + "[class]{}-[func]{siftDown}", + "[class]{}-[func]{heapSort}" + ], + "ruby": [ + "[class]{}-[func]{sift_down}", + "[class]{}-[func]{heap_sort}" + ] + }, + "[file]{insertion_sort}-[class]{}-[func]{insertion_sort}": { + "python": [ + "[class]{}-[func]{insertion_sort}" + ], + "cpp": [ + "[class]{}-[func]{insertionSort}" + ], + "java": [ + "[class]{insertion_sort}-[func]{insertionSort}" + ], + "csharp": [ + "[class]{insertion_sort}-[func]{InsertionSort}" + ], + "go": [ + "[class]{}-[func]{insertionSort}" + ], + "swift": [ + "[class]{}-[func]{insertionSort}" + ], + "javascript": [ + "[class]{}-[func]{insertionSort}" + ], + "typescript": [ + "[class]{}-[func]{insertionSort}" + ], + "dart": [ + "[class]{}-[func]{insertionSort}" + ], + "rust": [ + "[class]{}-[func]{insertion_sort}" + ], + "c": [ + "[class]{}-[func]{insertionSort}" + ], + "kotlin": [ + "[class]{}-[func]{insertionSort}" + ], + "ruby": [ + "[class]{}-[func]{insertion_sort}" + ] + }, + "[file]{merge_sort}-[class]{}-[func]{merge_sort}": { + "python": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{merge_sort}" + ], + "cpp": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{mergeSort}" + ], + "java": [ + "[class]{merge_sort}-[func]{merge}", + "[class]{merge_sort}-[func]{mergeSort}" + ], + "csharp": [ + "[class]{merge_sort}-[func]{Merge}", + "[class]{merge_sort}-[func]{MergeSort}" + ], + "go": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{mergeSort}" + ], + "swift": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{mergeSort}" + ], + "javascript": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{mergeSort}" + ], + "typescript": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{mergeSort}" + ], + "dart": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{mergeSort}" + ], + "rust": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{merge_sort}" + ], + "c": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{mergeSort}" + ], + "kotlin": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{mergeSort}" + ], + "ruby": [ + "[class]{}-[func]{merge}", + "[class]{}-[func]{merge_sort}" + ] + }, + "[file]{quick_sort}-[class]{quick_sort}-[func]{partition}": { + "python": [ + "[class]{QuickSort}-[func]{partition}" + ], + "cpp": [ + "[class]{QuickSort}-[func]{partition}" + ], + "java": [ + "[class]{QuickSort}-[func]{swap}", + "[class]{QuickSort}-[func]{partition}" + ], + "csharp": [ + "[class]{quickSort}-[func]{Swap}", + "[class]{quickSort}-[func]{Partition}" + ], + "go": [ + "[class]{quickSort}-[func]{partition}" + ], + "swift": [ + "[class]{}-[func]{partition}" + ], + "javascript": [ + "[class]{QuickSort}-[func]{swap}", + "[class]{QuickSort}-[func]{partition}" + ], + "typescript": [ + "[class]{QuickSort}-[func]{swap}", + "[class]{QuickSort}-[func]{partition}" + ], + "dart": [ + "[class]{QuickSort}-[func]{_swap}", + "[class]{QuickSort}-[func]{_partition}" + ], + "rust": [ + "[class]{QuickSort}-[func]{partition}" + ], + "c": [ + "[class]{}-[func]{swap}", + "[class]{}-[func]{partition}" + ], + "kotlin": [ + "[class]{}-[func]{swap}", + "[class]{}-[func]{partition}" + ], + "ruby": [ + "[class]{QuickSort}-[func]{partition}" + ] + }, + "[file]{quick_sort}-[class]{quick_sort}-[func]{quick_sort}": { + "python": [ + "[class]{QuickSort}-[func]{quick_sort}" + ], + "cpp": [ + "[class]{QuickSort}-[func]{quickSort}" + ], + "java": [ + "[class]{QuickSort}-[func]{quickSort}" + ], + "csharp": [ + "[class]{quickSort}-[func]{QuickSort}" + ], + "go": [ + "[class]{quickSort}-[func]{quickSort}" + ], + "swift": [ + "[class]{}-[func]{quickSort}" + ], + "javascript": [ + "[class]{QuickSort}-[func]{quickSort}" + ], + "typescript": [ + "[class]{QuickSort}-[func]{quickSort}" + ], + "dart": [ + "[class]{QuickSort}-[func]{quickSort}" + ], + "rust": [ + "[class]{QuickSort}-[func]{quick_sort}" + ], + "c": [ + "[class]{}-[func]{quickSort}" + ], + "kotlin": [ + "[class]{}-[func]{quickSort}" + ], + "ruby": [ + "[class]{QuickSort}-[func]{quick_sort}" + ] + }, + "[file]{quick_sort}-[class]{quick_sort_median}-[func]{partition}": { + "python": [ + "[class]{QuickSortMedian}-[func]{median_three}", + "[class]{QuickSortMedian}-[func]{partition}" + ], + "cpp": [ + "[class]{QuickSortMedian}-[func]{medianThree}", + "[class]{QuickSortMedian}-[func]{partition}" + ], + "java": [ + "[class]{QuickSortMedian}-[func]{medianThree}", + "[class]{QuickSortMedian}-[func]{partition}" + ], + "csharp": [ + "[class]{QuickSortMedian}-[func]{MedianThree}", + "[class]{QuickSortMedian}-[func]{Partition}" + ], + "go": [ + "[class]{quickSortMedian}-[func]{medianThree}", + "[class]{quickSortMedian}-[func]{partition}" + ], + "swift": [ + "[class]{}-[func]{medianThree}", + "[class]{}-[func]{partitionMedian}" + ], + "javascript": [ + "[class]{QuickSortMedian}-[func]{medianThree}", + "[class]{QuickSortMedian}-[func]{partition}" + ], + "typescript": [ + "[class]{QuickSortMedian}-[func]{medianThree}", + "[class]{QuickSortMedian}-[func]{partition}" + ], + "dart": [ + "[class]{QuickSortMedian}-[func]{_medianThree}", + "[class]{QuickSortMedian}-[func]{_partition}" + ], + "rust": [ + "[class]{QuickSortMedian}-[func]{median_three}", + "[class]{QuickSortMedian}-[func]{partition}" + ], + "c": [ + "[class]{}-[func]{medianThree}", + "[class]{}-[func]{partitionMedian}" + ], + "kotlin": [ + "[class]{}-[func]{medianThree}", + "[class]{}-[func]{partitionMedian}" + ], + "ruby": [ + "[class]{QuickSortMedian}-[func]{median_three}", + "[class]{QuickSortMedian}-[func]{partition}" + ] + }, + "[file]{quick_sort}-[class]{quick_sort_tail_call}-[func]{quick_sort}": { + "python": [ + "[class]{QuickSortTailCall}-[func]{quick_sort}" + ], + "cpp": [ + "[class]{QuickSortTailCall}-[func]{quickSort}" + ], + "java": [ + "[class]{QuickSortTailCall}-[func]{quickSort}" + ], + "csharp": [ + "[class]{QuickSortTailCall}-[func]{QuickSort}" + ], + "go": [ + "[class]{quickSortTailCall}-[func]{quickSort}" + ], + "swift": [ + "[class]{}-[func]{quickSortTailCall}" + ], + "javascript": [ + "[class]{QuickSortTailCall}-[func]{quickSort}" + ], + "typescript": [ + "[class]{QuickSortTailCall}-[func]{quickSort}" + ], + "dart": [ + "[class]{QuickSortTailCall}-[func]{quickSort}" + ], + "rust": [ + "[class]{QuickSortTailCall}-[func]{quick_sort}" + ], + "c": [ + "[class]{}-[func]{quickSortTailCall}" + ], + "kotlin": [ + "[class]{}-[func]{quickSortTailCall}" + ], + "ruby": [ + "[class]{QuickSortTailCall}-[func]{quick_sort}" + ] + }, + "[file]{radix_sort}-[class]{}-[func]{radix_sort}": { + "python": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{counting_sort_digit}", + "[class]{}-[func]{radix_sort}" + ], + "cpp": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{countingSortDigit}", + "[class]{}-[func]{radixSort}" + ], + "java": [ + "[class]{radix_sort}-[func]{digit}", + "[class]{radix_sort}-[func]{countingSortDigit}", + "[class]{radix_sort}-[func]{radixSort}" + ], + "csharp": [ + "[class]{radix_sort}-[func]{Digit}", + "[class]{radix_sort}-[func]{CountingSortDigit}", + "[class]{radix_sort}-[func]{RadixSort}" + ], + "go": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{countingSortDigit}", + "[class]{}-[func]{radixSort}" + ], + "swift": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{countingSortDigit}", + "[class]{}-[func]{radixSort}" + ], + "javascript": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{countingSortDigit}", + "[class]{}-[func]{radixSort}" + ], + "typescript": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{countingSortDigit}", + "[class]{}-[func]{radixSort}" + ], + "dart": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{countingSortDigit}", + "[class]{}-[func]{radixSort}" + ], + "rust": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{counting_sort_digit}", + "[class]{}-[func]{radix_sort}" + ], + "c": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{countingSortDigit}", + "[class]{}-[func]{radixSort}" + ], + "kotlin": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{countingSortDigit}", + "[class]{}-[func]{radixSort}" + ], + "ruby": [ + "[class]{}-[func]{digit}", + "[class]{}-[func]{counting_sort_digit}", + "[class]{}-[func]{radix_sort}" + ] + }, + "[file]{selection_sort}-[class]{}-[func]{selection_sort}": { + "python": [ + "[class]{}-[func]{selection_sort}" + ], + "cpp": [ + "[class]{}-[func]{selectionSort}" + ], + "java": [ + "[class]{selection_sort}-[func]{selectionSort}" + ], + "csharp": [ + "[class]{selection_sort}-[func]{SelectionSort}" + ], + "go": [ + "[class]{}-[func]{selectionSort}" + ], + "swift": [ + "[class]{}-[func]{selectionSort}" + ], + "javascript": [ + "[class]{}-[func]{selectionSort}" + ], + "typescript": [ + "[class]{}-[func]{selectionSort}" + ], + "dart": [ + "[class]{}-[func]{selectionSort}" + ], + "rust": [ + "[class]{}-[func]{selection_sort}" + ], + "c": [ + "[class]{}-[func]{selectionSort}" + ], + "kotlin": [ + "[class]{}-[func]{selectionSort}" + ], + "ruby": [ + "[class]{}-[func]{selection_sort}" + ] + } + }, + "chapter_stack_and_queue": { + "[file]{linkedlist_deque}-[class]{linked_list_deque}-[func]{}": { + "python": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "cpp": [ + "[class]{DoublyListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "java": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "csharp": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "go": [ + "[class]{linkedListDeque}-[func]{}" + ], + "swift": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "javascript": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "typescript": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "dart": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "rust": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "c": [ + "[class]{DoublyListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "kotlin": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ], + "ruby": [ + "[class]{ListNode}-[func]{}", + "[class]{LinkedListDeque}-[func]{}" + ] + }, + "[file]{array_deque}-[class]{array_deque}-[func]{}": { + "python": [ + "[class]{ArrayDeque}-[func]{}" + ], + "cpp": [ + "[class]{ArrayDeque}-[func]{}" + ], + "java": [ + "[class]{ArrayDeque}-[func]{}" + ], + "csharp": [ + "[class]{ArrayDeque}-[func]{}" + ], + "go": [ + "[class]{arrayDeque}-[func]{}" + ], + "swift": [ + "[class]{ArrayDeque}-[func]{}" + ], + "javascript": [ + "[class]{ArrayDeque}-[func]{}" + ], + "typescript": [ + "[class]{ArrayDeque}-[func]{}" + ], + "dart": [ + "[class]{ArrayDeque}-[func]{}" + ], + "rust": [ + "[class]{ArrayDeque}-[func]{}" + ], + "c": [ + "[class]{ArrayDeque}-[func]{}" + ], + "kotlin": [ + "[class]{ArrayDeque}-[func]{}" + ], + "ruby": [ + "[class]{ArrayDeque}-[func]{}" + ] + }, + "[file]{linkedlist_queue}-[class]{linked_list_queue}-[func]{}": { + "python": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "cpp": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "java": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "csharp": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "go": [ + "[class]{linkedListQueue}-[func]{}" + ], + "swift": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "javascript": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "typescript": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "dart": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "rust": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "c": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "kotlin": [ + "[class]{LinkedListQueue}-[func]{}" + ], + "ruby": [ + "[class]{LinkedListQueue}-[func]{}" + ] + }, + "[file]{array_queue}-[class]{array_queue}-[func]{}": { + "python": [ + "[class]{ArrayQueue}-[func]{}" + ], + "cpp": [ + "[class]{ArrayQueue}-[func]{}" + ], + "java": [ + "[class]{ArrayQueue}-[func]{}" + ], + "csharp": [ + "[class]{ArrayQueue}-[func]{}" + ], + "go": [ + "[class]{arrayQueue}-[func]{}" + ], + "swift": [ + "[class]{ArrayQueue}-[func]{}" + ], + "javascript": [ + "[class]{ArrayQueue}-[func]{}" + ], + "typescript": [ + "[class]{ArrayQueue}-[func]{}" + ], + "dart": [ + "[class]{ArrayQueue}-[func]{}" + ], + "rust": [ + "[class]{ArrayQueue}-[func]{}" + ], + "c": [ + "[class]{ArrayQueue}-[func]{}" + ], + "kotlin": [ + "[class]{ArrayQueue}-[func]{}" + ], + "ruby": [ + "[class]{ArrayQueue}-[func]{}" + ] + }, + "[file]{linkedlist_stack}-[class]{linked_list_stack}-[func]{}": { + "python": [ + "[class]{LinkedListStack}-[func]{}" + ], + "cpp": [ + "[class]{LinkedListStack}-[func]{}" + ], + "java": [ + "[class]{LinkedListStack}-[func]{}" + ], + "csharp": [ + "[class]{LinkedListStack}-[func]{}" + ], + "go": [ + "[class]{linkedListStack}-[func]{}" + ], + "swift": [ + "[class]{LinkedListStack}-[func]{}" + ], + "javascript": [ + "[class]{LinkedListStack}-[func]{}" + ], + "typescript": [ + "[class]{LinkedListStack}-[func]{}" + ], + "dart": [ + "[class]{LinkedListStack}-[func]{}" + ], + "rust": [ + "[class]{LinkedListStack}-[func]{}" + ], + "c": [ + "[class]{LinkedListStack}-[func]{}" + ], + "kotlin": [ + "[class]{LinkedListStack}-[func]{}" + ], + "ruby": [ + "[class]{LinkedListStack}-[func]{}" + ] + }, + "[file]{array_stack}-[class]{array_stack}-[func]{}": { + "python": [ + "[class]{ArrayStack}-[func]{}" + ], + "cpp": [ + "[class]{ArrayStack}-[func]{}" + ], + "java": [ + "[class]{ArrayStack}-[func]{}" + ], + "csharp": [ + "[class]{ArrayStack}-[func]{}" + ], + "go": [ + "[class]{arrayStack}-[func]{}" + ], + "swift": [ + "[class]{ArrayStack}-[func]{}" + ], + "javascript": [ + "[class]{ArrayStack}-[func]{}" + ], + "typescript": [ + "[class]{ArrayStack}-[func]{}" + ], + "dart": [ + "[class]{ArrayStack}-[func]{}" + ], + "rust": [ + "[class]{ArrayStack}-[func]{}" + ], + "c": [ + "[class]{ArrayStack}-[func]{}" + ], + "kotlin": [ + "[class]{ArrayStack}-[func]{}" + ], + "ruby": [ + "[class]{ArrayStack}-[func]{}" + ] + } + }, + "chapter_tree": { + "[file]{array_binary_tree}-[class]{array_binary_tree}-[func]{}": { + "python": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "cpp": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "java": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "csharp": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "go": [ + "[class]{arrayBinaryTree}-[func]{}" + ], + "swift": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "javascript": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "typescript": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "dart": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "rust": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "c": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "kotlin": [ + "[class]{ArrayBinaryTree}-[func]{}" + ], + "ruby": [ + "[class]{ArrayBinaryTree}-[func]{}" + ] + }, + "[file]{avl_tree}-[class]{avl_tree}-[func]{update_height}": { + "python": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{update_height}" + ], + "cpp": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{updateHeight}" + ], + "java": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{updateHeight}" + ], + "csharp": [ + "[class]{AVLTree}-[func]{Height}", + "[class]{AVLTree}-[func]{UpdateHeight}" + ], + "go": [ + "[class]{aVLTree}-[func]{height}", + "[class]{aVLTree}-[func]{updateHeight}" + ], + "swift": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{updateHeight}" + ], + "javascript": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{updateHeight}" + ], + "typescript": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{updateHeight}" + ], + "dart": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{updateHeight}" + ], + "rust": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{update_height}" + ], + "c": [ + "[class]{}-[func]{height}", + "[class]{}-[func]{updateHeight}" + ], + "kotlin": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{updateHeight}" + ], + "ruby": [ + "[class]{AVLTree}-[func]{height}", + "[class]{AVLTree}-[func]{update_height}" + ] + }, + "[file]{avl_tree}-[class]{avl_tree}-[func]{balance_factor}": { + "python": [ + "[class]{AVLTree}-[func]{balance_factor}" + ], + "cpp": [ + "[class]{AVLTree}-[func]{balanceFactor}" + ], + "java": [ + "[class]{AVLTree}-[func]{balanceFactor}" + ], + "csharp": [ + "[class]{AVLTree}-[func]{BalanceFactor}" + ], + "go": [ + "[class]{aVLTree}-[func]{balanceFactor}" + ], + "swift": [ + "[class]{AVLTree}-[func]{balanceFactor}" + ], + "javascript": [ + "[class]{AVLTree}-[func]{balanceFactor}" + ], + "typescript": [ + "[class]{AVLTree}-[func]{balanceFactor}" + ], + "dart": [ + "[class]{AVLTree}-[func]{balanceFactor}" + ], + "rust": [ + "[class]{AVLTree}-[func]{balance_factor}" + ], + "c": [ + "[class]{}-[func]{balanceFactor}" + ], + "kotlin": [ + "[class]{AVLTree}-[func]{balanceFactor}" + ], + "ruby": [ + "[class]{AVLTree}-[func]{balance_factor}" + ] + }, + "[file]{avl_tree}-[class]{avl_tree}-[func]{right_rotate}": { + "python": [ + "[class]{AVLTree}-[func]{right_rotate}" + ], + "cpp": [ + "[class]{AVLTree}-[func]{rightRotate}" + ], + "java": [ + "[class]{AVLTree}-[func]{rightRotate}" + ], + "csharp": [ + "[class]{AVLTree}-[func]{RightRotate}" + ], + "go": [ + "[class]{aVLTree}-[func]{rightRotate}" + ], + "swift": [ + "[class]{AVLTree}-[func]{rightRotate}" + ], + "javascript": [ + "[class]{AVLTree}-[func]{rightRotate}" + ], + "typescript": [ + "[class]{AVLTree}-[func]{rightRotate}" + ], + "dart": [ + "[class]{AVLTree}-[func]{rightRotate}" + ], + "rust": [ + "[class]{AVLTree}-[func]{right_rotate}" + ], + "c": [ + "[class]{}-[func]{rightRotate}" + ], + "kotlin": [ + "[class]{AVLTree}-[func]{rightRotate}" + ], + "ruby": [ + "[class]{AVLTree}-[func]{right_rotate}" + ] + }, + "[file]{avl_tree}-[class]{avl_tree}-[func]{left_rotate}": { + "python": [ + "[class]{AVLTree}-[func]{left_rotate}" + ], + "cpp": [ + "[class]{AVLTree}-[func]{leftRotate}" + ], + "java": [ + "[class]{AVLTree}-[func]{leftRotate}" + ], + "csharp": [ + "[class]{AVLTree}-[func]{LeftRotate}" + ], + "go": [ + "[class]{aVLTree}-[func]{leftRotate}" + ], + "swift": [ + "[class]{AVLTree}-[func]{leftRotate}" + ], + "javascript": [ + "[class]{AVLTree}-[func]{leftRotate}" + ], + "typescript": [ + "[class]{AVLTree}-[func]{leftRotate}" + ], + "dart": [ + "[class]{AVLTree}-[func]{leftRotate}" + ], + "rust": [ + "[class]{AVLTree}-[func]{left_rotate}" + ], + "c": [ + "[class]{}-[func]{leftRotate}" + ], + "kotlin": [ + "[class]{AVLTree}-[func]{leftRotate}" + ], + "ruby": [ + "[class]{AVLTree}-[func]{left_rotate}" + ] + }, + "[file]{avl_tree}-[class]{avl_tree}-[func]{rotate}": { + "python": [ + "[class]{AVLTree}-[func]{rotate}" + ], + "cpp": [ + "[class]{AVLTree}-[func]{rotate}" + ], + "java": [ + "[class]{AVLTree}-[func]{rotate}" + ], + "csharp": [ + "[class]{AVLTree}-[func]{Rotate}" + ], + "go": [ + "[class]{aVLTree}-[func]{rotate}" + ], + "swift": [ + "[class]{AVLTree}-[func]{rotate}" + ], + "javascript": [ + "[class]{AVLTree}-[func]{rotate}" + ], + "typescript": [ + "[class]{AVLTree}-[func]{rotate}" + ], + "dart": [ + "[class]{AVLTree}-[func]{rotate}" + ], + "rust": [ + "[class]{AVLTree}-[func]{rotate}" + ], + "c": [ + "[class]{}-[func]{rotate}" + ], + "kotlin": [ + "[class]{AVLTree}-[func]{rotate}" + ], + "ruby": [ + "[class]{AVLTree}-[func]{rotate}" + ] + }, + "[file]{avl_tree}-[class]{avl_tree}-[func]{insert_helper}": { + "python": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insert_helper}" + ], + "cpp": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insertHelper}" + ], + "java": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insertHelper}" + ], + "csharp": [ + "[class]{AVLTree}-[func]{Insert}", + "[class]{AVLTree}-[func]{InsertHelper}" + ], + "go": [ + "[class]{aVLTree}-[func]{insert}", + "[class]{aVLTree}-[func]{insertHelper}" + ], + "swift": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insertHelper}" + ], + "javascript": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insertHelper}" + ], + "typescript": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insertHelper}" + ], + "dart": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insertHelper}" + ], + "rust": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insert_helper}" + ], + "c": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{}-[func]{insertHelper}" + ], + "kotlin": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insertHelper}" + ], + "ruby": [ + "[class]{AVLTree}-[func]{insert}", + "[class]{AVLTree}-[func]{insert_helper}" + ] + }, + "[file]{avl_tree}-[class]{avl_tree}-[func]{remove_helper}": { + "python": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{remove_helper}" + ], + "cpp": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{removeHelper}" + ], + "java": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{removeHelper}" + ], + "csharp": [ + "[class]{AVLTree}-[func]{Remove}", + "[class]{AVLTree}-[func]{RemoveHelper}" + ], + "go": [ + "[class]{aVLTree}-[func]{remove}", + "[class]{aVLTree}-[func]{removeHelper}" + ], + "swift": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{removeHelper}" + ], + "javascript": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{removeHelper}" + ], + "typescript": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{removeHelper}" + ], + "dart": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{removeHelper}" + ], + "rust": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{remove_helper}" + ], + "c": [ + "[class]{AVLTree}-[func]{removeItem}", + "[class]{}-[func]{removeHelper}" + ], + "kotlin": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{removeHelper}" + ], + "ruby": [ + "[class]{AVLTree}-[func]{remove}", + "[class]{AVLTree}-[func]{remove_helper}" + ] + }, + "[file]{binary_search_tree}-[class]{binary_search_tree}-[func]{search}": { + "python": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "cpp": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "java": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "csharp": [ + "[class]{BinarySearchTree}-[func]{Search}" + ], + "go": [ + "[class]{binarySearchTree}-[func]{search}" + ], + "swift": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "javascript": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "typescript": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "dart": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "rust": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "c": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "kotlin": [ + "[class]{BinarySearchTree}-[func]{search}" + ], + "ruby": [ + "[class]{BinarySearchTree}-[func]{search}" + ] + }, + "[file]{binary_search_tree}-[class]{binary_search_tree}-[func]{insert}": { + "python": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "cpp": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "java": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "csharp": [ + "[class]{BinarySearchTree}-[func]{Insert}" + ], + "go": [ + "[class]{binarySearchTree}-[func]{insert}" + ], + "swift": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "javascript": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "typescript": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "dart": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "rust": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "c": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "kotlin": [ + "[class]{BinarySearchTree}-[func]{insert}" + ], + "ruby": [ + "[class]{BinarySearchTree}-[func]{insert}" + ] + }, + "[file]{binary_search_tree}-[class]{binary_search_tree}-[func]{remove}": { + "python": [ + "[class]{BinarySearchTree}-[func]{remove}" + ], + "cpp": [ + "[class]{BinarySearchTree}-[func]{remove}" + ], + "java": [ + "[class]{BinarySearchTree}-[func]{remove}" + ], + "csharp": [ + "[class]{BinarySearchTree}-[func]{Remove}" + ], + "go": [ + "[class]{binarySearchTree}-[func]{remove}" + ], + "swift": [ + "[class]{BinarySearchTree}-[func]{remove}" + ], + "javascript": [ + "[class]{BinarySearchTree}-[func]{remove}" + ], + "typescript": [ + "[class]{BinarySearchTree}-[func]{remove}" + ], + "dart": [ + "[class]{BinarySearchTree}-[func]{remove}" + ], + "rust": [ + "[class]{BinarySearchTree}-[func]{remove}" + ], + "c": [ + "[class]{BinarySearchTree}-[func]{removeItem}" + ], + "kotlin": [ + "[class]{BinarySearchTree}-[func]{remove}" + ], + "ruby": [ + "[class]{BinarySearchTree}-[func]{remove}" + ] + }, + "[file]{binary_tree_bfs}-[class]{}-[func]{level_order}": { + "python": [ + "[class]{}-[func]{level_order}" + ], + "cpp": [ + "[class]{}-[func]{levelOrder}" + ], + "java": [ + "[class]{binary_tree_bfs}-[func]{levelOrder}" + ], + "csharp": [ + "[class]{binary_tree_bfs}-[func]{LevelOrder}" + ], + "go": [ + "[class]{}-[func]{levelOrder}" + ], + "swift": [ + "[class]{}-[func]{levelOrder}" + ], + "javascript": [ + "[class]{}-[func]{levelOrder}" + ], + "typescript": [ + "[class]{}-[func]{levelOrder}" + ], + "dart": [ + "[class]{}-[func]{levelOrder}" + ], + "rust": [ + "[class]{}-[func]{level_order}" + ], + "c": [ + "[class]{}-[func]{levelOrder}" + ], + "kotlin": [ + "[class]{}-[func]{levelOrder}" + ], + "ruby": [ + "[class]{}-[func]{level_order}" + ] + }, + "[file]{binary_tree_dfs}-[class]{}-[func]{post_order}": { + "python": [ + "[class]{}-[func]{pre_order}", + "[class]{}-[func]{in_order}", + "[class]{}-[func]{post_order}" + ], + "cpp": [ + "[class]{}-[func]{preOrder}", + "[class]{}-[func]{inOrder}", + "[class]{}-[func]{postOrder}" + ], + "java": [ + "[class]{binary_tree_dfs}-[func]{preOrder}", + "[class]{binary_tree_dfs}-[func]{inOrder}", + "[class]{binary_tree_dfs}-[func]{postOrder}" + ], + "csharp": [ + "[class]{binary_tree_dfs}-[func]{PreOrder}", + "[class]{binary_tree_dfs}-[func]{InOrder}", + "[class]{binary_tree_dfs}-[func]{PostOrder}" + ], + "go": [ + "[class]{}-[func]{preOrder}", + "[class]{}-[func]{inOrder}", + "[class]{}-[func]{postOrder}" + ], + "swift": [ + "[class]{}-[func]{preOrder}", + "[class]{}-[func]{inOrder}", + "[class]{}-[func]{postOrder}" + ], + "javascript": [ + "[class]{}-[func]{preOrder}", + "[class]{}-[func]{inOrder}", + "[class]{}-[func]{postOrder}" + ], + "typescript": [ + "[class]{}-[func]{preOrder}", + "[class]{}-[func]{inOrder}", + "[class]{}-[func]{postOrder}" + ], + "dart": [ + "[class]{}-[func]{preOrder}", + "[class]{}-[func]{inOrder}", + "[class]{}-[func]{postOrder}" + ], + "rust": [ + "[class]{}-[func]{pre_order}", + "[class]{}-[func]{in_order}", + "[class]{}-[func]{post_order}" + ], + "c": [ + "[class]{}-[func]{preOrder}", + "[class]{}-[func]{inOrder}", + "[class]{}-[func]{postOrder}" + ], + "kotlin": [ + "[class]{}-[func]{preOrder}", + "[class]{}-[func]{inOrder}", + "[class]{}-[func]{postOrder}" + ], + "ruby": [ + "[class]{}-[func]{pre_order}", + "[class]{}-[func]{in_order}", + "[class]{}-[func]{post_order}" + ] + } + } +} diff --git a/codes/snippets/chapter_array_and_linkedlist/array.md b/codes/snippets/chapter_array_and_linkedlist/array.md new file mode 100644 index 000000000..e28b909ba --- /dev/null +++ b/codes/snippets/chapter_array_and_linkedlist/array.md @@ -0,0 +1,93 @@ + +```python title="array.py" +# 初始化数组 +arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="array.cpp" +/* 初始化数组 */ +// 存储在栈上 +int arr[5] = {}; +int nums[5] = { 1, 3, 2, 5, 4 }; +// 存储在堆上(需要手动释放空间) +int* arr1 = new int[5] {}; +int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +``` + +```java title="array.java" +/* 初始化数组 */ +int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } +int[] nums = { 1, 3, 2, 5, 4 }; +``` + +```csharp title="array.cs" +/* 初始化数组 */ +int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] +int[] nums = [1, 3, 2, 5, 4]; +``` + +```go title="array.go" +/* 初始化数组 */ +var arr [5]int +// 在 Go 中,指定长度时([5]int)为数组,不指定长度时([]int)为切片 +// 由于 Go 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度 +// 为了方便实现扩容 extend() 方法,以下将切片(Slice)看作数组(Array) +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="array.swift" +/* 初始化数组 */ +let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] +let nums = [1, 3, 2, 5, 4] +``` + +```javascript title="array.js" +/* 初始化数组 */ +var arr = new Array(5).fill(0); +var nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="array.ts" +/* 初始化数组 */ +let arr: number[] = new Array(5).fill(0); +let nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="array.dart" +/* 初始化数组 */ +List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="array.rs" +/* 初始化数组 */ +let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] +let slice: &[i32] = &[0; 5]; +// 在 Rust 中,指定长度时([i32; 5])为数组,不指定长度时(&[i32])为切片 +// 由于 Rust 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度 +// Vector 是 Rust 一般情况下用作动态数组的类型 +// 为了方便实现扩容 extend() 方法,以下将 vector 看作数组(array) +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="array.c" +/* 初始化数组 */ +int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } +int nums[5] = { 1, 3, 2, 5, 4 }; +``` + +```kotlin title="array.kt" +/* 初始化数组 */ +var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +var nums = intArrayOf(1, 3, 2, 5, 4) +``` + +```ruby title="array.rb" +# 初始化数组 +arr = Array.new(5, 0) +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E6%95%B0%E7%BB%84%0Aarr%20%3D%20%5B0%5D%20*%205%20%20%23%20%5B%200,%200,%200,%200,%200%20%5D%0Anums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/codes/snippets/chapter_array_and_linkedlist/linked_list.md new file mode 100644 index 000000000..0435e423f --- /dev/null +++ b/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -0,0 +1,516 @@ + +```python title="" +class ListNode: + """链表节点类""" + def __init__(self, val: int): + self.val: int = val # 节点值 + self.next: ListNode | None = None # 指向下一节点的引用 +``` + +```cpp title="" +/* 链表节点结构体 */ +struct ListNode { + int val; // 节点值 + ListNode *next; // 指向下一节点的指针 + ListNode(int x) : val(x), next(nullptr) {} // 构造函数 +}; +``` + +```java title="" +/* 链表节点类 */ +class ListNode { + int val; // 节点值 + ListNode next; // 指向下一节点的引用 + ListNode(int x) { val = x; } // 构造函数 +} +``` + +```csharp title="" +/* 链表节点类 */ +class ListNode(int x) { //构造函数 + int val = x; // 节点值 + ListNode? next; // 指向下一节点的引用 +} +``` + +```go title="" +/* 链表节点结构体 */ +type ListNode struct { + Val int // 节点值 + Next *ListNode // 指向下一节点的指针 +} + +// NewListNode 构造函数,创建一个新的链表 +func NewListNode(val int) *ListNode { + return &ListNode{ + Val: val, + Next: nil, + } +} +``` + +```swift title="" +/* 链表节点类 */ +class ListNode { + var val: Int // 节点值 + var next: ListNode? // 指向下一节点的引用 + + init(x: Int) { // 构造函数 + val = x + } +} +``` + +```javascript title="" +/* 链表节点类 */ +class ListNode { + constructor(val, next) { + this.val = (val === undefined ? 0 : val); // 节点值 + this.next = (next === undefined ? null : next); // 指向下一节点的引用 + } +} +``` + +```typescript title="" +/* 链表节点类 */ +class ListNode { + val: number; + next: ListNode | null; + constructor(val?: number, next?: ListNode | null) { + this.val = val === undefined ? 0 : val; // 节点值 + this.next = next === undefined ? null : next; // 指向下一节点的引用 + } +} +``` + +```dart title="" +/* 链表节点类 */ +class ListNode { + int val; // 节点值 + ListNode? next; // 指向下一节点的引用 + ListNode(this.val, [this.next]); // 构造函数 +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; +/* 链表节点类 */ +#[derive(Debug)] +struct ListNode { + val: i32, // 节点值 + next: Option>>, // 指向下一节点的指针 +} +``` + +```c title="" +/* 链表节点结构体 */ +typedef struct ListNode { + int val; // 节点值 + struct ListNode *next; // 指向下一节点的指针 +} ListNode; + +/* 构造函数 */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + return node; +} +``` + +```kotlin title="" +/* 链表节点类 */ +// 构造方法 +class ListNode(x: Int) { + val _val: Int = x // 节点值 + var next: ListNode? = null // 指向下一个节点的引用 +} +``` + +```ruby title="" +# 链表节点类 +class ListNode + attr_accessor :val # 节点值 + attr_accessor :next # 指向下一节点的引用 + + def initialize(val=0, next_node=nil) + @val = val + @next = next_node + end +end +``` + + +```python title="linked_list.py" +# 初始化链表 1 -> 3 -> 2 -> 5 -> 4 +# 初始化各个节点 +n0 = ListNode(1) +n1 = ListNode(3) +n2 = ListNode(2) +n3 = ListNode(5) +n4 = ListNode(4) +# 构建节点之间的引用 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```cpp title="linked_list.cpp" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +ListNode* n0 = new ListNode(1); +ListNode* n1 = new ListNode(3); +ListNode* n2 = new ListNode(2); +ListNode* n3 = new ListNode(5); +ListNode* n4 = new ListNode(4); +// 构建节点之间的引用 +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```java title="linked_list.java" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +ListNode n0 = new ListNode(1); +ListNode n1 = new ListNode(3); +ListNode n2 = new ListNode(2); +ListNode n3 = new ListNode(5); +ListNode n4 = new ListNode(4); +// 构建节点之间的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```csharp title="linked_list.cs" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +ListNode n0 = new(1); +ListNode n1 = new(3); +ListNode n2 = new(2); +ListNode n3 = new(5); +ListNode n4 = new(4); +// 构建节点之间的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```go title="linked_list.go" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +n0 := NewListNode(1) +n1 := NewListNode(3) +n2 := NewListNode(2) +n3 := NewListNode(5) +n4 := NewListNode(4) +// 构建节点之间的引用 +n0.Next = n1 +n1.Next = n2 +n2.Next = n3 +n3.Next = n4 +``` + +```swift title="linked_list.swift" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +let n0 = ListNode(x: 1) +let n1 = ListNode(x: 3) +let n2 = ListNode(x: 2) +let n3 = ListNode(x: 5) +let n4 = ListNode(x: 4) +// 构建节点之间的引用 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```javascript title="linked_list.js" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// 构建节点之间的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```typescript title="linked_list.ts" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// 构建节点之间的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```dart title="linked_list.dart" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */\ +// 初始化各个节点 +ListNode n0 = ListNode(1); +ListNode n1 = ListNode(3); +ListNode n2 = ListNode(2); +ListNode n3 = ListNode(5); +ListNode n4 = ListNode(4); +// 构建节点之间的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```rust title="linked_list.rs" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); +let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); +let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); +let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); +let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); + +// 构建节点之间的引用 +n0.borrow_mut().next = Some(n1.clone()); +n1.borrow_mut().next = Some(n2.clone()); +n2.borrow_mut().next = Some(n3.clone()); +n3.borrow_mut().next = Some(n4.clone()); +``` + +```c title="linked_list.c" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +ListNode* n0 = newListNode(1); +ListNode* n1 = newListNode(3); +ListNode* n2 = newListNode(2); +ListNode* n3 = newListNode(5); +ListNode* n4 = newListNode(4); +// 构建节点之间的引用 +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```kotlin title="linked_list.kt" +/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各个节点 +val n0 = ListNode(1) +val n1 = ListNode(3) +val n2 = ListNode(2) +val n3 = ListNode(5) +val n4 = ListNode(4) +// 构建节点之间的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```ruby title="linked_list.rb" +# 初始化链表 1 -> 3 -> 2 -> 5 -> 4 +# 初始化各个节点 +n0 = ListNode.new(1) +n1 = ListNode.new(3) +n2 = ListNode.new(2) +n3 = ListNode.new(5) +n4 = ListNode.new(4) +# 构建节点之间的引用 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%93%BE%E8%A1%A8%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%90%84%E4%B8%AA%E8%8A%82%E7%82%B9%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="" +class ListNode: + """双向链表节点类""" + def __init__(self, val: int): + self.val: int = val # 节点值 + self.next: ListNode | None = None # 指向后继节点的引用 + self.prev: ListNode | None = None # 指向前驱节点的引用 +``` + +```cpp title="" +/* 双向链表节点结构体 */ +struct ListNode { + int val; // 节点值 + ListNode *next; // 指向后继节点的指针 + ListNode *prev; // 指向前驱节点的指针 + ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 构造函数 +}; +``` + +```java title="" +/* 双向链表节点类 */ +class ListNode { + int val; // 节点值 + ListNode next; // 指向后继节点的引用 + ListNode prev; // 指向前驱节点的引用 + ListNode(int x) { val = x; } // 构造函数 +} +``` + +```csharp title="" +/* 双向链表节点类 */ +class ListNode(int x) { // 构造函数 + int val = x; // 节点值 + ListNode next; // 指向后继节点的引用 + ListNode prev; // 指向前驱节点的引用 +} +``` + +```go title="" +/* 双向链表节点结构体 */ +type DoublyListNode struct { + Val int // 节点值 + Next *DoublyListNode // 指向后继节点的指针 + Prev *DoublyListNode // 指向前驱节点的指针 +} + +// NewDoublyListNode 初始化 +func NewDoublyListNode(val int) *DoublyListNode { + return &DoublyListNode{ + Val: val, + Next: nil, + Prev: nil, + } +} +``` + +```swift title="" +/* 双向链表节点类 */ +class ListNode { + var val: Int // 节点值 + var next: ListNode? // 指向后继节点的引用 + var prev: ListNode? // 指向前驱节点的引用 + + init(x: Int) { // 构造函数 + val = x + } +} +``` + +```javascript title="" +/* 双向链表节点类 */ +class ListNode { + constructor(val, next, prev) { + this.val = val === undefined ? 0 : val; // 节点值 + this.next = next === undefined ? null : next; // 指向后继节点的引用 + this.prev = prev === undefined ? null : prev; // 指向前驱节点的引用 + } +} +``` + +```typescript title="" +/* 双向链表节点类 */ +class ListNode { + val: number; + next: ListNode | null; + prev: ListNode | null; + constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { + this.val = val === undefined ? 0 : val; // 节点值 + this.next = next === undefined ? null : next; // 指向后继节点的引用 + this.prev = prev === undefined ? null : prev; // 指向前驱节点的引用 + } +} +``` + +```dart title="" +/* 双向链表节点类 */ +class ListNode { + int val; // 节点值 + ListNode? next; // 指向后继节点的引用 + ListNode? prev; // 指向前驱节点的引用 + ListNode(this.val, [this.next, this.prev]); // 构造函数 +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 双向链表节点类型 */ +#[derive(Debug)] +struct ListNode { + val: i32, // 节点值 + next: Option>>, // 指向后继节点的指针 + prev: Option>>, // 指向前驱节点的指针 +} + +/* 构造函数 */ +impl ListNode { + fn new(val: i32) -> Self { + ListNode { + val, + next: None, + prev: None, + } + } +} +``` + +```c title="" +/* 双向链表节点结构体 */ +typedef struct ListNode { + int val; // 节点值 + struct ListNode *next; // 指向后继节点的指针 + struct ListNode *prev; // 指向前驱节点的指针 +} ListNode; + +/* 构造函数 */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + node->prev = NULL; + return node; +} +``` + +```kotlin title="" +/* 双向链表节点类 */ +// 构造方法 +class ListNode(x: Int) { + val _val: Int = x // 节点值 + var next: ListNode? = null // 指向后继节点的引用 + var prev: ListNode? = null // 指向前驱节点的引用 +} +``` + +```ruby title="" +# 双向链表节点类 +class ListNode + attr_accessor :val # 节点值 + attr_accessor :next # 指向后继节点的引用 + attr_accessor :prev # 指向前驱节点的引用 + + def initialize(val=0, next_node=nil, prev_node=nil) + @val = val + @next = next_node + @prev = prev_node + end +end +``` diff --git a/codes/snippets/chapter_array_and_linkedlist/list.md b/codes/snippets/chapter_array_and_linkedlist/list.md new file mode 100644 index 000000000..a8510672b --- /dev/null +++ b/codes/snippets/chapter_array_and_linkedlist/list.md @@ -0,0 +1,752 @@ + +```python title="list.py" +# 初始化列表 +# 无初始值 +nums1: list[int] = [] +# 有初始值 +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="list.cpp" +/* 初始化列表 */ +// 需注意,C++ 中 vector 即是本文描述的 nums +// 无初始值 +vector nums1; +// 有初始值 +vector nums = { 1, 3, 2, 5, 4 }; +``` + +```java title="list.java" +/* 初始化列表 */ +// 无初始值 +List nums1 = new ArrayList<>(); +// 有初始值(注意数组的元素类型需为 int[] 的包装类 Integer[]) +Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; +List nums = new ArrayList<>(Arrays.asList(numbers)); +``` + +```csharp title="list.cs" +/* 初始化列表 */ +// 无初始值 +List nums1 = []; +// 有初始值 +int[] numbers = [1, 3, 2, 5, 4]; +List nums = [.. numbers]; +``` + +```go title="list_test.go" +/* 初始化列表 */ +// 无初始值 +nums1 := []int{} +// 有初始值 +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="list.swift" +/* 初始化列表 */ +// 无初始值 +let nums1: [Int] = [] +// 有初始值 +var nums = [1, 3, 2, 5, 4] +``` + +```javascript title="list.js" +/* 初始化列表 */ +// 无初始值 +const nums1 = []; +// 有初始值 +const nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="list.ts" +/* 初始化列表 */ +// 无初始值 +const nums1: number[] = []; +// 有初始值 +const nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="list.dart" +/* 初始化列表 */ +// 无初始值 +List nums1 = []; +// 有初始值 +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="list.rs" +/* 初始化列表 */ +// 无初始值 +let nums1: Vec = Vec::new(); +// 有初始值 +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="list.c" +// C 未提供内置动态数组 +``` + +```kotlin title="list.kt" +/* 初始化列表 */ +// 无初始值 +var nums1 = listOf() +// 有初始值 +var numbers = arrayOf(1, 3, 2, 5, 4) +var nums = numbers.toMutableList() +``` + +```ruby title="list.rb" +# 初始化列表 +# 无初始值 +nums1 = [] +# 有初始值 +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20%23%20%E6%97%A0%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 访问元素 +num: int = nums[1] # 访问索引 1 处的元素 + +# 更新元素 +nums[1] = 0 # 将索引 1 处的元素更新为 0 +``` + +```cpp title="list.cpp" +/* 访问元素 */ +int num = nums[1]; // 访问索引 1 处的元素 + +/* 更新元素 */ +nums[1] = 0; // 将索引 1 处的元素更新为 0 +``` + +```java title="list.java" +/* 访问元素 */ +int num = nums.get(1); // 访问索引 1 处的元素 + +/* 更新元素 */ +nums.set(1, 0); // 将索引 1 处的元素更新为 0 +``` + +```csharp title="list.cs" +/* 访问元素 */ +int num = nums[1]; // 访问索引 1 处的元素 + +/* 更新元素 */ +nums[1] = 0; // 将索引 1 处的元素更新为 0 +``` + +```go title="list_test.go" +/* 访问元素 */ +num := nums[1] // 访问索引 1 处的元素 + +/* 更新元素 */ +nums[1] = 0 // 将索引 1 处的元素更新为 0 +``` + +```swift title="list.swift" +/* 访问元素 */ +let num = nums[1] // 访问索引 1 处的元素 + +/* 更新元素 */ +nums[1] = 0 // 将索引 1 处的元素更新为 0 +``` + +```javascript title="list.js" +/* 访问元素 */ +const num = nums[1]; // 访问索引 1 处的元素 + +/* 更新元素 */ +nums[1] = 0; // 将索引 1 处的元素更新为 0 +``` + +```typescript title="list.ts" +/* 访问元素 */ +const num: number = nums[1]; // 访问索引 1 处的元素 + +/* 更新元素 */ +nums[1] = 0; // 将索引 1 处的元素更新为 0 +``` + +```dart title="list.dart" +/* 访问元素 */ +int num = nums[1]; // 访问索引 1 处的元素 + +/* 更新元素 */ +nums[1] = 0; // 将索引 1 处的元素更新为 0 +``` + +```rust title="list.rs" +/* 访问元素 */ +let num: i32 = nums[1]; // 访问索引 1 处的元素 +/* 更新元素 */ +nums[1] = 0; // 将索引 1 处的元素更新为 0 +``` + +```c title="list.c" +// C 未提供内置动态数组 +``` + +```kotlin title="list.kt" +/* 访问元素 */ +val num = nums[1] // 访问索引 1 处的元素 +/* 更新元素 */ +nums[1] = 0 // 将索引 1 处的元素更新为 0 +``` + +```ruby title="list.rb" +# 访问元素 +num = nums[1] # 访问索引 1 处的元素 +# 更新元素 +nums[1] = 0 # 将索引 1 处的元素更新为 0 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E8%AE%BF%E9%97%AE%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%86%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E4%B8%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 清空列表 +nums.clear() + +# 在尾部添加元素 +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +# 在中间插入元素 +nums.insert(3, 6) # 在索引 3 处插入数字 6 + +# 删除元素 +nums.pop(3) # 删除索引 3 处的元素 +``` + +```cpp title="list.cpp" +/* 清空列表 */ +nums.clear(); + +/* 在尾部添加元素 */ +nums.push_back(1); +nums.push_back(3); +nums.push_back(2); +nums.push_back(5); +nums.push_back(4); + +/* 在中间插入元素 */ +nums.insert(nums.begin() + 3, 6); // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums.erase(nums.begin() + 3); // 删除索引 3 处的元素 +``` + +```java title="list.java" +/* 清空列表 */ +nums.clear(); + +/* 在尾部添加元素 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 在中间插入元素 */ +nums.add(3, 6); // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums.remove(3); // 删除索引 3 处的元素 +``` + +```csharp title="list.cs" +/* 清空列表 */ +nums.Clear(); + +/* 在尾部添加元素 */ +nums.Add(1); +nums.Add(3); +nums.Add(2); +nums.Add(5); +nums.Add(4); + +/* 在中间插入元素 */ +nums.Insert(3, 6); // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums.RemoveAt(3); // 删除索引 3 处的元素 +``` + +```go title="list_test.go" +/* 清空列表 */ +nums = nil + +/* 在尾部添加元素 */ +nums = append(nums, 1) +nums = append(nums, 3) +nums = append(nums, 2) +nums = append(nums, 5) +nums = append(nums, 4) + +/* 在中间插入元素 */ +nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums = append(nums[:3], nums[4:]...) // 删除索引 3 处的元素 +``` + +```swift title="list.swift" +/* 清空列表 */ +nums.removeAll() + +/* 在尾部添加元素 */ +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +/* 在中间插入元素 */ +nums.insert(6, at: 3) // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums.remove(at: 3) // 删除索引 3 处的元素 +``` + +```javascript title="list.js" +/* 清空列表 */ +nums.length = 0; + +/* 在尾部添加元素 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 在中间插入元素 */ +nums.splice(3, 0, 6); // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums.splice(3, 1); // 删除索引 3 处的元素 +``` + +```typescript title="list.ts" +/* 清空列表 */ +nums.length = 0; + +/* 在尾部添加元素 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 在中间插入元素 */ +nums.splice(3, 0, 6); // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums.splice(3, 1); // 删除索引 3 处的元素 +``` + +```dart title="list.dart" +/* 清空列表 */ +nums.clear(); + +/* 在尾部添加元素 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 在中间插入元素 */ +nums.insert(3, 6); // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums.removeAt(3); // 删除索引 3 处的元素 +``` + +```rust title="list.rs" +/* 清空列表 */ +nums.clear(); + +/* 在尾部添加元素 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 在中间插入元素 */ +nums.insert(3, 6); // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums.remove(3); // 删除索引 3 处的元素 +``` + +```c title="list.c" +// C 未提供内置动态数组 +``` + +```kotlin title="list.kt" +/* 清空列表 */ +nums.clear(); + +/* 在尾部添加元素 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 在中间插入元素 */ +nums.add(3, 6); // 在索引 3 处插入数字 6 + +/* 删除元素 */ +nums.remove(3); // 删除索引 3 处的元素 +``` + +```ruby title="list.rb" +# 清空列表 +nums.clear + +# 在尾部添加元素 +nums << 1 +nums << 3 +nums << 2 +nums << 5 +nums << 4 + +# 在中间插入元素 +nums.insert(3, 6) # 在索引 3 处插入数字 6 + +# 删除元素 +nums.delete_at(3) # 删除索引 3 处的元素 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B8%85%E7%A9%BA%E5%88%97%E8%A1%A8%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E5%B0%BE%E9%83%A8%E6%B7%BB%E5%8A%A0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.insert%283,%206%29%20%20%23%20%E5%9C%A8%E7%B4%A2%E5%BC%95%203%20%E5%A4%84%E6%8F%92%E5%85%A5%E6%95%B0%E5%AD%97%206%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E7%B4%A2%E5%BC%95%203%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 通过索引遍历列表 +count = 0 +for i in range(len(nums)): + count += nums[i] + +# 直接遍历列表元素 +for num in nums: + count += num +``` + +```cpp title="list.cpp" +/* 通过索引遍历列表 */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums[i]; +} + +/* 直接遍历列表元素 */ +count = 0; +for (int num : nums) { + count += num; +} +``` + +```java title="list.java" +/* 通过索引遍历列表 */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums.get(i); +} + +/* 直接遍历列表元素 */ +for (int num : nums) { + count += num; +} +``` + +```csharp title="list.cs" +/* 通过索引遍历列表 */ +int count = 0; +for (int i = 0; i < nums.Count; i++) { + count += nums[i]; +} + +/* 直接遍历列表元素 */ +count = 0; +foreach (int num in nums) { + count += num; +} +``` + +```go title="list_test.go" +/* 通过索引遍历列表 */ +count := 0 +for i := 0; i < len(nums); i++ { + count += nums[i] +} + +/* 直接遍历列表元素 */ +count = 0 +for _, num := range nums { + count += num +} +``` + +```swift title="list.swift" +/* 通过索引遍历列表 */ +var count = 0 +for i in nums.indices { + count += nums[i] +} + +/* 直接遍历列表元素 */ +count = 0 +for num in nums { + count += num +} +``` + +```javascript title="list.js" +/* 通过索引遍历列表 */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* 直接遍历列表元素 */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```typescript title="list.ts" +/* 通过索引遍历列表 */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* 直接遍历列表元素 */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```dart title="list.dart" +/* 通过索引遍历列表 */ +int count = 0; +for (var i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* 直接遍历列表元素 */ +count = 0; +for (var num in nums) { + count += num; +} +``` + +```rust title="list.rs" +// 通过索引遍历列表 +let mut _count = 0; +for i in 0..nums.len() { + _count += nums[i]; +} + +// 直接遍历列表元素 +_count = 0; +for num in &nums { + _count += num; +} +``` + +```c title="list.c" +// C 未提供内置动态数组 +``` + +```kotlin title="list.kt" +/* 通过索引遍历列表 */ +var count = 0 +for (i in nums.indices) { + count += nums[i] +} + +/* 直接遍历列表元素 */ +for (num in nums) { + count += num +} +``` + +```ruby title="list.rb" +# 通过索引遍历列表 +count = 0 +for i in 0...nums.length + count += nums[i] +end + +# 直接遍历列表元素 +count = 0 +for num in nums + count += num +end +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%80%9A%E8%BF%87%E7%B4%A2%E5%BC%95%E9%81%8D%E5%8E%86%E5%88%97%E8%A1%A8%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%E7%9B%B4%E6%8E%A5%E9%81%8D%E5%8E%86%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 拼接两个列表 +nums1: list[int] = [6, 8, 7, 10, 9] +nums += nums1 # 将列表 nums1 拼接到 nums 之后 +``` + +```cpp title="list.cpp" +/* 拼接两个列表 */ +vector nums1 = { 6, 8, 7, 10, 9 }; +// 将列表 nums1 拼接到 nums 之后 +nums.insert(nums.end(), nums1.begin(), nums1.end()); +``` + +```java title="list.java" +/* 拼接两个列表 */ +List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); +nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后 +``` + +```csharp title="list.cs" +/* 拼接两个列表 */ +List nums1 = [6, 8, 7, 10, 9]; +nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后 +``` + +```go title="list_test.go" +/* 拼接两个列表 */ +nums1 := []int{6, 8, 7, 10, 9} +nums = append(nums, nums1...) // 将列表 nums1 拼接到 nums 之后 +``` + +```swift title="list.swift" +/* 拼接两个列表 */ +let nums1 = [6, 8, 7, 10, 9] +nums.append(contentsOf: nums1) // 将列表 nums1 拼接到 nums 之后 +``` + +```javascript title="list.js" +/* 拼接两个列表 */ +const nums1 = [6, 8, 7, 10, 9]; +nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后 +``` + +```typescript title="list.ts" +/* 拼接两个列表 */ +const nums1: number[] = [6, 8, 7, 10, 9]; +nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后 +``` + +```dart title="list.dart" +/* 拼接两个列表 */ +List nums1 = [6, 8, 7, 10, 9]; +nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后 +``` + +```rust title="list.rs" +/* 拼接两个列表 */ +let nums1: Vec = vec![6, 8, 7, 10, 9]; +nums.extend(nums1); +``` + +```c title="list.c" +// C 未提供内置动态数组 +``` + +```kotlin title="list.kt" +/* 拼接两个列表 */ +val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() +nums.addAll(nums1) // 将列表 nums1 拼接到 nums 之后 +``` + +```ruby title="list.rb" +# 拼接两个列表 +nums1 = [6, 8, 7, 10, 9] +nums += nums1 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8B%BC%E6%8E%A5%E4%B8%A4%E4%B8%AA%E5%88%97%E8%A1%A8%0A%20%20%20%20nums1%20%3D%20%5B6,%208,%207,%2010,%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%E5%B0%86%E5%88%97%E8%A1%A8%20nums1%20%E6%8B%BC%E6%8E%A5%E5%88%B0%20nums%20%E4%B9%8B%E5%90%8E&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 排序列表 +nums.sort() # 排序后,列表元素从小到大排列 +``` + +```cpp title="list.cpp" +/* 排序列表 */ +sort(nums.begin(), nums.end()); // 排序后,列表元素从小到大排列 +``` + +```java title="list.java" +/* 排序列表 */ +Collections.sort(nums); // 排序后,列表元素从小到大排列 +``` + +```csharp title="list.cs" +/* 排序列表 */ +nums.Sort(); // 排序后,列表元素从小到大排列 +``` + +```go title="list_test.go" +/* 排序列表 */ +sort.Ints(nums) // 排序后,列表元素从小到大排列 +``` + +```swift title="list.swift" +/* 排序列表 */ +nums.sort() // 排序后,列表元素从小到大排列 +``` + +```javascript title="list.js" +/* 排序列表 */ +nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列 +``` + +```typescript title="list.ts" +/* 排序列表 */ +nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列 +``` + +```dart title="list.dart" +/* 排序列表 */ +nums.sort(); // 排序后,列表元素从小到大排列 +``` + +```rust title="list.rs" +/* 排序列表 */ +nums.sort(); // 排序后,列表元素从小到大排列 +``` + +```c title="list.c" +// C 未提供内置动态数组 +``` + +```kotlin title="list.kt" +/* 排序列表 */ +nums.sort() // 排序后,列表元素从小到大排列 +``` + +```ruby title="list.rb" +# 排序列表 +nums = nums.sort { |a, b| a <=> b } # 排序后,列表元素从小到大排列 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8E%92%E5%BA%8F%E5%88%97%E8%A1%A8%0A%20%20%20%20nums.sort%28%29%20%20%23%20%E6%8E%92%E5%BA%8F%E5%90%8E%EF%BC%8C%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%E4%BB%8E%E5%B0%8F%E5%88%B0%E5%A4%A7%E6%8E%92%E5%88%97&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_backtracking/backtracking_algorithm.md b/codes/snippets/chapter_backtracking/backtracking_algorithm.md new file mode 100644 index 000000000..a1c424bf4 --- /dev/null +++ b/codes/snippets/chapter_backtracking/backtracking_algorithm.md @@ -0,0 +1,308 @@ + +```python title="" +def backtrack(state: State, choices: list[choice], res: list[state]): + """回溯算法框架""" + # 判断是否为解 + if is_solution(state): + # 记录解 + record_solution(state, res) + # 不再继续搜索 + return + # 遍历所有选择 + for choice in choices: + # 剪枝:判断选择是否合法 + if is_valid(state, choice): + # 尝试:做出选择,更新状态 + make_choice(state, choice) + backtrack(state, choices, res) + # 回退:撤销选择,恢复到之前的状态 + undo_choice(state, choice) +``` + +```cpp title="" +/* 回溯算法框架 */ +void backtrack(State *state, vector &choices, vector &res) { + // 判断是否为解 + if (isSolution(state)) { + // 记录解 + recordSolution(state, res); + // 不再继续搜索 + return; + } + // 遍历所有选择 + for (Choice choice : choices) { + // 剪枝:判断选择是否合法 + if (isValid(state, choice)) { + // 尝试:做出选择,更新状态 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤销选择,恢复到之前的状态 + undoChoice(state, choice); + } + } +} +``` + +```java title="" +/* 回溯算法框架 */ +void backtrack(State state, List choices, List res) { + // 判断是否为解 + if (isSolution(state)) { + // 记录解 + recordSolution(state, res); + // 不再继续搜索 + return; + } + // 遍历所有选择 + for (Choice choice : choices) { + // 剪枝:判断选择是否合法 + if (isValid(state, choice)) { + // 尝试:做出选择,更新状态 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤销选择,恢复到之前的状态 + undoChoice(state, choice); + } + } +} +``` + +```csharp title="" +/* 回溯算法框架 */ +void Backtrack(State state, List choices, List res) { + // 判断是否为解 + if (IsSolution(state)) { + // 记录解 + RecordSolution(state, res); + // 不再继续搜索 + return; + } + // 遍历所有选择 + foreach (Choice choice in choices) { + // 剪枝:判断选择是否合法 + if (IsValid(state, choice)) { + // 尝试:做出选择,更新状态 + MakeChoice(state, choice); + Backtrack(state, choices, res); + // 回退:撤销选择,恢复到之前的状态 + UndoChoice(state, choice); + } + } +} +``` + +```go title="" +/* 回溯算法框架 */ +func backtrack(state *State, choices []Choice, res *[]State) { + // 判断是否为解 + if isSolution(state) { + // 记录解 + recordSolution(state, res) + // 不再继续搜索 + return + } + // 遍历所有选择 + for _, choice := range choices { + // 剪枝:判断选择是否合法 + if isValid(state, choice) { + // 尝试:做出选择,更新状态 + makeChoice(state, choice) + backtrack(state, choices, res) + // 回退:撤销选择,恢复到之前的状态 + undoChoice(state, choice) + } + } +} +``` + +```swift title="" +/* 回溯算法框架 */ +func backtrack(state: inout State, choices: [Choice], res: inout [State]) { + // 判断是否为解 + if isSolution(state: state) { + // 记录解 + recordSolution(state: state, res: &res) + // 不再继续搜索 + return + } + // 遍历所有选择 + for choice in choices { + // 剪枝:判断选择是否合法 + if isValid(state: state, choice: choice) { + // 尝试:做出选择,更新状态 + makeChoice(state: &state, choice: choice) + backtrack(state: &state, choices: choices, res: &res) + // 回退:撤销选择,恢复到之前的状态 + undoChoice(state: &state, choice: choice) + } + } +} +``` + +```javascript title="" +/* 回溯算法框架 */ +function backtrack(state, choices, res) { + // 判断是否为解 + if (isSolution(state)) { + // 记录解 + recordSolution(state, res); + // 不再继续搜索 + return; + } + // 遍历所有选择 + for (let choice of choices) { + // 剪枝:判断选择是否合法 + if (isValid(state, choice)) { + // 尝试:做出选择,更新状态 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤销选择,恢复到之前的状态 + undoChoice(state, choice); + } + } +} +``` + +```typescript title="" +/* 回溯算法框架 */ +function backtrack(state: State, choices: Choice[], res: State[]): void { + // 判断是否为解 + if (isSolution(state)) { + // 记录解 + recordSolution(state, res); + // 不再继续搜索 + return; + } + // 遍历所有选择 + for (let choice of choices) { + // 剪枝:判断选择是否合法 + if (isValid(state, choice)) { + // 尝试:做出选择,更新状态 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤销选择,恢复到之前的状态 + undoChoice(state, choice); + } + } +} +``` + +```dart title="" +/* 回溯算法框架 */ +void backtrack(State state, List, List res) { + // 判断是否为解 + if (isSolution(state)) { + // 记录解 + recordSolution(state, res); + // 不再继续搜索 + return; + } + // 遍历所有选择 + for (Choice choice in choices) { + // 剪枝:判断选择是否合法 + if (isValid(state, choice)) { + // 尝试:做出选择,更新状态 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤销选择,恢复到之前的状态 + undoChoice(state, choice); + } + } +} +``` + +```rust title="" +/* 回溯算法框架 */ +fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { + // 判断是否为解 + if is_solution(state) { + // 记录解 + record_solution(state, res); + // 不再继续搜索 + return; + } + // 遍历所有选择 + for choice in choices { + // 剪枝:判断选择是否合法 + if is_valid(state, choice) { + // 尝试:做出选择,更新状态 + make_choice(state, choice); + backtrack(state, choices, res); + // 回退:撤销选择,恢复到之前的状态 + undo_choice(state, choice); + } + } +} +``` + +```c title="" +/* 回溯算法框架 */ +void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { + // 判断是否为解 + if (isSolution(state)) { + // 记录解 + recordSolution(state, res, numRes); + // 不再继续搜索 + return; + } + // 遍历所有选择 + for (int i = 0; i < numChoices; i++) { + // 剪枝:判断选择是否合法 + if (isValid(state, &choices[i])) { + // 尝试:做出选择,更新状态 + makeChoice(state, &choices[i]); + backtrack(state, choices, numChoices, res, numRes); + // 回退:撤销选择,恢复到之前的状态 + undoChoice(state, &choices[i]); + } + } +} +``` + +```kotlin title="" +/* 回溯算法框架 */ +fun backtrack(state: State?, choices: List, res: List?) { + // 判断是否为解 + if (isSolution(state)) { + // 记录解 + recordSolution(state, res) + // 不再继续搜索 + return + } + // 遍历所有选择 + for (choice in choices) { + // 剪枝:判断选择是否合法 + if (isValid(state, choice)) { + // 尝试:做出选择,更新状态 + makeChoice(state, choice) + backtrack(state, choices, res) + // 回退:撤销选择,恢复到之前的状态 + undoChoice(state, choice) + } + } +} +``` + +```ruby title="" +### 回溯算法框架 ### +def backtrack(state, choices, res) + # 判断是否为解 + if is_solution?(state) + # 记录解 + record_solution(state, res) + return + end + + # 遍历所有选择 + for choice in choices + # 剪枝:判断选择是否合法 + if is_valid?(state, choice) + # 尝试:做出选择,更新状态 + make_choice(state, choice) + backtrack(state, choices, res) + # 回退:撤销选择,恢复到之前的状态 + undo_choice(state, choice) + end + end +end +``` diff --git a/codes/snippets/chapter_computational_complexity/space_complexity.md b/codes/snippets/chapter_computational_complexity/space_complexity.md new file mode 100644 index 000000000..d8b044698 --- /dev/null +++ b/codes/snippets/chapter_computational_complexity/space_complexity.md @@ -0,0 +1,682 @@ + +```python title="" +class Node: + """类""" + def __init__(self, x: int): + self.val: int = x # 节点值 + self.next: Node | None = None # 指向下一节点的引用 + +def function() -> int: + """函数""" + # 执行某些操作... + return 0 + +def algorithm(n) -> int: # 输入数据 + A = 0 # 暂存数据(常量,一般用大写字母表示) + b = 0 # 暂存数据(变量) + node = Node(0) # 暂存数据(对象) + c = function() # 栈帧空间(调用函数) + return A + b + c # 输出数据 +``` + +```cpp title="" +/* 结构体 */ +struct Node { + int val; + Node *next; + Node(int x) : val(x), next(nullptr) {} +}; + +/* 函数 */ +int func() { + // 执行某些操作... + return 0; +} + +int algorithm(int n) { // 输入数据 + const int a = 0; // 暂存数据(常量) + int b = 0; // 暂存数据(变量) + Node* node = new Node(0); // 暂存数据(对象) + int c = func(); // 栈帧空间(调用函数) + return a + b + c; // 输出数据 +} +``` + +```java title="" +/* 类 */ +class Node { + int val; + Node next; + Node(int x) { val = x; } +} + +/* 函数 */ +int function() { + // 执行某些操作... + return 0; +} + +int algorithm(int n) { // 输入数据 + final int a = 0; // 暂存数据(常量) + int b = 0; // 暂存数据(变量) + Node node = new Node(0); // 暂存数据(对象) + int c = function(); // 栈帧空间(调用函数) + return a + b + c; // 输出数据 +} +``` + +```csharp title="" +/* 类 */ +class Node(int x) { + int val = x; + Node next; +} + +/* 函数 */ +int Function() { + // 执行某些操作... + return 0; +} + +int Algorithm(int n) { // 输入数据 + const int a = 0; // 暂存数据(常量) + int b = 0; // 暂存数据(变量) + Node node = new(0); // 暂存数据(对象) + int c = Function(); // 栈帧空间(调用函数) + return a + b + c; // 输出数据 +} +``` + +```go title="" +/* 结构体 */ +type node struct { + val int + next *node +} + +/* 创建 node 结构体 */ +func newNode(val int) *node { + return &node{val: val} +} + +/* 函数 */ +func function() int { + // 执行某些操作... + return 0 +} + +func algorithm(n int) int { // 输入数据 + const a = 0 // 暂存数据(常量) + b := 0 // 暂存数据(变量) + newNode(0) // 暂存数据(对象) + c := function() // 栈帧空间(调用函数) + return a + b + c // 输出数据 +} +``` + +```swift title="" +/* 类 */ +class Node { + var val: Int + var next: Node? + + init(x: Int) { + val = x + } +} + +/* 函数 */ +func function() -> Int { + // 执行某些操作... + return 0 +} + +func algorithm(n: Int) -> Int { // 输入数据 + let a = 0 // 暂存数据(常量) + var b = 0 // 暂存数据(变量) + let node = Node(x: 0) // 暂存数据(对象) + let c = function() // 栈帧空间(调用函数) + return a + b + c // 输出数据 +} +``` + +```javascript title="" +/* 类 */ +class Node { + val; + next; + constructor(val) { + this.val = val === undefined ? 0 : val; // 节点值 + this.next = null; // 指向下一节点的引用 + } +} + +/* 函数 */ +function constFunc() { + // 执行某些操作 + return 0; +} + +function algorithm(n) { // 输入数据 + const a = 0; // 暂存数据(常量) + let b = 0; // 暂存数据(变量) + const node = new Node(0); // 暂存数据(对象) + const c = constFunc(); // 栈帧空间(调用函数) + return a + b + c; // 输出数据 +} +``` + +```typescript title="" +/* 类 */ +class Node { + val: number; + next: Node | null; + constructor(val?: number) { + this.val = val === undefined ? 0 : val; // 节点值 + this.next = null; // 指向下一节点的引用 + } +} + +/* 函数 */ +function constFunc(): number { + // 执行某些操作 + return 0; +} + +function algorithm(n: number): number { // 输入数据 + const a = 0; // 暂存数据(常量) + let b = 0; // 暂存数据(变量) + const node = new Node(0); // 暂存数据(对象) + const c = constFunc(); // 栈帧空间(调用函数) + return a + b + c; // 输出数据 +} +``` + +```dart title="" +/* 类 */ +class Node { + int val; + Node next; + Node(this.val, [this.next]); +} + +/* 函数 */ +int function() { + // 执行某些操作... + return 0; +} + +int algorithm(int n) { // 输入数据 + const int a = 0; // 暂存数据(常量) + int b = 0; // 暂存数据(变量) + Node node = Node(0); // 暂存数据(对象) + int c = function(); // 栈帧空间(调用函数) + return a + b + c; // 输出数据 +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 结构体 */ +struct Node { + val: i32, + next: Option>>, +} + +/* 创建 Node 结构体 */ +impl Node { + fn new(val: i32) -> Self { + Self { val: val, next: None } + } +} + +/* 函数 */ +fn function() -> i32 { + // 执行某些操作... + return 0; +} + +fn algorithm(n: i32) -> i32 { // 输入数据 + const a: i32 = 0; // 暂存数据(常量) + let mut b = 0; // 暂存数据(变量) + let node = Node::new(0); // 暂存数据(对象) + let c = function(); // 栈帧空间(调用函数) + return a + b + c; // 输出数据 +} +``` + +```c title="" +/* 函数 */ +int func() { + // 执行某些操作... + return 0; +} + +int algorithm(int n) { // 输入数据 + const int a = 0; // 暂存数据(常量) + int b = 0; // 暂存数据(变量) + int c = func(); // 栈帧空间(调用函数) + return a + b + c; // 输出数据 +} +``` + +```kotlin title="" +/* 类 */ +class Node(var _val: Int) { + var next: Node? = null +} + +/* 函数 */ +fun function(): Int { + // 执行某些操作... + return 0 +} + +fun algorithm(n: Int): Int { // 输入数据 + val a = 0 // 暂存数据(常量) + var b = 0 // 暂存数据(变量) + val node = Node(0) // 暂存数据(对象) + val c = function() // 栈帧空间(调用函数) + return a + b + c // 输出数据 +} +``` + +```ruby title="" +### 类 ### +class Node + attr_accessor :val # 节点值 + attr_accessor :next # 指向下一节点的引用 + + def initialize(x) + @val = x + end +end + +### 函数 ### +def function + # 执行某些操作... + 0 +end + +### 算法 ### +def algorithm(n) # 输入数据 + a = 0 # 暂存数据(常量) + b = 0 # 暂存数据(变量) + node = Node.new(0) # 暂存数据(对象) + c = function # 栈帧空间(调用函数) + a + b + c # 输出数据 +end +``` + + +```python title="" +def algorithm(n: int): + a = 0 # O(1) + b = [0] * 10000 # O(1) + if n > 10: + nums = [0] * n # O(n) +``` + +```cpp title="" +void algorithm(int n) { + int a = 0; // O(1) + vector b(10000); // O(1) + if (n > 10) + vector nums(n); // O(n) +} +``` + +```java title="" +void algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) + int[] nums = new int[n]; // O(n) +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) { + int[] nums = new int[n]; // O(n) + } +} +``` + +```go title="" +func algorithm(n int) { + a := 0 // O(1) + b := make([]int, 10000) // O(1) + var nums []int + if n > 10 { + nums := make([]int, n) // O(n) + } + fmt.Println(a, b, nums) +} +``` + +```swift title="" +func algorithm(n: Int) { + let a = 0 // O(1) + let b = Array(repeating: 0, count: 10000) // O(1) + if n > 10 { + let nums = Array(repeating: 0, count: n) // O(n) + } +} +``` + +```javascript title="" +function algorithm(n) { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 0; // O(1) + List b = List.filled(10000, 0); // O(1) + if (n > 10) { + List nums = List.filled(n, 0); // O(n) + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let a = 0; // O(1) + let b = [0; 10000]; // O(1) + if n > 10 { + let nums = vec![0; n as usize]; // O(n) + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 0; // O(1) + int b[10000]; // O(1) + if (n > 10) + int nums[n] = {0}; // O(n) +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + val a = 0 // O(1) + val b = IntArray(10000) // O(1) + if (n > 10) { + val nums = IntArray(n) // O(n) + } +} +``` + +```ruby title="" +def algorithm(n) + a = 0 # O(1) + b = Array.new(10000) # O(1) + nums = Array.new(n) if n > 10 # O(n) +end +``` + + +```python title="" +def function() -> int: + # 执行某些操作 + return 0 + +def loop(n: int): + """循环的空间复杂度为 O(1)""" + for _ in range(n): + function() + +def recur(n: int): + """递归的空间复杂度为 O(n)""" + if n == 1: + return + return recur(n - 1) +``` + +```cpp title="" +int func() { + // 执行某些操作 + return 0; +} +/* 循环的空间复杂度为 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* 递归的空间复杂度为 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```java title="" +int function() { + // 执行某些操作 + return 0; +} +/* 循环的空间复杂度为 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* 递归的空间复杂度为 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```csharp title="" +int Function() { + // 执行某些操作 + return 0; +} +/* 循环的空间复杂度为 O(1) */ +void Loop(int n) { + for (int i = 0; i < n; i++) { + Function(); + } +} +/* 递归的空间复杂度为 O(n) */ +int Recur(int n) { + if (n == 1) return 1; + return Recur(n - 1); +} +``` + +```go title="" +func function() int { + // 执行某些操作 + return 0 +} + +/* 循环的空间复杂度为 O(1) */ +func loop(n int) { + for i := 0; i < n; i++ { + function() + } +} + +/* 递归的空间复杂度为 O(n) */ +func recur(n int) { + if n == 1 { + return + } + recur(n - 1) +} +``` + +```swift title="" +@discardableResult +func function() -> Int { + // 执行某些操作 + return 0 +} + +/* 循环的空间复杂度为 O(1) */ +func loop(n: Int) { + for _ in 0 ..< n { + function() + } +} + +/* 递归的空间复杂度为 O(n) */ +func recur(n: Int) { + if n == 1 { + return + } + recur(n: n - 1) +} +``` + +```javascript title="" +function constFunc() { + // 执行某些操作 + return 0; +} +/* 循环的空间复杂度为 O(1) */ +function loop(n) { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* 递归的空间复杂度为 O(n) */ +function recur(n) { + if (n === 1) return; + return recur(n - 1); +} +``` + +```typescript title="" +function constFunc(): number { + // 执行某些操作 + return 0; +} +/* 循环的空间复杂度为 O(1) */ +function loop(n: number): void { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* 递归的空间复杂度为 O(n) */ +function recur(n: number): void { + if (n === 1) return; + return recur(n - 1); +} +``` + +```dart title="" +int function() { + // 执行某些操作 + return 0; +} +/* 循环的空间复杂度为 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* 递归的空间复杂度为 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```rust title="" +fn function() -> i32 { + // 执行某些操作 + return 0; +} +/* 循环的空间复杂度为 O(1) */ +fn loop(n: i32) { + for i in 0..n { + function(); + } +} +/* 递归的空间复杂度为 O(n) */ +fn recur(n: i32) { + if n == 1 { + return; + } + recur(n - 1); +} +``` + +```c title="" +int func() { + // 执行某些操作 + return 0; +} +/* 循环的空间复杂度为 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* 递归的空间复杂度为 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```kotlin title="" +fun function(): Int { + // 执行某些操作 + return 0 +} +/* 循环的空间复杂度为 O(1) */ +fun loop(n: Int) { + for (i in 0.. +```python title="" +# 在某运行平台下 +def algorithm(n: int): + a = 2 # 1 ns + a = a + 1 # 1 ns + a = a * 2 # 10 ns + # 循环 n 次 + for _ in range(n): # 1 ns + print(0) # 5 ns +``` + +```cpp title="" +// 在某运行平台下 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 循环 n 次 + for (int i = 0; i < n; i++) { // 1 ns + cout << 0 << endl; // 5 ns + } +} +``` + +```java title="" +// 在某运行平台下 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 循环 n 次 + for (int i = 0; i < n; i++) { // 1 ns + System.out.println(0); // 5 ns + } +} +``` + +```csharp title="" +// 在某运行平台下 +void Algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 循环 n 次 + for (int i = 0; i < n; i++) { // 1 ns + Console.WriteLine(0); // 5 ns + } +} +``` + +```go title="" +// 在某运行平台下 +func algorithm(n int) { + a := 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // 循环 n 次 + for i := 0; i < n; i++ { // 1 ns + fmt.Println(a) // 5 ns + } +} +``` + +```swift title="" +// 在某运行平台下 +func algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // 循环 n 次 + for _ in 0 ..< n { // 1 ns + print(0) // 5 ns + } +} +``` + +```javascript title="" +// 在某运行平台下 +function algorithm(n) { + var a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 循环 n 次 + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```typescript title="" +// 在某运行平台下 +function algorithm(n: number): void { + var a: number = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 循环 n 次 + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```dart title="" +// 在某运行平台下 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 循环 n 次 + for (int i = 0; i < n; i++) { // 1 ns + print(0); // 5 ns + } +} +``` + +```rust title="" +// 在某运行平台下 +fn algorithm(n: i32) { + let mut a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 循环 n 次 + for _ in 0..n { // 1 ns + println!("{}", 0); // 5 ns + } +} +``` + +```c title="" +// 在某运行平台下 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 循环 n 次 + for (int i = 0; i < n; i++) { // 1 ns + printf("%d", 0); // 5 ns + } +} +``` + +```kotlin title="" +// 在某运行平台下 +fun algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // 循环 n 次 + for (i in 0.. +```python title="" +# 算法 A 的时间复杂度:常数阶 +def algorithm_A(n: int): + print(0) +# 算法 B 的时间复杂度:线性阶 +def algorithm_B(n: int): + for _ in range(n): + print(0) +# 算法 C 的时间复杂度:常数阶 +def algorithm_C(n: int): + for _ in range(1000000): + print(0) +``` + +```cpp title="" +// 算法 A 的时间复杂度:常数阶 +void algorithm_A(int n) { + cout << 0 << endl; +} +// 算法 B 的时间复杂度:线性阶 +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + cout << 0 << endl; + } +} +// 算法 C 的时间复杂度:常数阶 +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + cout << 0 << endl; + } +} +``` + +```java title="" +// 算法 A 的时间复杂度:常数阶 +void algorithm_A(int n) { + System.out.println(0); +} +// 算法 B 的时间复杂度:线性阶 +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + System.out.println(0); + } +} +// 算法 C 的时间复杂度:常数阶 +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + System.out.println(0); + } +} +``` + +```csharp title="" +// 算法 A 的时间复杂度:常数阶 +void AlgorithmA(int n) { + Console.WriteLine(0); +} +// 算法 B 的时间复杂度:线性阶 +void AlgorithmB(int n) { + for (int i = 0; i < n; i++) { + Console.WriteLine(0); + } +} +// 算法 C 的时间复杂度:常数阶 +void AlgorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + Console.WriteLine(0); + } +} +``` + +```go title="" +// 算法 A 的时间复杂度:常数阶 +func algorithm_A(n int) { + fmt.Println(0) +} +// 算法 B 的时间复杂度:线性阶 +func algorithm_B(n int) { + for i := 0; i < n; i++ { + fmt.Println(0) + } +} +// 算法 C 的时间复杂度:常数阶 +func algorithm_C(n int) { + for i := 0; i < 1000000; i++ { + fmt.Println(0) + } +} +``` + +```swift title="" +// 算法 A 的时间复杂度:常数阶 +func algorithmA(n: Int) { + print(0) +} + +// 算法 B 的时间复杂度:线性阶 +func algorithmB(n: Int) { + for _ in 0 ..< n { + print(0) + } +} + +// 算法 C 的时间复杂度:常数阶 +func algorithmC(n: Int) { + for _ in 0 ..< 1_000_000 { + print(0) + } +} +``` + +```javascript title="" +// 算法 A 的时间复杂度:常数阶 +function algorithm_A(n) { + console.log(0); +} +// 算法 B 的时间复杂度:线性阶 +function algorithm_B(n) { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// 算法 C 的时间复杂度:常数阶 +function algorithm_C(n) { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} + +``` + +```typescript title="" +// 算法 A 的时间复杂度:常数阶 +function algorithm_A(n: number): void { + console.log(0); +} +// 算法 B 的时间复杂度:线性阶 +function algorithm_B(n: number): void { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// 算法 C 的时间复杂度:常数阶 +function algorithm_C(n: number): void { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} +``` + +```dart title="" +// 算法 A 的时间复杂度:常数阶 +void algorithmA(int n) { + print(0); +} +// 算法 B 的时间复杂度:线性阶 +void algorithmB(int n) { + for (int i = 0; i < n; i++) { + print(0); + } +} +// 算法 C 的时间复杂度:常数阶 +void algorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + print(0); + } +} +``` + +```rust title="" +// 算法 A 的时间复杂度:常数阶 +fn algorithm_A(n: i32) { + println!("{}", 0); +} +// 算法 B 的时间复杂度:线性阶 +fn algorithm_B(n: i32) { + for _ in 0..n { + println!("{}", 0); + } +} +// 算法 C 的时间复杂度:常数阶 +fn algorithm_C(n: i32) { + for _ in 0..1000000 { + println!("{}", 0); + } +} +``` + +```c title="" +// 算法 A 的时间复杂度:常数阶 +void algorithm_A(int n) { + printf("%d", 0); +} +// 算法 B 的时间复杂度:线性阶 +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + printf("%d", 0); + } +} +// 算法 C 的时间复杂度:常数阶 +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + printf("%d", 0); + } +} +``` + +```kotlin title="" +// 算法 A 的时间复杂度:常数阶 +fun algoritm_A(n: Int) { + println(0) +} +// 算法 B 的时间复杂度:线性阶 +fun algorithm_B(n: Int) { + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +1 + a = a + 1 # +1 + a = a * 2 # +1 + # 循环 n 次 + for i in range(n): # +1 + print(0) # +1 +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 循环 n 次 + for (int i = 0; i < n; i++) { // +1(每轮都执行 i ++) + cout << 0 << endl; // +1 + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 循环 n 次 + for (int i = 0; i < n; i++) { // +1(每轮都执行 i ++) + System.out.println(0); // +1 + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 循环 n 次 + for (int i = 0; i < n; i++) { // +1(每轮都执行 i ++) + Console.WriteLine(0); // +1 + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // 循环 n 次 + for i := 0; i < n; i++ { // +1 + fmt.Println(a) // +1 + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // 循环 n 次 + for _ in 0 ..< n { // +1 + print(0) // +1 + } +} +``` + +```javascript title="" +function algorithm(n) { + var a = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // 循环 n 次 + for(let i = 0; i < n; i++){ // +1(每轮都执行 i ++) + console.log(0); // +1 + } +} +``` + +```typescript title="" +function algorithm(n: number): void{ + var a: number = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // 循环 n 次 + for(let i = 0; i < n; i++){ // +1(每轮都执行 i ++) + console.log(0); // +1 + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 循环 n 次 + for (int i = 0; i < n; i++) { // +1(每轮都执行 i ++) + print(0); // +1 + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + + // 循环 n 次 + for _ in 0..n { // +1(每轮都执行 i ++) + println!("{}", 0); // +1 + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 循环 n 次 + for (int i = 0; i < n; i++) { // +1(每轮都执行 i ++) + printf("%d", 0); // +1 + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // 循环 n 次 + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +0(技巧 1) + a = a + n # +0(技巧 1) + # +n(技巧 2) + for i in range(5 * n + 1): + print(0) + # +n*n(技巧 3) + for i in range(2 * n): + for j in range(n + 1): + print(0) +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + cout << 0 << endl; + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + cout << 0 << endl; + } + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + System.out.println(0); + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + System.out.println(0); + } + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + Console.WriteLine(0); + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + Console.WriteLine(0); + } + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +0(技巧 1) + a = a + n // +0(技巧 1) + // +n(技巧 2) + for i := 0; i < 5 * n + 1; i++ { + fmt.Println(0) + } + // +n*n(技巧 3) + for i := 0; i < 2 * n; i++ { + for j := 0; j < n + 1; j++ { + fmt.Println(0) + } + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +0(技巧 1) + a = a + n // +0(技巧 1) + // +n(技巧 2) + for _ in 0 ..< (5 * n + 1) { + print(0) + } + // +n*n(技巧 3) + for _ in 0 ..< (2 * n) { + for _ in 0 ..< (n + 1) { + print(0) + } + } +} +``` + +```javascript title="" +function algorithm(n) { + let a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n(技巧 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + let a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n(技巧 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + print(0); + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + print(0); + } + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + + // +n(技巧 2) + for i in 0..(5 * n + 1) { + println!("{}", 0); + } + + // +n*n(技巧 3) + for i in 0..(2 * n) { + for j in 0..(n + 1) { + println!("{}", 0); + } + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + printf("%d", 0); + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + printf("%d", 0); + } + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +0(技巧 1) + a = a + n // +0(技巧 1) + // +n(技巧 2) + for (i in 0..<5 * n + 1) { + println(0) + } + // +n*n(技巧 3) + for (i in 0..<2 * n) { + for (j in 0.. +```python title="" +# 使用多种基本数据类型来初始化数组 +numbers: list[int] = [0] * 5 +decimals: list[float] = [0.0] * 5 +# Python 的字符实际上是长度为 1 的字符串 +characters: list[str] = ['0'] * 5 +bools: list[bool] = [False] * 5 +# Python 的列表可以自由存储各种基本数据类型和对象引用 +data = [0, 0.0, 'a', False, ListNode(0)] +``` + +```cpp title="" +// 使用多种基本数据类型来初始化数组 +int numbers[5]; +float decimals[5]; +char characters[5]; +bool bools[5]; +``` + +```java title="" +// 使用多种基本数据类型来初始化数组 +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +boolean[] bools = new boolean[5]; +``` + +```csharp title="" +// 使用多种基本数据类型来初始化数组 +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +bool[] bools = new bool[5]; +``` + +```go title="" +// 使用多种基本数据类型来初始化数组 +var numbers = [5]int{} +var decimals = [5]float64{} +var characters = [5]byte{} +var bools = [5]bool{} +``` + +```swift title="" +// 使用多种基本数据类型来初始化数组 +let numbers = Array(repeating: 0, count: 5) +let decimals = Array(repeating: 0.0, count: 5) +let characters: [Character] = Array(repeating: "a", count: 5) +let bools = Array(repeating: false, count: 5) +``` + +```javascript title="" +// JavaScript 的数组可以自由存储各种基本数据类型和对象 +const array = [0, 0.0, 'a', false]; +``` + +```typescript title="" +// 使用多种基本数据类型来初始化数组 +const numbers: number[] = []; +const characters: string[] = []; +const bools: boolean[] = []; +``` + +```dart title="" +// 使用多种基本数据类型来初始化数组 +List numbers = List.filled(5, 0); +List decimals = List.filled(5, 0.0); +List characters = List.filled(5, 'a'); +List bools = List.filled(5, false); +``` + +```rust title="" +// 使用多种基本数据类型来初始化数组 +let numbers: Vec = vec![0; 5]; +let decimals: Vec = vec![0.0; 5]; +let characters: Vec = vec!['0'; 5]; +let bools: Vec = vec![false; 5]; +``` + +```c title="" +// 使用多种基本数据类型来初始化数组 +int numbers[10]; +float decimals[10]; +char characters[10]; +bool bools[10]; +``` + +```kotlin title="" +// 使用多种基本数据类型来初始化数组 +val numbers = IntArray(5) +val decinals = FloatArray(5) +val characters = CharArray(5) +val bools = BooleanArray(5) +``` + +```ruby title="" +# Ruby 的列表可以自由存储各种基本数据类型和对象引用 +data = [0, 0.0, 'a', false, ListNode(0)] +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%A7%8D%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E6%9D%A5%E5%88%9D%E5%A7%8B%E5%8C%96%E6%95%B0%E7%BB%84%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20*%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20*%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E5%AD%97%E7%AC%A6%E5%AE%9E%E9%99%85%E4%B8%8A%E6%98%AF%E9%95%BF%E5%BA%A6%E4%B8%BA%201%20%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%0A%20%20%20%20characters%20%3D%20%5B'0'%5D%20*%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20*%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E5%88%97%E8%A1%A8%E5%8F%AF%E4%BB%A5%E8%87%AA%E7%94%B1%E5%AD%98%E5%82%A8%E5%90%84%E7%A7%8D%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%92%8C%E5%AF%B9%E8%B1%A1%E5%BC%95%E7%94%A8%0A%20%20%20%20data%20%3D%20%5B0,%200.0,%20'a',%20False,%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_hashing/hash_algorithm.md b/codes/snippets/chapter_hashing/hash_algorithm.md new file mode 100644 index 000000000..0e6a42f67 --- /dev/null +++ b/codes/snippets/chapter_hashing/hash_algorithm.md @@ -0,0 +1,263 @@ + +```python title="built_in_hash.py" +num = 3 +hash_num = hash(num) +# 整数 3 的哈希值为 3 + +bol = True +hash_bol = hash(bol) +# 布尔量 True 的哈希值为 1 + +dec = 3.14159 +hash_dec = hash(dec) +# 小数 3.14159 的哈希值为 326484311674566659 + +str = "Hello 算法" +hash_str = hash(str) +# 字符串“Hello 算法”的哈希值为 4617003410720528961 + +tup = (12836, "小哈") +hash_tup = hash(tup) +# 元组 (12836, '小哈') 的哈希值为 1029005403108185979 + +obj = ListNode(0) +hash_obj = hash(obj) +# 节点对象 的哈希值为 274267521 +``` + +```cpp title="built_in_hash.cpp" +int num = 3; +size_t hashNum = hash()(num); +// 整数 3 的哈希值为 3 + +bool bol = true; +size_t hashBol = hash()(bol); +// 布尔量 1 的哈希值为 1 + +double dec = 3.14159; +size_t hashDec = hash()(dec); +// 小数 3.14159 的哈希值为 4614256650576692846 + +string str = "Hello 算法"; +size_t hashStr = hash()(str); +// 字符串“Hello 算法”的哈希值为 15466937326284535026 + +// 在 C++ 中,内置 std::hash() 仅提供基本数据类型的哈希值计算 +// 数组、对象的哈希值计算需要自行实现 +``` + +```java title="built_in_hash.java" +int num = 3; +int hashNum = Integer.hashCode(num); +// 整数 3 的哈希值为 3 + +boolean bol = true; +int hashBol = Boolean.hashCode(bol); +// 布尔量 true 的哈希值为 1231 + +double dec = 3.14159; +int hashDec = Double.hashCode(dec); +// 小数 3.14159 的哈希值为 -1340954729 + +String str = "Hello 算法"; +int hashStr = str.hashCode(); +// 字符串“Hello 算法”的哈希值为 -727081396 + +Object[] arr = { 12836, "小哈" }; +int hashTup = Arrays.hashCode(arr); +// 数组 [12836, 小哈] 的哈希值为 1151158 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode(); +// 节点对象 utils.ListNode@7dc5e7b4 的哈希值为 2110121908 +``` + +```csharp title="built_in_hash.cs" +int num = 3; +int hashNum = num.GetHashCode(); +// 整数 3 的哈希值为 3; + +bool bol = true; +int hashBol = bol.GetHashCode(); +// 布尔量 true 的哈希值为 1; + +double dec = 3.14159; +int hashDec = dec.GetHashCode(); +// 小数 3.14159 的哈希值为 -1340954729; + +string str = "Hello 算法"; +int hashStr = str.GetHashCode(); +// 字符串“Hello 算法”的哈希值为 -586107568; + +object[] arr = [12836, "小哈"]; +int hashTup = arr.GetHashCode(); +// 数组 [12836, 小哈] 的哈希值为 42931033; + +ListNode obj = new(0); +int hashObj = obj.GetHashCode(); +// 节点对象 0 的哈希值为 39053774; +``` + +```go title="built_in_hash.go" +// Go 未提供内置 hash code 函数 +``` + +```swift title="built_in_hash.swift" +let num = 3 +let hashNum = num.hashValue +// 整数 3 的哈希值为 9047044699613009734 + +let bol = true +let hashBol = bol.hashValue +// 布尔量 true 的哈希值为 -4431640247352757451 + +let dec = 3.14159 +let hashDec = dec.hashValue +// 小数 3.14159 的哈希值为 -2465384235396674631 + +let str = "Hello 算法" +let hashStr = str.hashValue +// 字符串“Hello 算法”的哈希值为 -7850626797806988787 + +let arr = [AnyHashable(12836), AnyHashable("小哈")] +let hashTup = arr.hashValue +// 数组 [AnyHashable(12836), AnyHashable("小哈")] 的哈希值为 -2308633508154532996 + +let obj = ListNode(x: 0) +let hashObj = obj.hashValue +// 节点对象 utils.ListNode 的哈希值为 -2434780518035996159 +``` + +```javascript title="built_in_hash.js" +// JavaScript 未提供内置 hash code 函数 +``` + +```typescript title="built_in_hash.ts" +// TypeScript 未提供内置 hash code 函数 +``` + +```dart title="built_in_hash.dart" +int num = 3; +int hashNum = num.hashCode; +// 整数 3 的哈希值为 34803 + +bool bol = true; +int hashBol = bol.hashCode; +// 布尔值 true 的哈希值为 1231 + +double dec = 3.14159; +int hashDec = dec.hashCode; +// 小数 3.14159 的哈希值为 2570631074981783 + +String str = "Hello 算法"; +int hashStr = str.hashCode; +// 字符串“Hello 算法”的哈希值为 468167534 + +List arr = [12836, "小哈"]; +int hashArr = arr.hashCode; +// 数组 [12836, 小哈] 的哈希值为 976512528 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode; +// 节点对象 Instance of 'ListNode' 的哈希值为 1033450432 +``` + +```rust title="built_in_hash.rs" +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +let num = 3; +let mut num_hasher = DefaultHasher::new(); +num.hash(&mut num_hasher); +let hash_num = num_hasher.finish(); +// 整数 3 的哈希值为 568126464209439262 + +let bol = true; +let mut bol_hasher = DefaultHasher::new(); +bol.hash(&mut bol_hasher); +let hash_bol = bol_hasher.finish(); +// 布尔量 true 的哈希值为 4952851536318644461 + +let dec: f32 = 3.14159; +let mut dec_hasher = DefaultHasher::new(); +dec.to_bits().hash(&mut dec_hasher); +let hash_dec = dec_hasher.finish(); +// 小数 3.14159 的哈希值为 2566941990314602357 + +let str = "Hello 算法"; +let mut str_hasher = DefaultHasher::new(); +str.hash(&mut str_hasher); +let hash_str = str_hasher.finish(); +// 字符串“Hello 算法”的哈希值为 16092673739211250988 + +let arr = (&12836, &"小哈"); +let mut tup_hasher = DefaultHasher::new(); +arr.hash(&mut tup_hasher); +let hash_tup = tup_hasher.finish(); +// 元组 (12836, "小哈") 的哈希值为 1885128010422702749 + +let node = ListNode::new(42); +let mut hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut hasher); +let hash = hasher.finish(); +// 节点对象 RefCell { value: ListNode { val: 42, next: None } } 的哈希值为15387811073369036852 +``` + +```c title="built_in_hash.c" +// C 未提供内置 hash code 函数 +``` + +```kotlin title="built_in_hash.kt" +val num = 3 +val hashNum = num.hashCode() +// 整数 3 的哈希值为 3 + +val bol = true +val hashBol = bol.hashCode() +// 布尔量 true 的哈希值为 1231 + +val dec = 3.14159 +val hashDec = dec.hashCode() +// 小数 3.14159 的哈希值为 -1340954729 + +val str = "Hello 算法" +val hashStr = str.hashCode() +// 字符串“Hello 算法”的哈希值为 -727081396 + +val arr = arrayOf(12836, "小哈") +val hashTup = arr.hashCode() +// 数组 [12836, 小哈] 的哈希值为 189568618 + +val obj = ListNode(0) +val hashObj = obj.hashCode() +// 节点对象 utils.ListNode@1d81eb93 的哈希值为 495053715 +``` + +```ruby title="built_in_hash.rb" +num = 3 +hash_num = num.hash +# 整数 3 的哈希值为 -4385856518450339636 + +bol = true +hash_bol = bol.hash +# 布尔量 true 的哈希值为 -1617938112149317027 + +dec = 3.14159 +hash_dec = dec.hash +# 小数 3.14159 的哈希值为 -1479186995943067893 + +str = "Hello 算法" +hash_str = str.hash +# 字符串“Hello 算法”的哈希值为 -4075943250025831763 + +tup = [12836, '小哈'] +hash_tup = tup.hash +# 元组 (12836, '小哈') 的哈希值为 1999544809202288822 + +obj = ListNode.new(0) +hash_obj = obj.hash +# 节点对象 # 的哈希值为 4302940560806366381 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%E5%B8%83%E5%B0%94%E9%87%8F%20True%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%E5%AD%97%E7%AC%A6%E4%B8%B2%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836,%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%E5%85%83%E7%BB%84%20%2812836,%20'%E5%B0%8F%E5%93%88'%29%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%AF%B9%E8%B1%A1%20%3CListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_hashing/hash_map.md b/codes/snippets/chapter_hashing/hash_map.md new file mode 100644 index 000000000..ba875d260 --- /dev/null +++ b/codes/snippets/chapter_hashing/hash_map.md @@ -0,0 +1,457 @@ + +```python title="hash_map.py" +# 初始化哈希表 +hmap: dict = {} + +# 添加操作 +# 在哈希表中添加键值对 (key, value) +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +# 查询操作 +# 向哈希表中输入键 key ,得到值 value +name: str = hmap[15937] + +# 删除操作 +# 在哈希表中删除键值对 (key, value) +hmap.pop(10583) +``` + +```cpp title="hash_map.cpp" +/* 初始化哈希表 */ +unordered_map map; + +/* 添加操作 */ +// 在哈希表中添加键值对 (key, value) +map[12836] = "小哈"; +map[15937] = "小啰"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鸭"; + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +string name = map[15937]; + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +map.erase(10583); +``` + +```java title="hash_map.java" +/* 初始化哈希表 */ +Map map = new HashMap<>(); + +/* 添加操作 */ +// 在哈希表中添加键值对 (key, value) +map.put(12836, "小哈"); +map.put(15937, "小啰"); +map.put(16750, "小算"); +map.put(13276, "小法"); +map.put(10583, "小鸭"); + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +String name = map.get(15937); + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +map.remove(10583); +``` + +```csharp title="hash_map.cs" +/* 初始化哈希表 */ +Dictionary map = new() { + /* 添加操作 */ + // 在哈希表中添加键值对 (key, value) + { 12836, "小哈" }, + { 15937, "小啰" }, + { 16750, "小算" }, + { 13276, "小法" }, + { 10583, "小鸭" } +}; + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +string name = map[15937]; + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +map.Remove(10583); +``` + +```go title="hash_map_test.go" +/* 初始化哈希表 */ +hmap := make(map[int]string) + +/* 添加操作 */ +// 在哈希表中添加键值对 (key, value) +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +name := hmap[15937] + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +delete(hmap, 10583) +``` + +```swift title="hash_map.swift" +/* 初始化哈希表 */ +var map: [Int: String] = [:] + +/* 添加操作 */ +// 在哈希表中添加键值对 (key, value) +map[12836] = "小哈" +map[15937] = "小啰" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鸭" + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +let name = map[15937]! + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +map.removeValue(forKey: 10583) +``` + +```javascript title="hash_map.js" +/* 初始化哈希表 */ +const map = new Map(); +/* 添加操作 */ +// 在哈希表中添加键值对 (key, value) +map.set(12836, '小哈'); +map.set(15937, '小啰'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鸭'); + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +let name = map.get(15937); + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +map.delete(10583); +``` + +```typescript title="hash_map.ts" +/* 初始化哈希表 */ +const map = new Map(); +/* 添加操作 */ +// 在哈希表中添加键值对 (key, value) +map.set(12836, '小哈'); +map.set(15937, '小啰'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鸭'); +console.info('\n添加完成后,哈希表为\nKey -> Value'); +console.info(map); + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +let name = map.get(15937); +console.info('\n输入学号 15937 ,查询到姓名 ' + name); + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +map.delete(10583); +console.info('\n删除 10583 后,哈希表为\nKey -> Value'); +console.info(map); +``` + +```dart title="hash_map.dart" +/* 初始化哈希表 */ +Map map = {}; + +/* 添加操作 */ +// 在哈希表中添加键值对 (key, value) +map[12836] = "小哈"; +map[15937] = "小啰"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鸭"; + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +String name = map[15937]; + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +map.remove(10583); +``` + +```rust title="hash_map.rs" +use std::collections::HashMap; + +/* 初始化哈希表 */ +let mut map: HashMap = HashMap::new(); + +/* 添加操作 */ +// 在哈希表中添加键值对 (key, value) +map.insert(12836, "小哈".to_string()); +map.insert(15937, "小啰".to_string()); +map.insert(16750, "小算".to_string()); +map.insert(13279, "小法".to_string()); +map.insert(10583, "小鸭".to_string()); + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +let _name: Option<&String> = map.get(&15937); + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +let _removed_value: Option = map.remove(&10583); +``` + +```c title="hash_map.c" +// C 未提供内置哈希表 +``` + +```kotlin title="hash_map.kt" +/* 初始化哈希表 */ +val map = HashMap() + +/* 添加操作 */ +// 在哈希表中添加键值对 (key, value) +map[12836] = "小哈" +map[15937] = "小啰" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鸭" + +/* 查询操作 */ +// 向哈希表中输入键 key ,得到值 value +val name = map[15937] + +/* 删除操作 */ +// 在哈希表中删除键值对 (key, value) +map.remove(10583) +``` + +```ruby title="hash_map.rb" +# 初始化哈希表 +hmap = {} + +# 添加操作 +# 在哈希表中添加键值对 (key, value) +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +# 查询操作 +# 向哈希表中输入键 key ,得到值 value +name = hmap[15937] + +# 删除操作 +# 在哈希表中删除键值对 (key, value) +hmap.delete(10583) +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B7%BB%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%9F%A5%E8%AF%A2%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%90%91%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E8%BE%93%E5%85%A5%E9%94%AE%20key%20%EF%BC%8C%E5%BE%97%E5%88%B0%E5%80%BC%20value%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E5%88%A0%E9%99%A4%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="hash_map.py" +# 遍历哈希表 +# 遍历键值对 key->value +for key, value in hmap.items(): + print(key, "->", value) +# 单独遍历键 key +for key in hmap.keys(): + print(key) +# 单独遍历值 value +for value in hmap.values(): + print(value) +``` + +```cpp title="hash_map.cpp" +/* 遍历哈希表 */ +// 遍历键值对 key->value +for (auto kv: map) { + cout << kv.first << " -> " << kv.second << endl; +} +// 使用迭代器遍历 key->value +for (auto iter = map.begin(); iter != map.end(); iter++) { + cout << iter->first << "->" << iter->second << endl; +} +``` + +```java title="hash_map.java" +/* 遍历哈希表 */ +// 遍历键值对 key->value +for (Map.Entry kv: map.entrySet()) { + System.out.println(kv.getKey() + " -> " + kv.getValue()); +} +// 单独遍历键 key +for (int key: map.keySet()) { + System.out.println(key); +} +// 单独遍历值 value +for (String val: map.values()) { + System.out.println(val); +} +``` + +```csharp title="hash_map.cs" +/* 遍历哈希表 */ +// 遍历键值对 Key->Value +foreach (var kv in map) { + Console.WriteLine(kv.Key + " -> " + kv.Value); +} +// 单独遍历键 key +foreach (int key in map.Keys) { + Console.WriteLine(key); +} +// 单独遍历值 value +foreach (string val in map.Values) { + Console.WriteLine(val); +} +``` + +```go title="hash_map_test.go" +/* 遍历哈希表 */ +// 遍历键值对 key->value +for key, value := range hmap { + fmt.Println(key, "->", value) +} +// 单独遍历键 key +for key := range hmap { + fmt.Println(key) +} +// 单独遍历值 value +for _, value := range hmap { + fmt.Println(value) +} +``` + +```swift title="hash_map.swift" +/* 遍历哈希表 */ +// 遍历键值对 Key->Value +for (key, value) in map { + print("\(key) -> \(value)") +} +// 单独遍历键 Key +for key in map.keys { + print(key) +} +// 单独遍历值 Value +for value in map.values { + print(value) +} +``` + +```javascript title="hash_map.js" +/* 遍历哈希表 */ +console.info('\n遍历键值对 Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\n单独遍历键 Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\n单独遍历值 Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```typescript title="hash_map.ts" +/* 遍历哈希表 */ +console.info('\n遍历键值对 Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\n单独遍历键 Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\n单独遍历值 Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```dart title="hash_map.dart" +/* 遍历哈希表 */ +// 遍历键值对 Key->Value +map.forEach((key, value) { + print('$key -> $value'); +}); + +// 单独遍历键 Key +map.keys.forEach((key) { + print(key); +}); + +// 单独遍历值 Value +map.values.forEach((value) { + print(value); +}); +``` + +```rust title="hash_map.rs" +/* 遍历哈希表 */ +// 遍历键值对 Key->Value +for (key, value) in &map { + println!("{key} -> {value}"); +} + +// 单独遍历键 Key +for key in map.keys() { + println!("{key}"); +} + +// 单独遍历值 Value +for value in map.values() { + println!("{value}"); +} +``` + +```c title="hash_map.c" +// C 未提供内置哈希表 +``` + +```kotlin title="hash_map.kt" +/* 遍历哈希表 */ +// 遍历键值对 key->value +for ((key, value) in map) { + println("$key -> $value") +} +// 单独遍历键 key +for (key in map.keys) { + println(key) +} +// 单独遍历值 value +for (_val in map.values) { + println(_val) +} +``` + +```ruby title="hash_map.rb" +# 遍历哈希表 +# 遍历键值对 key->value +hmap.entries.each { |key, value| puts "#{key} -> #{value}" } + +# 单独遍历键 key +hmap.keys.each { |key| puts key } + +# 单独遍历值 value +hmap.values.each { |val| puts val } +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B7%BB%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E9%94%AE%E5%80%BC%E5%AF%B9%20key-%3Evalue%0A%20%20%20%20for%20key,%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key,%20%22-%3E%22,%20value%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E9%94%AE%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E5%80%BC%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_heap/heap.md b/codes/snippets/chapter_heap/heap.md new file mode 100644 index 000000000..97404fce3 --- /dev/null +++ b/codes/snippets/chapter_heap/heap.md @@ -0,0 +1,350 @@ + +```python title="heap.py" +# 初始化小顶堆 +min_heap, flag = [], 1 +# 初始化大顶堆 +max_heap, flag = [], -1 + +# Python 的 heapq 模块默认实现小顶堆 +# 考虑将“元素取负”后再入堆,这样就可以将大小关系颠倒,从而实现大顶堆 +# 在本示例中,flag = 1 时对应小顶堆,flag = -1 时对应大顶堆 + +# 元素入堆 +heapq.heappush(max_heap, flag * 1) +heapq.heappush(max_heap, flag * 3) +heapq.heappush(max_heap, flag * 2) +heapq.heappush(max_heap, flag * 5) +heapq.heappush(max_heap, flag * 4) + +# 获取堆顶元素 +peek: int = flag * max_heap[0] # 5 + +# 堆顶元素出堆 +# 出堆元素会形成一个从大到小的序列 +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 + +# 获取堆大小 +size: int = len(max_heap) + +# 判断堆是否为空 +is_empty: bool = not max_heap + +# 输入列表并建堆 +min_heap: list[int] = [1, 3, 2, 5, 4] +heapq.heapify(min_heap) +``` + +```cpp title="heap.cpp" +/* 初始化堆 */ +// 初始化小顶堆 +priority_queue, greater> minHeap; +// 初始化大顶堆 +priority_queue, less> maxHeap; + +/* 元素入堆 */ +maxHeap.push(1); +maxHeap.push(3); +maxHeap.push(2); +maxHeap.push(5); +maxHeap.push(4); + +/* 获取堆顶元素 */ +int peek = maxHeap.top(); // 5 + +/* 堆顶元素出堆 */ +// 出堆元素会形成一个从大到小的序列 +maxHeap.pop(); // 5 +maxHeap.pop(); // 4 +maxHeap.pop(); // 3 +maxHeap.pop(); // 2 +maxHeap.pop(); // 1 + +/* 获取堆大小 */ +int size = maxHeap.size(); + +/* 判断堆是否为空 */ +bool isEmpty = maxHeap.empty(); + +/* 输入列表并建堆 */ +vector input{1, 3, 2, 5, 4}; +priority_queue, greater> minHeap(input.begin(), input.end()); +``` + +```java title="heap.java" +/* 初始化堆 */ +// 初始化小顶堆 +Queue minHeap = new PriorityQueue<>(); +// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可) +Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + +/* 元素入堆 */ +maxHeap.offer(1); +maxHeap.offer(3); +maxHeap.offer(2); +maxHeap.offer(5); +maxHeap.offer(4); + +/* 获取堆顶元素 */ +int peek = maxHeap.peek(); // 5 + +/* 堆顶元素出堆 */ +// 出堆元素会形成一个从大到小的序列 +peek = maxHeap.poll(); // 5 +peek = maxHeap.poll(); // 4 +peek = maxHeap.poll(); // 3 +peek = maxHeap.poll(); // 2 +peek = maxHeap.poll(); // 1 + +/* 获取堆大小 */ +int size = maxHeap.size(); + +/* 判断堆是否为空 */ +boolean isEmpty = maxHeap.isEmpty(); + +/* 输入列表并建堆 */ +minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +``` + +```csharp title="heap.cs" +/* 初始化堆 */ +// 初始化小顶堆 +PriorityQueue minHeap = new(); +// 初始化大顶堆(使用 lambda 表达式修改 Comparer 即可) +PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + +/* 元素入堆 */ +maxHeap.Enqueue(1, 1); +maxHeap.Enqueue(3, 3); +maxHeap.Enqueue(2, 2); +maxHeap.Enqueue(5, 5); +maxHeap.Enqueue(4, 4); + +/* 获取堆顶元素 */ +int peek = maxHeap.Peek();//5 + +/* 堆顶元素出堆 */ +// 出堆元素会形成一个从大到小的序列 +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 + +/* 获取堆大小 */ +int size = maxHeap.Count; + +/* 判断堆是否为空 */ +bool isEmpty = maxHeap.Count == 0; + +/* 输入列表并建堆 */ +minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +``` + +```go title="heap.go" +// Go 语言中可以通过实现 heap.Interface 来构建整数大顶堆 +// 实现 heap.Interface 需要同时实现 sort.Interface +type intHeap []any + +// Push heap.Interface 的方法,实现推入元素到堆 +func (h *intHeap) Push(x any) { + // Push 和 Pop 使用 pointer receiver 作为参数 + // 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。 + *h = append(*h, x.(int)) +} + +// Pop heap.Interface 的方法,实现弹出堆顶元素 +func (h *intHeap) Pop() any { + // 待出堆元素存放在最后 + last := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return last +} + +// Len sort.Interface 的方法 +func (h *intHeap) Len() int { + return len(*h) +} + +// Less sort.Interface 的方法 +func (h *intHeap) Less(i, j int) bool { + // 如果实现小顶堆,则需要调整为小于号 + return (*h)[i].(int) > (*h)[j].(int) +} + +// Swap sort.Interface 的方法 +func (h *intHeap) Swap(i, j int) { + (*h)[i], (*h)[j] = (*h)[j], (*h)[i] +} + +// Top 获取堆顶元素 +func (h *intHeap) Top() any { + return (*h)[0] +} + +/* Driver Code */ +func TestHeap(t *testing.T) { + /* 初始化堆 */ + // 初始化大顶堆 + maxHeap := &intHeap{} + heap.Init(maxHeap) + /* 元素入堆 */ + // 调用 heap.Interface 的方法,来添加元素 + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 4) + heap.Push(maxHeap, 5) + + /* 获取堆顶元素 */ + top := maxHeap.Top() + fmt.Printf("堆顶元素为 %d\n", top) + + /* 堆顶元素出堆 */ + // 调用 heap.Interface 的方法,来移除元素 + heap.Pop(maxHeap) // 5 + heap.Pop(maxHeap) // 4 + heap.Pop(maxHeap) // 3 + heap.Pop(maxHeap) // 2 + heap.Pop(maxHeap) // 1 + + /* 获取堆大小 */ + size := len(*maxHeap) + fmt.Printf("堆元素数量为 %d\n", size) + + /* 判断堆是否为空 */ + isEmpty := len(*maxHeap) == 0 + fmt.Printf("堆是否为空 %t\n", isEmpty) +} +``` + +```swift title="heap.swift" +/* 初始化堆 */ +// Swift 的 Heap 类型同时支持最大堆和最小堆,且需要引入 swift-collections +var heap = Heap() + +/* 元素入堆 */ +heap.insert(1) +heap.insert(3) +heap.insert(2) +heap.insert(5) +heap.insert(4) + +/* 获取堆顶元素 */ +var peek = heap.max()! + +/* 堆顶元素出堆 */ +peek = heap.removeMax() // 5 +peek = heap.removeMax() // 4 +peek = heap.removeMax() // 3 +peek = heap.removeMax() // 2 +peek = heap.removeMax() // 1 + +/* 获取堆大小 */ +let size = heap.count + +/* 判断堆是否为空 */ +let isEmpty = heap.isEmpty + +/* 输入列表并建堆 */ +let heap2 = Heap([1, 3, 2, 5, 4]) +``` + +```javascript title="heap.js" +// JavaScript 未提供内置 Heap 类 +``` + +```typescript title="heap.ts" +// TypeScript 未提供内置 Heap 类 +``` + +```dart title="heap.dart" +// Dart 未提供内置 Heap 类 +``` + +```rust title="heap.rs" +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +/* 初始化堆 */ +// 初始化小顶堆 +let mut min_heap = BinaryHeap::>::new(); +// 初始化大顶堆 +let mut max_heap = BinaryHeap::new(); + +/* 元素入堆 */ +max_heap.push(1); +max_heap.push(3); +max_heap.push(2); +max_heap.push(5); +max_heap.push(4); + +/* 获取堆顶元素 */ +let peek = max_heap.peek().unwrap(); // 5 + +/* 堆顶元素出堆 */ +// 出堆元素会形成一个从大到小的序列 +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 + +/* 获取堆大小 */ +let size = max_heap.len(); + +/* 判断堆是否为空 */ +let is_empty = max_heap.is_empty(); + +/* 输入列表并建堆 */ +let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +``` + +```c title="heap.c" +// C 未提供内置 Heap 类 +``` + +```kotlin title="heap.kt" +/* 初始化堆 */ +// 初始化小顶堆 +var minHeap = PriorityQueue() +// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可) +val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + +/* 元素入堆 */ +maxHeap.offer(1) +maxHeap.offer(3) +maxHeap.offer(2) +maxHeap.offer(5) +maxHeap.offer(4) + +/* 获取堆顶元素 */ +var peek = maxHeap.peek() // 5 + +/* 堆顶元素出堆 */ +// 出堆元素会形成一个从大到小的序列 +peek = maxHeap.poll() // 5 +peek = maxHeap.poll() // 4 +peek = maxHeap.poll() // 3 +peek = maxHeap.poll() // 2 +peek = maxHeap.poll() // 1 + +/* 获取堆大小 */ +val size = maxHeap.size + +/* 判断堆是否为空 */ +val isEmpty = maxHeap.isEmpty() + +/* 输入列表并建堆 */ +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +``` + +```ruby title="heap.rb" +# Ruby 未提供内置 Heap 类 +``` + + +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20min_heap,%20flag%20%3D%20%5B%5D,%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20max_heap,%20flag%20%3D%20%5B%5D,%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E5%9D%97%E9%BB%98%E8%AE%A4%E5%AE%9E%E7%8E%B0%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E8%80%83%E8%99%91%E5%B0%86%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B4%9F%E2%80%9D%E5%90%8E%E5%86%8D%E5%85%A5%E5%A0%86%EF%BC%8C%E8%BF%99%E6%A0%B7%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%86%E5%A4%A7%E5%B0%8F%E5%85%B3%E7%B3%BB%E9%A2%A0%E5%80%92%EF%BC%8C%E4%BB%8E%E8%80%8C%E5%AE%9E%E7%8E%B0%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%B0%8F%E9%A1%B6%E5%A0%86%EF%BC%8Cflag%20%3D%20-1%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%201%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%203%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%202%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%205%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20*%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E5%85%83%E7%B4%A0%E4%BC%9A%E5%BD%A2%E6%88%90%E4%B8%80%E4%B8%AA%E4%BB%8E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E5%A0%86%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BE%93%E5%85%A5%E5%88%97%E8%A1%A8%E5%B9%B6%E5%BB%BA%E5%A0%86%0A%20%20%20%20min_heap%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_preface/suggestions.md b/codes/snippets/chapter_preface/suggestions.md new file mode 100644 index 000000000..543a19d90 --- /dev/null +++ b/codes/snippets/chapter_preface/suggestions.md @@ -0,0 +1,139 @@ + +```python title="" +"""标题注释,用于标注函数、类、测试样例等""" + +# 内容注释,用于详解代码 + +""" +多行 +注释 +""" +``` + +```cpp title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```java title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```csharp title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```go title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```swift title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```javascript title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```typescript title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```dart title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```rust title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +// 多行 +// 注释 +``` + +```c title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```kotlin title="" +/* 标题注释,用于标注函数、类、测试样例等 */ + +// 内容注释,用于详解代码 + +/** + * 多行 + * 注释 + */ +``` + +```ruby title="" +### 标题注释,用于标注函数、类、测试样例等 ### + +# 内容注释,用于详解代码 + +# 多行 +# 注释 +``` diff --git a/codes/snippets/chapter_stack_and_queue/deque.md b/codes/snippets/chapter_stack_and_queue/deque.md new file mode 100644 index 000000000..1f4d203d3 --- /dev/null +++ b/codes/snippets/chapter_stack_and_queue/deque.md @@ -0,0 +1,339 @@ + +```python title="deque.py" +from collections import deque + +# 初始化双向队列 +deq: deque[int] = deque() + +# 元素入队 +deq.append(2) # 添加至队尾 +deq.append(5) +deq.append(4) +deq.appendleft(3) # 添加至队首 +deq.appendleft(1) + +# 访问元素 +front: int = deq[0] # 队首元素 +rear: int = deq[-1] # 队尾元素 + +# 元素出队 +pop_front: int = deq.popleft() # 队首元素出队 +pop_rear: int = deq.pop() # 队尾元素出队 + +# 获取双向队列的长度 +size: int = len(deq) + +# 判断双向队列是否为空 +is_empty: bool = len(deq) == 0 +``` + +```cpp title="deque.cpp" +/* 初始化双向队列 */ +deque deque; + +/* 元素入队 */ +deque.push_back(2); // 添加至队尾 +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // 添加至队首 +deque.push_front(1); + +/* 访问元素 */ +int front = deque.front(); // 队首元素 +int back = deque.back(); // 队尾元素 + +/* 元素出队 */ +deque.pop_front(); // 队首元素出队 +deque.pop_back(); // 队尾元素出队 + +/* 获取双向队列的长度 */ +int size = deque.size(); + +/* 判断双向队列是否为空 */ +bool empty = deque.empty(); +``` + +```java title="deque.java" +/* 初始化双向队列 */ +Deque deque = new LinkedList<>(); + +/* 元素入队 */ +deque.offerLast(2); // 添加至队尾 +deque.offerLast(5); +deque.offerLast(4); +deque.offerFirst(3); // 添加至队首 +deque.offerFirst(1); + +/* 访问元素 */ +int peekFirst = deque.peekFirst(); // 队首元素 +int peekLast = deque.peekLast(); // 队尾元素 + +/* 元素出队 */ +int popFirst = deque.pollFirst(); // 队首元素出队 +int popLast = deque.pollLast(); // 队尾元素出队 + +/* 获取双向队列的长度 */ +int size = deque.size(); + +/* 判断双向队列是否为空 */ +boolean isEmpty = deque.isEmpty(); +``` + +```csharp title="deque.cs" +/* 初始化双向队列 */ +// 在 C# 中,将链表 LinkedList 看作双向队列来使用 +LinkedList deque = new(); + +/* 元素入队 */ +deque.AddLast(2); // 添加至队尾 +deque.AddLast(5); +deque.AddLast(4); +deque.AddFirst(3); // 添加至队首 +deque.AddFirst(1); + +/* 访问元素 */ +int peekFirst = deque.First.Value; // 队首元素 +int peekLast = deque.Last.Value; // 队尾元素 + +/* 元素出队 */ +deque.RemoveFirst(); // 队首元素出队 +deque.RemoveLast(); // 队尾元素出队 + +/* 获取双向队列的长度 */ +int size = deque.Count; + +/* 判断双向队列是否为空 */ +bool isEmpty = deque.Count == 0; +``` + +```go title="deque_test.go" +/* 初始化双向队列 */ +// 在 Go 中,将 list 作为双向队列使用 +deque := list.New() + +/* 元素入队 */ +deque.PushBack(2) // 添加至队尾 +deque.PushBack(5) +deque.PushBack(4) +deque.PushFront(3) // 添加至队首 +deque.PushFront(1) + +/* 访问元素 */ +front := deque.Front() // 队首元素 +rear := deque.Back() // 队尾元素 + +/* 元素出队 */ +deque.Remove(front) // 队首元素出队 +deque.Remove(rear) // 队尾元素出队 + +/* 获取双向队列的长度 */ +size := deque.Len() + +/* 判断双向队列是否为空 */ +isEmpty := deque.Len() == 0 +``` + +```swift title="deque.swift" +/* 初始化双向队列 */ +// Swift 没有内置的双向队列类,可以把 Array 当作双向队列来使用 +var deque: [Int] = [] + +/* 元素入队 */ +deque.append(2) // 添加至队尾 +deque.append(5) +deque.append(4) +deque.insert(3, at: 0) // 添加至队首 +deque.insert(1, at: 0) + +/* 访问元素 */ +let peekFirst = deque.first! // 队首元素 +let peekLast = deque.last! // 队尾元素 + +/* 元素出队 */ +// 使用 Array 模拟时 popFirst 的复杂度为 O(n) +let popFirst = deque.removeFirst() // 队首元素出队 +let popLast = deque.removeLast() // 队尾元素出队 + +/* 获取双向队列的长度 */ +let size = deque.count + +/* 判断双向队列是否为空 */ +let isEmpty = deque.isEmpty +``` + +```javascript title="deque.js" +/* 初始化双向队列 */ +// JavaScript 没有内置的双端队列,只能把 Array 当作双端队列来使用 +const deque = []; + +/* 元素入队 */ +deque.push(2); +deque.push(5); +deque.push(4); +// 请注意,由于是数组,unshift() 方法的时间复杂度为 O(n) +deque.unshift(3); +deque.unshift(1); + +/* 访问元素 */ +const peekFirst = deque[0]; +const peekLast = deque[deque.length - 1]; + +/* 元素出队 */ +// 请注意,由于是数组,shift() 方法的时间复杂度为 O(n) +const popFront = deque.shift(); +const popBack = deque.pop(); + +/* 获取双向队列的长度 */ +const size = deque.length; + +/* 判断双向队列是否为空 */ +const isEmpty = size === 0; +``` + +```typescript title="deque.ts" +/* 初始化双向队列 */ +// TypeScript 没有内置的双端队列,只能把 Array 当作双端队列来使用 +const deque: number[] = []; + +/* 元素入队 */ +deque.push(2); +deque.push(5); +deque.push(4); +// 请注意,由于是数组,unshift() 方法的时间复杂度为 O(n) +deque.unshift(3); +deque.unshift(1); + +/* 访问元素 */ +const peekFirst: number = deque[0]; +const peekLast: number = deque[deque.length - 1]; + +/* 元素出队 */ +// 请注意,由于是数组,shift() 方法的时间复杂度为 O(n) +const popFront: number = deque.shift() as number; +const popBack: number = deque.pop() as number; + +/* 获取双向队列的长度 */ +const size: number = deque.length; + +/* 判断双向队列是否为空 */ +const isEmpty: boolean = size === 0; +``` + +```dart title="deque.dart" +/* 初始化双向队列 */ +// 在 Dart 中,Queue 被定义为双向队列 +Queue deque = Queue(); + +/* 元素入队 */ +deque.addLast(2); // 添加至队尾 +deque.addLast(5); +deque.addLast(4); +deque.addFirst(3); // 添加至队首 +deque.addFirst(1); + +/* 访问元素 */ +int peekFirst = deque.first; // 队首元素 +int peekLast = deque.last; // 队尾元素 + +/* 元素出队 */ +int popFirst = deque.removeFirst(); // 队首元素出队 +int popLast = deque.removeLast(); // 队尾元素出队 + +/* 获取双向队列的长度 */ +int size = deque.length; + +/* 判断双向队列是否为空 */ +bool isEmpty = deque.isEmpty; +``` + +```rust title="deque.rs" +/* 初始化双向队列 */ +let mut deque: VecDeque = VecDeque::new(); + +/* 元素入队 */ +deque.push_back(2); // 添加至队尾 +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // 添加至队首 +deque.push_front(1); + +/* 访问元素 */ +if let Some(front) = deque.front() { // 队首元素 +} +if let Some(rear) = deque.back() { // 队尾元素 +} + +/* 元素出队 */ +if let Some(pop_front) = deque.pop_front() { // 队首元素出队 +} +if let Some(pop_rear) = deque.pop_back() { // 队尾元素出队 +} + +/* 获取双向队列的长度 */ +let size = deque.len(); + +/* 判断双向队列是否为空 */ +let is_empty = deque.is_empty(); +``` + +```c title="deque.c" +// C 未提供内置双向队列 +``` + +```kotlin title="deque.kt" +/* 初始化双向队列 */ +val deque = LinkedList() + +/* 元素入队 */ +deque.offerLast(2) // 添加至队尾 +deque.offerLast(5) +deque.offerLast(4) +deque.offerFirst(3) // 添加至队首 +deque.offerFirst(1) + +/* 访问元素 */ +val peekFirst = deque.peekFirst() // 队首元素 +val peekLast = deque.peekLast() // 队尾元素 + +/* 元素出队 */ +val popFirst = deque.pollFirst() // 队首元素出队 +val popLast = deque.pollLast() // 队尾元素出队 + +/* 获取双向队列的长度 */ +val size = deque.size + +/* 判断双向队列是否为空 */ +val isEmpty = deque.isEmpty() +``` + +```ruby title="deque.rb" +# 初始化双向队列 +# Ruby 没有内直的双端队列,只能把 Array 当作双端队列来使用 +deque = [] + +# 元素如队 +deque << 2 +deque << 5 +deque << 4 +# 请注意,由于是数组,Array#unshift 方法的时间复杂度为 O(n) +deque.unshift(3) +deque.unshift(1) + +# 访问元素 +peek_first = deque.first +peek_last = deque.last + +# 元素出队 +# 请注意,由于是数组, Array#shift 方法的时间复杂度为 O(n) +pop_front = deque.shift +pop_back = deque.pop + +# 获取双向队列的长度 +size = deque.length + +# 判断双向队列是否为空 +is_empty = size.zero? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E9%98%9F%0A%20%20%20%20deq.append%282%29%20%20%23%20%E6%B7%BB%E5%8A%A0%E8%87%B3%E9%98%9F%E5%B0%BE%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20%E6%B7%BB%E5%8A%A0%E8%87%B3%E9%98%9F%E9%A6%96%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%20deque%20%3D%22,%20deq%29%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22,%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%E9%98%9F%E5%B0%BE%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E9%98%9F%E5%B0%BE%E5%85%83%E7%B4%A0%20rear%20%3D%22,%20rear%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%87%BA%E9%98%9F%E5%85%83%E7%B4%A0%20%20pop_front%20%3D%22,%20pop_front%29%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%87%BA%E9%98%9F%E5%90%8E%20deque%20%3D%22,%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20%E9%98%9F%E5%B0%BE%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20print%28%22%E9%98%9F%E5%B0%BE%E5%87%BA%E9%98%9F%E5%85%83%E7%B4%A0%20%20pop_rear%20%3D%22,%20pop_rear%29%0A%20%20%20%20print%28%22%E9%98%9F%E5%B0%BE%E5%87%BA%E9%98%9F%E5%90%8E%20deque%20%3D%22,%20deq%29%0A%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E7%9A%84%E9%95%BF%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E9%95%BF%E5%BA%A6%20size%20%3D%22,%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%20%3D%22,%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_stack_and_queue/queue.md b/codes/snippets/chapter_stack_and_queue/queue.md new file mode 100644 index 000000000..801637e72 --- /dev/null +++ b/codes/snippets/chapter_stack_and_queue/queue.md @@ -0,0 +1,313 @@ + +```python title="queue.py" +from collections import deque + +# 初始化队列 +# 在 Python 中,我们一般将双向队列类 deque 当作队列使用 +# 虽然 queue.Queue() 是纯正的队列类,但不太好用,因此不推荐 +que: deque[int] = deque() + +# 元素入队 +que.append(1) +que.append(3) +que.append(2) +que.append(5) +que.append(4) + +# 访问队首元素 +front: int = que[0] + +# 元素出队 +pop: int = que.popleft() + +# 获取队列的长度 +size: int = len(que) + +# 判断队列是否为空 +is_empty: bool = len(que) == 0 +``` + +```cpp title="queue.cpp" +/* 初始化队列 */ +queue queue; + +/* 元素入队 */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 访问队首元素 */ +int front = queue.front(); + +/* 元素出队 */ +queue.pop(); + +/* 获取队列的长度 */ +int size = queue.size(); + +/* 判断队列是否为空 */ +bool empty = queue.empty(); +``` + +```java title="queue.java" +/* 初始化队列 */ +Queue queue = new LinkedList<>(); + +/* 元素入队 */ +queue.offer(1); +queue.offer(3); +queue.offer(2); +queue.offer(5); +queue.offer(4); + +/* 访问队首元素 */ +int peek = queue.peek(); + +/* 元素出队 */ +int pop = queue.poll(); + +/* 获取队列的长度 */ +int size = queue.size(); + +/* 判断队列是否为空 */ +boolean isEmpty = queue.isEmpty(); +``` + +```csharp title="queue.cs" +/* 初始化队列 */ +Queue queue = new(); + +/* 元素入队 */ +queue.Enqueue(1); +queue.Enqueue(3); +queue.Enqueue(2); +queue.Enqueue(5); +queue.Enqueue(4); + +/* 访问队首元素 */ +int peek = queue.Peek(); + +/* 元素出队 */ +int pop = queue.Dequeue(); + +/* 获取队列的长度 */ +int size = queue.Count; + +/* 判断队列是否为空 */ +bool isEmpty = queue.Count == 0; +``` + +```go title="queue_test.go" +/* 初始化队列 */ +// 在 Go 中,将 list 作为队列来使用 +queue := list.New() + +/* 元素入队 */ +queue.PushBack(1) +queue.PushBack(3) +queue.PushBack(2) +queue.PushBack(5) +queue.PushBack(4) + +/* 访问队首元素 */ +peek := queue.Front() + +/* 元素出队 */ +pop := queue.Front() +queue.Remove(pop) + +/* 获取队列的长度 */ +size := queue.Len() + +/* 判断队列是否为空 */ +isEmpty := queue.Len() == 0 +``` + +```swift title="queue.swift" +/* 初始化队列 */ +// Swift 没有内置的队列类,可以把 Array 当作队列来使用 +var queue: [Int] = [] + +/* 元素入队 */ +queue.append(1) +queue.append(3) +queue.append(2) +queue.append(5) +queue.append(4) + +/* 访问队首元素 */ +let peek = queue.first! + +/* 元素出队 */ +// 由于是数组,因此 removeFirst 的复杂度为 O(n) +let pop = queue.removeFirst() + +/* 获取队列的长度 */ +let size = queue.count + +/* 判断队列是否为空 */ +let isEmpty = queue.isEmpty +``` + +```javascript title="queue.js" +/* 初始化队列 */ +// JavaScript 没有内置的队列,可以把 Array 当作队列来使用 +const queue = []; + +/* 元素入队 */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 访问队首元素 */ +const peek = queue[0]; + +/* 元素出队 */ +// 底层是数组,因此 shift() 方法的时间复杂度为 O(n) +const pop = queue.shift(); + +/* 获取队列的长度 */ +const size = queue.length; + +/* 判断队列是否为空 */ +const empty = queue.length === 0; +``` + +```typescript title="queue.ts" +/* 初始化队列 */ +// TypeScript 没有内置的队列,可以把 Array 当作队列来使用 +const queue: number[] = []; + +/* 元素入队 */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 访问队首元素 */ +const peek = queue[0]; + +/* 元素出队 */ +// 底层是数组,因此 shift() 方法的时间复杂度为 O(n) +const pop = queue.shift(); + +/* 获取队列的长度 */ +const size = queue.length; + +/* 判断队列是否为空 */ +const empty = queue.length === 0; +``` + +```dart title="queue.dart" +/* 初始化队列 */ +// 在 Dart 中,队列类 Queue 是双向队列,也可作为队列使用 +Queue queue = Queue(); + +/* 元素入队 */ +queue.add(1); +queue.add(3); +queue.add(2); +queue.add(5); +queue.add(4); + +/* 访问队首元素 */ +int peek = queue.first; + +/* 元素出队 */ +int pop = queue.removeFirst(); + +/* 获取队列的长度 */ +int size = queue.length; + +/* 判断队列是否为空 */ +bool isEmpty = queue.isEmpty; +``` + +```rust title="queue.rs" +/* 初始化双向队列 */ +// 在 Rust 中使用双向队列作为普通队列来使用 +let mut deque: VecDeque = VecDeque::new(); + +/* 元素入队 */ +deque.push_back(1); +deque.push_back(3); +deque.push_back(2); +deque.push_back(5); +deque.push_back(4); + +/* 访问队首元素 */ +if let Some(front) = deque.front() { +} + +/* 元素出队 */ +if let Some(pop) = deque.pop_front() { +} + +/* 获取队列的长度 */ +let size = deque.len(); + +/* 判断队列是否为空 */ +let is_empty = deque.is_empty(); +``` + +```c title="queue.c" +// C 未提供内置队列 +``` + +```kotlin title="queue.kt" +/* 初始化队列 */ +val queue = LinkedList() + +/* 元素入队 */ +queue.offer(1) +queue.offer(3) +queue.offer(2) +queue.offer(5) +queue.offer(4) + +/* 访问队首元素 */ +val peek = queue.peek() + +/* 元素出队 */ +val pop = queue.poll() + +/* 获取队列的长度 */ +val size = queue.size + +/* 判断队列是否为空 */ +val isEmpty = queue.isEmpty() +``` + +```ruby title="queue.rb" +# 初始化队列 +# Ruby 内置的队列(Thread::Queue) 没有 peek 和遍历方法,可以把 Array 当作队列来使用 +queue = [] + +# 元素入队 +queue.push(1) +queue.push(3) +queue.push(2) +queue.push(5) +queue.push(4) + +# 访问队列元素 +peek = queue.first + +# 元素出队 +# 清注意,由于是数组,Array#shift 方法时间复杂度为 O(n) +pop = queue.shift + +# 获取队列的长度 +size = queue.length + +# 判断队列是否为空 +is_empty = queue.empty? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%98%9F%E5%88%97%0A%20%20%20%20%23%20%E5%9C%A8%20Python%20%E4%B8%AD%EF%BC%8C%E6%88%91%E4%BB%AC%E4%B8%80%E8%88%AC%E5%B0%86%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E7%B1%BB%20deque%20%E7%9C%8B%E4%BD%9C%E9%98%9F%E5%88%97%E4%BD%BF%E7%94%A8%0A%20%20%20%20%23%20%E8%99%BD%E7%84%B6%20queue.Queue%28%29%20%E6%98%AF%E7%BA%AF%E6%AD%A3%E7%9A%84%E9%98%9F%E5%88%97%E7%B1%BB%EF%BC%8C%E4%BD%86%E4%B8%8D%E5%A4%AA%E5%A5%BD%E7%94%A8%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E9%98%9F%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22%E9%98%9F%E5%88%97%20que%20%3D%22,%20que%29%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22,%20front%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E9%98%9F%E5%85%83%E7%B4%A0%20pop%20%3D%22,%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E9%98%9F%E5%90%8E%20que%20%3D%22,%20que%29%0A%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E9%98%9F%E5%88%97%E7%9A%84%E9%95%BF%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22%E9%98%9F%E5%88%97%E9%95%BF%E5%BA%A6%20size%20%3D%22,%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%20%3D%22,%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_stack_and_queue/stack.md b/codes/snippets/chapter_stack_and_queue/stack.md new file mode 100644 index 000000000..31de324a9 --- /dev/null +++ b/codes/snippets/chapter_stack_and_queue/stack.md @@ -0,0 +1,304 @@ + +```python title="stack.py" +# 初始化栈 +# Python 没有内置的栈类,可以把 list 当作栈来使用 +stack: list[int] = [] + +# 元素入栈 +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +# 访问栈顶元素 +peek: int = stack[-1] + +# 元素出栈 +pop: int = stack.pop() + +# 获取栈的长度 +size: int = len(stack) + +# 判断是否为空 +is_empty: bool = len(stack) == 0 +``` + +```cpp title="stack.cpp" +/* 初始化栈 */ +stack stack; + +/* 元素入栈 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 访问栈顶元素 */ +int top = stack.top(); + +/* 元素出栈 */ +stack.pop(); // 无返回值 + +/* 获取栈的长度 */ +int size = stack.size(); + +/* 判断是否为空 */ +bool empty = stack.empty(); +``` + +```java title="stack.java" +/* 初始化栈 */ +Stack stack = new Stack<>(); + +/* 元素入栈 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 访问栈顶元素 */ +int peek = stack.peek(); + +/* 元素出栈 */ +int pop = stack.pop(); + +/* 获取栈的长度 */ +int size = stack.size(); + +/* 判断是否为空 */ +boolean isEmpty = stack.isEmpty(); +``` + +```csharp title="stack.cs" +/* 初始化栈 */ +Stack stack = new(); + +/* 元素入栈 */ +stack.Push(1); +stack.Push(3); +stack.Push(2); +stack.Push(5); +stack.Push(4); + +/* 访问栈顶元素 */ +int peek = stack.Peek(); + +/* 元素出栈 */ +int pop = stack.Pop(); + +/* 获取栈的长度 */ +int size = stack.Count; + +/* 判断是否为空 */ +bool isEmpty = stack.Count == 0; +``` + +```go title="stack_test.go" +/* 初始化栈 */ +// 在 Go 中,推荐将 Slice 当作栈来使用 +var stack []int + +/* 元素入栈 */ +stack = append(stack, 1) +stack = append(stack, 3) +stack = append(stack, 2) +stack = append(stack, 5) +stack = append(stack, 4) + +/* 访问栈顶元素 */ +peek := stack[len(stack)-1] + +/* 元素出栈 */ +pop := stack[len(stack)-1] +stack = stack[:len(stack)-1] + +/* 获取栈的长度 */ +size := len(stack) + +/* 判断是否为空 */ +isEmpty := len(stack) == 0 +``` + +```swift title="stack.swift" +/* 初始化栈 */ +// Swift 没有内置的栈类,可以把 Array 当作栈来使用 +var stack: [Int] = [] + +/* 元素入栈 */ +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +/* 访问栈顶元素 */ +let peek = stack.last! + +/* 元素出栈 */ +let pop = stack.removeLast() + +/* 获取栈的长度 */ +let size = stack.count + +/* 判断是否为空 */ +let isEmpty = stack.isEmpty +``` + +```javascript title="stack.js" +/* 初始化栈 */ +// JavaScript 没有内置的栈类,可以把 Array 当作栈来使用 +const stack = []; + +/* 元素入栈 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 访问栈顶元素 */ +const peek = stack[stack.length-1]; + +/* 元素出栈 */ +const pop = stack.pop(); + +/* 获取栈的长度 */ +const size = stack.length; + +/* 判断是否为空 */ +const is_empty = stack.length === 0; +``` + +```typescript title="stack.ts" +/* 初始化栈 */ +// TypeScript 没有内置的栈类,可以把 Array 当作栈来使用 +const stack: number[] = []; + +/* 元素入栈 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 访问栈顶元素 */ +const peek = stack[stack.length - 1]; + +/* 元素出栈 */ +const pop = stack.pop(); + +/* 获取栈的长度 */ +const size = stack.length; + +/* 判断是否为空 */ +const is_empty = stack.length === 0; +``` + +```dart title="stack.dart" +/* 初始化栈 */ +// Dart 没有内置的栈类,可以把 List 当作栈来使用 +List stack = []; + +/* 元素入栈 */ +stack.add(1); +stack.add(3); +stack.add(2); +stack.add(5); +stack.add(4); + +/* 访问栈顶元素 */ +int peek = stack.last; + +/* 元素出栈 */ +int pop = stack.removeLast(); + +/* 获取栈的长度 */ +int size = stack.length; + +/* 判断是否为空 */ +bool isEmpty = stack.isEmpty; +``` + +```rust title="stack.rs" +/* 初始化栈 */ +// 把 Vec 当作栈来使用 +let mut stack: Vec = Vec::new(); + +/* 元素入栈 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 访问栈顶元素 */ +let top = stack.last().unwrap(); + +/* 元素出栈 */ +let pop = stack.pop().unwrap(); + +/* 获取栈的长度 */ +let size = stack.len(); + +/* 判断是否为空 */ +let is_empty = stack.is_empty(); +``` + +```c title="stack.c" +// C 未提供内置栈 +``` + +```kotlin title="stack.kt" +/* 初始化栈 */ +val stack = Stack() + +/* 元素入栈 */ +stack.push(1) +stack.push(3) +stack.push(2) +stack.push(5) +stack.push(4) + +/* 访问栈顶元素 */ +val peek = stack.peek() + +/* 元素出栈 */ +val pop = stack.pop() + +/* 获取栈的长度 */ +val size = stack.size + +/* 判断是否为空 */ +val isEmpty = stack.isEmpty() +``` + +```ruby title="stack.rb" +# 初始化栈 +# Ruby 没有内置的栈类,可以把 Array 当作栈来使用 +stack = [] + +# 元素入栈 +stack << 1 +stack << 3 +stack << 2 +stack << 5 +stack << 4 + +# 访问栈顶元素 +peek = stack.last + +# 元素出栈 +pop = stack.pop + +# 获取栈的长度 +size = stack.length + +# 判断是否为空 +is_empty = stack.empty? +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E6%A0%88%0A%20%20%20%20%23%20Python%20%E6%B2%A1%E6%9C%89%E5%86%85%E7%BD%AE%E7%9A%84%E6%A0%88%E7%B1%BB%EF%BC%8C%E5%8F%AF%E4%BB%A5%E6%8A%8A%20list%20%E5%BD%93%E4%BD%9C%E6%A0%88%E6%9D%A5%E4%BD%BF%E7%94%A8%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E6%A0%88%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22%E6%A0%88%20stack%20%3D%22,%20stack%29%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E6%A0%88%E9%A1%B6%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22%E6%A0%88%E9%A1%B6%E5%85%83%E7%B4%A0%20peek%20%3D%22,%20peek%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E6%A0%88%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E6%A0%88%E5%85%83%E7%B4%A0%20pop%20%3D%22,%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E6%A0%88%E5%90%8E%20stack%20%3D%22,%20stack%29%0A%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E6%A0%88%E7%9A%84%E9%95%BF%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22%E6%A0%88%E7%9A%84%E9%95%BF%E5%BA%A6%20size%20%3D%22,%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E6%A0%88%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%20%3D%22,%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_tree/array_representation_of_tree.md b/codes/snippets/chapter_tree/array_representation_of_tree.md new file mode 100644 index 000000000..269c9d72a --- /dev/null +++ b/codes/snippets/chapter_tree/array_representation_of_tree.md @@ -0,0 +1,78 @@ + +```python title="" +# 二叉树的数组表示 +# 使用 None 来表示空位 +tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] +``` + +```cpp title="" +/* 二叉树的数组表示 */ +// 使用 int 最大值 INT_MAX 标记空位 +vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```java title="" +/* 二叉树的数组表示 */ +// 使用 int 的包装类 Integer ,就可以使用 null 来标记空位 +Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; +``` + +```csharp title="" +/* 二叉树的数组表示 */ +// 使用 int? 可空类型 ,就可以使用 null 来标记空位 +int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```go title="" +/* 二叉树的数组表示 */ +// 使用 any 类型的切片, 就可以使用 nil 来标记空位 +tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} +``` + +```swift title="" +/* 二叉树的数组表示 */ +// 使用 Int? 可空类型 ,就可以使用 nil 来标记空位 +let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` + +```javascript title="" +/* 二叉树的数组表示 */ +// 使用 null 来表示空位 +let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```typescript title="" +/* 二叉树的数组表示 */ +// 使用 null 来表示空位 +let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```dart title="" +/* 二叉树的数组表示 */ +// 使用 int? 可空类型 ,就可以使用 null 来标记空位 +List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```rust title="" +/* 二叉树的数组表示 */ +// 使用 None 来标记空位 +let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; +``` + +```c title="" +/* 二叉树的数组表示 */ +// 使用 int 最大值标记空位,因此要求节点值不能为 INT_MAX +int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```kotlin title="" +/* 二叉树的数组表示 */ +// 使用 null 来表示空位 +val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) +``` + +```ruby title="" +### 二叉树的数组表示 ### +# 使用 nil 来表示空位 +tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` diff --git a/codes/snippets/chapter_tree/avl_tree.md b/codes/snippets/chapter_tree/avl_tree.md new file mode 100644 index 000000000..ec92149b6 --- /dev/null +++ b/codes/snippets/chapter_tree/avl_tree.md @@ -0,0 +1,182 @@ + +```python title="" +class TreeNode: + """AVL 树节点类""" + def __init__(self, val: int): + self.val: int = val # 节点值 + self.height: int = 0 # 节点高度 + self.left: TreeNode | None = None # 左子节点引用 + self.right: TreeNode | None = None # 右子节点引用 +``` + +```cpp title="" +/* AVL 树节点类 */ +struct TreeNode { + int val{}; // 节点值 + int height = 0; // 节点高度 + TreeNode *left{}; // 左子节点 + TreeNode *right{}; // 右子节点 + TreeNode() = default; + explicit TreeNode(int x) : val(x){} +}; +``` + +```java title="" +/* AVL 树节点类 */ +class TreeNode { + public int val; // 节点值 + public int height; // 节点高度 + public TreeNode left; // 左子节点 + public TreeNode right; // 右子节点 + public TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* AVL 树节点类 */ +class TreeNode(int? x) { + public int? val = x; // 节点值 + public int height; // 节点高度 + public TreeNode? left; // 左子节点引用 + public TreeNode? right; // 右子节点引用 +} +``` + +```go title="" +/* AVL 树节点结构体 */ +type TreeNode struct { + Val int // 节点值 + Height int // 节点高度 + Left *TreeNode // 左子节点引用 + Right *TreeNode // 右子节点引用 +} +``` + +```swift title="" +/* AVL 树节点类 */ +class TreeNode { + var val: Int // 节点值 + var height: Int // 节点高度 + var left: TreeNode? // 左子节点 + var right: TreeNode? // 右子节点 + + init(x: Int) { + val = x + height = 0 + } +} +``` + +```javascript title="" +/* AVL 树节点类 */ +class TreeNode { + val; // 节点值 + height; //节点高度 + left; // 左子节点指针 + right; // 右子节点指针 + constructor(val, left, right, height) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* AVL 树节点类 */ +class TreeNode { + val: number; // 节点值 + height: number; // 节点高度 + left: TreeNode | null; // 左子节点指针 + right: TreeNode | null; // 右子节点指针 + constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```dart title="" +/* AVL 树节点类 */ +class TreeNode { + int val; // 节点值 + int height; // 节点高度 + TreeNode? left; // 左子节点 + TreeNode? right; // 右子节点 + TreeNode(this.val, [this.height = 0, this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* AVL 树节点结构体 */ +struct TreeNode { + val: i32, // 节点值 + height: i32, // 节点高度 + left: Option>>, // 左子节点 + right: Option>>, // 右子节点 +} + +impl TreeNode { + /* 构造方法 */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + height: 0, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* AVL 树节点结构体 */ +typedef struct TreeNode { + int val; + int height; + struct TreeNode *left; + struct TreeNode *right; +} TreeNode; + +/* 构造函数 */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* AVL 树节点类 */ +class TreeNode(val _val: Int) { // 节点值 + var height: Int = 0 // 节点高度 + var left: TreeNode? = null // 左子节点 + var right: TreeNode? = null // 右子节点 +} +``` + +```ruby title="" +### AVL 树节点类 ### +class TreeNode + attr_accessor :val # 节点值 + attr_accessor :height # 节点高度 + attr_accessor :left # 左子节点引用 + attr_accessor :right # 右子节点引用 + + def initialize(val) + @val = val + @height = 0 + end +end +``` diff --git a/codes/snippets/chapter_tree/binary_tree.md b/codes/snippets/chapter_tree/binary_tree.md new file mode 100644 index 000000000..c7cf5fb70 --- /dev/null +++ b/codes/snippets/chapter_tree/binary_tree.md @@ -0,0 +1,502 @@ + +```python title="" +class TreeNode: + """二叉树节点类""" + def __init__(self, val: int): + self.val: int = val # 节点值 + self.left: TreeNode | None = None # 左子节点引用 + self.right: TreeNode | None = None # 右子节点引用 +``` + +```cpp title="" +/* 二叉树节点结构体 */ +struct TreeNode { + int val; // 节点值 + TreeNode *left; // 左子节点指针 + TreeNode *right; // 右子节点指针 + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; +``` + +```java title="" +/* 二叉树节点类 */ +class TreeNode { + int val; // 节点值 + TreeNode left; // 左子节点引用 + TreeNode right; // 右子节点引用 + TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* 二叉树节点类 */ +class TreeNode(int? x) { + public int? val = x; // 节点值 + public TreeNode? left; // 左子节点引用 + public TreeNode? right; // 右子节点引用 +} +``` + +```go title="" +/* 二叉树节点结构体 */ +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} +/* 构造方法 */ +func NewTreeNode(v int) *TreeNode { + return &TreeNode{ + Left: nil, // 左子节点指针 + Right: nil, // 右子节点指针 + Val: v, // 节点值 + } +} +``` + +```swift title="" +/* 二叉树节点类 */ +class TreeNode { + var val: Int // 节点值 + var left: TreeNode? // 左子节点引用 + var right: TreeNode? // 右子节点引用 + + init(x: Int) { + val = x + } +} +``` + +```javascript title="" +/* 二叉树节点类 */ +class TreeNode { + val; // 节点值 + left; // 左子节点指针 + right; // 右子节点指针 + constructor(val, left, right) { + this.val = val === undefined ? 0 : val; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* 二叉树节点类 */ +class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; // 节点值 + this.left = left === undefined ? null : left; // 左子节点引用 + this.right = right === undefined ? null : right; // 右子节点引用 + } +} +``` + +```dart title="" +/* 二叉树节点类 */ +class TreeNode { + int val; // 节点值 + TreeNode? left; // 左子节点引用 + TreeNode? right; // 右子节点引用 + TreeNode(this.val, [this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 二叉树节点结构体 */ +struct TreeNode { + val: i32, // 节点值 + left: Option>>, // 左子节点引用 + right: Option>>, // 右子节点引用 +} + +impl TreeNode { + /* 构造方法 */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* 二叉树节点结构体 */ +typedef struct TreeNode { + int val; // 节点值 + int height; // 节点高度 + struct TreeNode *left; // 左子节点指针 + struct TreeNode *right; // 右子节点指针 +} TreeNode; + +/* 构造函数 */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* 二叉树节点类 */ +class TreeNode(val _val: Int) { // 节点值 + var left: TreeNode? = null // 左子节点引用 + var right: TreeNode? = null // 右子节点引用 +} +``` + +```ruby title="" +### 二叉树节点类 ### +class TreeNode + attr_accessor :val # 节点值 + attr_accessor :left # 左子节点引用 + attr_accessor :right # 右子节点引用 + + def initialize(val) + @val = val + end +end +``` + + +```python title="binary_tree.py" +# 初始化二叉树 +# 初始化节点 +n1 = TreeNode(val=1) +n2 = TreeNode(val=2) +n3 = TreeNode(val=3) +n4 = TreeNode(val=4) +n5 = TreeNode(val=5) +# 构建节点之间的引用(指针) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```cpp title="binary_tree.cpp" +/* 初始化二叉树 */ +// 初始化节点 +TreeNode* n1 = new TreeNode(1); +TreeNode* n2 = new TreeNode(2); +TreeNode* n3 = new TreeNode(3); +TreeNode* n4 = new TreeNode(4); +TreeNode* n5 = new TreeNode(5); +// 构建节点之间的引用(指针) +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```java title="binary_tree.java" +// 初始化节点 +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// 构建节点之间的引用(指针) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```csharp title="binary_tree.cs" +/* 初始化二叉树 */ +// 初始化节点 +TreeNode n1 = new(1); +TreeNode n2 = new(2); +TreeNode n3 = new(3); +TreeNode n4 = new(4); +TreeNode n5 = new(5); +// 构建节点之间的引用(指针) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```go title="binary_tree.go" +/* 初始化二叉树 */ +// 初始化节点 +n1 := NewTreeNode(1) +n2 := NewTreeNode(2) +n3 := NewTreeNode(3) +n4 := NewTreeNode(4) +n5 := NewTreeNode(5) +// 构建节点之间的引用(指针) +n1.Left = n2 +n1.Right = n3 +n2.Left = n4 +n2.Right = n5 +``` + +```swift title="binary_tree.swift" +// 初始化节点 +let n1 = TreeNode(x: 1) +let n2 = TreeNode(x: 2) +let n3 = TreeNode(x: 3) +let n4 = TreeNode(x: 4) +let n5 = TreeNode(x: 5) +// 构建节点之间的引用(指针) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```javascript title="binary_tree.js" +/* 初始化二叉树 */ +// 初始化节点 +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// 构建节点之间的引用(指针) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```typescript title="binary_tree.ts" +/* 初始化二叉树 */ +// 初始化节点 +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// 构建节点之间的引用(指针) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```dart title="binary_tree.dart" +/* 初始化二叉树 */ +// 初始化节点 +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// 构建节点之间的引用(指针) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```rust title="binary_tree.rs" +// 初始化节点 +let n1 = TreeNode::new(1); +let n2 = TreeNode::new(2); +let n3 = TreeNode::new(3); +let n4 = TreeNode::new(4); +let n5 = TreeNode::new(5); +// 构建节点之间的引用(指针) +n1.borrow_mut().left = Some(n2.clone()); +n1.borrow_mut().right = Some(n3); +n2.borrow_mut().left = Some(n4); +n2.borrow_mut().right = Some(n5); +``` + +```c title="binary_tree.c" +/* 初始化二叉树 */ +// 初始化节点 +TreeNode *n1 = newTreeNode(1); +TreeNode *n2 = newTreeNode(2); +TreeNode *n3 = newTreeNode(3); +TreeNode *n4 = newTreeNode(4); +TreeNode *n5 = newTreeNode(5); +// 构建节点之间的引用(指针) +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```kotlin title="binary_tree.kt" +// 初始化节点 +val n1 = TreeNode(1) +val n2 = TreeNode(2) +val n3 = TreeNode(3) +val n4 = TreeNode(4) +val n5 = TreeNode(5) +// 构建节点之间的引用(指针) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```ruby title="binary_tree.rb" +# 初始化二叉树 +# 初始化节点 +n1 = TreeNode.new(1) +n2 = TreeNode.new(2) +n3 = TreeNode.new(3) +n4 = TreeNode.new(4) +n5 = TreeNode.new(5) +# 构建节点之间的引用(指针) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="binary_tree.py" +# 插入与删除节点 +p = TreeNode(0) +# 在 n1 -> n2 中间插入节点 P +n1.left = p +p.left = n2 +# 删除节点 P +n1.left = n2 +``` + +```cpp title="binary_tree.cpp" +/* 插入与删除节点 */ +TreeNode* P = new TreeNode(0); +// 在 n1 -> n2 中间插入节点 P +n1->left = P; +P->left = n2; +// 删除节点 P +n1->left = n2; +// 释放内存 +delete P; +``` + +```java title="binary_tree.java" +TreeNode P = new TreeNode(0); +// 在 n1 -> n2 中间插入节点 P +n1.left = P; +P.left = n2; +// 删除节点 P +n1.left = n2; +``` + +```csharp title="binary_tree.cs" +/* 插入与删除节点 */ +TreeNode P = new(0); +// 在 n1 -> n2 中间插入节点 P +n1.left = P; +P.left = n2; +// 删除节点 P +n1.left = n2; +``` + +```go title="binary_tree.go" +/* 插入与删除节点 */ +// 在 n1 -> n2 中间插入节点 P +p := NewTreeNode(0) +n1.Left = p +p.Left = n2 +// 删除节点 P +n1.Left = n2 +``` + +```swift title="binary_tree.swift" +let P = TreeNode(x: 0) +// 在 n1 -> n2 中间插入节点 P +n1.left = P +P.left = n2 +// 删除节点 P +n1.left = n2 +``` + +```javascript title="binary_tree.js" +/* 插入与删除节点 */ +let P = new TreeNode(0); +// 在 n1 -> n2 中间插入节点 P +n1.left = P; +P.left = n2; +// 删除节点 P +n1.left = n2; +``` + +```typescript title="binary_tree.ts" +/* 插入与删除节点 */ +const P = new TreeNode(0); +// 在 n1 -> n2 中间插入节点 P +n1.left = P; +P.left = n2; +// 删除节点 P +n1.left = n2; +``` + +```dart title="binary_tree.dart" +/* 插入与删除节点 */ +TreeNode P = new TreeNode(0); +// 在 n1 -> n2 中间插入节点 P +n1.left = P; +P.left = n2; +// 删除节点 P +n1.left = n2; +``` + +```rust title="binary_tree.rs" +let p = TreeNode::new(0); +// 在 n1 -> n2 中间插入节点 P +n1.borrow_mut().left = Some(p.clone()); +p.borrow_mut().left = Some(n2.clone()); +// 删除节点 p +n1.borrow_mut().left = Some(n2); +``` + +```c title="binary_tree.c" +/* 插入与删除节点 */ +TreeNode *P = newTreeNode(0); +// 在 n1 -> n2 中间插入节点 P +n1->left = P; +P->left = n2; +// 删除节点 P +n1->left = n2; +// 释放内存 +free(P); +``` + +```kotlin title="binary_tree.kt" +val P = TreeNode(0) +// 在 n1 -> n2 中间插入节点 P +n1.left = P +P.left = n2 +// 删除节点 P +n1.left = n2 +``` + +```ruby title="binary_tree.rb" +# 插入与删除节点 +_p = TreeNode.new(0) +# 在 n1 -> n2 中间插入节点 _p +n1.left = _p +_p.left = n2 +# 删除节点 +n1.left = n2 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/docs/chapter_array_and_linkedlist/array.md b/docs/chapter_array_and_linkedlist/array.md index d89d97b1b..385abaa92 100755 --- a/docs/chapter_array_and_linkedlist/array.md +++ b/docs/chapter_array_and_linkedlist/array.md @@ -10,125 +10,13 @@ 我们可以根据需求选用数组的两种初始化方式:无初始值、给定初始值。在未指定初始值的情况下,大多数编程语言会将数组元素初始化为 $0$ : -=== "Python" - - ```python title="array.py" - # 初始化数组 - arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="array.cpp" - /* 初始化数组 */ - // 存储在栈上 - int arr[5] = {}; - int nums[5] = { 1, 3, 2, 5, 4 }; - // 存储在堆上(需要手动释放空间) - int* arr1 = new int[5] {}; - int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="array.java" - /* 初始化数组 */ - int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } - int[] nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "C#" - - ```csharp title="array.cs" - /* 初始化数组 */ - int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] - int[] nums = [1, 3, 2, 5, 4]; - ``` - -=== "Go" - - ```go title="array.go" - /* 初始化数组 */ - var arr [5]int - // 在 Go 中,指定长度时([5]int)为数组,不指定长度时([]int)为切片 - // 由于 Go 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度 - // 为了方便实现扩容 extend() 方法,以下将切片(Slice)看作数组(Array) - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="array.swift" - /* 初始化数组 */ - let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] - let nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="array.js" - /* 初始化数组 */ - var arr = new Array(5).fill(0); - var nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="array.ts" - /* 初始化数组 */ - let arr: number[] = new Array(5).fill(0); - let nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="array.dart" - /* 初始化数组 */ - List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="array.rs" - /* 初始化数组 */ - let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] - let slice: &[i32] = &[0; 5]; - // 在 Rust 中,指定长度时([i32; 5])为数组,不指定长度时(&[i32])为切片 - // 由于 Rust 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度 - // Vector 是 Rust 一般情况下用作动态数组的类型 - // 为了方便实现扩容 extend() 方法,以下将 vector 看作数组(array) - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="array.c" - /* 初始化数组 */ - int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } - int nums[5] = { 1, 3, 2, 5, 4 }; - ``` - -=== "Kotlin" - - ```kotlin title="array.kt" - /* 初始化数组 */ - var arr = IntArray(5) // { 0, 0, 0, 0, 0 } - var nums = intArrayOf(1, 3, 2, 5, 4) - ``` - -=== "Ruby" - - ```ruby title="array.rb" - # 初始化数组 - arr = Array.new(5, 0) - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_array +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E6%95%B0%E7%BB%84%0Aarr%20%3D%20%5B0%5D%20*%205%20%20%23%20%5B%200,%200,%200,%200,%200%20%5D%0Anums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_array_tutor ### 访问元素 diff --git a/docs/chapter_array_and_linkedlist/linked_list.md b/docs/chapter_array_and_linkedlist/linked_list.md index 2114df60c..2c47b5f48 100755 --- a/docs/chapter_array_and_linkedlist/linked_list.md +++ b/docs/chapter_array_and_linkedlist/linked_list.md @@ -16,174 +16,9 @@ 如以下代码所示,链表节点 `ListNode` 除了包含值,还需额外保存一个引用(指针)。因此在相同数据量下,**链表比数组占用更多的内存空间**。 -=== "Python" - - ```python title="" - class ListNode: - """链表节点类""" - def __init__(self, val: int): - self.val: int = val # 节点值 - self.next: ListNode | None = None # 指向下一节点的引用 - ``` - -=== "C++" - - ```cpp title="" - /* 链表节点结构体 */ - struct ListNode { - int val; // 节点值 - ListNode *next; // 指向下一节点的指针 - ListNode(int x) : val(x), next(nullptr) {} // 构造函数 - }; - ``` - -=== "Java" - - ```java title="" - /* 链表节点类 */ - class ListNode { - int val; // 节点值 - ListNode next; // 指向下一节点的引用 - ListNode(int x) { val = x; } // 构造函数 - } - ``` - -=== "C#" - - ```csharp title="" - /* 链表节点类 */ - class ListNode(int x) { //构造函数 - int val = x; // 节点值 - ListNode? next; // 指向下一节点的引用 - } - ``` - -=== "Go" - - ```go title="" - /* 链表节点结构体 */ - type ListNode struct { - Val int // 节点值 - Next *ListNode // 指向下一节点的指针 - } - - // NewListNode 构造函数,创建一个新的链表 - func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 链表节点类 */ - class ListNode { - var val: Int // 节点值 - var next: ListNode? // 指向下一节点的引用 - - init(x: Int) { // 构造函数 - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 链表节点类 */ - class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // 节点值 - this.next = (next === undefined ? null : next); // 指向下一节点的引用 - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 链表节点类 */ - class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 节点值 - this.next = next === undefined ? null : next; // 指向下一节点的引用 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 链表节点类 */ - class ListNode { - int val; // 节点值 - ListNode? next; // 指向下一节点的引用 - ListNode(this.val, [this.next]); // 构造函数 - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - /* 链表节点类 */ - #[derive(Debug)] - struct ListNode { - val: i32, // 节点值 - next: Option>>, // 指向下一节点的指针 - } - ``` - -=== "C" - - ```c title="" - /* 链表节点结构体 */ - typedef struct ListNode { - int val; // 节点值 - struct ListNode *next; // 指向下一节点的指针 - } ListNode; - - /* 构造函数 */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 链表节点类 */ - // 构造方法 - class ListNode(x: Int) { - val _val: Int = x // 节点值 - var next: ListNode? = null // 指向下一个节点的引用 - } - ``` - -=== "Ruby" - - ```ruby title="" - # 链表节点类 - class ListNode - attr_accessor :val # 节点值 - attr_accessor :next # 指向下一节点的引用 - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end - end - ``` +```snippet +list_node_class +``` ## 链表常用操作 @@ -191,231 +26,13 @@ 建立链表分为两步,第一步是初始化各个节点对象,第二步是构建节点之间的引用关系。初始化完成后,我们就可以从链表的头节点出发,通过引用指向 `next` 依次访问所有节点。 -=== "Python" - - ```python title="linked_list.py" - # 初始化链表 1 -> 3 -> 2 -> 5 -> 4 - # 初始化各个节点 - n0 = ListNode(1) - n1 = ListNode(3) - n2 = ListNode(2) - n3 = ListNode(5) - n4 = ListNode(4) - # 构建节点之间的引用 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "C++" - - ```cpp title="linked_list.cpp" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - ListNode* n0 = new ListNode(1); - ListNode* n1 = new ListNode(3); - ListNode* n2 = new ListNode(2); - ListNode* n3 = new ListNode(5); - ListNode* n4 = new ListNode(4); - // 构建节点之间的引用 - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Java" - - ```java title="linked_list.java" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - ListNode n0 = new ListNode(1); - ListNode n1 = new ListNode(3); - ListNode n2 = new ListNode(2); - ListNode n3 = new ListNode(5); - ListNode n4 = new ListNode(4); - // 构建节点之间的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "C#" - - ```csharp title="linked_list.cs" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - ListNode n0 = new(1); - ListNode n1 = new(3); - ListNode n2 = new(2); - ListNode n3 = new(5); - ListNode n4 = new(4); - // 构建节点之间的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Go" - - ```go title="linked_list.go" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - n0 := NewListNode(1) - n1 := NewListNode(3) - n2 := NewListNode(2) - n3 := NewListNode(5) - n4 := NewListNode(4) - // 构建节点之间的引用 - n0.Next = n1 - n1.Next = n2 - n2.Next = n3 - n3.Next = n4 - ``` - -=== "Swift" - - ```swift title="linked_list.swift" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - let n0 = ListNode(x: 1) - let n1 = ListNode(x: 3) - let n2 = ListNode(x: 2) - let n3 = ListNode(x: 5) - let n4 = ListNode(x: 4) - // 构建节点之间的引用 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "JS" - - ```javascript title="linked_list.js" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // 构建节点之间的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "TS" - - ```typescript title="linked_list.ts" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // 构建节点之间的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Dart" - - ```dart title="linked_list.dart" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */\ - // 初始化各个节点 - ListNode n0 = ListNode(1); - ListNode n1 = ListNode(3); - ListNode n2 = ListNode(2); - ListNode n3 = ListNode(5); - ListNode n4 = ListNode(4); - // 构建节点之间的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Rust" - - ```rust title="linked_list.rs" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); - let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); - let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); - let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); - let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); - - // 构建节点之间的引用 - n0.borrow_mut().next = Some(n1.clone()); - n1.borrow_mut().next = Some(n2.clone()); - n2.borrow_mut().next = Some(n3.clone()); - n3.borrow_mut().next = Some(n4.clone()); - ``` - -=== "C" - - ```c title="linked_list.c" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - ListNode* n0 = newListNode(1); - ListNode* n1 = newListNode(3); - ListNode* n2 = newListNode(2); - ListNode* n3 = newListNode(5); - ListNode* n4 = newListNode(4); - // 构建节点之间的引用 - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Kotlin" - - ```kotlin title="linked_list.kt" - /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各个节点 - val n0 = ListNode(1) - val n1 = ListNode(3) - val n2 = ListNode(2) - val n3 = ListNode(5) - val n4 = ListNode(4) - // 构建节点之间的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Ruby" - - ```ruby title="linked_list.rb" - # 初始化链表 1 -> 3 -> 2 -> 5 -> 4 - # 初始化各个节点 - n0 = ListNode.new(1) - n1 = ListNode.new(3) - n2 = ListNode.new(2) - n3 = ListNode.new(5) - n4 = ListNode.new(4) - # 构建节点之间的引用 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` +```snippet +init_linked_list +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%93%BE%E8%A1%A8%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%90%84%E4%B8%AA%E8%8A%82%E7%82%B9%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_linked_list_tutor 数组整体是一个变量,比如数组 `nums` 包含元素 `nums[0]` 和 `nums[1]` 等,而链表是由多个独立的节点对象组成的。**我们通常将头节点当作链表的代称**,比如以上代码中的链表可记作链表 `n0` 。 @@ -482,203 +99,9 @@ - **环形链表**:如果我们令单向链表的尾节点指向头节点(首尾相接),则得到一个环形链表。在环形链表中,任意节点都可以视作头节点。 - **双向链表**:与单向链表相比,双向链表记录了两个方向的引用。双向链表的节点定义同时包含指向后继节点(下一个节点)和前驱节点(上一个节点)的引用(指针)。相较于单向链表,双向链表更具灵活性,可以朝两个方向遍历链表,但相应地也需要占用更多的内存空间。 -=== "Python" - - ```python title="" - class ListNode: - """双向链表节点类""" - def __init__(self, val: int): - self.val: int = val # 节点值 - self.next: ListNode | None = None # 指向后继节点的引用 - self.prev: ListNode | None = None # 指向前驱节点的引用 - ``` - -=== "C++" - - ```cpp title="" - /* 双向链表节点结构体 */ - struct ListNode { - int val; // 节点值 - ListNode *next; // 指向后继节点的指针 - ListNode *prev; // 指向前驱节点的指针 - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 构造函数 - }; - ``` - -=== "Java" - - ```java title="" - /* 双向链表节点类 */ - class ListNode { - int val; // 节点值 - ListNode next; // 指向后继节点的引用 - ListNode prev; // 指向前驱节点的引用 - ListNode(int x) { val = x; } // 构造函数 - } - ``` - -=== "C#" - - ```csharp title="" - /* 双向链表节点类 */ - class ListNode(int x) { // 构造函数 - int val = x; // 节点值 - ListNode next; // 指向后继节点的引用 - ListNode prev; // 指向前驱节点的引用 - } - ``` - -=== "Go" - - ```go title="" - /* 双向链表节点结构体 */ - type DoublyListNode struct { - Val int // 节点值 - Next *DoublyListNode // 指向后继节点的指针 - Prev *DoublyListNode // 指向前驱节点的指针 - } - - // NewDoublyListNode 初始化 - func NewDoublyListNode(val int) *DoublyListNode { - return &DoublyListNode{ - Val: val, - Next: nil, - Prev: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 双向链表节点类 */ - class ListNode { - var val: Int // 节点值 - var next: ListNode? // 指向后继节点的引用 - var prev: ListNode? // 指向前驱节点的引用 - - init(x: Int) { // 构造函数 - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 双向链表节点类 */ - class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // 节点值 - this.next = next === undefined ? null : next; // 指向后继节点的引用 - this.prev = prev === undefined ? null : prev; // 指向前驱节点的引用 - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 双向链表节点类 */ - class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 节点值 - this.next = next === undefined ? null : next; // 指向后继节点的引用 - this.prev = prev === undefined ? null : prev; // 指向前驱节点的引用 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 双向链表节点类 */ - class ListNode { - int val; // 节点值 - ListNode? next; // 指向后继节点的引用 - ListNode? prev; // 指向前驱节点的引用 - ListNode(this.val, [this.next, this.prev]); // 构造函数 - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 双向链表节点类型 */ - #[derive(Debug)] - struct ListNode { - val: i32, // 节点值 - next: Option>>, // 指向后继节点的指针 - prev: Option>>, // 指向前驱节点的指针 - } - - /* 构造函数 */ - impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } - } - ``` - -=== "C" - - ```c title="" - /* 双向链表节点结构体 */ - typedef struct ListNode { - int val; // 节点值 - struct ListNode *next; // 指向后继节点的指针 - struct ListNode *prev; // 指向前驱节点的指针 - } ListNode; - - /* 构造函数 */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 双向链表节点类 */ - // 构造方法 - class ListNode(x: Int) { - val _val: Int = x // 节点值 - var next: ListNode? = null // 指向后继节点的引用 - var prev: ListNode? = null // 指向前驱节点的引用 - } - ``` - -=== "Ruby" - - ```ruby title="" - # 双向链表节点类 - class ListNode - attr_accessor :val # 节点值 - attr_accessor :next # 指向后继节点的引用 - attr_accessor :prev # 指向前驱节点的引用 - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end - end - ``` +```snippet +doubly_list_node_class +``` ![常见链表种类](linked_list.assets/linkedlist_common_types.svg) diff --git a/docs/chapter_array_and_linkedlist/list.md b/docs/chapter_array_and_linkedlist/list.md index ded6505eb..4878e14bd 100755 --- a/docs/chapter_array_and_linkedlist/list.md +++ b/docs/chapter_array_and_linkedlist/list.md @@ -17,934 +17,73 @@ 我们通常使用“无初始值”和“有初始值”这两种初始化方法: -=== "Python" - - ```python title="list.py" - # 初始化列表 - # 无初始值 - nums1: list[int] = [] - # 有初始值 - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 初始化列表 */ - // 需注意,C++ 中 vector 即是本文描述的 nums - // 无初始值 - vector nums1; - // 有初始值 - vector nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="list.java" - /* 初始化列表 */ - // 无初始值 - List nums1 = new ArrayList<>(); - // 有初始值(注意数组的元素类型需为 int[] 的包装类 Integer[]) - Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; - List nums = new ArrayList<>(Arrays.asList(numbers)); - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 初始化列表 */ - // 无初始值 - List nums1 = []; - // 有初始值 - int[] numbers = [1, 3, 2, 5, 4]; - List nums = [.. numbers]; - ``` - -=== "Go" - - ```go title="list_test.go" - /* 初始化列表 */ - // 无初始值 - nums1 := []int{} - // 有初始值 - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 初始化列表 */ - // 无初始值 - let nums1: [Int] = [] - // 有初始值 - var nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="list.js" - /* 初始化列表 */ - // 无初始值 - const nums1 = []; - // 有初始值 - const nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 初始化列表 */ - // 无初始值 - const nums1: number[] = []; - // 有初始值 - const nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 初始化列表 */ - // 无初始值 - List nums1 = []; - // 有初始值 - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 初始化列表 */ - // 无初始值 - let nums1: Vec = Vec::new(); - // 有初始值 - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="list.c" - // C 未提供内置动态数组 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 初始化列表 */ - // 无初始值 - var nums1 = listOf() - // 有初始值 - var numbers = arrayOf(1, 3, 2, 5, 4) - var nums = numbers.toMutableList() - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 初始化列表 - # 无初始值 - nums1 = [] - # 有初始值 - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_list +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20%23%20%E6%97%A0%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_list_tutor ### 访问元素 列表本质上是数组,因此可以在 $O(1)$ 时间内访问和更新元素,效率很高。 -=== "Python" - - ```python title="list.py" - # 访问元素 - num: int = nums[1] # 访问索引 1 处的元素 - - # 更新元素 - nums[1] = 0 # 将索引 1 处的元素更新为 0 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 访问元素 */ - int num = nums[1]; // 访问索引 1 处的元素 - - /* 更新元素 */ - nums[1] = 0; // 将索引 1 处的元素更新为 0 - ``` - -=== "Java" - - ```java title="list.java" - /* 访问元素 */ - int num = nums.get(1); // 访问索引 1 处的元素 - - /* 更新元素 */ - nums.set(1, 0); // 将索引 1 处的元素更新为 0 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 访问元素 */ - int num = nums[1]; // 访问索引 1 处的元素 - - /* 更新元素 */ - nums[1] = 0; // 将索引 1 处的元素更新为 0 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 访问元素 */ - num := nums[1] // 访问索引 1 处的元素 - - /* 更新元素 */ - nums[1] = 0 // 将索引 1 处的元素更新为 0 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 访问元素 */ - let num = nums[1] // 访问索引 1 处的元素 - - /* 更新元素 */ - nums[1] = 0 // 将索引 1 处的元素更新为 0 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 访问元素 */ - const num = nums[1]; // 访问索引 1 处的元素 - - /* 更新元素 */ - nums[1] = 0; // 将索引 1 处的元素更新为 0 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 访问元素 */ - const num: number = nums[1]; // 访问索引 1 处的元素 - - /* 更新元素 */ - nums[1] = 0; // 将索引 1 处的元素更新为 0 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 访问元素 */ - int num = nums[1]; // 访问索引 1 处的元素 - - /* 更新元素 */ - nums[1] = 0; // 将索引 1 处的元素更新为 0 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 访问元素 */ - let num: i32 = nums[1]; // 访问索引 1 处的元素 - /* 更新元素 */ - nums[1] = 0; // 将索引 1 处的元素更新为 0 - ``` - -=== "C" - - ```c title="list.c" - // C 未提供内置动态数组 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 访问元素 */ - val num = nums[1] // 访问索引 1 处的元素 - /* 更新元素 */ - nums[1] = 0 // 将索引 1 处的元素更新为 0 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 访问元素 - num = nums[1] # 访问索引 1 处的元素 - # 更新元素 - nums[1] = 0 # 将索引 1 处的元素更新为 0 - ``` +```snippet +access_element +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E8%AE%BF%E9%97%AE%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%86%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E4%B8%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor access_element_tutor ### 插入与删除元素 相较于数组,列表可以自由地添加与删除元素。在列表尾部添加元素的时间复杂度为 $O(1)$ ,但插入和删除元素的效率仍与数组相同,时间复杂度为 $O(n)$ 。 -=== "Python" - - ```python title="list.py" - # 清空列表 - nums.clear() - - # 在尾部添加元素 - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - # 在中间插入元素 - nums.insert(3, 6) # 在索引 3 处插入数字 6 - - # 删除元素 - nums.pop(3) # 删除索引 3 处的元素 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 清空列表 */ - nums.clear(); - - /* 在尾部添加元素 */ - nums.push_back(1); - nums.push_back(3); - nums.push_back(2); - nums.push_back(5); - nums.push_back(4); - - /* 在中间插入元素 */ - nums.insert(nums.begin() + 3, 6); // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums.erase(nums.begin() + 3); // 删除索引 3 处的元素 - ``` - -=== "Java" - - ```java title="list.java" - /* 清空列表 */ - nums.clear(); - - /* 在尾部添加元素 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 在中间插入元素 */ - nums.add(3, 6); // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums.remove(3); // 删除索引 3 处的元素 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 清空列表 */ - nums.Clear(); - - /* 在尾部添加元素 */ - nums.Add(1); - nums.Add(3); - nums.Add(2); - nums.Add(5); - nums.Add(4); - - /* 在中间插入元素 */ - nums.Insert(3, 6); // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums.RemoveAt(3); // 删除索引 3 处的元素 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 清空列表 */ - nums = nil - - /* 在尾部添加元素 */ - nums = append(nums, 1) - nums = append(nums, 3) - nums = append(nums, 2) - nums = append(nums, 5) - nums = append(nums, 4) - - /* 在中间插入元素 */ - nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums = append(nums[:3], nums[4:]...) // 删除索引 3 处的元素 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 清空列表 */ - nums.removeAll() - - /* 在尾部添加元素 */ - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - /* 在中间插入元素 */ - nums.insert(6, at: 3) // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums.remove(at: 3) // 删除索引 3 处的元素 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 清空列表 */ - nums.length = 0; - - /* 在尾部添加元素 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 在中间插入元素 */ - nums.splice(3, 0, 6); // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums.splice(3, 1); // 删除索引 3 处的元素 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 清空列表 */ - nums.length = 0; - - /* 在尾部添加元素 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 在中间插入元素 */ - nums.splice(3, 0, 6); // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums.splice(3, 1); // 删除索引 3 处的元素 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 清空列表 */ - nums.clear(); - - /* 在尾部添加元素 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 在中间插入元素 */ - nums.insert(3, 6); // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums.removeAt(3); // 删除索引 3 处的元素 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 清空列表 */ - nums.clear(); - - /* 在尾部添加元素 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 在中间插入元素 */ - nums.insert(3, 6); // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums.remove(3); // 删除索引 3 处的元素 - ``` - -=== "C" - - ```c title="list.c" - // C 未提供内置动态数组 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 清空列表 */ - nums.clear(); - - /* 在尾部添加元素 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 在中间插入元素 */ - nums.add(3, 6); // 在索引 3 处插入数字 6 - - /* 删除元素 */ - nums.remove(3); // 删除索引 3 处的元素 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 清空列表 - nums.clear - - # 在尾部添加元素 - nums << 1 - nums << 3 - nums << 2 - nums << 5 - nums << 4 - - # 在中间插入元素 - nums.insert(3, 6) # 在索引 3 处插入数字 6 - - # 删除元素 - nums.delete_at(3) # 删除索引 3 处的元素 - ``` +```snippet +insert_remove_element +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B8%85%E7%A9%BA%E5%88%97%E8%A1%A8%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E5%B0%BE%E9%83%A8%E6%B7%BB%E5%8A%A0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.insert%283,%206%29%20%20%23%20%E5%9C%A8%E7%B4%A2%E5%BC%95%203%20%E5%A4%84%E6%8F%92%E5%85%A5%E6%95%B0%E5%AD%97%206%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E7%B4%A2%E5%BC%95%203%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_element_tutor ### 遍历列表 与数组一样,列表可以根据索引遍历,也可以直接遍历各元素。 -=== "Python" - - ```python title="list.py" - # 通过索引遍历列表 - count = 0 - for i in range(len(nums)): - count += nums[i] - - # 直接遍历列表元素 - for num in nums: - count += num - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 通过索引遍历列表 */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums[i]; - } - - /* 直接遍历列表元素 */ - count = 0; - for (int num : nums) { - count += num; - } - ``` - -=== "Java" - - ```java title="list.java" - /* 通过索引遍历列表 */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums.get(i); - } - - /* 直接遍历列表元素 */ - for (int num : nums) { - count += num; - } - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 通过索引遍历列表 */ - int count = 0; - for (int i = 0; i < nums.Count; i++) { - count += nums[i]; - } - - /* 直接遍历列表元素 */ - count = 0; - foreach (int num in nums) { - count += num; - } - ``` - -=== "Go" - - ```go title="list_test.go" - /* 通过索引遍历列表 */ - count := 0 - for i := 0; i < len(nums); i++ { - count += nums[i] - } - - /* 直接遍历列表元素 */ - count = 0 - for _, num := range nums { - count += num - } - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 通过索引遍历列表 */ - var count = 0 - for i in nums.indices { - count += nums[i] - } - - /* 直接遍历列表元素 */ - count = 0 - for num in nums { - count += num - } - ``` - -=== "JS" - - ```javascript title="list.js" - /* 通过索引遍历列表 */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* 直接遍历列表元素 */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 通过索引遍历列表 */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* 直接遍历列表元素 */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 通过索引遍历列表 */ - int count = 0; - for (var i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* 直接遍历列表元素 */ - count = 0; - for (var num in nums) { - count += num; - } - ``` - -=== "Rust" - - ```rust title="list.rs" - // 通过索引遍历列表 - let mut _count = 0; - for i in 0..nums.len() { - _count += nums[i]; - } - - // 直接遍历列表元素 - _count = 0; - for num in &nums { - _count += num; - } - ``` - -=== "C" - - ```c title="list.c" - // C 未提供内置动态数组 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 通过索引遍历列表 */ - var count = 0 - for (i in nums.indices) { - count += nums[i] - } - - /* 直接遍历列表元素 */ - for (num in nums) { - count += num - } - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 通过索引遍历列表 - count = 0 - for i in 0...nums.length - count += nums[i] - end - - # 直接遍历列表元素 - count = 0 - for num in nums - count += num - end - ``` +```snippet +iterate_list +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%80%9A%E8%BF%87%E7%B4%A2%E5%BC%95%E9%81%8D%E5%8E%86%E5%88%97%E8%A1%A8%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%E7%9B%B4%E6%8E%A5%E9%81%8D%E5%8E%86%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor iterate_list_tutor ### 拼接列表 给定一个新列表 `nums1` ,我们可以将其拼接到原列表的尾部。 -=== "Python" - - ```python title="list.py" - # 拼接两个列表 - nums1: list[int] = [6, 8, 7, 10, 9] - nums += nums1 # 将列表 nums1 拼接到 nums 之后 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 拼接两个列表 */ - vector nums1 = { 6, 8, 7, 10, 9 }; - // 将列表 nums1 拼接到 nums 之后 - nums.insert(nums.end(), nums1.begin(), nums1.end()); - ``` - -=== "Java" - - ```java title="list.java" - /* 拼接两个列表 */ - List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); - nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 拼接两个列表 */ - List nums1 = [6, 8, 7, 10, 9]; - nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 拼接两个列表 */ - nums1 := []int{6, 8, 7, 10, 9} - nums = append(nums, nums1...) // 将列表 nums1 拼接到 nums 之后 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 拼接两个列表 */ - let nums1 = [6, 8, 7, 10, 9] - nums.append(contentsOf: nums1) // 将列表 nums1 拼接到 nums 之后 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 拼接两个列表 */ - const nums1 = [6, 8, 7, 10, 9]; - nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 拼接两个列表 */ - const nums1: number[] = [6, 8, 7, 10, 9]; - nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 拼接两个列表 */ - List nums1 = [6, 8, 7, 10, 9]; - nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 拼接两个列表 */ - let nums1: Vec = vec![6, 8, 7, 10, 9]; - nums.extend(nums1); - ``` - -=== "C" - - ```c title="list.c" - // C 未提供内置动态数组 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 拼接两个列表 */ - val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() - nums.addAll(nums1) // 将列表 nums1 拼接到 nums 之后 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 拼接两个列表 - nums1 = [6, 8, 7, 10, 9] - nums += nums1 - ``` +```snippet +concat_list +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8B%BC%E6%8E%A5%E4%B8%A4%E4%B8%AA%E5%88%97%E8%A1%A8%0A%20%20%20%20nums1%20%3D%20%5B6,%208,%207,%2010,%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%E5%B0%86%E5%88%97%E8%A1%A8%20nums1%20%E6%8B%BC%E6%8E%A5%E5%88%B0%20nums%20%E4%B9%8B%E5%90%8E&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor concat_list_tutor ### 排序列表 完成列表排序后,我们便可以使用在数组类算法题中经常考查的“二分查找”和“双指针”算法。 -=== "Python" - - ```python title="list.py" - # 排序列表 - nums.sort() # 排序后,列表元素从小到大排列 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 排序列表 */ - sort(nums.begin(), nums.end()); // 排序后,列表元素从小到大排列 - ``` - -=== "Java" - - ```java title="list.java" - /* 排序列表 */ - Collections.sort(nums); // 排序后,列表元素从小到大排列 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 排序列表 */ - nums.Sort(); // 排序后,列表元素从小到大排列 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 排序列表 */ - sort.Ints(nums) // 排序后,列表元素从小到大排列 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 排序列表 */ - nums.sort() // 排序后,列表元素从小到大排列 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 排序列表 */ - nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 排序列表 */ - nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 排序列表 */ - nums.sort(); // 排序后,列表元素从小到大排列 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 排序列表 */ - nums.sort(); // 排序后,列表元素从小到大排列 - ``` - -=== "C" - - ```c title="list.c" - // C 未提供内置动态数组 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 排序列表 */ - nums.sort() // 排序后,列表元素从小到大排列 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 排序列表 - nums = nums.sort { |a, b| a <=> b } # 排序后,列表元素从小到大排列 - ``` +```snippet +sort_list +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8E%92%E5%BA%8F%E5%88%97%E8%A1%A8%0A%20%20%20%20nums.sort%28%29%20%20%23%20%E6%8E%92%E5%BA%8F%E5%90%8E%EF%BC%8C%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%E4%BB%8E%E5%B0%8F%E5%88%B0%E5%A4%A7%E6%8E%92%E5%88%97&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor sort_list_tutor ## 列表实现 diff --git a/docs/chapter_backtracking/backtracking_algorithm.md b/docs/chapter_backtracking/backtracking_algorithm.md index 1fc1072ca..1f1e5e6c0 100644 --- a/docs/chapter_backtracking/backtracking_algorithm.md +++ b/docs/chapter_backtracking/backtracking_algorithm.md @@ -95,339 +95,9 @@ 在以下框架代码中,`state` 表示问题的当前状态,`choices` 表示当前状态下可以做出的选择: -=== "Python" - - ```python title="" - def backtrack(state: State, choices: list[choice], res: list[state]): - """回溯算法框架""" - # 判断是否为解 - if is_solution(state): - # 记录解 - record_solution(state, res) - # 不再继续搜索 - return - # 遍历所有选择 - for choice in choices: - # 剪枝:判断选择是否合法 - if is_valid(state, choice): - # 尝试:做出选择,更新状态 - make_choice(state, choice) - backtrack(state, choices, res) - # 回退:撤销选择,恢复到之前的状态 - undo_choice(state, choice) - ``` - -=== "C++" - - ```cpp title="" - /* 回溯算法框架 */ - void backtrack(State *state, vector &choices, vector &res) { - // 判断是否为解 - if (isSolution(state)) { - // 记录解 - recordSolution(state, res); - // 不再继续搜索 - return; - } - // 遍历所有选择 - for (Choice choice : choices) { - // 剪枝:判断选择是否合法 - if (isValid(state, choice)) { - // 尝试:做出选择,更新状态 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤销选择,恢复到之前的状态 - undoChoice(state, choice); - } - } - } - ``` - -=== "Java" - - ```java title="" - /* 回溯算法框架 */ - void backtrack(State state, List choices, List res) { - // 判断是否为解 - if (isSolution(state)) { - // 记录解 - recordSolution(state, res); - // 不再继续搜索 - return; - } - // 遍历所有选择 - for (Choice choice : choices) { - // 剪枝:判断选择是否合法 - if (isValid(state, choice)) { - // 尝试:做出选择,更新状态 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤销选择,恢复到之前的状态 - undoChoice(state, choice); - } - } - } - ``` - -=== "C#" - - ```csharp title="" - /* 回溯算法框架 */ - void Backtrack(State state, List choices, List res) { - // 判断是否为解 - if (IsSolution(state)) { - // 记录解 - RecordSolution(state, res); - // 不再继续搜索 - return; - } - // 遍历所有选择 - foreach (Choice choice in choices) { - // 剪枝:判断选择是否合法 - if (IsValid(state, choice)) { - // 尝试:做出选择,更新状态 - MakeChoice(state, choice); - Backtrack(state, choices, res); - // 回退:撤销选择,恢复到之前的状态 - UndoChoice(state, choice); - } - } - } - ``` - -=== "Go" - - ```go title="" - /* 回溯算法框架 */ - func backtrack(state *State, choices []Choice, res *[]State) { - // 判断是否为解 - if isSolution(state) { - // 记录解 - recordSolution(state, res) - // 不再继续搜索 - return - } - // 遍历所有选择 - for _, choice := range choices { - // 剪枝:判断选择是否合法 - if isValid(state, choice) { - // 尝试:做出选择,更新状态 - makeChoice(state, choice) - backtrack(state, choices, res) - // 回退:撤销选择,恢复到之前的状态 - undoChoice(state, choice) - } - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 回溯算法框架 */ - func backtrack(state: inout State, choices: [Choice], res: inout [State]) { - // 判断是否为解 - if isSolution(state: state) { - // 记录解 - recordSolution(state: state, res: &res) - // 不再继续搜索 - return - } - // 遍历所有选择 - for choice in choices { - // 剪枝:判断选择是否合法 - if isValid(state: state, choice: choice) { - // 尝试:做出选择,更新状态 - makeChoice(state: &state, choice: choice) - backtrack(state: &state, choices: choices, res: &res) - // 回退:撤销选择,恢复到之前的状态 - undoChoice(state: &state, choice: choice) - } - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 回溯算法框架 */ - function backtrack(state, choices, res) { - // 判断是否为解 - if (isSolution(state)) { - // 记录解 - recordSolution(state, res); - // 不再继续搜索 - return; - } - // 遍历所有选择 - for (let choice of choices) { - // 剪枝:判断选择是否合法 - if (isValid(state, choice)) { - // 尝试:做出选择,更新状态 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤销选择,恢复到之前的状态 - undoChoice(state, choice); - } - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 回溯算法框架 */ - function backtrack(state: State, choices: Choice[], res: State[]): void { - // 判断是否为解 - if (isSolution(state)) { - // 记录解 - recordSolution(state, res); - // 不再继续搜索 - return; - } - // 遍历所有选择 - for (let choice of choices) { - // 剪枝:判断选择是否合法 - if (isValid(state, choice)) { - // 尝试:做出选择,更新状态 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤销选择,恢复到之前的状态 - undoChoice(state, choice); - } - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 回溯算法框架 */ - void backtrack(State state, List, List res) { - // 判断是否为解 - if (isSolution(state)) { - // 记录解 - recordSolution(state, res); - // 不再继续搜索 - return; - } - // 遍历所有选择 - for (Choice choice in choices) { - // 剪枝:判断选择是否合法 - if (isValid(state, choice)) { - // 尝试:做出选择,更新状态 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤销选择,恢复到之前的状态 - undoChoice(state, choice); - } - } - } - ``` - -=== "Rust" - - ```rust title="" - /* 回溯算法框架 */ - fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { - // 判断是否为解 - if is_solution(state) { - // 记录解 - record_solution(state, res); - // 不再继续搜索 - return; - } - // 遍历所有选择 - for choice in choices { - // 剪枝:判断选择是否合法 - if is_valid(state, choice) { - // 尝试:做出选择,更新状态 - make_choice(state, choice); - backtrack(state, choices, res); - // 回退:撤销选择,恢复到之前的状态 - undo_choice(state, choice); - } - } - } - ``` - -=== "C" - - ```c title="" - /* 回溯算法框架 */ - void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { - // 判断是否为解 - if (isSolution(state)) { - // 记录解 - recordSolution(state, res, numRes); - // 不再继续搜索 - return; - } - // 遍历所有选择 - for (int i = 0; i < numChoices; i++) { - // 剪枝:判断选择是否合法 - if (isValid(state, &choices[i])) { - // 尝试:做出选择,更新状态 - makeChoice(state, &choices[i]); - backtrack(state, choices, numChoices, res, numRes); - // 回退:撤销选择,恢复到之前的状态 - undoChoice(state, &choices[i]); - } - } - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 回溯算法框架 */ - fun backtrack(state: State?, choices: List, res: List?) { - // 判断是否为解 - if (isSolution(state)) { - // 记录解 - recordSolution(state, res) - // 不再继续搜索 - return - } - // 遍历所有选择 - for (choice in choices) { - // 剪枝:判断选择是否合法 - if (isValid(state, choice)) { - // 尝试:做出选择,更新状态 - makeChoice(state, choice) - backtrack(state, choices, res) - // 回退:撤销选择,恢复到之前的状态 - undoChoice(state, choice) - } - } - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 回溯算法框架 ### - def backtrack(state, choices, res) - # 判断是否为解 - if is_solution?(state) - # 记录解 - record_solution(state, res) - return - end - - # 遍历所有选择 - for choice in choices - # 剪枝:判断选择是否合法 - if is_valid?(state, choice) - # 尝试:做出选择,更新状态 - make_choice(state, choice) - backtrack(state, choices, res) - # 回退:撤销选择,恢复到之前的状态 - undo_choice(state, choice) - end - end - end - ``` +```snippet +backtrack_framework +``` 接下来,我们基于框架代码来解决例题三。状态 `state` 为节点遍历路径,选择 `choices` 为当前节点的左子节点和右子节点,结果 `res` 是路径列表: diff --git a/docs/chapter_computational_complexity/space_complexity.md b/docs/chapter_computational_complexity/space_complexity.md index 04b2bbb99..596245254 100755 --- a/docs/chapter_computational_complexity/space_complexity.md +++ b/docs/chapter_computational_complexity/space_complexity.md @@ -24,342 +24,9 @@ 相关代码如下: -=== "Python" - - ```python title="" - class Node: - """类""" - def __init__(self, x: int): - self.val: int = x # 节点值 - self.next: Node | None = None # 指向下一节点的引用 - - def function() -> int: - """函数""" - # 执行某些操作... - return 0 - - def algorithm(n) -> int: # 输入数据 - A = 0 # 暂存数据(常量,一般用大写字母表示) - b = 0 # 暂存数据(变量) - node = Node(0) # 暂存数据(对象) - c = function() # 栈帧空间(调用函数) - return A + b + c # 输出数据 - ``` - -=== "C++" - - ```cpp title="" - /* 结构体 */ - struct Node { - int val; - Node *next; - Node(int x) : val(x), next(nullptr) {} - }; - - /* 函数 */ - int func() { - // 执行某些操作... - return 0; - } - - int algorithm(int n) { // 输入数据 - const int a = 0; // 暂存数据(常量) - int b = 0; // 暂存数据(变量) - Node* node = new Node(0); // 暂存数据(对象) - int c = func(); // 栈帧空间(调用函数) - return a + b + c; // 输出数据 - } - ``` - -=== "Java" - - ```java title="" - /* 类 */ - class Node { - int val; - Node next; - Node(int x) { val = x; } - } - - /* 函数 */ - int function() { - // 执行某些操作... - return 0; - } - - int algorithm(int n) { // 输入数据 - final int a = 0; // 暂存数据(常量) - int b = 0; // 暂存数据(变量) - Node node = new Node(0); // 暂存数据(对象) - int c = function(); // 栈帧空间(调用函数) - return a + b + c; // 输出数据 - } - ``` - -=== "C#" - - ```csharp title="" - /* 类 */ - class Node(int x) { - int val = x; - Node next; - } - - /* 函数 */ - int Function() { - // 执行某些操作... - return 0; - } - - int Algorithm(int n) { // 输入数据 - const int a = 0; // 暂存数据(常量) - int b = 0; // 暂存数据(变量) - Node node = new(0); // 暂存数据(对象) - int c = Function(); // 栈帧空间(调用函数) - return a + b + c; // 输出数据 - } - ``` - -=== "Go" - - ```go title="" - /* 结构体 */ - type node struct { - val int - next *node - } - - /* 创建 node 结构体 */ - func newNode(val int) *node { - return &node{val: val} - } - - /* 函数 */ - func function() int { - // 执行某些操作... - return 0 - } - - func algorithm(n int) int { // 输入数据 - const a = 0 // 暂存数据(常量) - b := 0 // 暂存数据(变量) - newNode(0) // 暂存数据(对象) - c := function() // 栈帧空间(调用函数) - return a + b + c // 输出数据 - } - ``` - -=== "Swift" - - ```swift title="" - /* 类 */ - class Node { - var val: Int - var next: Node? - - init(x: Int) { - val = x - } - } - - /* 函数 */ - func function() -> Int { - // 执行某些操作... - return 0 - } - - func algorithm(n: Int) -> Int { // 输入数据 - let a = 0 // 暂存数据(常量) - var b = 0 // 暂存数据(变量) - let node = Node(x: 0) // 暂存数据(对象) - let c = function() // 栈帧空间(调用函数) - return a + b + c // 输出数据 - } - ``` - -=== "JS" - - ```javascript title="" - /* 类 */ - class Node { - val; - next; - constructor(val) { - this.val = val === undefined ? 0 : val; // 节点值 - this.next = null; // 指向下一节点的引用 - } - } - - /* 函数 */ - function constFunc() { - // 执行某些操作 - return 0; - } - - function algorithm(n) { // 输入数据 - const a = 0; // 暂存数据(常量) - let b = 0; // 暂存数据(变量) - const node = new Node(0); // 暂存数据(对象) - const c = constFunc(); // 栈帧空间(调用函数) - return a + b + c; // 输出数据 - } - ``` - -=== "TS" - - ```typescript title="" - /* 类 */ - class Node { - val: number; - next: Node | null; - constructor(val?: number) { - this.val = val === undefined ? 0 : val; // 节点值 - this.next = null; // 指向下一节点的引用 - } - } - - /* 函数 */ - function constFunc(): number { - // 执行某些操作 - return 0; - } - - function algorithm(n: number): number { // 输入数据 - const a = 0; // 暂存数据(常量) - let b = 0; // 暂存数据(变量) - const node = new Node(0); // 暂存数据(对象) - const c = constFunc(); // 栈帧空间(调用函数) - return a + b + c; // 输出数据 - } - ``` - -=== "Dart" - - ```dart title="" - /* 类 */ - class Node { - int val; - Node next; - Node(this.val, [this.next]); - } - - /* 函数 */ - int function() { - // 执行某些操作... - return 0; - } - - int algorithm(int n) { // 输入数据 - const int a = 0; // 暂存数据(常量) - int b = 0; // 暂存数据(变量) - Node node = Node(0); // 暂存数据(对象) - int c = function(); // 栈帧空间(调用函数) - return a + b + c; // 输出数据 - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 结构体 */ - struct Node { - val: i32, - next: Option>>, - } - - /* 创建 Node 结构体 */ - impl Node { - fn new(val: i32) -> Self { - Self { val: val, next: None } - } - } - - /* 函数 */ - fn function() -> i32 { - // 执行某些操作... - return 0; - } - - fn algorithm(n: i32) -> i32 { // 输入数据 - const a: i32 = 0; // 暂存数据(常量) - let mut b = 0; // 暂存数据(变量) - let node = Node::new(0); // 暂存数据(对象) - let c = function(); // 栈帧空间(调用函数) - return a + b + c; // 输出数据 - } - ``` - -=== "C" - - ```c title="" - /* 函数 */ - int func() { - // 执行某些操作... - return 0; - } - - int algorithm(int n) { // 输入数据 - const int a = 0; // 暂存数据(常量) - int b = 0; // 暂存数据(变量) - int c = func(); // 栈帧空间(调用函数) - return a + b + c; // 输出数据 - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 类 */ - class Node(var _val: Int) { - var next: Node? = null - } - - /* 函数 */ - fun function(): Int { - // 执行某些操作... - return 0 - } - - fun algorithm(n: Int): Int { // 输入数据 - val a = 0 // 暂存数据(常量) - var b = 0 // 暂存数据(变量) - val node = Node(0) // 暂存数据(对象) - val c = function() // 栈帧空间(调用函数) - return a + b + c // 输出数据 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 类 ### - class Node - attr_accessor :val # 节点值 - attr_accessor :next # 指向下一节点的引用 - - def initialize(x) - @val = x - end - end - - ### 函数 ### - def function - # 执行某些操作... - 0 - end - - ### 算法 ### - def algorithm(n) # 输入数据 - a = 0 # 暂存数据(常量) - b = 0 # 暂存数据(变量) - node = Node.new(0) # 暂存数据(对象) - c = function # 栈帧空间(调用函数) - a + b + c # 输出数据 - end - ``` +```snippet +space_categories +``` ## 推算方法 @@ -372,428 +39,15 @@ 1. **以最差输入数据为准**:当 $n < 10$ 时,空间复杂度为 $O(1)$ ;但当 $n > 10$ 时,初始化的数组 `nums` 占用 $O(n)$ 空间,因此最差空间复杂度为 $O(n)$ 。 2. **以算法运行中的峰值内存为准**:例如,程序在执行最后一行之前,占用 $O(1)$ 空间;当初始化数组 `nums` 时,程序占用 $O(n)$ 空间,因此最差空间复杂度为 $O(n)$ 。 -=== "Python" - - ```python title="" - def algorithm(n: int): - a = 0 # O(1) - b = [0] * 10000 # O(1) - if n > 10: - nums = [0] * n # O(n) - ``` - -=== "C++" - - ```cpp title="" - void algorithm(int n) { - int a = 0; // O(1) - vector b(10000); // O(1) - if (n > 10) - vector nums(n); // O(n) - } - ``` - -=== "Java" - - ```java title="" - void algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) - int[] nums = new int[n]; // O(n) - } - ``` - -=== "C#" - - ```csharp title="" - void Algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) { - int[] nums = new int[n]; // O(n) - } - } - ``` - -=== "Go" - - ```go title="" - func algorithm(n int) { - a := 0 // O(1) - b := make([]int, 10000) // O(1) - var nums []int - if n > 10 { - nums := make([]int, n) // O(n) - } - fmt.Println(a, b, nums) - } - ``` - -=== "Swift" - - ```swift title="" - func algorithm(n: Int) { - let a = 0 // O(1) - let b = Array(repeating: 0, count: 10000) // O(1) - if n > 10 { - let nums = Array(repeating: 0, count: n) // O(n) - } - } - ``` - -=== "JS" - - ```javascript title="" - function algorithm(n) { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "TS" - - ```typescript title="" - function algorithm(n: number): void { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "Dart" - - ```dart title="" - void algorithm(int n) { - int a = 0; // O(1) - List b = List.filled(10000, 0); // O(1) - if (n > 10) { - List nums = List.filled(n, 0); // O(n) - } - } - ``` - -=== "Rust" - - ```rust title="" - fn algorithm(n: i32) { - let a = 0; // O(1) - let b = [0; 10000]; // O(1) - if n > 10 { - let nums = vec![0; n as usize]; // O(n) - } - } - ``` - -=== "C" - - ```c title="" - void algorithm(int n) { - int a = 0; // O(1) - int b[10000]; // O(1) - if (n > 10) - int nums[n] = {0}; // O(n) - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun algorithm(n: Int) { - val a = 0 // O(1) - val b = IntArray(10000) // O(1) - if (n > 10) { - val nums = IntArray(n) // O(n) - } - } - ``` - -=== "Ruby" - - ```ruby title="" - def algorithm(n) - a = 0 # O(1) - b = Array.new(10000) # O(1) - nums = Array.new(n) if n > 10 # O(n) - end - ``` +```snippet +worst_case_space +``` **在递归函数中,需要注意统计栈帧空间**。观察以下代码: -=== "Python" - - ```python title="" - def function() -> int: - # 执行某些操作 - return 0 - - def loop(n: int): - """循环的空间复杂度为 O(1)""" - for _ in range(n): - function() - - def recur(n: int): - """递归的空间复杂度为 O(n)""" - if n == 1: - return - return recur(n - 1) - ``` - -=== "C++" - - ```cpp title="" - int func() { - // 执行某些操作 - return 0; - } - /* 循环的空间复杂度为 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* 递归的空间复杂度为 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Java" - - ```java title="" - int function() { - // 执行某些操作 - return 0; - } - /* 循环的空间复杂度为 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* 递归的空间复杂度为 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "C#" - - ```csharp title="" - int Function() { - // 执行某些操作 - return 0; - } - /* 循环的空间复杂度为 O(1) */ - void Loop(int n) { - for (int i = 0; i < n; i++) { - Function(); - } - } - /* 递归的空间复杂度为 O(n) */ - int Recur(int n) { - if (n == 1) return 1; - return Recur(n - 1); - } - ``` - -=== "Go" - - ```go title="" - func function() int { - // 执行某些操作 - return 0 - } - - /* 循环的空间复杂度为 O(1) */ - func loop(n int) { - for i := 0; i < n; i++ { - function() - } - } - - /* 递归的空间复杂度为 O(n) */ - func recur(n int) { - if n == 1 { - return - } - recur(n - 1) - } - ``` - -=== "Swift" - - ```swift title="" - @discardableResult - func function() -> Int { - // 执行某些操作 - return 0 - } - - /* 循环的空间复杂度为 O(1) */ - func loop(n: Int) { - for _ in 0 ..< n { - function() - } - } - - /* 递归的空间复杂度为 O(n) */ - func recur(n: Int) { - if n == 1 { - return - } - recur(n: n - 1) - } - ``` - -=== "JS" - - ```javascript title="" - function constFunc() { - // 执行某些操作 - return 0; - } - /* 循环的空间复杂度为 O(1) */ - function loop(n) { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* 递归的空间复杂度为 O(n) */ - function recur(n) { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "TS" - - ```typescript title="" - function constFunc(): number { - // 执行某些操作 - return 0; - } - /* 循环的空间复杂度为 O(1) */ - function loop(n: number): void { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* 递归的空间复杂度为 O(n) */ - function recur(n: number): void { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "Dart" - - ```dart title="" - int function() { - // 执行某些操作 - return 0; - } - /* 循环的空间复杂度为 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* 递归的空间复杂度为 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Rust" - - ```rust title="" - fn function() -> i32 { - // 执行某些操作 - return 0; - } - /* 循环的空间复杂度为 O(1) */ - fn loop(n: i32) { - for i in 0..n { - function(); - } - } - /* 递归的空间复杂度为 O(n) */ - fn recur(n: i32) { - if n == 1 { - return; - } - recur(n - 1); - } - ``` - -=== "C" - - ```c title="" - int func() { - // 执行某些操作 - return 0; - } - /* 循环的空间复杂度为 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* 递归的空间复杂度为 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun function(): Int { - // 执行某些操作 - return 0 - } - /* 循环的空间复杂度为 O(1) */ - fun loop(n: Int) { - for (i in 0.. numbers = List.filled(5, 0); - List decimals = List.filled(5, 0.0); - List characters = List.filled(5, 'a'); - List bools = List.filled(5, false); - ``` - -=== "Rust" - - ```rust title="" - // 使用多种基本数据类型来初始化数组 - let numbers: Vec = vec![0; 5]; - let decimals: Vec = vec![0.0; 5]; - let characters: Vec = vec!['0'; 5]; - let bools: Vec = vec![false; 5]; - ``` - -=== "C" - - ```c title="" - // 使用多种基本数据类型来初始化数组 - int numbers[10]; - float decimals[10]; - char characters[10]; - bool bools[10]; - ``` - -=== "Kotlin" - - ```kotlin title="" - // 使用多种基本数据类型来初始化数组 - val numbers = IntArray(5) - val decinals = FloatArray(5) - val characters = CharArray(5) - val bools = BooleanArray(5) - ``` - -=== "Ruby" - - ```ruby title="" - # Ruby 的列表可以自由存储各种基本数据类型和对象引用 - data = [0, 0.0, 'a', false, ListNode(0)] - ``` +```snippet +basic_type_arrays +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%A7%8D%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E6%9D%A5%E5%88%9D%E5%A7%8B%E5%8C%96%E6%95%B0%E7%BB%84%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20*%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20*%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E5%AD%97%E7%AC%A6%E5%AE%9E%E9%99%85%E4%B8%8A%E6%98%AF%E9%95%BF%E5%BA%A6%E4%B8%BA%201%20%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%0A%20%20%20%20characters%20%3D%20%5B'0'%5D%20*%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20*%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E5%88%97%E8%A1%A8%E5%8F%AF%E4%BB%A5%E8%87%AA%E7%94%B1%E5%AD%98%E5%82%A8%E5%90%84%E7%A7%8D%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%92%8C%E5%AF%B9%E8%B1%A1%E5%BC%95%E7%94%A8%0A%20%20%20%20data%20%3D%20%5B0,%200.0,%20'a',%20False,%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor basic_type_arrays_tutor diff --git a/docs/chapter_hashing/hash_algorithm.md b/docs/chapter_hashing/hash_algorithm.md index 686382273..6688c2960 100644 --- a/docs/chapter_hashing/hash_algorithm.md +++ b/docs/chapter_hashing/hash_algorithm.md @@ -113,295 +113,13 @@ $$ 请注意,不同编程语言的内置哈希值计算函数的定义和方法不同。 -=== "Python" - - ```python title="built_in_hash.py" - num = 3 - hash_num = hash(num) - # 整数 3 的哈希值为 3 - - bol = True - hash_bol = hash(bol) - # 布尔量 True 的哈希值为 1 - - dec = 3.14159 - hash_dec = hash(dec) - # 小数 3.14159 的哈希值为 326484311674566659 - - str = "Hello 算法" - hash_str = hash(str) - # 字符串“Hello 算法”的哈希值为 4617003410720528961 - - tup = (12836, "小哈") - hash_tup = hash(tup) - # 元组 (12836, '小哈') 的哈希值为 1029005403108185979 - - obj = ListNode(0) - hash_obj = hash(obj) - # 节点对象 的哈希值为 274267521 - ``` - -=== "C++" - - ```cpp title="built_in_hash.cpp" - int num = 3; - size_t hashNum = hash()(num); - // 整数 3 的哈希值为 3 - - bool bol = true; - size_t hashBol = hash()(bol); - // 布尔量 1 的哈希值为 1 - - double dec = 3.14159; - size_t hashDec = hash()(dec); - // 小数 3.14159 的哈希值为 4614256650576692846 - - string str = "Hello 算法"; - size_t hashStr = hash()(str); - // 字符串“Hello 算法”的哈希值为 15466937326284535026 - - // 在 C++ 中,内置 std::hash() 仅提供基本数据类型的哈希值计算 - // 数组、对象的哈希值计算需要自行实现 - ``` - -=== "Java" - - ```java title="built_in_hash.java" - int num = 3; - int hashNum = Integer.hashCode(num); - // 整数 3 的哈希值为 3 - - boolean bol = true; - int hashBol = Boolean.hashCode(bol); - // 布尔量 true 的哈希值为 1231 - - double dec = 3.14159; - int hashDec = Double.hashCode(dec); - // 小数 3.14159 的哈希值为 -1340954729 - - String str = "Hello 算法"; - int hashStr = str.hashCode(); - // 字符串“Hello 算法”的哈希值为 -727081396 - - Object[] arr = { 12836, "小哈" }; - int hashTup = Arrays.hashCode(arr); - // 数组 [12836, 小哈] 的哈希值为 1151158 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode(); - // 节点对象 utils.ListNode@7dc5e7b4 的哈希值为 2110121908 - ``` - -=== "C#" - - ```csharp title="built_in_hash.cs" - int num = 3; - int hashNum = num.GetHashCode(); - // 整数 3 的哈希值为 3; - - bool bol = true; - int hashBol = bol.GetHashCode(); - // 布尔量 true 的哈希值为 1; - - double dec = 3.14159; - int hashDec = dec.GetHashCode(); - // 小数 3.14159 的哈希值为 -1340954729; - - string str = "Hello 算法"; - int hashStr = str.GetHashCode(); - // 字符串“Hello 算法”的哈希值为 -586107568; - - object[] arr = [12836, "小哈"]; - int hashTup = arr.GetHashCode(); - // 数组 [12836, 小哈] 的哈希值为 42931033; - - ListNode obj = new(0); - int hashObj = obj.GetHashCode(); - // 节点对象 0 的哈希值为 39053774; - ``` - -=== "Go" - - ```go title="built_in_hash.go" - // Go 未提供内置 hash code 函数 - ``` - -=== "Swift" - - ```swift title="built_in_hash.swift" - let num = 3 - let hashNum = num.hashValue - // 整数 3 的哈希值为 9047044699613009734 - - let bol = true - let hashBol = bol.hashValue - // 布尔量 true 的哈希值为 -4431640247352757451 - - let dec = 3.14159 - let hashDec = dec.hashValue - // 小数 3.14159 的哈希值为 -2465384235396674631 - - let str = "Hello 算法" - let hashStr = str.hashValue - // 字符串“Hello 算法”的哈希值为 -7850626797806988787 - - let arr = [AnyHashable(12836), AnyHashable("小哈")] - let hashTup = arr.hashValue - // 数组 [AnyHashable(12836), AnyHashable("小哈")] 的哈希值为 -2308633508154532996 - - let obj = ListNode(x: 0) - let hashObj = obj.hashValue - // 节点对象 utils.ListNode 的哈希值为 -2434780518035996159 - ``` - -=== "JS" - - ```javascript title="built_in_hash.js" - // JavaScript 未提供内置 hash code 函数 - ``` - -=== "TS" - - ```typescript title="built_in_hash.ts" - // TypeScript 未提供内置 hash code 函数 - ``` - -=== "Dart" - - ```dart title="built_in_hash.dart" - int num = 3; - int hashNum = num.hashCode; - // 整数 3 的哈希值为 34803 - - bool bol = true; - int hashBol = bol.hashCode; - // 布尔值 true 的哈希值为 1231 - - double dec = 3.14159; - int hashDec = dec.hashCode; - // 小数 3.14159 的哈希值为 2570631074981783 - - String str = "Hello 算法"; - int hashStr = str.hashCode; - // 字符串“Hello 算法”的哈希值为 468167534 - - List arr = [12836, "小哈"]; - int hashArr = arr.hashCode; - // 数组 [12836, 小哈] 的哈希值为 976512528 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode; - // 节点对象 Instance of 'ListNode' 的哈希值为 1033450432 - ``` - -=== "Rust" - - ```rust title="built_in_hash.rs" - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - - let num = 3; - let mut num_hasher = DefaultHasher::new(); - num.hash(&mut num_hasher); - let hash_num = num_hasher.finish(); - // 整数 3 的哈希值为 568126464209439262 - - let bol = true; - let mut bol_hasher = DefaultHasher::new(); - bol.hash(&mut bol_hasher); - let hash_bol = bol_hasher.finish(); - // 布尔量 true 的哈希值为 4952851536318644461 - - let dec: f32 = 3.14159; - let mut dec_hasher = DefaultHasher::new(); - dec.to_bits().hash(&mut dec_hasher); - let hash_dec = dec_hasher.finish(); - // 小数 3.14159 的哈希值为 2566941990314602357 - - let str = "Hello 算法"; - let mut str_hasher = DefaultHasher::new(); - str.hash(&mut str_hasher); - let hash_str = str_hasher.finish(); - // 字符串“Hello 算法”的哈希值为 16092673739211250988 - - let arr = (&12836, &"小哈"); - let mut tup_hasher = DefaultHasher::new(); - arr.hash(&mut tup_hasher); - let hash_tup = tup_hasher.finish(); - // 元组 (12836, "小哈") 的哈希值为 1885128010422702749 - - let node = ListNode::new(42); - let mut hasher = DefaultHasher::new(); - node.borrow().val.hash(&mut hasher); - let hash = hasher.finish(); - // 节点对象 RefCell { value: ListNode { val: 42, next: None } } 的哈希值为15387811073369036852 - ``` - -=== "C" - - ```c title="built_in_hash.c" - // C 未提供内置 hash code 函数 - ``` - -=== "Kotlin" - - ```kotlin title="built_in_hash.kt" - val num = 3 - val hashNum = num.hashCode() - // 整数 3 的哈希值为 3 - - val bol = true - val hashBol = bol.hashCode() - // 布尔量 true 的哈希值为 1231 - - val dec = 3.14159 - val hashDec = dec.hashCode() - // 小数 3.14159 的哈希值为 -1340954729 - - val str = "Hello 算法" - val hashStr = str.hashCode() - // 字符串“Hello 算法”的哈希值为 -727081396 - - val arr = arrayOf(12836, "小哈") - val hashTup = arr.hashCode() - // 数组 [12836, 小哈] 的哈希值为 189568618 - - val obj = ListNode(0) - val hashObj = obj.hashCode() - // 节点对象 utils.ListNode@1d81eb93 的哈希值为 495053715 - ``` - -=== "Ruby" - - ```ruby title="built_in_hash.rb" - num = 3 - hash_num = num.hash - # 整数 3 的哈希值为 -4385856518450339636 - - bol = true - hash_bol = bol.hash - # 布尔量 true 的哈希值为 -1617938112149317027 - - dec = 3.14159 - hash_dec = dec.hash - # 小数 3.14159 的哈希值为 -1479186995943067893 - - str = "Hello 算法" - hash_str = str.hash - # 字符串“Hello 算法”的哈希值为 -4075943250025831763 - - tup = [12836, '小哈'] - hash_tup = tup.hash - # 元组 (12836, '小哈') 的哈希值为 1999544809202288822 - - obj = ListNode.new(0) - hash_obj = obj.hash - # 节点对象 # 的哈希值为 4302940560806366381 - ``` +```snippet +builtin_hash +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%E5%B8%83%E5%B0%94%E9%87%8F%20True%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%E5%AD%97%E7%AC%A6%E4%B8%B2%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836,%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%E5%85%83%E7%BB%84%20%2812836,%20'%E5%B0%8F%E5%93%88'%29%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%AF%B9%E8%B1%A1%20%3CListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor builtin_hash_tutor 在许多编程语言中,**只有不可变对象才可作为哈希表的 `key`** 。假如我们将列表(动态数组)作为 `key` ,当列表的内容发生变化时,它的哈希值也随之改变,我们就无法在哈希表中查询到原先的 `value` 了。 diff --git a/docs/chapter_hashing/hash_map.md b/docs/chapter_hashing/hash_map.md index 5c1abe9b1..ef9c1f1a7 100755 --- a/docs/chapter_hashing/hash_map.md +++ b/docs/chapter_hashing/hash_map.md @@ -26,517 +26,23 @@ 哈希表的常见操作包括:初始化、查询操作、添加键值对和删除键值对等,示例代码如下: -=== "Python" - - ```python title="hash_map.py" - # 初始化哈希表 - hmap: dict = {} - - # 添加操作 - # 在哈希表中添加键值对 (key, value) - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - # 查询操作 - # 向哈希表中输入键 key ,得到值 value - name: str = hmap[15937] - - # 删除操作 - # 在哈希表中删除键值对 (key, value) - hmap.pop(10583) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* 初始化哈希表 */ - unordered_map map; - - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - map[12836] = "小哈"; - map[15937] = "小啰"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鸭"; - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - string name = map[15937]; - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - map.erase(10583); - ``` - -=== "Java" - - ```java title="hash_map.java" - /* 初始化哈希表 */ - Map map = new HashMap<>(); - - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - map.put(12836, "小哈"); - map.put(15937, "小啰"); - map.put(16750, "小算"); - map.put(13276, "小法"); - map.put(10583, "小鸭"); - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - String name = map.get(15937); - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - map.remove(10583); - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* 初始化哈希表 */ - Dictionary map = new() { - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - { 12836, "小哈" }, - { 15937, "小啰" }, - { 16750, "小算" }, - { 13276, "小法" }, - { 10583, "小鸭" } - }; - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - string name = map[15937]; - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - map.Remove(10583); - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* 初始化哈希表 */ - hmap := make(map[int]string) - - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - name := hmap[15937] - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - delete(hmap, 10583) - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* 初始化哈希表 */ - var map: [Int: String] = [:] - - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - map[12836] = "小哈" - map[15937] = "小啰" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鸭" - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - let name = map[15937]! - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - map.removeValue(forKey: 10583) - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* 初始化哈希表 */ - const map = new Map(); - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - map.set(12836, '小哈'); - map.set(15937, '小啰'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鸭'); - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - let name = map.get(15937); - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - map.delete(10583); - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* 初始化哈希表 */ - const map = new Map(); - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - map.set(12836, '小哈'); - map.set(15937, '小啰'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鸭'); - console.info('\n添加完成后,哈希表为\nKey -> Value'); - console.info(map); - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - let name = map.get(15937); - console.info('\n输入学号 15937 ,查询到姓名 ' + name); - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - map.delete(10583); - console.info('\n删除 10583 后,哈希表为\nKey -> Value'); - console.info(map); - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* 初始化哈希表 */ - Map map = {}; - - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - map[12836] = "小哈"; - map[15937] = "小啰"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鸭"; - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - String name = map[15937]; - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - map.remove(10583); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - use std::collections::HashMap; - - /* 初始化哈希表 */ - let mut map: HashMap = HashMap::new(); - - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - map.insert(12836, "小哈".to_string()); - map.insert(15937, "小啰".to_string()); - map.insert(16750, "小算".to_string()); - map.insert(13279, "小法".to_string()); - map.insert(10583, "小鸭".to_string()); - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - let _name: Option<&String> = map.get(&15937); - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - let _removed_value: Option = map.remove(&10583); - ``` - -=== "C" - - ```c title="hash_map.c" - // C 未提供内置哈希表 - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* 初始化哈希表 */ - val map = HashMap() - - /* 添加操作 */ - // 在哈希表中添加键值对 (key, value) - map[12836] = "小哈" - map[15937] = "小啰" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鸭" - - /* 查询操作 */ - // 向哈希表中输入键 key ,得到值 value - val name = map[15937] - - /* 删除操作 */ - // 在哈希表中删除键值对 (key, value) - map.remove(10583) - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # 初始化哈希表 - hmap = {} - - # 添加操作 - # 在哈希表中添加键值对 (key, value) - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - # 查询操作 - # 向哈希表中输入键 key ,得到值 value - name = hmap[15937] - - # 删除操作 - # 在哈希表中删除键值对 (key, value) - hmap.delete(10583) - ``` +```snippet +hash_map_operations +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B7%BB%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%9F%A5%E8%AF%A2%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%90%91%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E8%BE%93%E5%85%A5%E9%94%AE%20key%20%EF%BC%8C%E5%BE%97%E5%88%B0%E5%80%BC%20value%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E5%88%A0%E9%99%A4%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_operations_tutor 哈希表有三种常用的遍历方式:遍历键值对、遍历键和遍历值。示例代码如下: -=== "Python" - - ```python title="hash_map.py" - # 遍历哈希表 - # 遍历键值对 key->value - for key, value in hmap.items(): - print(key, "->", value) - # 单独遍历键 key - for key in hmap.keys(): - print(key) - # 单独遍历值 value - for value in hmap.values(): - print(value) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* 遍历哈希表 */ - // 遍历键值对 key->value - for (auto kv: map) { - cout << kv.first << " -> " << kv.second << endl; - } - // 使用迭代器遍历 key->value - for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; - } - ``` - -=== "Java" - - ```java title="hash_map.java" - /* 遍历哈希表 */ - // 遍历键值对 key->value - for (Map.Entry kv: map.entrySet()) { - System.out.println(kv.getKey() + " -> " + kv.getValue()); - } - // 单独遍历键 key - for (int key: map.keySet()) { - System.out.println(key); - } - // 单独遍历值 value - for (String val: map.values()) { - System.out.println(val); - } - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* 遍历哈希表 */ - // 遍历键值对 Key->Value - foreach (var kv in map) { - Console.WriteLine(kv.Key + " -> " + kv.Value); - } - // 单独遍历键 key - foreach (int key in map.Keys) { - Console.WriteLine(key); - } - // 单独遍历值 value - foreach (string val in map.Values) { - Console.WriteLine(val); - } - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* 遍历哈希表 */ - // 遍历键值对 key->value - for key, value := range hmap { - fmt.Println(key, "->", value) - } - // 单独遍历键 key - for key := range hmap { - fmt.Println(key) - } - // 单独遍历值 value - for _, value := range hmap { - fmt.Println(value) - } - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* 遍历哈希表 */ - // 遍历键值对 Key->Value - for (key, value) in map { - print("\(key) -> \(value)") - } - // 单独遍历键 Key - for key in map.keys { - print(key) - } - // 单独遍历值 Value - for value in map.values { - print(value) - } - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* 遍历哈希表 */ - console.info('\n遍历键值对 Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\n单独遍历键 Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\n单独遍历值 Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* 遍历哈希表 */ - console.info('\n遍历键值对 Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\n单独遍历键 Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\n单独遍历值 Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* 遍历哈希表 */ - // 遍历键值对 Key->Value - map.forEach((key, value) { - print('$key -> $value'); - }); - - // 单独遍历键 Key - map.keys.forEach((key) { - print(key); - }); - - // 单独遍历值 Value - map.values.forEach((value) { - print(value); - }); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - /* 遍历哈希表 */ - // 遍历键值对 Key->Value - for (key, value) in &map { - println!("{key} -> {value}"); - } - - // 单独遍历键 Key - for key in map.keys() { - println!("{key}"); - } - - // 单独遍历值 Value - for value in map.values() { - println!("{value}"); - } - ``` - -=== "C" - - ```c title="hash_map.c" - // C 未提供内置哈希表 - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* 遍历哈希表 */ - // 遍历键值对 key->value - for ((key, value) in map) { - println("$key -> $value") - } - // 单独遍历键 key - for (key in map.keys) { - println(key) - } - // 单独遍历值 value - for (_val in map.values) { - println(_val) - } - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # 遍历哈希表 - # 遍历键值对 key->value - hmap.entries.each { |key, value| puts "#{key} -> #{value}" } - - # 单独遍历键 key - hmap.keys.each { |key| puts key } - - # 单独遍历值 value - hmap.values.each { |val| puts val } - ``` +```snippet +hash_map_traversal +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B7%BB%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E9%94%AE%E5%80%BC%E5%AF%B9%20key-%3Evalue%0A%20%20%20%20for%20key,%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key,%20%22-%3E%22,%20value%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E9%94%AE%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E5%80%BC%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_traversal_tutor ## 哈希表简单实现 diff --git a/docs/chapter_heap/heap.md b/docs/chapter_heap/heap.md index 25257fc63..73766b4ab 100644 --- a/docs/chapter_heap/heap.md +++ b/docs/chapter_heap/heap.md @@ -35,382 +35,13 @@ 类似于排序算法中的“从小到大排列”和“从大到小排列”,我们可以通过设置一个 `flag` 或修改 `Comparator` 实现“小顶堆”与“大顶堆”之间的转换。代码如下所示: -=== "Python" - - ```python title="heap.py" - # 初始化小顶堆 - min_heap, flag = [], 1 - # 初始化大顶堆 - max_heap, flag = [], -1 - - # Python 的 heapq 模块默认实现小顶堆 - # 考虑将“元素取负”后再入堆,这样就可以将大小关系颠倒,从而实现大顶堆 - # 在本示例中,flag = 1 时对应小顶堆,flag = -1 时对应大顶堆 - - # 元素入堆 - heapq.heappush(max_heap, flag * 1) - heapq.heappush(max_heap, flag * 3) - heapq.heappush(max_heap, flag * 2) - heapq.heappush(max_heap, flag * 5) - heapq.heappush(max_heap, flag * 4) - - # 获取堆顶元素 - peek: int = flag * max_heap[0] # 5 - - # 堆顶元素出堆 - # 出堆元素会形成一个从大到小的序列 - val = flag * heapq.heappop(max_heap) # 5 - val = flag * heapq.heappop(max_heap) # 4 - val = flag * heapq.heappop(max_heap) # 3 - val = flag * heapq.heappop(max_heap) # 2 - val = flag * heapq.heappop(max_heap) # 1 - - # 获取堆大小 - size: int = len(max_heap) - - # 判断堆是否为空 - is_empty: bool = not max_heap - - # 输入列表并建堆 - min_heap: list[int] = [1, 3, 2, 5, 4] - heapq.heapify(min_heap) - ``` - -=== "C++" - - ```cpp title="heap.cpp" - /* 初始化堆 */ - // 初始化小顶堆 - priority_queue, greater> minHeap; - // 初始化大顶堆 - priority_queue, less> maxHeap; - - /* 元素入堆 */ - maxHeap.push(1); - maxHeap.push(3); - maxHeap.push(2); - maxHeap.push(5); - maxHeap.push(4); - - /* 获取堆顶元素 */ - int peek = maxHeap.top(); // 5 - - /* 堆顶元素出堆 */ - // 出堆元素会形成一个从大到小的序列 - maxHeap.pop(); // 5 - maxHeap.pop(); // 4 - maxHeap.pop(); // 3 - maxHeap.pop(); // 2 - maxHeap.pop(); // 1 - - /* 获取堆大小 */ - int size = maxHeap.size(); - - /* 判断堆是否为空 */ - bool isEmpty = maxHeap.empty(); - - /* 输入列表并建堆 */ - vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); - ``` - -=== "Java" - - ```java title="heap.java" - /* 初始化堆 */ - // 初始化小顶堆 - Queue minHeap = new PriorityQueue<>(); - // 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可) - Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); - - /* 元素入堆 */ - maxHeap.offer(1); - maxHeap.offer(3); - maxHeap.offer(2); - maxHeap.offer(5); - maxHeap.offer(4); - - /* 获取堆顶元素 */ - int peek = maxHeap.peek(); // 5 - - /* 堆顶元素出堆 */ - // 出堆元素会形成一个从大到小的序列 - peek = maxHeap.poll(); // 5 - peek = maxHeap.poll(); // 4 - peek = maxHeap.poll(); // 3 - peek = maxHeap.poll(); // 2 - peek = maxHeap.poll(); // 1 - - /* 获取堆大小 */ - int size = maxHeap.size(); - - /* 判断堆是否为空 */ - boolean isEmpty = maxHeap.isEmpty(); - - /* 输入列表并建堆 */ - minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); - ``` - -=== "C#" - - ```csharp title="heap.cs" - /* 初始化堆 */ - // 初始化小顶堆 - PriorityQueue minHeap = new(); - // 初始化大顶堆(使用 lambda 表达式修改 Comparer 即可) - PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); - - /* 元素入堆 */ - maxHeap.Enqueue(1, 1); - maxHeap.Enqueue(3, 3); - maxHeap.Enqueue(2, 2); - maxHeap.Enqueue(5, 5); - maxHeap.Enqueue(4, 4); - - /* 获取堆顶元素 */ - int peek = maxHeap.Peek();//5 - - /* 堆顶元素出堆 */ - // 出堆元素会形成一个从大到小的序列 - peek = maxHeap.Dequeue(); // 5 - peek = maxHeap.Dequeue(); // 4 - peek = maxHeap.Dequeue(); // 3 - peek = maxHeap.Dequeue(); // 2 - peek = maxHeap.Dequeue(); // 1 - - /* 获取堆大小 */ - int size = maxHeap.Count; - - /* 判断堆是否为空 */ - bool isEmpty = maxHeap.Count == 0; - - /* 输入列表并建堆 */ - minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); - ``` - -=== "Go" - - ```go title="heap.go" - // Go 语言中可以通过实现 heap.Interface 来构建整数大顶堆 - // 实现 heap.Interface 需要同时实现 sort.Interface - type intHeap []any - - // Push heap.Interface 的方法,实现推入元素到堆 - func (h *intHeap) Push(x any) { - // Push 和 Pop 使用 pointer receiver 作为参数 - // 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。 - *h = append(*h, x.(int)) - } - - // Pop heap.Interface 的方法,实现弹出堆顶元素 - func (h *intHeap) Pop() any { - // 待出堆元素存放在最后 - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last - } - - // Len sort.Interface 的方法 - func (h *intHeap) Len() int { - return len(*h) - } - - // Less sort.Interface 的方法 - func (h *intHeap) Less(i, j int) bool { - // 如果实现小顶堆,则需要调整为小于号 - return (*h)[i].(int) > (*h)[j].(int) - } - - // Swap sort.Interface 的方法 - func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] - } - - // Top 获取堆顶元素 - func (h *intHeap) Top() any { - return (*h)[0] - } - - /* Driver Code */ - func TestHeap(t *testing.T) { - /* 初始化堆 */ - // 初始化大顶堆 - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* 元素入堆 */ - // 调用 heap.Interface 的方法,来添加元素 - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* 获取堆顶元素 */ - top := maxHeap.Top() - fmt.Printf("堆顶元素为 %d\n", top) - - /* 堆顶元素出堆 */ - // 调用 heap.Interface 的方法,来移除元素 - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 - - /* 获取堆大小 */ - size := len(*maxHeap) - fmt.Printf("堆元素数量为 %d\n", size) - - /* 判断堆是否为空 */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("堆是否为空 %t\n", isEmpty) - } - ``` - -=== "Swift" - - ```swift title="heap.swift" - /* 初始化堆 */ - // Swift 的 Heap 类型同时支持最大堆和最小堆,且需要引入 swift-collections - var heap = Heap() - - /* 元素入堆 */ - heap.insert(1) - heap.insert(3) - heap.insert(2) - heap.insert(5) - heap.insert(4) - - /* 获取堆顶元素 */ - var peek = heap.max()! - - /* 堆顶元素出堆 */ - peek = heap.removeMax() // 5 - peek = heap.removeMax() // 4 - peek = heap.removeMax() // 3 - peek = heap.removeMax() // 2 - peek = heap.removeMax() // 1 - - /* 获取堆大小 */ - let size = heap.count - - /* 判断堆是否为空 */ - let isEmpty = heap.isEmpty - - /* 输入列表并建堆 */ - let heap2 = Heap([1, 3, 2, 5, 4]) - ``` - -=== "JS" - - ```javascript title="heap.js" - // JavaScript 未提供内置 Heap 类 - ``` - -=== "TS" - - ```typescript title="heap.ts" - // TypeScript 未提供内置 Heap 类 - ``` - -=== "Dart" - - ```dart title="heap.dart" - // Dart 未提供内置 Heap 类 - ``` - -=== "Rust" - - ```rust title="heap.rs" - use std::collections::BinaryHeap; - use std::cmp::Reverse; - - /* 初始化堆 */ - // 初始化小顶堆 - let mut min_heap = BinaryHeap::>::new(); - // 初始化大顶堆 - let mut max_heap = BinaryHeap::new(); - - /* 元素入堆 */ - max_heap.push(1); - max_heap.push(3); - max_heap.push(2); - max_heap.push(5); - max_heap.push(4); - - /* 获取堆顶元素 */ - let peek = max_heap.peek().unwrap(); // 5 - - /* 堆顶元素出堆 */ - // 出堆元素会形成一个从大到小的序列 - let peek = max_heap.pop().unwrap(); // 5 - let peek = max_heap.pop().unwrap(); // 4 - let peek = max_heap.pop().unwrap(); // 3 - let peek = max_heap.pop().unwrap(); // 2 - let peek = max_heap.pop().unwrap(); // 1 - - /* 获取堆大小 */ - let size = max_heap.len(); - - /* 判断堆是否为空 */ - let is_empty = max_heap.is_empty(); - - /* 输入列表并建堆 */ - let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); - ``` - -=== "C" - - ```c title="heap.c" - // C 未提供内置 Heap 类 - ``` - -=== "Kotlin" - - ```kotlin title="heap.kt" - /* 初始化堆 */ - // 初始化小顶堆 - var minHeap = PriorityQueue() - // 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可) - val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } - - /* 元素入堆 */ - maxHeap.offer(1) - maxHeap.offer(3) - maxHeap.offer(2) - maxHeap.offer(5) - maxHeap.offer(4) - - /* 获取堆顶元素 */ - var peek = maxHeap.peek() // 5 - - /* 堆顶元素出堆 */ - // 出堆元素会形成一个从大到小的序列 - peek = maxHeap.poll() // 5 - peek = maxHeap.poll() // 4 - peek = maxHeap.poll() // 3 - peek = maxHeap.poll() // 2 - peek = maxHeap.poll() // 1 - - /* 获取堆大小 */ - val size = maxHeap.size - - /* 判断堆是否为空 */ - val isEmpty = maxHeap.isEmpty() - - /* 输入列表并建堆 */ - minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) - ``` - -=== "Ruby" - - ```ruby title="heap.rb" - # Ruby 未提供内置 Heap 类 - ``` +```snippet +heap_operations +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20min_heap,%20flag%20%3D%20%5B%5D,%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20max_heap,%20flag%20%3D%20%5B%5D,%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E5%9D%97%E9%BB%98%E8%AE%A4%E5%AE%9E%E7%8E%B0%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E8%80%83%E8%99%91%E5%B0%86%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B4%9F%E2%80%9D%E5%90%8E%E5%86%8D%E5%85%A5%E5%A0%86%EF%BC%8C%E8%BF%99%E6%A0%B7%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%86%E5%A4%A7%E5%B0%8F%E5%85%B3%E7%B3%BB%E9%A2%A0%E5%80%92%EF%BC%8C%E4%BB%8E%E8%80%8C%E5%AE%9E%E7%8E%B0%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%B0%8F%E9%A1%B6%E5%A0%86%EF%BC%8Cflag%20%3D%20-1%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%201%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%203%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%202%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%205%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20*%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E5%85%83%E7%B4%A0%E4%BC%9A%E5%BD%A2%E6%88%90%E4%B8%80%E4%B8%AA%E4%BB%8E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E5%A0%86%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BE%93%E5%85%A5%E5%88%97%E8%A1%A8%E5%B9%B6%E5%BB%BA%E5%A0%86%0A%20%20%20%20min_heap%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor heap_operations_tutor ## 堆的实现 diff --git a/docs/chapter_preface/suggestions.md b/docs/chapter_preface/suggestions.md index d62d7297a..bcfa825fc 100644 --- a/docs/chapter_preface/suggestions.md +++ b/docs/chapter_preface/suggestions.md @@ -13,170 +13,9 @@ - 当涉及编程语言之间不一致的名词时,本书均以 Python 为准,例如使用 `None` 来表示“空”。 - 本书部分放弃了编程语言的注释规范,以换取更加紧凑的内容排版。注释主要分为三种类型:标题注释、内容注释、多行注释。 -=== "Python" - - ```python title="" - """标题注释,用于标注函数、类、测试样例等""" - - # 内容注释,用于详解代码 - - """ - 多行 - 注释 - """ - ``` - -=== "C++" - - ```cpp title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "Java" - - ```java title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "C#" - - ```csharp title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "Go" - - ```go title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "Swift" - - ```swift title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "JS" - - ```javascript title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "TS" - - ```typescript title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "Dart" - - ```dart title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "Rust" - - ```rust title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - // 多行 - // 注释 - ``` - -=== "C" - - ```c title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 标题注释,用于标注函数、类、测试样例等 */ - - // 内容注释,用于详解代码 - - /** - * 多行 - * 注释 - */ - ``` - -=== "Ruby" - - ```ruby title="" - ### 标题注释,用于标注函数、类、测试样例等 ### - - # 内容注释,用于详解代码 - - # 多行 - # 注释 - ``` +```snippet +comment_style +``` ## 在动画图解中高效学习 diff --git a/docs/chapter_stack_and_queue/deque.md b/docs/chapter_stack_and_queue/deque.md index 01ef5c98c..a2a25a2e5 100644 --- a/docs/chapter_stack_and_queue/deque.md +++ b/docs/chapter_stack_and_queue/deque.md @@ -21,371 +21,13 @@ 同样地,我们可以直接使用编程语言中已实现的双向队列类: -=== "Python" - - ```python title="deque.py" - from collections import deque - - # 初始化双向队列 - deq: deque[int] = deque() - - # 元素入队 - deq.append(2) # 添加至队尾 - deq.append(5) - deq.append(4) - deq.appendleft(3) # 添加至队首 - deq.appendleft(1) - - # 访问元素 - front: int = deq[0] # 队首元素 - rear: int = deq[-1] # 队尾元素 - - # 元素出队 - pop_front: int = deq.popleft() # 队首元素出队 - pop_rear: int = deq.pop() # 队尾元素出队 - - # 获取双向队列的长度 - size: int = len(deq) - - # 判断双向队列是否为空 - is_empty: bool = len(deq) == 0 - ``` - -=== "C++" - - ```cpp title="deque.cpp" - /* 初始化双向队列 */ - deque deque; - - /* 元素入队 */ - deque.push_back(2); // 添加至队尾 - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // 添加至队首 - deque.push_front(1); - - /* 访问元素 */ - int front = deque.front(); // 队首元素 - int back = deque.back(); // 队尾元素 - - /* 元素出队 */ - deque.pop_front(); // 队首元素出队 - deque.pop_back(); // 队尾元素出队 - - /* 获取双向队列的长度 */ - int size = deque.size(); - - /* 判断双向队列是否为空 */ - bool empty = deque.empty(); - ``` - -=== "Java" - - ```java title="deque.java" - /* 初始化双向队列 */ - Deque deque = new LinkedList<>(); - - /* 元素入队 */ - deque.offerLast(2); // 添加至队尾 - deque.offerLast(5); - deque.offerLast(4); - deque.offerFirst(3); // 添加至队首 - deque.offerFirst(1); - - /* 访问元素 */ - int peekFirst = deque.peekFirst(); // 队首元素 - int peekLast = deque.peekLast(); // 队尾元素 - - /* 元素出队 */ - int popFirst = deque.pollFirst(); // 队首元素出队 - int popLast = deque.pollLast(); // 队尾元素出队 - - /* 获取双向队列的长度 */ - int size = deque.size(); - - /* 判断双向队列是否为空 */ - boolean isEmpty = deque.isEmpty(); - ``` - -=== "C#" - - ```csharp title="deque.cs" - /* 初始化双向队列 */ - // 在 C# 中,将链表 LinkedList 看作双向队列来使用 - LinkedList deque = new(); - - /* 元素入队 */ - deque.AddLast(2); // 添加至队尾 - deque.AddLast(5); - deque.AddLast(4); - deque.AddFirst(3); // 添加至队首 - deque.AddFirst(1); - - /* 访问元素 */ - int peekFirst = deque.First.Value; // 队首元素 - int peekLast = deque.Last.Value; // 队尾元素 - - /* 元素出队 */ - deque.RemoveFirst(); // 队首元素出队 - deque.RemoveLast(); // 队尾元素出队 - - /* 获取双向队列的长度 */ - int size = deque.Count; - - /* 判断双向队列是否为空 */ - bool isEmpty = deque.Count == 0; - ``` - -=== "Go" - - ```go title="deque_test.go" - /* 初始化双向队列 */ - // 在 Go 中,将 list 作为双向队列使用 - deque := list.New() - - /* 元素入队 */ - deque.PushBack(2) // 添加至队尾 - deque.PushBack(5) - deque.PushBack(4) - deque.PushFront(3) // 添加至队首 - deque.PushFront(1) - - /* 访问元素 */ - front := deque.Front() // 队首元素 - rear := deque.Back() // 队尾元素 - - /* 元素出队 */ - deque.Remove(front) // 队首元素出队 - deque.Remove(rear) // 队尾元素出队 - - /* 获取双向队列的长度 */ - size := deque.Len() - - /* 判断双向队列是否为空 */ - isEmpty := deque.Len() == 0 - ``` - -=== "Swift" - - ```swift title="deque.swift" - /* 初始化双向队列 */ - // Swift 没有内置的双向队列类,可以把 Array 当作双向队列来使用 - var deque: [Int] = [] - - /* 元素入队 */ - deque.append(2) // 添加至队尾 - deque.append(5) - deque.append(4) - deque.insert(3, at: 0) // 添加至队首 - deque.insert(1, at: 0) - - /* 访问元素 */ - let peekFirst = deque.first! // 队首元素 - let peekLast = deque.last! // 队尾元素 - - /* 元素出队 */ - // 使用 Array 模拟时 popFirst 的复杂度为 O(n) - let popFirst = deque.removeFirst() // 队首元素出队 - let popLast = deque.removeLast() // 队尾元素出队 - - /* 获取双向队列的长度 */ - let size = deque.count - - /* 判断双向队列是否为空 */ - let isEmpty = deque.isEmpty - ``` - -=== "JS" - - ```javascript title="deque.js" - /* 初始化双向队列 */ - // JavaScript 没有内置的双端队列,只能把 Array 当作双端队列来使用 - const deque = []; - - /* 元素入队 */ - deque.push(2); - deque.push(5); - deque.push(4); - // 请注意,由于是数组,unshift() 方法的时间复杂度为 O(n) - deque.unshift(3); - deque.unshift(1); - - /* 访问元素 */ - const peekFirst = deque[0]; - const peekLast = deque[deque.length - 1]; - - /* 元素出队 */ - // 请注意,由于是数组,shift() 方法的时间复杂度为 O(n) - const popFront = deque.shift(); - const popBack = deque.pop(); - - /* 获取双向队列的长度 */ - const size = deque.length; - - /* 判断双向队列是否为空 */ - const isEmpty = size === 0; - ``` - -=== "TS" - - ```typescript title="deque.ts" - /* 初始化双向队列 */ - // TypeScript 没有内置的双端队列,只能把 Array 当作双端队列来使用 - const deque: number[] = []; - - /* 元素入队 */ - deque.push(2); - deque.push(5); - deque.push(4); - // 请注意,由于是数组,unshift() 方法的时间复杂度为 O(n) - deque.unshift(3); - deque.unshift(1); - - /* 访问元素 */ - const peekFirst: number = deque[0]; - const peekLast: number = deque[deque.length - 1]; - - /* 元素出队 */ - // 请注意,由于是数组,shift() 方法的时间复杂度为 O(n) - const popFront: number = deque.shift() as number; - const popBack: number = deque.pop() as number; - - /* 获取双向队列的长度 */ - const size: number = deque.length; - - /* 判断双向队列是否为空 */ - const isEmpty: boolean = size === 0; - ``` - -=== "Dart" - - ```dart title="deque.dart" - /* 初始化双向队列 */ - // 在 Dart 中,Queue 被定义为双向队列 - Queue deque = Queue(); - - /* 元素入队 */ - deque.addLast(2); // 添加至队尾 - deque.addLast(5); - deque.addLast(4); - deque.addFirst(3); // 添加至队首 - deque.addFirst(1); - - /* 访问元素 */ - int peekFirst = deque.first; // 队首元素 - int peekLast = deque.last; // 队尾元素 - - /* 元素出队 */ - int popFirst = deque.removeFirst(); // 队首元素出队 - int popLast = deque.removeLast(); // 队尾元素出队 - - /* 获取双向队列的长度 */ - int size = deque.length; - - /* 判断双向队列是否为空 */ - bool isEmpty = deque.isEmpty; - ``` - -=== "Rust" - - ```rust title="deque.rs" - /* 初始化双向队列 */ - let mut deque: VecDeque = VecDeque::new(); - - /* 元素入队 */ - deque.push_back(2); // 添加至队尾 - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // 添加至队首 - deque.push_front(1); - - /* 访问元素 */ - if let Some(front) = deque.front() { // 队首元素 - } - if let Some(rear) = deque.back() { // 队尾元素 - } - - /* 元素出队 */ - if let Some(pop_front) = deque.pop_front() { // 队首元素出队 - } - if let Some(pop_rear) = deque.pop_back() { // 队尾元素出队 - } - - /* 获取双向队列的长度 */ - let size = deque.len(); - - /* 判断双向队列是否为空 */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="deque.c" - // C 未提供内置双向队列 - ``` - -=== "Kotlin" - - ```kotlin title="deque.kt" - /* 初始化双向队列 */ - val deque = LinkedList() - - /* 元素入队 */ - deque.offerLast(2) // 添加至队尾 - deque.offerLast(5) - deque.offerLast(4) - deque.offerFirst(3) // 添加至队首 - deque.offerFirst(1) - - /* 访问元素 */ - val peekFirst = deque.peekFirst() // 队首元素 - val peekLast = deque.peekLast() // 队尾元素 - - /* 元素出队 */ - val popFirst = deque.pollFirst() // 队首元素出队 - val popLast = deque.pollLast() // 队尾元素出队 - - /* 获取双向队列的长度 */ - val size = deque.size - - /* 判断双向队列是否为空 */ - val isEmpty = deque.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="deque.rb" - # 初始化双向队列 - # Ruby 没有内直的双端队列,只能把 Array 当作双端队列来使用 - deque = [] - - # 元素如队 - deque << 2 - deque << 5 - deque << 4 - # 请注意,由于是数组,Array#unshift 方法的时间复杂度为 O(n) - deque.unshift(3) - deque.unshift(1) - - # 访问元素 - peek_first = deque.first - peek_last = deque.last - - # 元素出队 - # 请注意,由于是数组, Array#shift 方法的时间复杂度为 O(n) - pop_front = deque.shift - pop_back = deque.pop - - # 获取双向队列的长度 - size = deque.length - - # 判断双向队列是否为空 - is_empty = size.zero? - ``` +```snippet +deque_operations +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E9%98%9F%0A%20%20%20%20deq.append%282%29%20%20%23%20%E6%B7%BB%E5%8A%A0%E8%87%B3%E9%98%9F%E5%B0%BE%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20%E6%B7%BB%E5%8A%A0%E8%87%B3%E9%98%9F%E9%A6%96%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%20deque%20%3D%22,%20deq%29%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22,%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%E9%98%9F%E5%B0%BE%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E9%98%9F%E5%B0%BE%E5%85%83%E7%B4%A0%20rear%20%3D%22,%20rear%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%87%BA%E9%98%9F%E5%85%83%E7%B4%A0%20%20pop_front%20%3D%22,%20pop_front%29%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%87%BA%E9%98%9F%E5%90%8E%20deque%20%3D%22,%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20%E9%98%9F%E5%B0%BE%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20print%28%22%E9%98%9F%E5%B0%BE%E5%87%BA%E9%98%9F%E5%85%83%E7%B4%A0%20%20pop_rear%20%3D%22,%20pop_rear%29%0A%20%20%20%20print%28%22%E9%98%9F%E5%B0%BE%E5%87%BA%E9%98%9F%E5%90%8E%20deque%20%3D%22,%20deq%29%0A%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E7%9A%84%E9%95%BF%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E9%95%BF%E5%BA%A6%20size%20%3D%22,%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%20%3D%22,%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor deque_operations_tutor ## 双向队列实现 * diff --git a/docs/chapter_stack_and_queue/queue.md b/docs/chapter_stack_and_queue/queue.md index 32f8933bd..255c372b3 100755 --- a/docs/chapter_stack_and_queue/queue.md +++ b/docs/chapter_stack_and_queue/queue.md @@ -20,345 +20,13 @@ 我们可以直接使用编程语言中现成的队列类: -=== "Python" - - ```python title="queue.py" - from collections import deque - - # 初始化队列 - # 在 Python 中,我们一般将双向队列类 deque 当作队列使用 - # 虽然 queue.Queue() 是纯正的队列类,但不太好用,因此不推荐 - que: deque[int] = deque() - - # 元素入队 - que.append(1) - que.append(3) - que.append(2) - que.append(5) - que.append(4) - - # 访问队首元素 - front: int = que[0] - - # 元素出队 - pop: int = que.popleft() - - # 获取队列的长度 - size: int = len(que) - - # 判断队列是否为空 - is_empty: bool = len(que) == 0 - ``` - -=== "C++" - - ```cpp title="queue.cpp" - /* 初始化队列 */ - queue queue; - - /* 元素入队 */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 访问队首元素 */ - int front = queue.front(); - - /* 元素出队 */ - queue.pop(); - - /* 获取队列的长度 */ - int size = queue.size(); - - /* 判断队列是否为空 */ - bool empty = queue.empty(); - ``` - -=== "Java" - - ```java title="queue.java" - /* 初始化队列 */ - Queue queue = new LinkedList<>(); - - /* 元素入队 */ - queue.offer(1); - queue.offer(3); - queue.offer(2); - queue.offer(5); - queue.offer(4); - - /* 访问队首元素 */ - int peek = queue.peek(); - - /* 元素出队 */ - int pop = queue.poll(); - - /* 获取队列的长度 */ - int size = queue.size(); - - /* 判断队列是否为空 */ - boolean isEmpty = queue.isEmpty(); - ``` - -=== "C#" - - ```csharp title="queue.cs" - /* 初始化队列 */ - Queue queue = new(); - - /* 元素入队 */ - queue.Enqueue(1); - queue.Enqueue(3); - queue.Enqueue(2); - queue.Enqueue(5); - queue.Enqueue(4); - - /* 访问队首元素 */ - int peek = queue.Peek(); - - /* 元素出队 */ - int pop = queue.Dequeue(); - - /* 获取队列的长度 */ - int size = queue.Count; - - /* 判断队列是否为空 */ - bool isEmpty = queue.Count == 0; - ``` - -=== "Go" - - ```go title="queue_test.go" - /* 初始化队列 */ - // 在 Go 中,将 list 作为队列来使用 - queue := list.New() - - /* 元素入队 */ - queue.PushBack(1) - queue.PushBack(3) - queue.PushBack(2) - queue.PushBack(5) - queue.PushBack(4) - - /* 访问队首元素 */ - peek := queue.Front() - - /* 元素出队 */ - pop := queue.Front() - queue.Remove(pop) - - /* 获取队列的长度 */ - size := queue.Len() - - /* 判断队列是否为空 */ - isEmpty := queue.Len() == 0 - ``` - -=== "Swift" - - ```swift title="queue.swift" - /* 初始化队列 */ - // Swift 没有内置的队列类,可以把 Array 当作队列来使用 - var queue: [Int] = [] - - /* 元素入队 */ - queue.append(1) - queue.append(3) - queue.append(2) - queue.append(5) - queue.append(4) - - /* 访问队首元素 */ - let peek = queue.first! - - /* 元素出队 */ - // 由于是数组,因此 removeFirst 的复杂度为 O(n) - let pop = queue.removeFirst() - - /* 获取队列的长度 */ - let size = queue.count - - /* 判断队列是否为空 */ - let isEmpty = queue.isEmpty - ``` - -=== "JS" - - ```javascript title="queue.js" - /* 初始化队列 */ - // JavaScript 没有内置的队列,可以把 Array 当作队列来使用 - const queue = []; - - /* 元素入队 */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 访问队首元素 */ - const peek = queue[0]; - - /* 元素出队 */ - // 底层是数组,因此 shift() 方法的时间复杂度为 O(n) - const pop = queue.shift(); - - /* 获取队列的长度 */ - const size = queue.length; - - /* 判断队列是否为空 */ - const empty = queue.length === 0; - ``` - -=== "TS" - - ```typescript title="queue.ts" - /* 初始化队列 */ - // TypeScript 没有内置的队列,可以把 Array 当作队列来使用 - const queue: number[] = []; - - /* 元素入队 */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 访问队首元素 */ - const peek = queue[0]; - - /* 元素出队 */ - // 底层是数组,因此 shift() 方法的时间复杂度为 O(n) - const pop = queue.shift(); - - /* 获取队列的长度 */ - const size = queue.length; - - /* 判断队列是否为空 */ - const empty = queue.length === 0; - ``` - -=== "Dart" - - ```dart title="queue.dart" - /* 初始化队列 */ - // 在 Dart 中,队列类 Queue 是双向队列,也可作为队列使用 - Queue queue = Queue(); - - /* 元素入队 */ - queue.add(1); - queue.add(3); - queue.add(2); - queue.add(5); - queue.add(4); - - /* 访问队首元素 */ - int peek = queue.first; - - /* 元素出队 */ - int pop = queue.removeFirst(); - - /* 获取队列的长度 */ - int size = queue.length; - - /* 判断队列是否为空 */ - bool isEmpty = queue.isEmpty; - ``` - -=== "Rust" - - ```rust title="queue.rs" - /* 初始化双向队列 */ - // 在 Rust 中使用双向队列作为普通队列来使用 - let mut deque: VecDeque = VecDeque::new(); - - /* 元素入队 */ - deque.push_back(1); - deque.push_back(3); - deque.push_back(2); - deque.push_back(5); - deque.push_back(4); - - /* 访问队首元素 */ - if let Some(front) = deque.front() { - } - - /* 元素出队 */ - if let Some(pop) = deque.pop_front() { - } - - /* 获取队列的长度 */ - let size = deque.len(); - - /* 判断队列是否为空 */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="queue.c" - // C 未提供内置队列 - ``` - -=== "Kotlin" - - ```kotlin title="queue.kt" - /* 初始化队列 */ - val queue = LinkedList() - - /* 元素入队 */ - queue.offer(1) - queue.offer(3) - queue.offer(2) - queue.offer(5) - queue.offer(4) - - /* 访问队首元素 */ - val peek = queue.peek() - - /* 元素出队 */ - val pop = queue.poll() - - /* 获取队列的长度 */ - val size = queue.size - - /* 判断队列是否为空 */ - val isEmpty = queue.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="queue.rb" - # 初始化队列 - # Ruby 内置的队列(Thread::Queue) 没有 peek 和遍历方法,可以把 Array 当作队列来使用 - queue = [] - - # 元素入队 - queue.push(1) - queue.push(3) - queue.push(2) - queue.push(5) - queue.push(4) - - # 访问队列元素 - peek = queue.first - - # 元素出队 - # 清注意,由于是数组,Array#shift 方法时间复杂度为 O(n) - pop = queue.shift - - # 获取队列的长度 - size = queue.length - - # 判断队列是否为空 - is_empty = queue.empty? - ``` +```snippet +queue_operations +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%98%9F%E5%88%97%0A%20%20%20%20%23%20%E5%9C%A8%20Python%20%E4%B8%AD%EF%BC%8C%E6%88%91%E4%BB%AC%E4%B8%80%E8%88%AC%E5%B0%86%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E7%B1%BB%20deque%20%E7%9C%8B%E4%BD%9C%E9%98%9F%E5%88%97%E4%BD%BF%E7%94%A8%0A%20%20%20%20%23%20%E8%99%BD%E7%84%B6%20queue.Queue%28%29%20%E6%98%AF%E7%BA%AF%E6%AD%A3%E7%9A%84%E9%98%9F%E5%88%97%E7%B1%BB%EF%BC%8C%E4%BD%86%E4%B8%8D%E5%A4%AA%E5%A5%BD%E7%94%A8%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E9%98%9F%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22%E9%98%9F%E5%88%97%20que%20%3D%22,%20que%29%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22,%20front%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E9%98%9F%E5%85%83%E7%B4%A0%20pop%20%3D%22,%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E9%98%9F%E5%90%8E%20que%20%3D%22,%20que%29%0A%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E9%98%9F%E5%88%97%E7%9A%84%E9%95%BF%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22%E9%98%9F%E5%88%97%E9%95%BF%E5%BA%A6%20size%20%3D%22,%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%20%3D%22,%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor queue_operations_tutor ## 队列实现 diff --git a/docs/chapter_stack_and_queue/stack.md b/docs/chapter_stack_and_queue/stack.md index d06d6fb59..6ddf348cb 100755 --- a/docs/chapter_stack_and_queue/stack.md +++ b/docs/chapter_stack_and_queue/stack.md @@ -22,336 +22,13 @@ 通常情况下,我们可以直接使用编程语言内置的栈类。然而,某些语言可能没有专门提供栈类,这时我们可以将该语言的“数组”或“链表”当作栈来使用,并在程序逻辑上忽略与栈无关的操作。 -=== "Python" - - ```python title="stack.py" - # 初始化栈 - # Python 没有内置的栈类,可以把 list 当作栈来使用 - stack: list[int] = [] - - # 元素入栈 - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - # 访问栈顶元素 - peek: int = stack[-1] - - # 元素出栈 - pop: int = stack.pop() - - # 获取栈的长度 - size: int = len(stack) - - # 判断是否为空 - is_empty: bool = len(stack) == 0 - ``` - -=== "C++" - - ```cpp title="stack.cpp" - /* 初始化栈 */ - stack stack; - - /* 元素入栈 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 访问栈顶元素 */ - int top = stack.top(); - - /* 元素出栈 */ - stack.pop(); // 无返回值 - - /* 获取栈的长度 */ - int size = stack.size(); - - /* 判断是否为空 */ - bool empty = stack.empty(); - ``` - -=== "Java" - - ```java title="stack.java" - /* 初始化栈 */ - Stack stack = new Stack<>(); - - /* 元素入栈 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 访问栈顶元素 */ - int peek = stack.peek(); - - /* 元素出栈 */ - int pop = stack.pop(); - - /* 获取栈的长度 */ - int size = stack.size(); - - /* 判断是否为空 */ - boolean isEmpty = stack.isEmpty(); - ``` - -=== "C#" - - ```csharp title="stack.cs" - /* 初始化栈 */ - Stack stack = new(); - - /* 元素入栈 */ - stack.Push(1); - stack.Push(3); - stack.Push(2); - stack.Push(5); - stack.Push(4); - - /* 访问栈顶元素 */ - int peek = stack.Peek(); - - /* 元素出栈 */ - int pop = stack.Pop(); - - /* 获取栈的长度 */ - int size = stack.Count; - - /* 判断是否为空 */ - bool isEmpty = stack.Count == 0; - ``` - -=== "Go" - - ```go title="stack_test.go" - /* 初始化栈 */ - // 在 Go 中,推荐将 Slice 当作栈来使用 - var stack []int - - /* 元素入栈 */ - stack = append(stack, 1) - stack = append(stack, 3) - stack = append(stack, 2) - stack = append(stack, 5) - stack = append(stack, 4) - - /* 访问栈顶元素 */ - peek := stack[len(stack)-1] - - /* 元素出栈 */ - pop := stack[len(stack)-1] - stack = stack[:len(stack)-1] - - /* 获取栈的长度 */ - size := len(stack) - - /* 判断是否为空 */ - isEmpty := len(stack) == 0 - ``` - -=== "Swift" - - ```swift title="stack.swift" - /* 初始化栈 */ - // Swift 没有内置的栈类,可以把 Array 当作栈来使用 - var stack: [Int] = [] - - /* 元素入栈 */ - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - /* 访问栈顶元素 */ - let peek = stack.last! - - /* 元素出栈 */ - let pop = stack.removeLast() - - /* 获取栈的长度 */ - let size = stack.count - - /* 判断是否为空 */ - let isEmpty = stack.isEmpty - ``` - -=== "JS" - - ```javascript title="stack.js" - /* 初始化栈 */ - // JavaScript 没有内置的栈类,可以把 Array 当作栈来使用 - const stack = []; - - /* 元素入栈 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 访问栈顶元素 */ - const peek = stack[stack.length-1]; - - /* 元素出栈 */ - const pop = stack.pop(); - - /* 获取栈的长度 */ - const size = stack.length; - - /* 判断是否为空 */ - const is_empty = stack.length === 0; - ``` - -=== "TS" - - ```typescript title="stack.ts" - /* 初始化栈 */ - // TypeScript 没有内置的栈类,可以把 Array 当作栈来使用 - const stack: number[] = []; - - /* 元素入栈 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 访问栈顶元素 */ - const peek = stack[stack.length - 1]; - - /* 元素出栈 */ - const pop = stack.pop(); - - /* 获取栈的长度 */ - const size = stack.length; - - /* 判断是否为空 */ - const is_empty = stack.length === 0; - ``` - -=== "Dart" - - ```dart title="stack.dart" - /* 初始化栈 */ - // Dart 没有内置的栈类,可以把 List 当作栈来使用 - List stack = []; - - /* 元素入栈 */ - stack.add(1); - stack.add(3); - stack.add(2); - stack.add(5); - stack.add(4); - - /* 访问栈顶元素 */ - int peek = stack.last; - - /* 元素出栈 */ - int pop = stack.removeLast(); - - /* 获取栈的长度 */ - int size = stack.length; - - /* 判断是否为空 */ - bool isEmpty = stack.isEmpty; - ``` - -=== "Rust" - - ```rust title="stack.rs" - /* 初始化栈 */ - // 把 Vec 当作栈来使用 - let mut stack: Vec = Vec::new(); - - /* 元素入栈 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 访问栈顶元素 */ - let top = stack.last().unwrap(); - - /* 元素出栈 */ - let pop = stack.pop().unwrap(); - - /* 获取栈的长度 */ - let size = stack.len(); - - /* 判断是否为空 */ - let is_empty = stack.is_empty(); - ``` - -=== "C" - - ```c title="stack.c" - // C 未提供内置栈 - ``` - -=== "Kotlin" - - ```kotlin title="stack.kt" - /* 初始化栈 */ - val stack = Stack() - - /* 元素入栈 */ - stack.push(1) - stack.push(3) - stack.push(2) - stack.push(5) - stack.push(4) - - /* 访问栈顶元素 */ - val peek = stack.peek() - - /* 元素出栈 */ - val pop = stack.pop() - - /* 获取栈的长度 */ - val size = stack.size - - /* 判断是否为空 */ - val isEmpty = stack.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="stack.rb" - # 初始化栈 - # Ruby 没有内置的栈类,可以把 Array 当作栈来使用 - stack = [] - - # 元素入栈 - stack << 1 - stack << 3 - stack << 2 - stack << 5 - stack << 4 - - # 访问栈顶元素 - peek = stack.last - - # 元素出栈 - pop = stack.pop - - # 获取栈的长度 - size = stack.length - - # 判断是否为空 - is_empty = stack.empty? - ``` +```snippet +stack_operations +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E6%A0%88%0A%20%20%20%20%23%20Python%20%E6%B2%A1%E6%9C%89%E5%86%85%E7%BD%AE%E7%9A%84%E6%A0%88%E7%B1%BB%EF%BC%8C%E5%8F%AF%E4%BB%A5%E6%8A%8A%20list%20%E5%BD%93%E4%BD%9C%E6%A0%88%E6%9D%A5%E4%BD%BF%E7%94%A8%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E6%A0%88%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22%E6%A0%88%20stack%20%3D%22,%20stack%29%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E6%A0%88%E9%A1%B6%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22%E6%A0%88%E9%A1%B6%E5%85%83%E7%B4%A0%20peek%20%3D%22,%20peek%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E6%A0%88%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E6%A0%88%E5%85%83%E7%B4%A0%20pop%20%3D%22,%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E6%A0%88%E5%90%8E%20stack%20%3D%22,%20stack%29%0A%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E6%A0%88%E7%9A%84%E9%95%BF%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22%E6%A0%88%E7%9A%84%E9%95%BF%E5%BA%A6%20size%20%3D%22,%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E6%A0%88%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%20%3D%22,%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor stack_operations_tutor ## 栈的实现 diff --git a/docs/chapter_tree/array_representation_of_tree.md b/docs/chapter_tree/array_representation_of_tree.md index 8c1f3f371..dd02a147c 100644 --- a/docs/chapter_tree/array_representation_of_tree.md +++ b/docs/chapter_tree/array_representation_of_tree.md @@ -24,109 +24,9 @@ 为了解决此问题,**我们可以考虑在层序遍历序列中显式地写出所有 `None`** 。如下图所示,这样处理后,层序遍历序列就可以唯一表示二叉树了。示例代码如下: -=== "Python" - - ```python title="" - # 二叉树的数组表示 - # 使用 None 来表示空位 - tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] - ``` - -=== "C++" - - ```cpp title="" - /* 二叉树的数组表示 */ - // 使用 int 最大值 INT_MAX 标记空位 - vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Java" - - ```java title="" - /* 二叉树的数组表示 */ - // 使用 int 的包装类 Integer ,就可以使用 null 来标记空位 - Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; - ``` - -=== "C#" - - ```csharp title="" - /* 二叉树的数组表示 */ - // 使用 int? 可空类型 ,就可以使用 null 来标记空位 - int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Go" - - ```go title="" - /* 二叉树的数组表示 */ - // 使用 any 类型的切片, 就可以使用 nil 来标记空位 - tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} - ``` - -=== "Swift" - - ```swift title="" - /* 二叉树的数组表示 */ - // 使用 Int? 可空类型 ,就可以使用 nil 来标记空位 - let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` - -=== "JS" - - ```javascript title="" - /* 二叉树的数组表示 */ - // 使用 null 来表示空位 - let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "TS" - - ```typescript title="" - /* 二叉树的数组表示 */ - // 使用 null 来表示空位 - let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Dart" - - ```dart title="" - /* 二叉树的数组表示 */ - // 使用 int? 可空类型 ,就可以使用 null 来标记空位 - List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Rust" - - ```rust title="" - /* 二叉树的数组表示 */ - // 使用 None 来标记空位 - let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; - ``` - -=== "C" - - ```c title="" - /* 二叉树的数组表示 */ - // 使用 int 最大值标记空位,因此要求节点值不能为 INT_MAX - int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 二叉树的数组表示 */ - // 使用 null 来表示空位 - val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) - ``` - -=== "Ruby" - - ```ruby title="" - ### 二叉树的数组表示 ### - # 使用 nil 来表示空位 - tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` +```snippet +tree_array_representation +``` ![任意类型二叉树的数组表示](array_representation_of_tree.assets/array_representation_with_empty.svg) diff --git a/docs/chapter_tree/avl_tree.md b/docs/chapter_tree/avl_tree.md index 74d3d8c5c..393a1651b 100644 --- a/docs/chapter_tree/avl_tree.md +++ b/docs/chapter_tree/avl_tree.md @@ -20,213 +20,9 @@ AVL 树既是二叉搜索树,也是平衡二叉树,同时满足这两类二 由于 AVL 树的相关操作需要获取节点高度,因此我们需要为节点类添加 `height` 变量: -=== "Python" - - ```python title="" - class TreeNode: - """AVL 树节点类""" - def __init__(self, val: int): - self.val: int = val # 节点值 - self.height: int = 0 # 节点高度 - self.left: TreeNode | None = None # 左子节点引用 - self.right: TreeNode | None = None # 右子节点引用 - ``` - -=== "C++" - - ```cpp title="" - /* AVL 树节点类 */ - struct TreeNode { - int val{}; // 节点值 - int height = 0; // 节点高度 - TreeNode *left{}; // 左子节点 - TreeNode *right{}; // 右子节点 - TreeNode() = default; - explicit TreeNode(int x) : val(x){} - }; - ``` - -=== "Java" - - ```java title="" - /* AVL 树节点类 */ - class TreeNode { - public int val; // 节点值 - public int height; // 节点高度 - public TreeNode left; // 左子节点 - public TreeNode right; // 右子节点 - public TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* AVL 树节点类 */ - class TreeNode(int? x) { - public int? val = x; // 节点值 - public int height; // 节点高度 - public TreeNode? left; // 左子节点引用 - public TreeNode? right; // 右子节点引用 - } - ``` - -=== "Go" - - ```go title="" - /* AVL 树节点结构体 */ - type TreeNode struct { - Val int // 节点值 - Height int // 节点高度 - Left *TreeNode // 左子节点引用 - Right *TreeNode // 右子节点引用 - } - ``` - -=== "Swift" - - ```swift title="" - /* AVL 树节点类 */ - class TreeNode { - var val: Int // 节点值 - var height: Int // 节点高度 - var left: TreeNode? // 左子节点 - var right: TreeNode? // 右子节点 - - init(x: Int) { - val = x - height = 0 - } - } - ``` - -=== "JS" - - ```javascript title="" - /* AVL 树节点类 */ - class TreeNode { - val; // 节点值 - height; //节点高度 - left; // 左子节点指针 - right; // 右子节点指针 - constructor(val, left, right, height) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* AVL 树节点类 */ - class TreeNode { - val: number; // 节点值 - height: number; // 节点高度 - left: TreeNode | null; // 左子节点指针 - right: TreeNode | null; // 右子节点指针 - constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "Dart" - - ```dart title="" - /* AVL 树节点类 */ - class TreeNode { - int val; // 节点值 - int height; // 节点高度 - TreeNode? left; // 左子节点 - TreeNode? right; // 右子节点 - TreeNode(this.val, [this.height = 0, this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* AVL 树节点结构体 */ - struct TreeNode { - val: i32, // 节点值 - height: i32, // 节点高度 - left: Option>>, // 左子节点 - right: Option>>, // 右子节点 - } - - impl TreeNode { - /* 构造方法 */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - height: 0, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* AVL 树节点结构体 */ - typedef struct TreeNode { - int val; - int height; - struct TreeNode *left; - struct TreeNode *right; - } TreeNode; - - /* 构造函数 */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* AVL 树节点类 */ - class TreeNode(val _val: Int) { // 节点值 - var height: Int = 0 // 节点高度 - var left: TreeNode? = null // 左子节点 - var right: TreeNode? = null // 右子节点 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### AVL 树节点类 ### - class TreeNode - attr_accessor :val # 节点值 - attr_accessor :height # 节点高度 - attr_accessor :left # 左子节点引用 - attr_accessor :right # 右子节点引用 - - def initialize(val) - @val = val - @height = 0 - end - end - ``` +```snippet +avl_tree_node +``` “节点高度”是指从该节点到它的最远叶节点的距离,即所经过的“边”的数量。需要特别注意的是,叶节点的高度为 $0$ ,而空节点的高度为 $-1$ 。我们将创建两个工具函数,分别用于获取和更新节点的高度: diff --git a/docs/chapter_tree/binary_tree.md b/docs/chapter_tree/binary_tree.md index edc862403..ea524d702 100644 --- a/docs/chapter_tree/binary_tree.md +++ b/docs/chapter_tree/binary_tree.md @@ -2,204 +2,9 @@ 二叉树(binary tree)是一种非线性数据结构,代表“祖先”与“后代”之间的派生关系,体现了“一分为二”的分治逻辑。与链表类似,二叉树的基本单元是节点,每个节点包含值、左子节点引用和右子节点引用。 -=== "Python" - - ```python title="" - class TreeNode: - """二叉树节点类""" - def __init__(self, val: int): - self.val: int = val # 节点值 - self.left: TreeNode | None = None # 左子节点引用 - self.right: TreeNode | None = None # 右子节点引用 - ``` - -=== "C++" - - ```cpp title="" - /* 二叉树节点结构体 */ - struct TreeNode { - int val; // 节点值 - TreeNode *left; // 左子节点指针 - TreeNode *right; // 右子节点指针 - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - }; - ``` - -=== "Java" - - ```java title="" - /* 二叉树节点类 */ - class TreeNode { - int val; // 节点值 - TreeNode left; // 左子节点引用 - TreeNode right; // 右子节点引用 - TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* 二叉树节点类 */ - class TreeNode(int? x) { - public int? val = x; // 节点值 - public TreeNode? left; // 左子节点引用 - public TreeNode? right; // 右子节点引用 - } - ``` - -=== "Go" - - ```go title="" - /* 二叉树节点结构体 */ - type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode - } - /* 构造方法 */ - func NewTreeNode(v int) *TreeNode { - return &TreeNode{ - Left: nil, // 左子节点指针 - Right: nil, // 右子节点指针 - Val: v, // 节点值 - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 二叉树节点类 */ - class TreeNode { - var val: Int // 节点值 - var left: TreeNode? // 左子节点引用 - var right: TreeNode? // 右子节点引用 - - init(x: Int) { - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 二叉树节点类 */ - class TreeNode { - val; // 节点值 - left; // 左子节点指针 - right; // 右子节点指针 - constructor(val, left, right) { - this.val = val === undefined ? 0 : val; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 二叉树节点类 */ - class TreeNode { - val: number; - left: TreeNode | null; - right: TreeNode | null; - - constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; // 节点值 - this.left = left === undefined ? null : left; // 左子节点引用 - this.right = right === undefined ? null : right; // 右子节点引用 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 二叉树节点类 */ - class TreeNode { - int val; // 节点值 - TreeNode? left; // 左子节点引用 - TreeNode? right; // 右子节点引用 - TreeNode(this.val, [this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 二叉树节点结构体 */ - struct TreeNode { - val: i32, // 节点值 - left: Option>>, // 左子节点引用 - right: Option>>, // 右子节点引用 - } - - impl TreeNode { - /* 构造方法 */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* 二叉树节点结构体 */ - typedef struct TreeNode { - int val; // 节点值 - int height; // 节点高度 - struct TreeNode *left; // 左子节点指针 - struct TreeNode *right; // 右子节点指针 - } TreeNode; - - /* 构造函数 */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 二叉树节点类 */ - class TreeNode(val _val: Int) { // 节点值 - var left: TreeNode? = null // 左子节点引用 - var right: TreeNode? = null // 右子节点引用 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 二叉树节点类 ### - class TreeNode - attr_accessor :val # 节点值 - attr_accessor :left # 左子节点引用 - attr_accessor :right # 右子节点引用 - - def initialize(val) - @val = val - end - end - ``` +```snippet +tree_node_class +``` 每个节点都有两个引用(指针),分别指向左子节点(left-child node)和右子节点(right-child node),该节点被称为这两个子节点的父节点(parent node)。当给定一个二叉树的节点时,我们将该节点的左子节点及其以下节点形成的树称为该节点的左子树(left subtree),同理可得右子树(right subtree)。 @@ -232,226 +37,13 @@ 与链表类似,首先初始化节点,然后构建引用(指针)。 -=== "Python" - - ```python title="binary_tree.py" - # 初始化二叉树 - # 初始化节点 - n1 = TreeNode(val=1) - n2 = TreeNode(val=2) - n3 = TreeNode(val=3) - n4 = TreeNode(val=4) - n5 = TreeNode(val=5) - # 构建节点之间的引用(指针) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* 初始化二叉树 */ - // 初始化节点 - TreeNode* n1 = new TreeNode(1); - TreeNode* n2 = new TreeNode(2); - TreeNode* n3 = new TreeNode(3); - TreeNode* n4 = new TreeNode(4); - TreeNode* n5 = new TreeNode(5); - // 构建节点之间的引用(指针) - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Java" - - ```java title="binary_tree.java" - // 初始化节点 - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // 构建节点之间的引用(指针) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* 初始化二叉树 */ - // 初始化节点 - TreeNode n1 = new(1); - TreeNode n2 = new(2); - TreeNode n3 = new(3); - TreeNode n4 = new(4); - TreeNode n5 = new(5); - // 构建节点之间的引用(指针) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* 初始化二叉树 */ - // 初始化节点 - n1 := NewTreeNode(1) - n2 := NewTreeNode(2) - n3 := NewTreeNode(3) - n4 := NewTreeNode(4) - n5 := NewTreeNode(5) - // 构建节点之间的引用(指针) - n1.Left = n2 - n1.Right = n3 - n2.Left = n4 - n2.Right = n5 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - // 初始化节点 - let n1 = TreeNode(x: 1) - let n2 = TreeNode(x: 2) - let n3 = TreeNode(x: 3) - let n4 = TreeNode(x: 4) - let n5 = TreeNode(x: 5) - // 构建节点之间的引用(指针) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* 初始化二叉树 */ - // 初始化节点 - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // 构建节点之间的引用(指针) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* 初始化二叉树 */ - // 初始化节点 - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // 构建节点之间的引用(指针) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* 初始化二叉树 */ - // 初始化节点 - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // 构建节点之间的引用(指针) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - // 初始化节点 - let n1 = TreeNode::new(1); - let n2 = TreeNode::new(2); - let n3 = TreeNode::new(3); - let n4 = TreeNode::new(4); - let n5 = TreeNode::new(5); - // 构建节点之间的引用(指针) - n1.borrow_mut().left = Some(n2.clone()); - n1.borrow_mut().right = Some(n3); - n2.borrow_mut().left = Some(n4); - n2.borrow_mut().right = Some(n5); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* 初始化二叉树 */ - // 初始化节点 - TreeNode *n1 = newTreeNode(1); - TreeNode *n2 = newTreeNode(2); - TreeNode *n3 = newTreeNode(3); - TreeNode *n4 = newTreeNode(4); - TreeNode *n5 = newTreeNode(5); - // 构建节点之间的引用(指针) - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - // 初始化节点 - val n1 = TreeNode(1) - val n2 = TreeNode(2) - val n3 = TreeNode(3) - val n4 = TreeNode(4) - val n5 = TreeNode(5) - // 构建节点之间的引用(指针) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # 初始化二叉树 - # 初始化节点 - n1 = TreeNode.new(1) - n2 = TreeNode.new(2) - n3 = TreeNode.new(3) - n4 = TreeNode.new(4) - n5 = TreeNode.new(5) - # 构建节点之间的引用(指针) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` +```snippet +init_binary_tree +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_binary_tree_tutor ### 插入与删除节点 @@ -459,165 +51,13 @@ ![在二叉树中插入与删除节点](binary_tree.assets/binary_tree_add_remove.svg) -=== "Python" - - ```python title="binary_tree.py" - # 插入与删除节点 - p = TreeNode(0) - # 在 n1 -> n2 中间插入节点 P - n1.left = p - p.left = n2 - # 删除节点 P - n1.left = n2 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* 插入与删除节点 */ - TreeNode* P = new TreeNode(0); - // 在 n1 -> n2 中间插入节点 P - n1->left = P; - P->left = n2; - // 删除节点 P - n1->left = n2; - // 释放内存 - delete P; - ``` - -=== "Java" - - ```java title="binary_tree.java" - TreeNode P = new TreeNode(0); - // 在 n1 -> n2 中间插入节点 P - n1.left = P; - P.left = n2; - // 删除节点 P - n1.left = n2; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* 插入与删除节点 */ - TreeNode P = new(0); - // 在 n1 -> n2 中间插入节点 P - n1.left = P; - P.left = n2; - // 删除节点 P - n1.left = n2; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* 插入与删除节点 */ - // 在 n1 -> n2 中间插入节点 P - p := NewTreeNode(0) - n1.Left = p - p.Left = n2 - // 删除节点 P - n1.Left = n2 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - let P = TreeNode(x: 0) - // 在 n1 -> n2 中间插入节点 P - n1.left = P - P.left = n2 - // 删除节点 P - n1.left = n2 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* 插入与删除节点 */ - let P = new TreeNode(0); - // 在 n1 -> n2 中间插入节点 P - n1.left = P; - P.left = n2; - // 删除节点 P - n1.left = n2; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* 插入与删除节点 */ - const P = new TreeNode(0); - // 在 n1 -> n2 中间插入节点 P - n1.left = P; - P.left = n2; - // 删除节点 P - n1.left = n2; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* 插入与删除节点 */ - TreeNode P = new TreeNode(0); - // 在 n1 -> n2 中间插入节点 P - n1.left = P; - P.left = n2; - // 删除节点 P - n1.left = n2; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - let p = TreeNode::new(0); - // 在 n1 -> n2 中间插入节点 P - n1.borrow_mut().left = Some(p.clone()); - p.borrow_mut().left = Some(n2.clone()); - // 删除节点 p - n1.borrow_mut().left = Some(n2); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* 插入与删除节点 */ - TreeNode *P = newTreeNode(0); - // 在 n1 -> n2 中间插入节点 P - n1->left = P; - P->left = n2; - // 删除节点 P - n1->left = n2; - // 释放内存 - free(P); - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - val P = TreeNode(0) - // 在 n1 -> n2 中间插入节点 P - n1.left = P - P.left = n2 - // 删除节点 P - n1.left = n2 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # 插入与删除节点 - _p = TreeNode.new(0) - # 在 n1 -> n2 中间插入节点 _p - n1.left = _p - _p.left = n2 - # 删除节点 - n1.left = n2 - ``` +```snippet +insert_remove_node +``` ??? pythontutor "可视化运行" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_node_tutor !!! tip diff --git a/en/codes/snippets/chapter_array_and_linkedlist/array.md b/en/codes/snippets/chapter_array_and_linkedlist/array.md new file mode 100644 index 000000000..2ea652fe9 --- /dev/null +++ b/en/codes/snippets/chapter_array_and_linkedlist/array.md @@ -0,0 +1,93 @@ + +```python title="array.py" +# Initialize arrays +arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="array.cpp" +/* Initialize arrays */ +// Stored on the stack +int arr[5] = {}; +int nums[5] = { 1, 3, 2, 5, 4 }; +// Stored on the heap (memory must be freed manually) +int* arr1 = new int[5] {}; +int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +``` + +```java title="array.java" +/* Initialize arrays */ +int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } +int[] nums = { 1, 3, 2, 5, 4 }; +``` + +```csharp title="array.cs" +/* Initialize arrays */ +int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] +int[] nums = [1, 3, 2, 5, 4]; +``` + +```go title="array.go" +/* Initialize arrays */ +var arr [5]int +// In Go, [5]int is an array with a specified length; []int is a slice +// Go array lengths are determined at compile time and must be constants +// To make extend() easier to implement, we treat slices as arrays below +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="array.swift" +/* Initialize arrays */ +let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] +let nums = [1, 3, 2, 5, 4] +``` + +```javascript title="array.js" +/* Initialize arrays */ +var arr = new Array(5).fill(0); +var nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="array.ts" +/* Initialize arrays */ +let arr: number[] = new Array(5).fill(0); +let nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="array.dart" +/* Initialize arrays */ +List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="array.rs" +/* Initialize arrays */ +let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] +let slice: &[i32] = &[0; 5]; +// In Rust, [i32; 5] is an array with a specified length; &[i32] is a slice +// Rust array lengths are determined at compile time and must be constants +// Vector is Rust's usual dynamic array type +// To make extend() easier to implement, we treat a vector as an array below +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="array.c" +/* Initialize arrays */ +int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } +int nums[5] = { 1, 3, 2, 5, 4 }; +``` + +```kotlin title="array.kt" +/* Initialize arrays */ +var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +var nums = intArrayOf(1, 3, 2, 5, 4) +``` + +```ruby title="array.rb" +# Initialize arrays +arr = Array.new(5, 0) +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%23%20Initialize%20arrays%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/en/codes/snippets/chapter_array_and_linkedlist/linked_list.md new file mode 100644 index 000000000..ae5fd27f1 --- /dev/null +++ b/en/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -0,0 +1,516 @@ + +```python title="" +class ListNode: + """Linked list node class""" + def __init__(self, val: int): + self.val: int = val # Node value + self.next: ListNode | None = None # Reference to the next node +``` + +```cpp title="" +/* Linked list node structure */ +struct ListNode { + int val; // Node value + ListNode *next; // Pointer to the next node + ListNode(int x) : val(x), next(nullptr) {} // Constructor +}; +``` + +```java title="" +/* Linked list node class */ +class ListNode { + int val; // Node value + ListNode next; // Reference to the next node + ListNode(int x) { val = x; } // Constructor +} +``` + +```csharp title="" +/* Linked list node class */ +class ListNode(int x) { // Constructor + int val = x; // Node value + ListNode? next; // Reference to the next node +} +``` + +```go title="" +/* Linked list node structure */ +type ListNode struct { + Val int // Node value + Next *ListNode // Pointer to the next node +} + +// NewListNode constructor: create a new linked list +func NewListNode(val int) *ListNode { + return &ListNode{ + Val: val, + Next: nil, + } +} +``` + +```swift title="" +/* Linked list node class */ +class ListNode { + var val: Int // Node value + var next: ListNode? // Reference to the next node + + init(x: Int) { // Constructor + val = x + } +} +``` + +```javascript title="" +/* Linked list node class */ +class ListNode { + constructor(val, next) { + this.val = (val === undefined ? 0 : val); // Node value + this.next = (next === undefined ? null : next); // Reference to the next node + } +} +``` + +```typescript title="" +/* Linked list node class */ +class ListNode { + val: number; + next: ListNode | null; + constructor(val?: number, next?: ListNode | null) { + this.val = val === undefined ? 0 : val; // Node value + this.next = next === undefined ? null : next; // Reference to the next node + } +} +``` + +```dart title="" +/* Linked list node class */ +class ListNode { + int val; // Node value + ListNode? next; // Reference to the next node + ListNode(this.val, [this.next]); // Constructor +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; +/* Linked list node class */ +#[derive(Debug)] +struct ListNode { + val: i32, // Node value + next: Option>>, // Pointer to the next node +} +``` + +```c title="" +/* Linked list node structure */ +typedef struct ListNode { + int val; // Node value + struct ListNode *next; // Pointer to the next node +} ListNode; + +/* Constructor */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + return node; +} +``` + +```kotlin title="" +/* Linked list node class */ +// Constructor +class ListNode(x: Int) { + val _val: Int = x // Node value + var next: ListNode? = null // Reference to the next node +} +``` + +```ruby title="" +# Linked list node class +class ListNode + attr_accessor :val # Node value + attr_accessor :next # Reference to the next node + + def initialize(val=0, next_node=nil) + @val = val + @next = next_node + end +end +``` + + +```python title="linked_list.py" +# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 +# Initialize the nodes +n0 = ListNode(1) +n1 = ListNode(3) +n2 = ListNode(2) +n3 = ListNode(5) +n4 = ListNode(4) +# Link the nodes with references +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```cpp title="linked_list.cpp" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +ListNode* n0 = new ListNode(1); +ListNode* n1 = new ListNode(3); +ListNode* n2 = new ListNode(2); +ListNode* n3 = new ListNode(5); +ListNode* n4 = new ListNode(4); +// Link the nodes with references +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```java title="linked_list.java" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +ListNode n0 = new ListNode(1); +ListNode n1 = new ListNode(3); +ListNode n2 = new ListNode(2); +ListNode n3 = new ListNode(5); +ListNode n4 = new ListNode(4); +// Link the nodes with references +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```csharp title="linked_list.cs" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +ListNode n0 = new(1); +ListNode n1 = new(3); +ListNode n2 = new(2); +ListNode n3 = new(5); +ListNode n4 = new(4); +// Link the nodes with references +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```go title="linked_list.go" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +n0 := NewListNode(1) +n1 := NewListNode(3) +n2 := NewListNode(2) +n3 := NewListNode(5) +n4 := NewListNode(4) +// Link the nodes with references +n0.Next = n1 +n1.Next = n2 +n2.Next = n3 +n3.Next = n4 +``` + +```swift title="linked_list.swift" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +let n0 = ListNode(x: 1) +let n1 = ListNode(x: 3) +let n2 = ListNode(x: 2) +let n3 = ListNode(x: 5) +let n4 = ListNode(x: 4) +// Link the nodes with references +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```javascript title="linked_list.js" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// Link the nodes with references +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```typescript title="linked_list.ts" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// Link the nodes with references +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```dart title="linked_list.dart" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */\ +// Initialize the nodes +ListNode n0 = ListNode(1); +ListNode n1 = ListNode(3); +ListNode n2 = ListNode(2); +ListNode n3 = ListNode(5); +ListNode n4 = ListNode(4); +// Link the nodes with references +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```rust title="linked_list.rs" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); +let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); +let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); +let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); +let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); + +// Link the nodes with references +n0.borrow_mut().next = Some(n1.clone()); +n1.borrow_mut().next = Some(n2.clone()); +n2.borrow_mut().next = Some(n3.clone()); +n3.borrow_mut().next = Some(n4.clone()); +``` + +```c title="linked_list.c" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +ListNode* n0 = newListNode(1); +ListNode* n1 = newListNode(3); +ListNode* n2 = newListNode(2); +ListNode* n3 = newListNode(5); +ListNode* n4 = newListNode(4); +// Link the nodes with references +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```kotlin title="linked_list.kt" +/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ +// Initialize the nodes +val n0 = ListNode(1) +val n1 = ListNode(3) +val n2 = ListNode(2) +val n3 = ListNode(5) +val n4 = ListNode(4) +// Link the nodes with references +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```ruby title="linked_list.rb" +# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 +# Initialize the nodes +n0 = ListNode.new(1) +n1 = ListNode.new(3) +n2 = ListNode.new(2) +n3 = ListNode.new(5) +n4 = ListNode.new(4) +# Link the nodes with references +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked%20list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20successor%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20the%20linked%20list%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20Initialize%20the%20nodes%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20Link%20the%20nodes%20with%20references%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="" +class ListNode: + """Doubly linked list node class""" + def __init__(self, val: int): + self.val: int = val # Node value + self.next: ListNode | None = None # Reference to the successor + self.prev: ListNode | None = None # Reference to the predecessor +``` + +```cpp title="" +/* Doubly linked list node structure */ +struct ListNode { + int val; // Node value + ListNode *next; // Pointer to the successor + ListNode *prev; // Pointer to the predecessor + ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // Constructor +}; +``` + +```java title="" +/* Doubly linked list node class */ +class ListNode { + int val; // Node value + ListNode next; // Reference to the successor + ListNode prev; // Reference to the predecessor + ListNode(int x) { val = x; } // Constructor +} +``` + +```csharp title="" +/* Doubly linked list node class */ +class ListNode(int x) { // Constructor + int val = x; // Node value + ListNode next; // Reference to the successor + ListNode prev; // Reference to the predecessor +} +``` + +```go title="" +/* Doubly linked list node structure */ +type DoublyListNode struct { + Val int // Node value + Next *DoublyListNode // Pointer to the successor + Prev *DoublyListNode // Pointer to the predecessor +} + +// Initialize a node with NewDoublyListNode +func NewDoublyListNode(val int) *DoublyListNode { + return &DoublyListNode{ + Val: val, + Next: nil, + Prev: nil, + } +} +``` + +```swift title="" +/* Doubly linked list node class */ +class ListNode { + var val: Int // Node value + var next: ListNode? // Reference to the successor + var prev: ListNode? // Reference to the predecessor + + init(x: Int) { // Constructor + val = x + } +} +``` + +```javascript title="" +/* Doubly linked list node class */ +class ListNode { + constructor(val, next, prev) { + this.val = val === undefined ? 0 : val; // Node value + this.next = next === undefined ? null : next; // Reference to the successor + this.prev = prev === undefined ? null : prev; // Reference to the predecessor + } +} +``` + +```typescript title="" +/* Doubly linked list node class */ +class ListNode { + val: number; + next: ListNode | null; + prev: ListNode | null; + constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { + this.val = val === undefined ? 0 : val; // Node value + this.next = next === undefined ? null : next; // Reference to the successor + this.prev = prev === undefined ? null : prev; // Reference to the predecessor + } +} +``` + +```dart title="" +/* Doubly linked list node class */ +class ListNode { + int val; // Node value + ListNode? next; // Reference to the successor + ListNode? prev; // Reference to the predecessor + ListNode(this.val, [this.next, this.prev]); // Constructor +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* Doubly linked list node type */ +#[derive(Debug)] +struct ListNode { + val: i32, // Node value + next: Option>>, // Pointer to the successor + prev: Option>>, // Pointer to the predecessor +} + +/* Constructor */ +impl ListNode { + fn new(val: i32) -> Self { + ListNode { + val, + next: None, + prev: None, + } + } +} +``` + +```c title="" +/* Doubly linked list node structure */ +typedef struct ListNode { + int val; // Node value + struct ListNode *next; // Pointer to the successor + struct ListNode *prev; // Pointer to the predecessor +} ListNode; + +/* Constructor */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + node->prev = NULL; + return node; +} +``` + +```kotlin title="" +/* Doubly linked list node class */ +// Constructor +class ListNode(x: Int) { + val _val: Int = x // Node value + var next: ListNode? = null // Reference to the successor + var prev: ListNode? = null // Reference to the predecessor +} +``` + +```ruby title="" +# Doubly linked list node class +class ListNode + attr_accessor :val # Node value + attr_accessor :next # Reference to the successor + attr_accessor :prev # Reference to the predecessor + + def initialize(val=0, next_node=nil, prev_node=nil) + @val = val + @next = next_node + @prev = prev_node + end +end +``` diff --git a/en/codes/snippets/chapter_array_and_linkedlist/list.md b/en/codes/snippets/chapter_array_and_linkedlist/list.md new file mode 100644 index 000000000..d6c188b93 --- /dev/null +++ b/en/codes/snippets/chapter_array_and_linkedlist/list.md @@ -0,0 +1,752 @@ + +```python title="list.py" +# Initialize lists +# Without initial values +nums1: list[int] = [] +# With initial values +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="list.cpp" +/* Initialize lists */ +// In C++, vector is the list type used for nums here +// Without initial values +vector nums1; +// With initial values +vector nums = { 1, 3, 2, 5, 4 }; +``` + +```java title="list.java" +/* Initialize lists */ +// Without initial values +List nums1 = new ArrayList<>(); +// With initial values (use Integer[], the boxed counterpart of int[]) +Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; +List nums = new ArrayList<>(Arrays.asList(numbers)); +``` + +```csharp title="list.cs" +/* Initialize lists */ +// Without initial values +List nums1 = []; +// With initial values +int[] numbers = [1, 3, 2, 5, 4]; +List nums = [.. numbers]; +``` + +```go title="list_test.go" +/* Initialize lists */ +// Without initial values +nums1 := []int{} +// With initial values +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="list.swift" +/* Initialize lists */ +// Without initial values +let nums1: [Int] = [] +// With initial values +var nums = [1, 3, 2, 5, 4] +``` + +```javascript title="list.js" +/* Initialize lists */ +// Without initial values +const nums1 = []; +// With initial values +const nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="list.ts" +/* Initialize lists */ +// Without initial values +const nums1: number[] = []; +// With initial values +const nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="list.dart" +/* Initialize lists */ +// Without initial values +List nums1 = []; +// With initial values +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="list.rs" +/* Initialize lists */ +// Without initial values +let nums1: Vec = Vec::new(); +// With initial values +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="list.c" +// C does not provide a built-in dynamic array +``` + +```kotlin title="list.kt" +/* Initialize lists */ +// Without initial values +var nums1 = listOf() +// With initial values +var numbers = arrayOf(1, 3, 2, 5, 4) +var nums = numbers.toMutableList() +``` + +```ruby title="list.rb" +# Initialize lists +# Without initial values +nums1 = [] +# With initial values +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20%23%20Without%20initial%20values%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Access an element +num: int = nums[1] # Access the element at index 1 + +# Update an element +nums[1] = 0 # Set the element at index 1 to 0 +``` + +```cpp title="list.cpp" +/* Access an element */ +int num = nums[1]; // Access the element at index 1 + +/* Update an element */ +nums[1] = 0; // Set the element at index 1 to 0 +``` + +```java title="list.java" +/* Access an element */ +int num = nums.get(1); // Access the element at index 1 + +/* Update an element */ +nums.set(1, 0); // Set the element at index 1 to 0 +``` + +```csharp title="list.cs" +/* Access an element */ +int num = nums[1]; // Access the element at index 1 + +/* Update an element */ +nums[1] = 0; // Set the element at index 1 to 0 +``` + +```go title="list_test.go" +/* Access an element */ +num := nums[1] // Access the element at index 1 + +/* Update an element */ +nums[1] = 0 // Set the element at index 1 to 0 +``` + +```swift title="list.swift" +/* Access an element */ +let num = nums[1] // Access the element at index 1 + +/* Update an element */ +nums[1] = 0 // Set the element at index 1 to 0 +``` + +```javascript title="list.js" +/* Access an element */ +const num = nums[1]; // Access the element at index 1 + +/* Update an element */ +nums[1] = 0; // Set the element at index 1 to 0 +``` + +```typescript title="list.ts" +/* Access an element */ +const num: number = nums[1]; // Access the element at index 1 + +/* Update an element */ +nums[1] = 0; // Set the element at index 1 to 0 +``` + +```dart title="list.dart" +/* Access an element */ +int num = nums[1]; // Access the element at index 1 + +/* Update an element */ +nums[1] = 0; // Set the element at index 1 to 0 +``` + +```rust title="list.rs" +/* Access an element */ +let num: i32 = nums[1]; // Access the element at index 1 +/* Update an element */ +nums[1] = 0; // Set the element at index 1 to 0 +``` + +```c title="list.c" +// C does not provide a built-in dynamic array +``` + +```kotlin title="list.kt" +/* Access an element */ +val num = nums[1] // Access the element at index 1 +/* Update an element */ +nums[1] = 0 // Set the element at index 1 to 0 +``` + +```ruby title="list.rb" +# Access an element +num = nums[1] # Access the element at index 1 +# Update an element +nums[1] = 0 # Set the element at index 1 to 0 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20Access%20an%20element%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20Access%20the%20element%20at%20index%201%0A%0A%20%20%20%20%23%20Update%20an%20element%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20Set%20the%20element%20at%20index%201%20to%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Clear the list +nums.clear() + +# Append elements +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +# Insert an element in the middle +nums.insert(3, 6) # Insert 6 at index 3 + +# Remove an element +nums.pop(3) # Remove the element at index 3 +``` + +```cpp title="list.cpp" +/* Clear the list */ +nums.clear(); + +/* Append elements */ +nums.push_back(1); +nums.push_back(3); +nums.push_back(2); +nums.push_back(5); +nums.push_back(4); + +/* Insert an element in the middle */ +nums.insert(nums.begin() + 3, 6); // Insert 6 at index 3 + +/* Remove an element */ +nums.erase(nums.begin() + 3); // Remove the element at index 3 +``` + +```java title="list.java" +/* Clear the list */ +nums.clear(); + +/* Append elements */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* Insert an element in the middle */ +nums.add(3, 6); // Insert 6 at index 3 + +/* Remove an element */ +nums.remove(3); // Remove the element at index 3 +``` + +```csharp title="list.cs" +/* Clear the list */ +nums.Clear(); + +/* Append elements */ +nums.Add(1); +nums.Add(3); +nums.Add(2); +nums.Add(5); +nums.Add(4); + +/* Insert an element in the middle */ +nums.Insert(3, 6); // Insert 6 at index 3 + +/* Remove an element */ +nums.RemoveAt(3); // Remove the element at index 3 +``` + +```go title="list_test.go" +/* Clear the list */ +nums = nil + +/* Append elements */ +nums = append(nums, 1) +nums = append(nums, 3) +nums = append(nums, 2) +nums = append(nums, 5) +nums = append(nums, 4) + +/* Insert an element in the middle */ +nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert 6 at index 3 + +/* Remove an element */ +nums = append(nums[:3], nums[4:]...) // Remove the element at index 3 +``` + +```swift title="list.swift" +/* Clear the list */ +nums.removeAll() + +/* Append elements */ +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +/* Insert an element in the middle */ +nums.insert(6, at: 3) // Insert 6 at index 3 + +/* Remove an element */ +nums.remove(at: 3) // Remove the element at index 3 +``` + +```javascript title="list.js" +/* Clear the list */ +nums.length = 0; + +/* Append elements */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* Insert an element in the middle */ +nums.splice(3, 0, 6); // Insert 6 at index 3 + +/* Remove an element */ +nums.splice(3, 1); // Remove the element at index 3 +``` + +```typescript title="list.ts" +/* Clear the list */ +nums.length = 0; + +/* Append elements */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* Insert an element in the middle */ +nums.splice(3, 0, 6); // Insert 6 at index 3 + +/* Remove an element */ +nums.splice(3, 1); // Remove the element at index 3 +``` + +```dart title="list.dart" +/* Clear the list */ +nums.clear(); + +/* Append elements */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* Insert an element in the middle */ +nums.insert(3, 6); // Insert 6 at index 3 + +/* Remove an element */ +nums.removeAt(3); // Remove the element at index 3 +``` + +```rust title="list.rs" +/* Clear the list */ +nums.clear(); + +/* Append elements */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* Insert an element in the middle */ +nums.insert(3, 6); // Insert 6 at index 3 + +/* Remove an element */ +nums.remove(3); // Remove the element at index 3 +``` + +```c title="list.c" +// C does not provide a built-in dynamic array +``` + +```kotlin title="list.kt" +/* Clear the list */ +nums.clear(); + +/* Append elements */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* Insert an element in the middle */ +nums.add(3, 6); // Insert 6 at index 3 + +/* Remove an element */ +nums.remove(3); // Remove the element at index 3 +``` + +```ruby title="list.rb" +# Clear the list +nums.clear + +# Append elements +nums << 1 +nums << 3 +nums << 2 +nums << 5 +nums << 4 + +# Insert an element in the middle +nums.insert(3, 6) # Insert 6 at index 3 + +# Remove an element +nums.delete_at(3) # Remove the element at index 3 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Clear%20the%20list%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20Append%20elements%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20Insert%20an%20element%20in%20the%20middle%0A%20%20%20%20nums.insert%283%2C%206%29%20%20%23%20Insert%206%20at%20index%203%0A%20%20%20%20%0A%20%20%20%20%23%20Remove%20an%20element%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20Remove%20the%20element%20at%20index%203&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Traverse the list by index +count = 0 +for i in range(len(nums)): + count += nums[i] + +# Traverse list elements directly +for num in nums: + count += num +``` + +```cpp title="list.cpp" +/* Traverse the list by index */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums[i]; +} + +/* Traverse list elements directly */ +count = 0; +for (int num : nums) { + count += num; +} +``` + +```java title="list.java" +/* Traverse the list by index */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums.get(i); +} + +/* Traverse list elements directly */ +for (int num : nums) { + count += num; +} +``` + +```csharp title="list.cs" +/* Traverse the list by index */ +int count = 0; +for (int i = 0; i < nums.Count; i++) { + count += nums[i]; +} + +/* Traverse list elements directly */ +count = 0; +foreach (int num in nums) { + count += num; +} +``` + +```go title="list_test.go" +/* Traverse the list by index */ +count := 0 +for i := 0; i < len(nums); i++ { + count += nums[i] +} + +/* Traverse list elements directly */ +count = 0 +for _, num := range nums { + count += num +} +``` + +```swift title="list.swift" +/* Traverse the list by index */ +var count = 0 +for i in nums.indices { + count += nums[i] +} + +/* Traverse list elements directly */ +count = 0 +for num in nums { + count += num +} +``` + +```javascript title="list.js" +/* Traverse the list by index */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* Traverse list elements directly */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```typescript title="list.ts" +/* Traverse the list by index */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* Traverse list elements directly */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```dart title="list.dart" +/* Traverse the list by index */ +int count = 0; +for (var i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* Traverse list elements directly */ +count = 0; +for (var num in nums) { + count += num; +} +``` + +```rust title="list.rs" +// Traverse the list by index +let mut _count = 0; +for i in 0..nums.len() { + _count += nums[i]; +} + +// Traverse list elements directly +_count = 0; +for num in &nums { + _count += num; +} +``` + +```c title="list.c" +// C does not provide a built-in dynamic array +``` + +```kotlin title="list.kt" +/* Traverse the list by index */ +var count = 0 +for (i in nums.indices) { + count += nums[i] +} + +/* Traverse list elements directly */ +for (num in nums) { + count += num +} +``` + +```ruby title="list.rb" +# Traverse the list by index +count = 0 +for i in 0...nums.length + count += nums[i] +end + +# Traverse list elements directly +count = 0 +for num in nums + count += num +end +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Traverse%20the%20list%20by%20index%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20Traverse%20list%20elements%20directly%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Concatenate two lists +nums1: list[int] = [6, 8, 7, 10, 9] +nums += nums1 # Append nums1 to nums +``` + +```cpp title="list.cpp" +/* Concatenate two lists */ +vector nums1 = { 6, 8, 7, 10, 9 }; +// Append nums1 to nums +nums.insert(nums.end(), nums1.begin(), nums1.end()); +``` + +```java title="list.java" +/* Concatenate two lists */ +List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); +nums.addAll(nums1); // Append nums1 to nums +``` + +```csharp title="list.cs" +/* Concatenate two lists */ +List nums1 = [6, 8, 7, 10, 9]; +nums.AddRange(nums1); // Append nums1 to nums +``` + +```go title="list_test.go" +/* Concatenate two lists */ +nums1 := []int{6, 8, 7, 10, 9} +nums = append(nums, nums1...) // Append nums1 to nums +``` + +```swift title="list.swift" +/* Concatenate two lists */ +let nums1 = [6, 8, 7, 10, 9] +nums.append(contentsOf: nums1) // Append nums1 to nums +``` + +```javascript title="list.js" +/* Concatenate two lists */ +const nums1 = [6, 8, 7, 10, 9]; +nums.push(...nums1); // Append nums1 to nums +``` + +```typescript title="list.ts" +/* Concatenate two lists */ +const nums1: number[] = [6, 8, 7, 10, 9]; +nums.push(...nums1); // Append nums1 to nums +``` + +```dart title="list.dart" +/* Concatenate two lists */ +List nums1 = [6, 8, 7, 10, 9]; +nums.addAll(nums1); // Append nums1 to nums +``` + +```rust title="list.rs" +/* Concatenate two lists */ +let nums1: Vec = vec![6, 8, 7, 10, 9]; +nums.extend(nums1); +``` + +```c title="list.c" +// C does not provide a built-in dynamic array +``` + +```kotlin title="list.kt" +/* Concatenate two lists */ +val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() +nums.addAll(nums1) // Append nums1 to nums +``` + +```ruby title="list.rb" +# Concatenate two lists +nums1 = [6, 8, 7, 10, 9] +nums += nums1 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Concatenate%20two%20lists%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20Append%20nums1%20to%20nums&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Sort the list +nums.sort() # After sorting, elements are in ascending order +``` + +```cpp title="list.cpp" +/* Sort the list */ +sort(nums.begin(), nums.end()); // After sorting, elements are in ascending order +``` + +```java title="list.java" +/* Sort the list */ +Collections.sort(nums); // After sorting, elements are in ascending order +``` + +```csharp title="list.cs" +/* Sort the list */ +nums.Sort(); // After sorting, elements are in ascending order +``` + +```go title="list_test.go" +/* Sort the list */ +sort.Ints(nums) // After sorting, elements are in ascending order +``` + +```swift title="list.swift" +/* Sort the list */ +nums.sort() // After sorting, elements are in ascending order +``` + +```javascript title="list.js" +/* Sort the list */ +nums.sort((a, b) => a - b); // After sorting, elements are in ascending order +``` + +```typescript title="list.ts" +/* Sort the list */ +nums.sort((a, b) => a - b); // After sorting, elements are in ascending order +``` + +```dart title="list.dart" +/* Sort the list */ +nums.sort(); // After sorting, elements are in ascending order +``` + +```rust title="list.rs" +/* Sort the list */ +nums.sort(); // After sorting, elements are in ascending order +``` + +```c title="list.c" +// C does not provide a built-in dynamic array +``` + +```kotlin title="list.kt" +/* Sort the list */ +nums.sort() // After sorting, elements are in ascending order +``` + +```ruby title="list.rb" +# Sort the list +nums = nums.sort { |a, b| a <=> b } # After sorting, elements are in ascending order +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Sort%20the%20list%0A%20%20%20%20nums.sort%28%29%20%20%23%20After%20sorting%2C%20elements%20are%20in%20ascending%20order&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_backtracking/backtracking_algorithm.md b/en/codes/snippets/chapter_backtracking/backtracking_algorithm.md new file mode 100644 index 000000000..742f2b1ad --- /dev/null +++ b/en/codes/snippets/chapter_backtracking/backtracking_algorithm.md @@ -0,0 +1,308 @@ + +```python title="" +def backtrack(state: State, choices: list[choice], res: list[state]): + """Backtracking template""" + # Check whether the state is a solution + if is_solution(state): + # Record the solution + record_solution(state, res) + # Stop searching this branch + return + # Try every choice + for choice in choices: + # Prune: check whether the choice is valid + if is_valid(state, choice): + # Try: make the choice and update the state + make_choice(state, choice) + backtrack(state, choices, res) + # Backtrack: undo the choice and restore the previous state + undo_choice(state, choice) +``` + +```cpp title="" +/* Backtracking template */ +void backtrack(State *state, vector &choices, vector &res) { + // Check whether the state is a solution + if (isSolution(state)) { + // Record the solution + recordSolution(state, res); + // Stop searching this branch + return; + } + // Try every choice + for (Choice choice : choices) { + // Prune: check whether the choice is valid + if (isValid(state, choice)) { + // Try: make the choice and update the state + makeChoice(state, choice); + backtrack(state, choices, res); + // Backtrack: undo the choice and restore the previous state + undoChoice(state, choice); + } + } +} +``` + +```java title="" +/* Backtracking template */ +void backtrack(State state, List choices, List res) { + // Check whether the state is a solution + if (isSolution(state)) { + // Record the solution + recordSolution(state, res); + // Stop searching this branch + return; + } + // Try every choice + for (Choice choice : choices) { + // Prune: check whether the choice is valid + if (isValid(state, choice)) { + // Try: make the choice and update the state + makeChoice(state, choice); + backtrack(state, choices, res); + // Backtrack: undo the choice and restore the previous state + undoChoice(state, choice); + } + } +} +``` + +```csharp title="" +/* Backtracking template */ +void Backtrack(State state, List choices, List res) { + // Check whether the state is a solution + if (IsSolution(state)) { + // Record the solution + RecordSolution(state, res); + // Stop searching this branch + return; + } + // Try every choice + foreach (Choice choice in choices) { + // Prune: check whether the choice is valid + if (IsValid(state, choice)) { + // Try: make the choice and update the state + MakeChoice(state, choice); + Backtrack(state, choices, res); + // Backtrack: undo the choice and restore the previous state + UndoChoice(state, choice); + } + } +} +``` + +```go title="" +/* Backtracking template */ +func backtrack(state *State, choices []Choice, res *[]State) { + // Check whether the state is a solution + if isSolution(state) { + // Record the solution + recordSolution(state, res) + // Stop searching this branch + return + } + // Try every choice + for _, choice := range choices { + // Prune: check whether the choice is valid + if isValid(state, choice) { + // Try: make the choice and update the state + makeChoice(state, choice) + backtrack(state, choices, res) + // Backtrack: undo the choice and restore the previous state + undoChoice(state, choice) + } + } +} +``` + +```swift title="" +/* Backtracking template */ +func backtrack(state: inout State, choices: [Choice], res: inout [State]) { + // Check whether the state is a solution + if isSolution(state: state) { + // Record the solution + recordSolution(state: state, res: &res) + // Stop searching this branch + return + } + // Try every choice + for choice in choices { + // Prune: check whether the choice is valid + if isValid(state: state, choice: choice) { + // Try: make the choice and update the state + makeChoice(state: &state, choice: choice) + backtrack(state: &state, choices: choices, res: &res) + // Backtrack: undo the choice and restore the previous state + undoChoice(state: &state, choice: choice) + } + } +} +``` + +```javascript title="" +/* Backtracking template */ +function backtrack(state, choices, res) { + // Check whether the state is a solution + if (isSolution(state)) { + // Record the solution + recordSolution(state, res); + // Stop searching this branch + return; + } + // Try every choice + for (let choice of choices) { + // Prune: check whether the choice is valid + if (isValid(state, choice)) { + // Try: make the choice and update the state + makeChoice(state, choice); + backtrack(state, choices, res); + // Backtrack: undo the choice and restore the previous state + undoChoice(state, choice); + } + } +} +``` + +```typescript title="" +/* Backtracking template */ +function backtrack(state: State, choices: Choice[], res: State[]): void { + // Check whether the state is a solution + if (isSolution(state)) { + // Record the solution + recordSolution(state, res); + // Stop searching this branch + return; + } + // Try every choice + for (let choice of choices) { + // Prune: check whether the choice is valid + if (isValid(state, choice)) { + // Try: make the choice and update the state + makeChoice(state, choice); + backtrack(state, choices, res); + // Backtrack: undo the choice and restore the previous state + undoChoice(state, choice); + } + } +} +``` + +```dart title="" +/* Backtracking template */ +void backtrack(State state, List, List res) { + // Check whether the state is a solution + if (isSolution(state)) { + // Record the solution + recordSolution(state, res); + // Stop searching this branch + return; + } + // Try every choice + for (Choice choice in choices) { + // Prune: check whether the choice is valid + if (isValid(state, choice)) { + // Try: make the choice and update the state + makeChoice(state, choice); + backtrack(state, choices, res); + // Backtrack: undo the choice and restore the previous state + undoChoice(state, choice); + } + } +} +``` + +```rust title="" +/* Backtracking template */ +fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { + // Check whether the state is a solution + if is_solution(state) { + // Record the solution + record_solution(state, res); + // Stop searching this branch + return; + } + // Try every choice + for choice in choices { + // Prune: check whether the choice is valid + if is_valid(state, choice) { + // Try: make the choice and update the state + make_choice(state, choice); + backtrack(state, choices, res); + // Backtrack: undo the choice and restore the previous state + undo_choice(state, choice); + } + } +} +``` + +```c title="" +/* Backtracking template */ +void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { + // Check whether the state is a solution + if (isSolution(state)) { + // Record the solution + recordSolution(state, res, numRes); + // Stop searching this branch + return; + } + // Try every choice + for (int i = 0; i < numChoices; i++) { + // Prune: check whether the choice is valid + if (isValid(state, &choices[i])) { + // Try: make the choice and update the state + makeChoice(state, &choices[i]); + backtrack(state, choices, numChoices, res, numRes); + // Backtrack: undo the choice and restore the previous state + undoChoice(state, &choices[i]); + } + } +} +``` + +```kotlin title="" +/* Backtracking template */ +fun backtrack(state: State?, choices: List, res: List?) { + // Check whether the state is a solution + if (isSolution(state)) { + // Record the solution + recordSolution(state, res) + // Stop searching this branch + return + } + // Try every choice + for (choice in choices) { + // Prune: check whether the choice is valid + if (isValid(state, choice)) { + // Try: make the choice and update the state + makeChoice(state, choice) + backtrack(state, choices, res) + // Backtrack: undo the choice and restore the previous state + undoChoice(state, choice) + } + } +} +``` + +```ruby title="" +### Backtracking template ### +def backtrack(state, choices, res) + # Check whether the state is a solution + if is_solution?(state) + # Record the solution + record_solution(state, res) + return + end + + # Try every choice + for choice in choices + # Prune: check whether the choice is valid + if is_valid?(state, choice) + # Try: make the choice and update the state + make_choice(state, choice) + backtrack(state, choices, res) + # Backtrack: undo the choice and restore the previous state + undo_choice(state, choice) + end + end +end +``` diff --git a/en/codes/snippets/chapter_computational_complexity/space_complexity.md b/en/codes/snippets/chapter_computational_complexity/space_complexity.md new file mode 100644 index 000000000..4b090cb2d --- /dev/null +++ b/en/codes/snippets/chapter_computational_complexity/space_complexity.md @@ -0,0 +1,682 @@ + +```python title="" +class Node: + """Class""" + def __init__(self, x: int): + self.val: int = x # Node value + self.next: Node | None = None # Reference to the next node + +def function() -> int: + """Function""" + # Perform some operations... + return 0 + +def algorithm(n) -> int: # Input data + A = 0 # Temporary data (constant, conventionally named in uppercase) + b = 0 # Temporary data (variable) + node = Node(0) # Temporary data (object) + c = function() # Stack frame (function call) + return A + b + c # Output data +``` + +```cpp title="" +/* Structure */ +struct Node { + int val; + Node *next; + Node(int x) : val(x), next(nullptr) {} +}; + +/* Function */ +int func() { + // Perform some operations... + return 0; +} + +int algorithm(int n) { // Input data + const int a = 0; // Temporary data (constant) + int b = 0; // Temporary data (variable) + Node* node = new Node(0); // Temporary data (object) + int c = func(); // Stack frame (function call) + return a + b + c; // Output data +} +``` + +```java title="" +/* Class */ +class Node { + int val; + Node next; + Node(int x) { val = x; } +} + +/* Function */ +int function() { + // Perform some operations... + return 0; +} + +int algorithm(int n) { // Input data + final int a = 0; // Temporary data (constant) + int b = 0; // Temporary data (variable) + Node node = new Node(0); // Temporary data (object) + int c = function(); // Stack frame (function call) + return a + b + c; // Output data +} +``` + +```csharp title="" +/* Class */ +class Node(int x) { + int val = x; + Node next; +} + +/* Function */ +int Function() { + // Perform some operations... + return 0; +} + +int Algorithm(int n) { // Input data + const int a = 0; // Temporary data (constant) + int b = 0; // Temporary data (variable) + Node node = new(0); // Temporary data (object) + int c = Function(); // Stack frame (function call) + return a + b + c; // Output data +} +``` + +```go title="" +/* Structure */ +type node struct { + val int + next *node +} + +/* Create a node structure */ +func newNode(val int) *node { + return &node{val: val} +} + +/* Function */ +func function() int { + // Perform some operations... + return 0 +} + +func algorithm(n int) int { // Input data + const a = 0 // Temporary data (constant) + b := 0 // Temporary data (variable) + newNode(0) // Temporary data (object) + c := function() // Stack frame (function call) + return a + b + c // Output data +} +``` + +```swift title="" +/* Class */ +class Node { + var val: Int + var next: Node? + + init(x: Int) { + val = x + } +} + +/* Function */ +func function() -> Int { + // Perform some operations... + return 0 +} + +func algorithm(n: Int) -> Int { // Input data + let a = 0 // Temporary data (constant) + var b = 0 // Temporary data (variable) + let node = Node(x: 0) // Temporary data (object) + let c = function() // Stack frame (function call) + return a + b + c // Output data +} +``` + +```javascript title="" +/* Class */ +class Node { + val; + next; + constructor(val) { + this.val = val === undefined ? 0 : val; // Node value + this.next = null; // Reference to the next node + } +} + +/* Function */ +function constFunc() { + // Perform some operations + return 0; +} + +function algorithm(n) { // Input data + const a = 0; // Temporary data (constant) + let b = 0; // Temporary data (variable) + const node = new Node(0); // Temporary data (object) + const c = constFunc(); // Stack frame (function call) + return a + b + c; // Output data +} +``` + +```typescript title="" +/* Class */ +class Node { + val: number; + next: Node | null; + constructor(val?: number) { + this.val = val === undefined ? 0 : val; // Node value + this.next = null; // Reference to the next node + } +} + +/* Function */ +function constFunc(): number { + // Perform some operations + return 0; +} + +function algorithm(n: number): number { // Input data + const a = 0; // Temporary data (constant) + let b = 0; // Temporary data (variable) + const node = new Node(0); // Temporary data (object) + const c = constFunc(); // Stack frame (function call) + return a + b + c; // Output data +} +``` + +```dart title="" +/* Class */ +class Node { + int val; + Node next; + Node(this.val, [this.next]); +} + +/* Function */ +int function() { + // Perform some operations... + return 0; +} + +int algorithm(int n) { // Input data + const int a = 0; // Temporary data (constant) + int b = 0; // Temporary data (variable) + Node node = Node(0); // Temporary data (object) + int c = function(); // Stack frame (function call) + return a + b + c; // Output data +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* Structure */ +struct Node { + val: i32, + next: Option>>, +} + +/* Create a Node structure */ +impl Node { + fn new(val: i32) -> Self { + Self { val: val, next: None } + } +} + +/* Function */ +fn function() -> i32 { + // Perform some operations... + return 0; +} + +fn algorithm(n: i32) -> i32 { // Input data + const a: i32 = 0; // Temporary data (constant) + let mut b = 0; // Temporary data (variable) + let node = Node::new(0); // Temporary data (object) + let c = function(); // Stack frame (function call) + return a + b + c; // Output data +} +``` + +```c title="" +/* Function */ +int func() { + // Perform some operations... + return 0; +} + +int algorithm(int n) { // Input data + const int a = 0; // Temporary data (constant) + int b = 0; // Temporary data (variable) + int c = func(); // Stack frame (function call) + return a + b + c; // Output data +} +``` + +```kotlin title="" +/* Class */ +class Node(var _val: Int) { + var next: Node? = null +} + +/* Function */ +fun function(): Int { + // Perform some operations... + return 0 +} + +fun algorithm(n: Int): Int { // Input data + val a = 0 // Temporary data (constant) + var b = 0 // Temporary data (variable) + val node = Node(0) // Temporary data (object) + val c = function() // Stack frame (function call) + return a + b + c // Output data +} +``` + +```ruby title="" +### Class ### +class Node + attr_accessor :val # Node value + attr_accessor :next # Reference to the next node + + def initialize(x) + @val = x + end +end + +### Function ### +def function + # Perform some operations... + 0 +end + +### Algorithm ### +def algorithm(n) # Input data + a = 0 # Temporary data (constant) + b = 0 # Temporary data (variable) + node = Node.new(0) # Temporary data (object) + c = function # Stack frame (function call) + a + b + c # Output data +end +``` + + +```python title="" +def algorithm(n: int): + a = 0 # O(1) + b = [0] * 10000 # O(1) + if n > 10: + nums = [0] * n # O(n) +``` + +```cpp title="" +void algorithm(int n) { + int a = 0; // O(1) + vector b(10000); // O(1) + if (n > 10) + vector nums(n); // O(n) +} +``` + +```java title="" +void algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) + int[] nums = new int[n]; // O(n) +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) { + int[] nums = new int[n]; // O(n) + } +} +``` + +```go title="" +func algorithm(n int) { + a := 0 // O(1) + b := make([]int, 10000) // O(1) + var nums []int + if n > 10 { + nums := make([]int, n) // O(n) + } + fmt.Println(a, b, nums) +} +``` + +```swift title="" +func algorithm(n: Int) { + let a = 0 // O(1) + let b = Array(repeating: 0, count: 10000) // O(1) + if n > 10 { + let nums = Array(repeating: 0, count: n) // O(n) + } +} +``` + +```javascript title="" +function algorithm(n) { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 0; // O(1) + List b = List.filled(10000, 0); // O(1) + if (n > 10) { + List nums = List.filled(n, 0); // O(n) + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let a = 0; // O(1) + let b = [0; 10000]; // O(1) + if n > 10 { + let nums = vec![0; n as usize]; // O(n) + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 0; // O(1) + int b[10000]; // O(1) + if (n > 10) + int nums[n] = {0}; // O(n) +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + val a = 0 // O(1) + val b = IntArray(10000) // O(1) + if (n > 10) { + val nums = IntArray(n) // O(n) + } +} +``` + +```ruby title="" +def algorithm(n) + a = 0 # O(1) + b = Array.new(10000) # O(1) + nums = Array.new(n) if n > 10 # O(n) +end +``` + + +```python title="" +def function() -> int: + # Perform some operations + return 0 + +def loop(n: int): + """The loop uses O(1) space""" + for _ in range(n): + function() + +def recur(n: int): + """The recursion uses O(n) space""" + if n == 1: + return + return recur(n - 1) +``` + +```cpp title="" +int func() { + // Perform some operations + return 0; +} +/* The loop uses O(1) space */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* The recursion uses O(n) space */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```java title="" +int function() { + // Perform some operations + return 0; +} +/* The loop uses O(1) space */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* The recursion uses O(n) space */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```csharp title="" +int Function() { + // Perform some operations + return 0; +} +/* The loop uses O(1) space */ +void Loop(int n) { + for (int i = 0; i < n; i++) { + Function(); + } +} +/* The recursion uses O(n) space */ +int Recur(int n) { + if (n == 1) return 1; + return Recur(n - 1); +} +``` + +```go title="" +func function() int { + // Perform some operations + return 0 +} + +/* The loop uses O(1) space */ +func loop(n int) { + for i := 0; i < n; i++ { + function() + } +} + +/* The recursion uses O(n) space */ +func recur(n int) { + if n == 1 { + return + } + recur(n - 1) +} +``` + +```swift title="" +@discardableResult +func function() -> Int { + // Perform some operations + return 0 +} + +/* The loop uses O(1) space */ +func loop(n: Int) { + for _ in 0 ..< n { + function() + } +} + +/* The recursion uses O(n) space */ +func recur(n: Int) { + if n == 1 { + return + } + recur(n: n - 1) +} +``` + +```javascript title="" +function constFunc() { + // Perform some operations + return 0; +} +/* The loop uses O(1) space */ +function loop(n) { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* The recursion uses O(n) space */ +function recur(n) { + if (n === 1) return; + return recur(n - 1); +} +``` + +```typescript title="" +function constFunc(): number { + // Perform some operations + return 0; +} +/* The loop uses O(1) space */ +function loop(n: number): void { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* The recursion uses O(n) space */ +function recur(n: number): void { + if (n === 1) return; + return recur(n - 1); +} +``` + +```dart title="" +int function() { + // Perform some operations + return 0; +} +/* The loop uses O(1) space */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* The recursion uses O(n) space */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```rust title="" +fn function() -> i32 { + // Perform some operations + return 0; +} +/* The loop uses O(1) space */ +fn loop(n: i32) { + for i in 0..n { + function(); + } +} +/* The recursion uses O(n) space */ +fn recur(n: i32) { + if n == 1 { + return; + } + recur(n - 1); +} +``` + +```c title="" +int func() { + // Perform some operations + return 0; +} +/* The loop uses O(1) space */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* The recursion uses O(n) space */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```kotlin title="" +fun function(): Int { + // Perform some operations + return 0 +} +/* The loop uses O(1) space */ +fun loop(n: Int) { + for (i in 0.. +```python title="" +# On a particular execution platform +def algorithm(n: int): + a = 2 # 1 ns + a = a + 1 # 1 ns + a = a * 2 # 10 ns + # Repeat n times + for _ in range(n): # 1 ns + print(0) # 5 ns +``` + +```cpp title="" +// On a particular execution platform +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // Repeat n times + for (int i = 0; i < n; i++) { // 1 ns + cout << 0 << endl; // 5 ns + } +} +``` + +```java title="" +// On a particular execution platform +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // Repeat n times + for (int i = 0; i < n; i++) { // 1 ns + System.out.println(0); // 5 ns + } +} +``` + +```csharp title="" +// On a particular execution platform +void Algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // Repeat n times + for (int i = 0; i < n; i++) { // 1 ns + Console.WriteLine(0); // 5 ns + } +} +``` + +```go title="" +// On a particular execution platform +func algorithm(n int) { + a := 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // Repeat n times + for i := 0; i < n; i++ { // 1 ns + fmt.Println(a) // 5 ns + } +} +``` + +```swift title="" +// On a particular execution platform +func algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // Repeat n times + for _ in 0 ..< n { // 1 ns + print(0) // 5 ns + } +} +``` + +```javascript title="" +// On a particular execution platform +function algorithm(n) { + var a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // Repeat n times + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```typescript title="" +// On a particular execution platform +function algorithm(n: number): void { + var a: number = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // Repeat n times + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```dart title="" +// On a particular execution platform +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // Repeat n times + for (int i = 0; i < n; i++) { // 1 ns + print(0); // 5 ns + } +} +``` + +```rust title="" +// On a particular execution platform +fn algorithm(n: i32) { + let mut a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // Repeat n times + for _ in 0..n { // 1 ns + println!("{}", 0); // 5 ns + } +} +``` + +```c title="" +// On a particular execution platform +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // Repeat n times + for (int i = 0; i < n; i++) { // 1 ns + printf("%d", 0); // 5 ns + } +} +``` + +```kotlin title="" +// On a particular execution platform +fun algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // Repeat n times + for (i in 0.. +```python title="" +# Algorithm A: constant time complexity +def algorithm_A(n: int): + print(0) +# Algorithm B: linear time complexity +def algorithm_B(n: int): + for _ in range(n): + print(0) +# Algorithm C: constant time complexity +def algorithm_C(n: int): + for _ in range(1000000): + print(0) +``` + +```cpp title="" +// Algorithm A: constant time complexity +void algorithm_A(int n) { + cout << 0 << endl; +} +// Algorithm B: linear time complexity +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + cout << 0 << endl; + } +} +// Algorithm C: constant time complexity +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + cout << 0 << endl; + } +} +``` + +```java title="" +// Algorithm A: constant time complexity +void algorithm_A(int n) { + System.out.println(0); +} +// Algorithm B: linear time complexity +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + System.out.println(0); + } +} +// Algorithm C: constant time complexity +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + System.out.println(0); + } +} +``` + +```csharp title="" +// Algorithm A: constant time complexity +void AlgorithmA(int n) { + Console.WriteLine(0); +} +// Algorithm B: linear time complexity +void AlgorithmB(int n) { + for (int i = 0; i < n; i++) { + Console.WriteLine(0); + } +} +// Algorithm C: constant time complexity +void AlgorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + Console.WriteLine(0); + } +} +``` + +```go title="" +// Algorithm A: constant time complexity +func algorithm_A(n int) { + fmt.Println(0) +} +// Algorithm B: linear time complexity +func algorithm_B(n int) { + for i := 0; i < n; i++ { + fmt.Println(0) + } +} +// Algorithm C: constant time complexity +func algorithm_C(n int) { + for i := 0; i < 1000000; i++ { + fmt.Println(0) + } +} +``` + +```swift title="" +// Algorithm A: constant time complexity +func algorithmA(n: Int) { + print(0) +} + +// Algorithm B: linear time complexity +func algorithmB(n: Int) { + for _ in 0 ..< n { + print(0) + } +} + +// Algorithm C: constant time complexity +func algorithmC(n: Int) { + for _ in 0 ..< 1_000_000 { + print(0) + } +} +``` + +```javascript title="" +// Algorithm A: constant time complexity +function algorithm_A(n) { + console.log(0); +} +// Algorithm B: linear time complexity +function algorithm_B(n) { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// Algorithm C: constant time complexity +function algorithm_C(n) { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} + +``` + +```typescript title="" +// Algorithm A: constant time complexity +function algorithm_A(n: number): void { + console.log(0); +} +// Algorithm B: linear time complexity +function algorithm_B(n: number): void { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// Algorithm C: constant time complexity +function algorithm_C(n: number): void { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} +``` + +```dart title="" +// Algorithm A: constant time complexity +void algorithmA(int n) { + print(0); +} +// Algorithm B: linear time complexity +void algorithmB(int n) { + for (int i = 0; i < n; i++) { + print(0); + } +} +// Algorithm C: constant time complexity +void algorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + print(0); + } +} +``` + +```rust title="" +// Algorithm A: constant time complexity +fn algorithm_A(n: i32) { + println!("{}", 0); +} +// Algorithm B: linear time complexity +fn algorithm_B(n: i32) { + for _ in 0..n { + println!("{}", 0); + } +} +// Algorithm C: constant time complexity +fn algorithm_C(n: i32) { + for _ in 0..1000000 { + println!("{}", 0); + } +} +``` + +```c title="" +// Algorithm A: constant time complexity +void algorithm_A(int n) { + printf("%d", 0); +} +// Algorithm B: linear time complexity +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + printf("%d", 0); + } +} +// Algorithm C: constant time complexity +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + printf("%d", 0); + } +} +``` + +```kotlin title="" +// Algorithm A: constant time complexity +fun algoritm_A(n: Int) { + println(0) +} +// Algorithm B: linear time complexity +fun algorithm_B(n: Int) { + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +1 + a = a + 1 # +1 + a = a * 2 # +1 + # Repeat n times + for i in range(n): # +1 + print(0) # +1 +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Repeat n times + for (int i = 0; i < n; i++) { // +1 (i ++ executes each iteration) + cout << 0 << endl; // +1 + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Repeat n times + for (int i = 0; i < n; i++) { // +1 (i ++ executes each iteration) + System.out.println(0); // +1 + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Repeat n times + for (int i = 0; i < n; i++) { // +1 (i ++ executes each iteration) + Console.WriteLine(0); // +1 + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // Repeat n times + for i := 0; i < n; i++ { // +1 + fmt.Println(a) // +1 + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // Repeat n times + for _ in 0 ..< n { // +1 + print(0) // +1 + } +} +``` + +```javascript title="" +function algorithm(n) { + var a = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // Repeat n times + for(let i = 0; i < n; i++){ // +1 (i ++ executes each iteration) + console.log(0); // +1 + } +} +``` + +```typescript title="" +function algorithm(n: number): void{ + var a: number = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // Repeat n times + for(let i = 0; i < n; i++){ // +1 (i ++ executes each iteration) + console.log(0); // +1 + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Repeat n times + for (int i = 0; i < n; i++) { // +1 (i ++ executes each iteration) + print(0); // +1 + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + + // Repeat n times + for _ in 0..n { // +1 (i ++ executes each iteration) + println!("{}", 0); // +1 + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Repeat n times + for (int i = 0; i < n; i++) { // +1 (i ++ executes each iteration) + printf("%d", 0); // +1 + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // Repeat n times + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +0 (shortcut 1) + a = a + n # +0 (shortcut 1) + # +n (shortcut 2) + for i in range(5 * n + 1): + print(0) + # +n*n (shortcut 3) + for i in range(2 * n): + for j in range(n + 1): + print(0) +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +0 (shortcut 1) + a = a + n; // +0 (shortcut 1) + // +n (shortcut 2) + for (int i = 0; i < 5 * n + 1; i++) { + cout << 0 << endl; + } + // +n*n (shortcut 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + cout << 0 << endl; + } + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +0 (shortcut 1) + a = a + n; // +0 (shortcut 1) + // +n (shortcut 2) + for (int i = 0; i < 5 * n + 1; i++) { + System.out.println(0); + } + // +n*n (shortcut 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + System.out.println(0); + } + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +0 (shortcut 1) + a = a + n; // +0 (shortcut 1) + // +n (shortcut 2) + for (int i = 0; i < 5 * n + 1; i++) { + Console.WriteLine(0); + } + // +n*n (shortcut 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + Console.WriteLine(0); + } + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +0 (shortcut 1) + a = a + n // +0 (shortcut 1) + // +n (shortcut 2) + for i := 0; i < 5 * n + 1; i++ { + fmt.Println(0) + } + // +n*n (shortcut 3) + for i := 0; i < 2 * n; i++ { + for j := 0; j < n + 1; j++ { + fmt.Println(0) + } + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +0 (shortcut 1) + a = a + n // +0 (shortcut 1) + // +n (shortcut 2) + for _ in 0 ..< (5 * n + 1) { + print(0) + } + // +n*n (shortcut 3) + for _ in 0 ..< (2 * n) { + for _ in 0 ..< (n + 1) { + print(0) + } + } +} +``` + +```javascript title="" +function algorithm(n) { + let a = 1; // +0 (shortcut 1) + a = a + n; // +0 (shortcut 1) + // +n (shortcut 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n (shortcut 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + let a = 1; // +0 (shortcut 1) + a = a + n; // +0 (shortcut 1) + // +n (shortcut 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n (shortcut 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +0 (shortcut 1) + a = a + n; // +0 (shortcut 1) + // +n (shortcut 2) + for (int i = 0; i < 5 * n + 1; i++) { + print(0); + } + // +n*n (shortcut 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + print(0); + } + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +0 (shortcut 1) + a = a + n; // +0 (shortcut 1) + + // +n (shortcut 2) + for i in 0..(5 * n + 1) { + println!("{}", 0); + } + + // +n*n (shortcut 3) + for i in 0..(2 * n) { + for j in 0..(n + 1) { + println!("{}", 0); + } + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +0 (shortcut 1) + a = a + n; // +0 (shortcut 1) + // +n (shortcut 2) + for (int i = 0; i < 5 * n + 1; i++) { + printf("%d", 0); + } + // +n*n (shortcut 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + printf("%d", 0); + } + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +0 (shortcut 1) + a = a + n // +0 (shortcut 1) + // +n (shortcut 2) + for (i in 0..<5 * n + 1) { + println(0) + } + // +n*n (shortcut 3) + for (i in 0..<2 * n) { + for (j in 0.. +```python title="" +# Initialize arrays with different basic data types +numbers: list[int] = [0] * 5 +decimals: list[float] = [0.0] * 5 +# A Python character is a string of length 1 +characters: list[str] = ['0'] * 5 +bools: list[bool] = [False] * 5 +# Python lists can hold different basic data types and object references +data = [0, 0.0, 'a', False, ListNode(0)] +``` + +```cpp title="" +// Initialize arrays with different basic data types +int numbers[5]; +float decimals[5]; +char characters[5]; +bool bools[5]; +``` + +```java title="" +// Initialize arrays with different basic data types +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +boolean[] bools = new boolean[5]; +``` + +```csharp title="" +// Initialize arrays with different basic data types +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +bool[] bools = new bool[5]; +``` + +```go title="" +// Initialize arrays with different basic data types +var numbers = [5]int{} +var decimals = [5]float64{} +var characters = [5]byte{} +var bools = [5]bool{} +``` + +```swift title="" +// Initialize arrays with different basic data types +let numbers = Array(repeating: 0, count: 5) +let decimals = Array(repeating: 0.0, count: 5) +let characters: [Character] = Array(repeating: "a", count: 5) +let bools = Array(repeating: false, count: 5) +``` + +```javascript title="" +// JavaScript arrays can hold different basic data types and objects +const array = [0, 0.0, 'a', false]; +``` + +```typescript title="" +// Initialize arrays with different basic data types +const numbers: number[] = []; +const characters: string[] = []; +const bools: boolean[] = []; +``` + +```dart title="" +// Initialize arrays with different basic data types +List numbers = List.filled(5, 0); +List decimals = List.filled(5, 0.0); +List characters = List.filled(5, 'a'); +List bools = List.filled(5, false); +``` + +```rust title="" +// Initialize arrays with different basic data types +let numbers: Vec = vec![0; 5]; +let decimals: Vec = vec![0.0; 5]; +let characters: Vec = vec!['0'; 5]; +let bools: Vec = vec![false; 5]; +``` + +```c title="" +// Initialize arrays with different basic data types +int numbers[10]; +float decimals[10]; +char characters[10]; +bool bools[10]; +``` + +```kotlin title="" +// Initialize arrays with different basic data types +val numbers = IntArray(5) +val decinals = FloatArray(5) +val characters = CharArray(5) +val bools = BooleanArray(5) +``` + +```ruby title="" +# Ruby arrays can hold different basic data types and object references +data = [0, 0.0, 'a', false, ListNode(0)] +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked%20list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20successor%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20arrays%20with%20different%20basic%20data%20types%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20%2A%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20%2A%205%0A%20%20%20%20%23%20A%20Python%20character%20is%20a%20string%20of%20length%201%0A%20%20%20%20characters%20%3D%20%5B%270%27%5D%20%2A%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20%2A%205%0A%20%20%20%20%23%20Python%20lists%20can%20hold%20different%20basic%20data%20types%20and%20object%20references%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20%27a%27%2C%20False%2C%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_hashing/hash_algorithm.md b/en/codes/snippets/chapter_hashing/hash_algorithm.md new file mode 100644 index 000000000..8c702b736 --- /dev/null +++ b/en/codes/snippets/chapter_hashing/hash_algorithm.md @@ -0,0 +1,263 @@ + +```python title="built_in_hash.py" +num = 3 +hash_num = hash(num) +# The hash of the integer 3 is 3 + +bol = True +hash_bol = hash(bol) +# The hash of the Boolean True is 1 + +dec = 3.14159 +hash_dec = hash(dec) +# The hash of the floating-point number 3.14159 is 326484311674566659 + +str = "Hello 算法" +hash_str = hash(str) +# The hash of the string “Hello 算法” is 4617003410720528961 + +tup = (12836, "小哈") +hash_tup = hash(tup) +# The hash of the tuple (12836, '小哈') is 1029005403108185979 + +obj = ListNode(0) +hash_obj = hash(obj) +# The hash of the node object is 274267521 +``` + +```cpp title="built_in_hash.cpp" +int num = 3; +size_t hashNum = hash()(num); +// The hash of the integer 3 is 3 + +bool bol = true; +size_t hashBol = hash()(bol); +// The hash of the Boolean 1 is 1 + +double dec = 3.14159; +size_t hashDec = hash()(dec); +// The hash of the floating-point number 3.14159 is 4614256650576692846 + +string str = "Hello 算法"; +size_t hashStr = hash()(str); +// The hash of the string “Hello 算法” is 15466937326284535026 + +// In C++, built-in std::hash() provides hashing only for basic data types +// Hashing for arrays and objects must be implemented separately +``` + +```java title="built_in_hash.java" +int num = 3; +int hashNum = Integer.hashCode(num); +// The hash of the integer 3 is 3 + +boolean bol = true; +int hashBol = Boolean.hashCode(bol); +// The hash of the Boolean true is 1231 + +double dec = 3.14159; +int hashDec = Double.hashCode(dec); +// The hash of the floating-point number 3.14159 is -1340954729 + +String str = "Hello 算法"; +int hashStr = str.hashCode(); +// The hash of the string “Hello 算法” is -727081396 + +Object[] arr = { 12836, "小哈" }; +int hashTup = Arrays.hashCode(arr); +// The hash of the array [12836, 小哈] is 1151158 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode(); +// The hash of the node object utils.ListNode@7dc5e7b4 is 2110121908 +``` + +```csharp title="built_in_hash.cs" +int num = 3; +int hashNum = num.GetHashCode(); +// The hash of the integer 3 is 3; + +bool bol = true; +int hashBol = bol.GetHashCode(); +// The hash of the Boolean true is 1; + +double dec = 3.14159; +int hashDec = dec.GetHashCode(); +// The hash of the floating-point number 3.14159 is -1340954729; + +string str = "Hello 算法"; +int hashStr = str.GetHashCode(); +// The hash of the string “Hello 算法” is -586107568; + +object[] arr = [12836, "小哈"]; +int hashTup = arr.GetHashCode(); +// The hash of the array [12836, 小哈] is 42931033; + +ListNode obj = new(0); +int hashObj = obj.GetHashCode(); +// The hash of the node object 0 is 39053774; +``` + +```go title="built_in_hash.go" +// Go provides no built-in hash-code function +``` + +```swift title="built_in_hash.swift" +let num = 3 +let hashNum = num.hashValue +// The hash of the integer 3 is 9047044699613009734 + +let bol = true +let hashBol = bol.hashValue +// The hash of the Boolean true is -4431640247352757451 + +let dec = 3.14159 +let hashDec = dec.hashValue +// The hash of the floating-point number 3.14159 is -2465384235396674631 + +let str = "Hello 算法" +let hashStr = str.hashValue +// The hash of the string “Hello 算法” is -7850626797806988787 + +let arr = [AnyHashable(12836), AnyHashable("小哈")] +let hashTup = arr.hashValue +// The hash of the array [AnyHashable(12836), AnyHashable("小哈")] is -2308633508154532996 + +let obj = ListNode(x: 0) +let hashObj = obj.hashValue +// The hash of the node object utils.ListNode is -2434780518035996159 +``` + +```javascript title="built_in_hash.js" +// JavaScript provides no built-in hash-code function +``` + +```typescript title="built_in_hash.ts" +// TypeScript provides no built-in hash-code function +``` + +```dart title="built_in_hash.dart" +int num = 3; +int hashNum = num.hashCode; +// The hash of the integer 3 is 34803 + +bool bol = true; +int hashBol = bol.hashCode; +// The hash of the Boolean true is 1231 + +double dec = 3.14159; +int hashDec = dec.hashCode; +// The hash of the floating-point number 3.14159 is 2570631074981783 + +String str = "Hello 算法"; +int hashStr = str.hashCode; +// The hash of the string “Hello 算法” is 468167534 + +List arr = [12836, "小哈"]; +int hashArr = arr.hashCode; +// The hash of the array [12836, 小哈] is 976512528 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode; +// The hash of the node object Instance of 'ListNode' is 1033450432 +``` + +```rust title="built_in_hash.rs" +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +let num = 3; +let mut num_hasher = DefaultHasher::new(); +num.hash(&mut num_hasher); +let hash_num = num_hasher.finish(); +// The hash of the integer 3 is 568126464209439262 + +let bol = true; +let mut bol_hasher = DefaultHasher::new(); +bol.hash(&mut bol_hasher); +let hash_bol = bol_hasher.finish(); +// The hash of the Boolean true is 4952851536318644461 + +let dec: f32 = 3.14159; +let mut dec_hasher = DefaultHasher::new(); +dec.to_bits().hash(&mut dec_hasher); +let hash_dec = dec_hasher.finish(); +// The hash of the floating-point number 3.14159 is 2566941990314602357 + +let str = "Hello 算法"; +let mut str_hasher = DefaultHasher::new(); +str.hash(&mut str_hasher); +let hash_str = str_hasher.finish(); +// The hash of the string “Hello 算法” is 16092673739211250988 + +let arr = (&12836, &"小哈"); +let mut tup_hasher = DefaultHasher::new(); +arr.hash(&mut tup_hasher); +let hash_tup = tup_hasher.finish(); +// The hash of the tuple (12836, "小哈") is 1885128010422702749 + +let node = ListNode::new(42); +let mut hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut hasher); +let hash = hasher.finish(); +// The hash of the node object RefCell { value: ListNode { val: 42, next: None } } is 15387811073369036852 +``` + +```c title="built_in_hash.c" +// C provides no built-in hash-code function +``` + +```kotlin title="built_in_hash.kt" +val num = 3 +val hashNum = num.hashCode() +// The hash of the integer 3 is 3 + +val bol = true +val hashBol = bol.hashCode() +// The hash of the Boolean true is 1231 + +val dec = 3.14159 +val hashDec = dec.hashCode() +// The hash of the floating-point number 3.14159 is -1340954729 + +val str = "Hello 算法" +val hashStr = str.hashCode() +// The hash of the string “Hello 算法” is -727081396 + +val arr = arrayOf(12836, "小哈") +val hashTup = arr.hashCode() +// The hash of the array [12836, 小哈] is 189568618 + +val obj = ListNode(0) +val hashObj = obj.hashCode() +// The hash of the node object utils.ListNode@1d81eb93 is 495053715 +``` + +```ruby title="built_in_hash.rb" +num = 3 +hash_num = num.hash +# The hash of the integer 3 is -4385856518450339636 + +bol = true +hash_bol = bol.hash +# The hash of the Boolean true is -1617938112149317027 + +dec = 3.14159 +hash_dec = dec.hash +# The hash of the floating-point number 3.14159 is -1479186995943067893 + +str = "Hello 算法" +hash_str = str.hash +# The hash of the string “Hello 算法” is -4075943250025831763 + +tup = [12836, '小哈'] +hash_tup = tup.hash +# The hash of the tuple (12836, '小哈') is 1999544809202288822 + +obj = ListNode.new(0) +hash_obj = obj.hash +# The hash of the node object # is 4302940560806366381 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked-list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20next%20node%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20integer%203%20is%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20Boolean%20True%20is%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20floating-point%20number%203.14159%20is%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20string%20%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%20is%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20tuple%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20is%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20node%20object%20%3CListNode%20object%20at%200x1058fd810%3E%20is%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_hashing/hash_map.md b/en/codes/snippets/chapter_hashing/hash_map.md new file mode 100644 index 000000000..c1e4a28cf --- /dev/null +++ b/en/codes/snippets/chapter_hashing/hash_map.md @@ -0,0 +1,457 @@ + +```python title="hash_map.py" +# Initialize a hash table +hmap: dict = {} + +# Insertion +# Add key-value pairs (key, value) to the hash table +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +# Lookup +# Look up key in the hash table to obtain value +name: str = hmap[15937] + +# Deletion +# Remove a key-value pair (key, value) from the hash table +hmap.pop(10583) +``` + +```cpp title="hash_map.cpp" +/* Initialize a hash table */ +unordered_map map; + +/* Insertion */ +// Add key-value pairs (key, value) to the hash table +map[12836] = "小哈"; +map[15937] = "小啰"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鸭"; + +/* Lookup */ +// Look up key in the hash table to obtain value +string name = map[15937]; + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +map.erase(10583); +``` + +```java title="hash_map.java" +/* Initialize a hash table */ +Map map = new HashMap<>(); + +/* Insertion */ +// Add key-value pairs (key, value) to the hash table +map.put(12836, "小哈"); +map.put(15937, "小啰"); +map.put(16750, "小算"); +map.put(13276, "小法"); +map.put(10583, "小鸭"); + +/* Lookup */ +// Look up key in the hash table to obtain value +String name = map.get(15937); + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +map.remove(10583); +``` + +```csharp title="hash_map.cs" +/* Initialize a hash table */ +Dictionary map = new() { + /* Insertion */ + // Add key-value pairs (key, value) to the hash table + { 12836, "小哈" }, + { 15937, "小啰" }, + { 16750, "小算" }, + { 13276, "小法" }, + { 10583, "小鸭" } +}; + +/* Lookup */ +// Look up key in the hash table to obtain value +string name = map[15937]; + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +map.Remove(10583); +``` + +```go title="hash_map_test.go" +/* Initialize a hash table */ +hmap := make(map[int]string) + +/* Insertion */ +// Add key-value pairs (key, value) to the hash table +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +/* Lookup */ +// Look up key in the hash table to obtain value +name := hmap[15937] + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +delete(hmap, 10583) +``` + +```swift title="hash_map.swift" +/* Initialize a hash table */ +var map: [Int: String] = [:] + +/* Insertion */ +// Add key-value pairs (key, value) to the hash table +map[12836] = "小哈" +map[15937] = "小啰" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鸭" + +/* Lookup */ +// Look up key in the hash table to obtain value +let name = map[15937]! + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +map.removeValue(forKey: 10583) +``` + +```javascript title="hash_map.js" +/* Initialize a hash table */ +const map = new Map(); +/* Insertion */ +// Add key-value pairs (key, value) to the hash table +map.set(12836, '小哈'); +map.set(15937, '小啰'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鸭'); + +/* Lookup */ +// Look up key in the hash table to obtain value +let name = map.get(15937); + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +map.delete(10583); +``` + +```typescript title="hash_map.ts" +/* Initialize a hash table */ +const map = new Map(); +/* Insertion */ +// Add key-value pairs (key, value) to the hash table +map.set(12836, '小哈'); +map.set(15937, '小啰'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鸭'); +console.info('\nAfter insertion, the hash table is\nKey -> Value'); +console.info(map); + +/* Lookup */ +// Look up key in the hash table to obtain value +let name = map.get(15937); +console.info('\nLooking up student ID 15937 gives the name ' + name); + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +map.delete(10583); +console.info('\nAfter deleting 10583, the hash table is\nKey -> Value'); +console.info(map); +``` + +```dart title="hash_map.dart" +/* Initialize a hash table */ +Map map = {}; + +/* Insertion */ +// Add key-value pairs (key, value) to the hash table +map[12836] = "小哈"; +map[15937] = "小啰"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鸭"; + +/* Lookup */ +// Look up key in the hash table to obtain value +String name = map[15937]; + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +map.remove(10583); +``` + +```rust title="hash_map.rs" +use std::collections::HashMap; + +/* Initialize a hash table */ +let mut map: HashMap = HashMap::new(); + +/* Insertion */ +// Add key-value pairs (key, value) to the hash table +map.insert(12836, "小哈".to_string()); +map.insert(15937, "小啰".to_string()); +map.insert(16750, "小算".to_string()); +map.insert(13279, "小法".to_string()); +map.insert(10583, "小鸭".to_string()); + +/* Lookup */ +// Look up key in the hash table to obtain value +let _name: Option<&String> = map.get(&15937); + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +let _removed_value: Option = map.remove(&10583); +``` + +```c title="hash_map.c" +// C provides no built-in hash table +``` + +```kotlin title="hash_map.kt" +/* Initialize a hash table */ +val map = HashMap() + +/* Insertion */ +// Add key-value pairs (key, value) to the hash table +map[12836] = "小哈" +map[15937] = "小啰" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鸭" + +/* Lookup */ +// Look up key in the hash table to obtain value +val name = map[15937] + +/* Deletion */ +// Remove a key-value pair (key, value) from the hash table +map.remove(10583) +``` + +```ruby title="hash_map.rb" +# Initialize a hash table +hmap = {} + +# Insertion +# Add key-value pairs (key, value) to the hash table +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +# Lookup +# Look up key in the hash table to obtain value +name = hmap[15937] + +# Deletion +# Remove a key-value pair (key, value) from the hash table +hmap.delete(10583) +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20hash%20table%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20Insertion%0A%20%20%20%20%23%20Add%20key-value%20pairs%20%28key%2C%20value%29%20to%20the%20hash%20table%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20Lookup%0A%20%20%20%20%23%20Look%20up%20key%20in%20the%20hash%20table%20to%20obtain%20value%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Deletion%0A%20%20%20%20%23%20Remove%20a%20key-value%20pair%20%28key%2C%20value%29%20from%20the%20hash%20table%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="hash_map.py" +# Traverse the hash table +# Traverse key-value pairs: key->value +for key, value in hmap.items(): + print(key, "->", value) +# Traverse keys only: key +for key in hmap.keys(): + print(key) +# Traverse values only: value +for value in hmap.values(): + print(value) +``` + +```cpp title="hash_map.cpp" +/* Traverse the hash table */ +// Traverse key-value pairs: key->value +for (auto kv: map) { + cout << kv.first << " -> " << kv.second << endl; +} +// Use an iterator to traverse key->value pairs +for (auto iter = map.begin(); iter != map.end(); iter++) { + cout << iter->first << "->" << iter->second << endl; +} +``` + +```java title="hash_map.java" +/* Traverse the hash table */ +// Traverse key-value pairs: key->value +for (Map.Entry kv: map.entrySet()) { + System.out.println(kv.getKey() + " -> " + kv.getValue()); +} +// Traverse keys only: key +for (int key: map.keySet()) { + System.out.println(key); +} +// Traverse values only: value +for (String val: map.values()) { + System.out.println(val); +} +``` + +```csharp title="hash_map.cs" +/* Traverse the hash table */ +// Traverse key-value pairs: Key->Value +foreach (var kv in map) { + Console.WriteLine(kv.Key + " -> " + kv.Value); +} +// Traverse keys only: key +foreach (int key in map.Keys) { + Console.WriteLine(key); +} +// Traverse values only: value +foreach (string val in map.Values) { + Console.WriteLine(val); +} +``` + +```go title="hash_map_test.go" +/* Traverse the hash table */ +// Traverse key-value pairs: key->value +for key, value := range hmap { + fmt.Println(key, "->", value) +} +// Traverse keys only: key +for key := range hmap { + fmt.Println(key) +} +// Traverse values only: value +for _, value := range hmap { + fmt.Println(value) +} +``` + +```swift title="hash_map.swift" +/* Traverse the hash table */ +// Traverse key-value pairs: Key->Value +for (key, value) in map { + print("\(key) -> \(value)") +} +// Traverse keys only: Key +for key in map.keys { + print(key) +} +// Traverse values only: Value +for value in map.values { + print(value) +} +``` + +```javascript title="hash_map.js" +/* Traverse the hash table */ +console.info('\nTraverse key-value pairs: Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\nTraverse keys only: Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\nTraverse values only: Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```typescript title="hash_map.ts" +/* Traverse the hash table */ +console.info('\nTraverse key-value pairs: Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\nTraverse keys only: Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\nTraverse values only: Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```dart title="hash_map.dart" +/* Traverse the hash table */ +// Traverse key-value pairs: Key->Value +map.forEach((key, value) { + print('$key -> $value'); +}); + +// Traverse keys only: Key +map.keys.forEach((key) { + print(key); +}); + +// Traverse values only: Value +map.values.forEach((value) { + print(value); +}); +``` + +```rust title="hash_map.rs" +/* Traverse the hash table */ +// Traverse key-value pairs: Key->Value +for (key, value) in &map { + println!("{key} -> {value}"); +} + +// Traverse keys only: Key +for key in map.keys() { + println!("{key}"); +} + +// Traverse values only: Value +for value in map.values() { + println!("{value}"); +} +``` + +```c title="hash_map.c" +// C provides no built-in hash table +``` + +```kotlin title="hash_map.kt" +/* Traverse the hash table */ +// Traverse key-value pairs: key->value +for ((key, value) in map) { + println("$key -> $value") +} +// Traverse keys only: key +for (key in map.keys) { + println(key) +} +// Traverse values only: value +for (_val in map.values) { + println(_val) +} +``` + +```ruby title="hash_map.rb" +# Traverse the hash table +# Traverse key-value pairs: key->value +hmap.entries.each { |key, value| puts "#{key} -> #{value}" } + +# Traverse keys only: key +hmap.keys.each { |key| puts key } + +# Traverse values only: value +hmap.values.each { |val| puts val } +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20hash%20table%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20Insertion%0A%20%20%20%20%23%20Add%20key-value%20pairs%20%28key%2C%20value%29%20to%20the%20hash%20table%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20Traverse%20the%20hash%20table%0A%20%20%20%20%23%20Traverse%20key-value%20pairs%3A%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20Traverse%20keys%20only%3A%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20Traverse%20values%20only%3A%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_heap/heap.md b/en/codes/snippets/chapter_heap/heap.md new file mode 100644 index 000000000..89fb6310e --- /dev/null +++ b/en/codes/snippets/chapter_heap/heap.md @@ -0,0 +1,350 @@ + +```python title="heap.py" +# Initialize a min heap +min_heap, flag = [], 1 +# Initialize a max heap +max_heap, flag = [], -1 + +# Python's heapq module implements a min heap by default +# Negate elements before insertion to reverse their order and implement a max heap +# Here, flag = 1 gives a min heap and flag = -1 gives a max heap + +# Insert elements into the heap +heapq.heappush(max_heap, flag * 1) +heapq.heappush(max_heap, flag * 3) +heapq.heappush(max_heap, flag * 2) +heapq.heappush(max_heap, flag * 5) +heapq.heappush(max_heap, flag * 4) + +# Access the root element +peek: int = flag * max_heap[0] # 5 + +# Remove root elements +# Removed elements form a descending sequence +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 + +# Get the heap size +size: int = len(max_heap) + +# Check whether the heap is empty +is_empty: bool = not max_heap + +# Build a heap from a list +min_heap: list[int] = [1, 3, 2, 5, 4] +heapq.heapify(min_heap) +``` + +```cpp title="heap.cpp" +/* Initialize a heap */ +// Initialize a min heap +priority_queue, greater> minHeap; +// Initialize a max heap +priority_queue, less> maxHeap; + +/* Insert elements into the heap */ +maxHeap.push(1); +maxHeap.push(3); +maxHeap.push(2); +maxHeap.push(5); +maxHeap.push(4); + +/* Access the root element */ +int peek = maxHeap.top(); // 5 + +/* Remove root elements */ +// Removed elements form a descending sequence +maxHeap.pop(); // 5 +maxHeap.pop(); // 4 +maxHeap.pop(); // 3 +maxHeap.pop(); // 2 +maxHeap.pop(); // 1 + +/* Get the heap size */ +int size = maxHeap.size(); + +/* Check whether the heap is empty */ +bool isEmpty = maxHeap.empty(); + +/* Build a heap from a list */ +vector input{1, 3, 2, 5, 4}; +priority_queue, greater> minHeap(input.begin(), input.end()); +``` + +```java title="heap.java" +/* Initialize a heap */ +// Initialize a min heap +Queue minHeap = new PriorityQueue<>(); +// Initialize a max heap by changing the Comparator with a lambda expression +Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + +/* Insert elements into the heap */ +maxHeap.offer(1); +maxHeap.offer(3); +maxHeap.offer(2); +maxHeap.offer(5); +maxHeap.offer(4); + +/* Access the root element */ +int peek = maxHeap.peek(); // 5 + +/* Remove root elements */ +// Removed elements form a descending sequence +peek = maxHeap.poll(); // 5 +peek = maxHeap.poll(); // 4 +peek = maxHeap.poll(); // 3 +peek = maxHeap.poll(); // 2 +peek = maxHeap.poll(); // 1 + +/* Get the heap size */ +int size = maxHeap.size(); + +/* Check whether the heap is empty */ +boolean isEmpty = maxHeap.isEmpty(); + +/* Build a heap from a list */ +minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +``` + +```csharp title="heap.cs" +/* Initialize a heap */ +// Initialize a min heap +PriorityQueue minHeap = new(); +// Initialize a max heap by changing the Comparer with a lambda expression +PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + +/* Insert elements into the heap */ +maxHeap.Enqueue(1, 1); +maxHeap.Enqueue(3, 3); +maxHeap.Enqueue(2, 2); +maxHeap.Enqueue(5, 5); +maxHeap.Enqueue(4, 4); + +/* Access the root element */ +int peek = maxHeap.Peek();//5 + +/* Remove root elements */ +// Removed elements form a descending sequence +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 + +/* Get the heap size */ +int size = maxHeap.Count; + +/* Check whether the heap is empty */ +bool isEmpty = maxHeap.Count == 0; + +/* Build a heap from a list */ +minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +``` + +```go title="heap.go" +// In Go, implement heap.Interface to build an integer max heap +// Implementing heap.Interface also requires implementing sort.Interface +type intHeap []any + +// Push implements the heap.Interface method for inserting an element +func (h *intHeap) Push(x any) { + // Push and Pop use pointer receivers + // because they change the slice length as well as its contents. + *h = append(*h, x.(int)) +} + +// Pop implements the heap.Interface method used to remove the root element +func (h *intHeap) Pop() any { + // The element to remove has been placed at the end + last := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return last +} + +// Len implements a sort.Interface method +func (h *intHeap) Len() int { + return len(*h) +} + +// Less implements a sort.Interface method +func (h *intHeap) Less(i, j int) bool { + // For a min heap, change this to a less-than comparison + return (*h)[i].(int) > (*h)[j].(int) +} + +// Swap implements a sort.Interface method +func (h *intHeap) Swap(i, j int) { + (*h)[i], (*h)[j] = (*h)[j], (*h)[i] +} + +// Top returns the root element +func (h *intHeap) Top() any { + return (*h)[0] +} + +/* Driver Code */ +func TestHeap(t *testing.T) { + /* Initialize a heap */ + // Initialize a max heap + maxHeap := &intHeap{} + heap.Init(maxHeap) + /* Insert elements into the heap */ + // Call the heap.Interface methods to add elements + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 4) + heap.Push(maxHeap, 5) + + /* Access the root element */ + top := maxHeap.Top() + fmt.Printf("The root element is %d\n", top) + + /* Remove root elements */ + // Call the heap.Interface methods to remove elements + heap.Pop(maxHeap) // 5 + heap.Pop(maxHeap) // 4 + heap.Pop(maxHeap) // 3 + heap.Pop(maxHeap) // 2 + heap.Pop(maxHeap) // 1 + + /* Get the heap size */ + size := len(*maxHeap) + fmt.Printf("The heap contains %d elements\n", size) + + /* Check whether the heap is empty */ + isEmpty := len(*maxHeap) == 0 + fmt.Printf("Is the heap empty: %t\n", isEmpty) +} +``` + +```swift title="heap.swift" +/* Initialize a heap */ +// Swift's Heap type supports both minimum and maximum operations and requires swift-collections +var heap = Heap() + +/* Insert elements into the heap */ +heap.insert(1) +heap.insert(3) +heap.insert(2) +heap.insert(5) +heap.insert(4) + +/* Access the root element */ +var peek = heap.max()! + +/* Remove root elements */ +peek = heap.removeMax() // 5 +peek = heap.removeMax() // 4 +peek = heap.removeMax() // 3 +peek = heap.removeMax() // 2 +peek = heap.removeMax() // 1 + +/* Get the heap size */ +let size = heap.count + +/* Check whether the heap is empty */ +let isEmpty = heap.isEmpty + +/* Build a heap from a list */ +let heap2 = Heap([1, 3, 2, 5, 4]) +``` + +```javascript title="heap.js" +// JavaScript provides no built-in Heap class +``` + +```typescript title="heap.ts" +// TypeScript provides no built-in Heap class +``` + +```dart title="heap.dart" +// Dart provides no built-in Heap class +``` + +```rust title="heap.rs" +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +/* Initialize a heap */ +// Initialize a min heap +let mut min_heap = BinaryHeap::>::new(); +// Initialize a max heap +let mut max_heap = BinaryHeap::new(); + +/* Insert elements into the heap */ +max_heap.push(1); +max_heap.push(3); +max_heap.push(2); +max_heap.push(5); +max_heap.push(4); + +/* Access the root element */ +let peek = max_heap.peek().unwrap(); // 5 + +/* Remove root elements */ +// Removed elements form a descending sequence +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 + +/* Get the heap size */ +let size = max_heap.len(); + +/* Check whether the heap is empty */ +let is_empty = max_heap.is_empty(); + +/* Build a heap from a list */ +let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +``` + +```c title="heap.c" +// C provides no built-in Heap class +``` + +```kotlin title="heap.kt" +/* Initialize a heap */ +// Initialize a min heap +var minHeap = PriorityQueue() +// Initialize a max heap by changing the Comparator with a lambda expression +val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + +/* Insert elements into the heap */ +maxHeap.offer(1) +maxHeap.offer(3) +maxHeap.offer(2) +maxHeap.offer(5) +maxHeap.offer(4) + +/* Access the root element */ +var peek = maxHeap.peek() // 5 + +/* Remove root elements */ +// Removed elements form a descending sequence +peek = maxHeap.poll() // 5 +peek = maxHeap.poll() // 4 +peek = maxHeap.poll() // 3 +peek = maxHeap.poll() // 2 +peek = maxHeap.poll() // 1 + +/* Get the heap size */ +val size = maxHeap.size + +/* Check whether the heap is empty */ +val isEmpty = maxHeap.isEmpty() + +/* Build a heap from a list */ +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +``` + +```ruby title="heap.rb" +# Ruby provides no built-in Heap class +``` + + +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20min%20heap%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20Initialize%20a%20max%20heap%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%27s%20heapq%20module%20implements%20a%20min%20heap%20by%20default%0A%20%20%20%20%23%20Negate%20elements%20before%20insertion%20to%20reverse%20their%20order%20and%20implement%20a%20max%20heap%0A%20%20%20%20%23%20Here%2C%20flag%20%3D%201%20gives%20a%20min%20heap%20and%20flag%20%3D%20-1%20gives%20a%20max%20heap%0A%20%20%20%20%0A%20%20%20%20%23%20Insert%20elements%20into%20the%20heap%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20Access%20the%20root%20element%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20Remove%20root%20elements%0A%20%20%20%20%23%20Removed%20elements%20form%20a%20descending%20sequence%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20Get%20the%20heap%20size%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20Check%20whether%20the%20heap%20is%20empty%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20Build%20a%20heap%20from%20a%20list%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_preface/suggestions.md b/en/codes/snippets/chapter_preface/suggestions.md new file mode 100644 index 000000000..2c7249180 --- /dev/null +++ b/en/codes/snippets/chapter_preface/suggestions.md @@ -0,0 +1,139 @@ + +```python title="" +"""Heading comment identifying a function, class, test case, and so on""" + +# Explanatory comment describing the code in detail + +""" +Multiline +comment +""" +``` + +```cpp title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```java title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```csharp title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```go title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```swift title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```javascript title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```typescript title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```dart title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```rust title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +// Multiline +// comment +``` + +```c title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```kotlin title="" +/* Heading comment identifying a function, class, test case, and so on */ + +// Explanatory comment describing the code in detail + +/** + * Multiline + * comment + */ +``` + +```ruby title="" +### Heading comment identifying a function, class, test case, and so on ### + +# Explanatory comment describing the code in detail + +# Multiline +# comment +``` diff --git a/en/codes/snippets/chapter_stack_and_queue/deque.md b/en/codes/snippets/chapter_stack_and_queue/deque.md new file mode 100644 index 000000000..bed0f7ba4 --- /dev/null +++ b/en/codes/snippets/chapter_stack_and_queue/deque.md @@ -0,0 +1,339 @@ + +```python title="deque.py" +from collections import deque + +# Initialize a deque +deq: deque[int] = deque() + +# Enqueue elements +deq.append(2) # Add at the rear +deq.append(5) +deq.append(4) +deq.appendleft(3) # Add at the front +deq.appendleft(1) + +# Access elements +front: int = deq[0] # Front element +rear: int = deq[-1] # Rear element + +# Dequeue elements +pop_front: int = deq.popleft() # Remove the front element +pop_rear: int = deq.pop() # Remove the rear element + +# Get the deque size +size: int = len(deq) + +# Check whether the deque is empty +is_empty: bool = len(deq) == 0 +``` + +```cpp title="deque.cpp" +/* Initialize a deque */ +deque deque; + +/* Enqueue elements */ +deque.push_back(2); // Add at the rear +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // Add at the front +deque.push_front(1); + +/* Access elements */ +int front = deque.front(); // Front element +int back = deque.back(); // Rear element + +/* Dequeue elements */ +deque.pop_front(); // Remove the front element +deque.pop_back(); // Remove the rear element + +/* Get the deque size */ +int size = deque.size(); + +/* Check whether the deque is empty */ +bool empty = deque.empty(); +``` + +```java title="deque.java" +/* Initialize a deque */ +Deque deque = new LinkedList<>(); + +/* Enqueue elements */ +deque.offerLast(2); // Add at the rear +deque.offerLast(5); +deque.offerLast(4); +deque.offerFirst(3); // Add at the front +deque.offerFirst(1); + +/* Access elements */ +int peekFirst = deque.peekFirst(); // Front element +int peekLast = deque.peekLast(); // Rear element + +/* Dequeue elements */ +int popFirst = deque.pollFirst(); // Remove the front element +int popLast = deque.pollLast(); // Remove the rear element + +/* Get the deque size */ +int size = deque.size(); + +/* Check whether the deque is empty */ +boolean isEmpty = deque.isEmpty(); +``` + +```csharp title="deque.cs" +/* Initialize a deque */ +// In C#, use a LinkedList as a deque +LinkedList deque = new(); + +/* Enqueue elements */ +deque.AddLast(2); // Add at the rear +deque.AddLast(5); +deque.AddLast(4); +deque.AddFirst(3); // Add at the front +deque.AddFirst(1); + +/* Access elements */ +int peekFirst = deque.First.Value; // Front element +int peekLast = deque.Last.Value; // Rear element + +/* Dequeue elements */ +deque.RemoveFirst(); // Remove the front element +deque.RemoveLast(); // Remove the rear element + +/* Get the deque size */ +int size = deque.Count; + +/* Check whether the deque is empty */ +bool isEmpty = deque.Count == 0; +``` + +```go title="deque_test.go" +/* Initialize a deque */ +// In Go, use a list as a deque +deque := list.New() + +/* Enqueue elements */ +deque.PushBack(2) // Add at the rear +deque.PushBack(5) +deque.PushBack(4) +deque.PushFront(3) // Add at the front +deque.PushFront(1) + +/* Access elements */ +front := deque.Front() // Front element +rear := deque.Back() // Rear element + +/* Dequeue elements */ +deque.Remove(front) // Remove the front element +deque.Remove(rear) // Remove the rear element + +/* Get the deque size */ +size := deque.Len() + +/* Check whether the deque is empty */ +isEmpty := deque.Len() == 0 +``` + +```swift title="deque.swift" +/* Initialize a deque */ +// Swift has no built-in deque class; use an Array as a deque +var deque: [Int] = [] + +/* Enqueue elements */ +deque.append(2) // Add at the rear +deque.append(5) +deque.append(4) +deque.insert(3, at: 0) // Add at the front +deque.insert(1, at: 0) + +/* Access elements */ +let peekFirst = deque.first! // Front element +let peekLast = deque.last! // Rear element + +/* Dequeue elements */ +// When using an Array, popFirst takes O(n) time +let popFirst = deque.removeFirst() // Remove the front element +let popLast = deque.removeLast() // Remove the rear element + +/* Get the deque size */ +let size = deque.count + +/* Check whether the deque is empty */ +let isEmpty = deque.isEmpty +``` + +```javascript title="deque.js" +/* Initialize a deque */ +// JavaScript has no built-in deque; use an Array instead +const deque = []; + +/* Enqueue elements */ +deque.push(2); +deque.push(5); +deque.push(4); +// Note that this is an array, so unshift() takes O(n) time +deque.unshift(3); +deque.unshift(1); + +/* Access elements */ +const peekFirst = deque[0]; +const peekLast = deque[deque.length - 1]; + +/* Dequeue elements */ +// Note that this is an array, so shift() takes O(n) time +const popFront = deque.shift(); +const popBack = deque.pop(); + +/* Get the deque size */ +const size = deque.length; + +/* Check whether the deque is empty */ +const isEmpty = size === 0; +``` + +```typescript title="deque.ts" +/* Initialize a deque */ +// TypeScript has no built-in deque; use an Array instead +const deque: number[] = []; + +/* Enqueue elements */ +deque.push(2); +deque.push(5); +deque.push(4); +// Note that this is an array, so unshift() takes O(n) time +deque.unshift(3); +deque.unshift(1); + +/* Access elements */ +const peekFirst: number = deque[0]; +const peekLast: number = deque[deque.length - 1]; + +/* Dequeue elements */ +// Note that this is an array, so shift() takes O(n) time +const popFront: number = deque.shift() as number; +const popBack: number = deque.pop() as number; + +/* Get the deque size */ +const size: number = deque.length; + +/* Check whether the deque is empty */ +const isEmpty: boolean = size === 0; +``` + +```dart title="deque.dart" +/* Initialize a deque */ +// In Dart, Queue is defined as a deque +Queue deque = Queue(); + +/* Enqueue elements */ +deque.addLast(2); // Add at the rear +deque.addLast(5); +deque.addLast(4); +deque.addFirst(3); // Add at the front +deque.addFirst(1); + +/* Access elements */ +int peekFirst = deque.first; // Front element +int peekLast = deque.last; // Rear element + +/* Dequeue elements */ +int popFirst = deque.removeFirst(); // Remove the front element +int popLast = deque.removeLast(); // Remove the rear element + +/* Get the deque size */ +int size = deque.length; + +/* Check whether the deque is empty */ +bool isEmpty = deque.isEmpty; +``` + +```rust title="deque.rs" +/* Initialize a deque */ +let mut deque: VecDeque = VecDeque::new(); + +/* Enqueue elements */ +deque.push_back(2); // Add at the rear +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // Add at the front +deque.push_front(1); + +/* Access elements */ +if let Some(front) = deque.front() { // Front element +} +if let Some(rear) = deque.back() { // Rear element +} + +/* Dequeue elements */ +if let Some(pop_front) = deque.pop_front() { // Remove the front element +} +if let Some(pop_rear) = deque.pop_back() { // Remove the rear element +} + +/* Get the deque size */ +let size = deque.len(); + +/* Check whether the deque is empty */ +let is_empty = deque.is_empty(); +``` + +```c title="deque.c" +// C provides no built-in deque +``` + +```kotlin title="deque.kt" +/* Initialize a deque */ +val deque = LinkedList() + +/* Enqueue elements */ +deque.offerLast(2) // Add at the rear +deque.offerLast(5) +deque.offerLast(4) +deque.offerFirst(3) // Add at the front +deque.offerFirst(1) + +/* Access elements */ +val peekFirst = deque.peekFirst() // Front element +val peekLast = deque.peekLast() // Rear element + +/* Dequeue elements */ +val popFirst = deque.pollFirst() // Remove the front element +val popLast = deque.pollLast() // Remove the rear element + +/* Get the deque size */ +val size = deque.size + +/* Check whether the deque is empty */ +val isEmpty = deque.isEmpty() +``` + +```ruby title="deque.rb" +# Initialize a deque +# Ruby has no built-in deque; use an Array instead +deque = [] + +# Enqueue elements +deque << 2 +deque << 5 +deque << 4 +# Note that this is an array, so Array#unshift takes O(n) time +deque.unshift(3) +deque.unshift(1) + +# Access elements +peek_first = deque.first +peek_last = deque.last + +# Dequeue elements +# Note that this is an array, so Array#shift takes O(n) time +pop_front = deque.shift +pop_back = deque.pop + +# Get the deque size +size = deque.length + +# Check whether the deque is empty +is_empty = size.zero? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20deque%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20Enqueue%20elements%0A%20%20%20%20deq.append%282%29%20%20%23%20Add%20at%20the%20rear%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20Add%20at%20the%20front%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22Deque%3A%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20Access%20elements%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20Front%20element%0A%20%20%20%20print%28%22Front%20element%3A%20front%20%3D%22%2C%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20Rear%20element%0A%20%20%20%20print%28%22Rear%20element%3A%20rear%20%3D%22%2C%20rear%29%0A%0A%20%20%20%20%23%20Dequeue%20elements%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20Remove%20the%20front%20element%0A%20%20%20%20print%28%22Element%20removed%20from%20the%20front%3A%20pop_front%20%3D%22%2C%20pop_front%29%0A%20%20%20%20print%28%22After%20removing%20from%20the%20front%3A%20deque%20%3D%22%2C%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20Remove%20the%20rear%20element%0A%20%20%20%20print%28%22Element%20removed%20from%20the%20rear%3A%20pop_rear%20%3D%22%2C%20pop_rear%29%0A%20%20%20%20print%28%22After%20removing%20from%20the%20rear%3A%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20Get%20the%20deque%20size%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22Deque%20size%3A%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20Check%20whether%20the%20deque%20is%20empty%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22Is%20the%20deque%20empty%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_stack_and_queue/queue.md b/en/codes/snippets/chapter_stack_and_queue/queue.md new file mode 100644 index 000000000..9121a06bc --- /dev/null +++ b/en/codes/snippets/chapter_stack_and_queue/queue.md @@ -0,0 +1,313 @@ + +```python title="queue.py" +from collections import deque + +# Initialize a queue +# In Python, we usually use the deque class as a queue +# Although queue.Queue() is a dedicated queue class, it is less convenient and is not recommended here +que: deque[int] = deque() + +# Enqueue elements +que.append(1) +que.append(3) +que.append(2) +que.append(5) +que.append(4) + +# Access the front element +front: int = que[0] + +# Dequeue an element +pop: int = que.popleft() + +# Get the queue size +size: int = len(que) + +# Check whether the queue is empty +is_empty: bool = len(que) == 0 +``` + +```cpp title="queue.cpp" +/* Initialize a queue */ +queue queue; + +/* Enqueue elements */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* Access the front element */ +int front = queue.front(); + +/* Dequeue an element */ +queue.pop(); + +/* Get the queue size */ +int size = queue.size(); + +/* Check whether the queue is empty */ +bool empty = queue.empty(); +``` + +```java title="queue.java" +/* Initialize a queue */ +Queue queue = new LinkedList<>(); + +/* Enqueue elements */ +queue.offer(1); +queue.offer(3); +queue.offer(2); +queue.offer(5); +queue.offer(4); + +/* Access the front element */ +int peek = queue.peek(); + +/* Dequeue an element */ +int pop = queue.poll(); + +/* Get the queue size */ +int size = queue.size(); + +/* Check whether the queue is empty */ +boolean isEmpty = queue.isEmpty(); +``` + +```csharp title="queue.cs" +/* Initialize a queue */ +Queue queue = new(); + +/* Enqueue elements */ +queue.Enqueue(1); +queue.Enqueue(3); +queue.Enqueue(2); +queue.Enqueue(5); +queue.Enqueue(4); + +/* Access the front element */ +int peek = queue.Peek(); + +/* Dequeue an element */ +int pop = queue.Dequeue(); + +/* Get the queue size */ +int size = queue.Count; + +/* Check whether the queue is empty */ +bool isEmpty = queue.Count == 0; +``` + +```go title="queue_test.go" +/* Initialize a queue */ +// In Go, use a list as a queue +queue := list.New() + +/* Enqueue elements */ +queue.PushBack(1) +queue.PushBack(3) +queue.PushBack(2) +queue.PushBack(5) +queue.PushBack(4) + +/* Access the front element */ +peek := queue.Front() + +/* Dequeue an element */ +pop := queue.Front() +queue.Remove(pop) + +/* Get the queue size */ +size := queue.Len() + +/* Check whether the queue is empty */ +isEmpty := queue.Len() == 0 +``` + +```swift title="queue.swift" +/* Initialize a queue */ +// Swift has no built-in queue class; use an Array as a queue +var queue: [Int] = [] + +/* Enqueue elements */ +queue.append(1) +queue.append(3) +queue.append(2) +queue.append(5) +queue.append(4) + +/* Access the front element */ +let peek = queue.first! + +/* Dequeue an element */ +// Because this is an array, removeFirst takes O(n) time +let pop = queue.removeFirst() + +/* Get the queue size */ +let size = queue.count + +/* Check whether the queue is empty */ +let isEmpty = queue.isEmpty +``` + +```javascript title="queue.js" +/* Initialize a queue */ +// JavaScript has no built-in queue; use an Array as a queue +const queue = []; + +/* Enqueue elements */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* Access the front element */ +const peek = queue[0]; + +/* Dequeue an element */ +// The underlying structure is an array, so shift() takes O(n) time +const pop = queue.shift(); + +/* Get the queue size */ +const size = queue.length; + +/* Check whether the queue is empty */ +const empty = queue.length === 0; +``` + +```typescript title="queue.ts" +/* Initialize a queue */ +// TypeScript has no built-in queue; use an Array as a queue +const queue: number[] = []; + +/* Enqueue elements */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* Access the front element */ +const peek = queue[0]; + +/* Dequeue an element */ +// The underlying structure is an array, so shift() takes O(n) time +const pop = queue.shift(); + +/* Get the queue size */ +const size = queue.length; + +/* Check whether the queue is empty */ +const empty = queue.length === 0; +``` + +```dart title="queue.dart" +/* Initialize a queue */ +// In Dart, Queue is a deque and can also be used as a queue +Queue queue = Queue(); + +/* Enqueue elements */ +queue.add(1); +queue.add(3); +queue.add(2); +queue.add(5); +queue.add(4); + +/* Access the front element */ +int peek = queue.first; + +/* Dequeue an element */ +int pop = queue.removeFirst(); + +/* Get the queue size */ +int size = queue.length; + +/* Check whether the queue is empty */ +bool isEmpty = queue.isEmpty; +``` + +```rust title="queue.rs" +/* Initialize a deque */ +// In Rust, use a deque as an ordinary queue +let mut deque: VecDeque = VecDeque::new(); + +/* Enqueue elements */ +deque.push_back(1); +deque.push_back(3); +deque.push_back(2); +deque.push_back(5); +deque.push_back(4); + +/* Access the front element */ +if let Some(front) = deque.front() { +} + +/* Dequeue an element */ +if let Some(pop) = deque.pop_front() { +} + +/* Get the queue size */ +let size = deque.len(); + +/* Check whether the queue is empty */ +let is_empty = deque.is_empty(); +``` + +```c title="queue.c" +// C provides no built-in queue +``` + +```kotlin title="queue.kt" +/* Initialize a queue */ +val queue = LinkedList() + +/* Enqueue elements */ +queue.offer(1) +queue.offer(3) +queue.offer(2) +queue.offer(5) +queue.offer(4) + +/* Access the front element */ +val peek = queue.peek() + +/* Dequeue an element */ +val pop = queue.poll() + +/* Get the queue size */ +val size = queue.size + +/* Check whether the queue is empty */ +val isEmpty = queue.isEmpty() +``` + +```ruby title="queue.rb" +# Initialize a queue +# Ruby's built-in Thread::Queue has no peek or traversal methods; use an Array as a queue +queue = [] + +# Enqueue elements +queue.push(1) +queue.push(3) +queue.push(2) +queue.push(5) +queue.push(4) + +# Access the front element of the queue +peek = queue.first + +# Dequeue an element +# Note that this is an array, so Array#shift takes O(n) time +pop = queue.shift + +# Get the queue size +size = queue.length + +# Check whether the queue is empty +is_empty = queue.empty? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20queue%0A%20%20%20%20%23%20In%20Python%2C%20we%20usually%20use%20the%20deque%20class%20as%20a%20queue%0A%20%20%20%20%23%20Although%20queue.Queue%28%29%20is%20a%20dedicated%20queue%20class%2C%20it%20is%20less%20convenient%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20Enqueue%20elements%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22Queue%3A%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20Access%20the%20front%20element%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22Front%20element%3A%20front%20%3D%22%2C%20front%29%0A%0A%20%20%20%20%23%20Dequeue%20an%20element%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22Dequeued%20element%3A%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22After%20dequeuing%3A%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20Get%20the%20queue%20size%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22Queue%20size%3A%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20Check%20whether%20the%20queue%20is%20empty%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22Is%20the%20queue%20empty%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_stack_and_queue/stack.md b/en/codes/snippets/chapter_stack_and_queue/stack.md new file mode 100644 index 000000000..32d607cb1 --- /dev/null +++ b/en/codes/snippets/chapter_stack_and_queue/stack.md @@ -0,0 +1,304 @@ + +```python title="stack.py" +# Initialize a stack +# Python has no built-in stack class; use a list as a stack +stack: list[int] = [] + +# Push elements +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +# Access the top element +peek: int = stack[-1] + +# Pop an element +pop: int = stack.pop() + +# Get the stack size +size: int = len(stack) + +# Check whether the stack is empty +is_empty: bool = len(stack) == 0 +``` + +```cpp title="stack.cpp" +/* Initialize a stack */ +stack stack; + +/* Push elements */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Access the top element */ +int top = stack.top(); + +/* Pop an element */ +stack.pop(); // No return value + +/* Get the stack size */ +int size = stack.size(); + +/* Check whether the stack is empty */ +bool empty = stack.empty(); +``` + +```java title="stack.java" +/* Initialize a stack */ +Stack stack = new Stack<>(); + +/* Push elements */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Access the top element */ +int peek = stack.peek(); + +/* Pop an element */ +int pop = stack.pop(); + +/* Get the stack size */ +int size = stack.size(); + +/* Check whether the stack is empty */ +boolean isEmpty = stack.isEmpty(); +``` + +```csharp title="stack.cs" +/* Initialize a stack */ +Stack stack = new(); + +/* Push elements */ +stack.Push(1); +stack.Push(3); +stack.Push(2); +stack.Push(5); +stack.Push(4); + +/* Access the top element */ +int peek = stack.Peek(); + +/* Pop an element */ +int pop = stack.Pop(); + +/* Get the stack size */ +int size = stack.Count; + +/* Check whether the stack is empty */ +bool isEmpty = stack.Count == 0; +``` + +```go title="stack_test.go" +/* Initialize a stack */ +// In Go, a slice is recommended for use as a stack +var stack []int + +/* Push elements */ +stack = append(stack, 1) +stack = append(stack, 3) +stack = append(stack, 2) +stack = append(stack, 5) +stack = append(stack, 4) + +/* Access the top element */ +peek := stack[len(stack)-1] + +/* Pop an element */ +pop := stack[len(stack)-1] +stack = stack[:len(stack)-1] + +/* Get the stack size */ +size := len(stack) + +/* Check whether the stack is empty */ +isEmpty := len(stack) == 0 +``` + +```swift title="stack.swift" +/* Initialize a stack */ +// Swift has no built-in stack class; use an Array as a stack +var stack: [Int] = [] + +/* Push elements */ +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +/* Access the top element */ +let peek = stack.last! + +/* Pop an element */ +let pop = stack.removeLast() + +/* Get the stack size */ +let size = stack.count + +/* Check whether the stack is empty */ +let isEmpty = stack.isEmpty +``` + +```javascript title="stack.js" +/* Initialize a stack */ +// JavaScript has no built-in stack class; use an Array as a stack +const stack = []; + +/* Push elements */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Access the top element */ +const peek = stack[stack.length-1]; + +/* Pop an element */ +const pop = stack.pop(); + +/* Get the stack size */ +const size = stack.length; + +/* Check whether the stack is empty */ +const is_empty = stack.length === 0; +``` + +```typescript title="stack.ts" +/* Initialize a stack */ +// TypeScript has no built-in stack class; use an Array as a stack +const stack: number[] = []; + +/* Push elements */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Access the top element */ +const peek = stack[stack.length - 1]; + +/* Pop an element */ +const pop = stack.pop(); + +/* Get the stack size */ +const size = stack.length; + +/* Check whether the stack is empty */ +const is_empty = stack.length === 0; +``` + +```dart title="stack.dart" +/* Initialize a stack */ +// Dart has no built-in stack class; use a List as a stack +List stack = []; + +/* Push elements */ +stack.add(1); +stack.add(3); +stack.add(2); +stack.add(5); +stack.add(4); + +/* Access the top element */ +int peek = stack.last; + +/* Pop an element */ +int pop = stack.removeLast(); + +/* Get the stack size */ +int size = stack.length; + +/* Check whether the stack is empty */ +bool isEmpty = stack.isEmpty; +``` + +```rust title="stack.rs" +/* Initialize a stack */ +// Use a Vec as a stack +let mut stack: Vec = Vec::new(); + +/* Push elements */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Access the top element */ +let top = stack.last().unwrap(); + +/* Pop an element */ +let pop = stack.pop().unwrap(); + +/* Get the stack size */ +let size = stack.len(); + +/* Check whether the stack is empty */ +let is_empty = stack.is_empty(); +``` + +```c title="stack.c" +// C provides no built-in stack +``` + +```kotlin title="stack.kt" +/* Initialize a stack */ +val stack = Stack() + +/* Push elements */ +stack.push(1) +stack.push(3) +stack.push(2) +stack.push(5) +stack.push(4) + +/* Access the top element */ +val peek = stack.peek() + +/* Pop an element */ +val pop = stack.pop() + +/* Get the stack size */ +val size = stack.size + +/* Check whether the stack is empty */ +val isEmpty = stack.isEmpty() +``` + +```ruby title="stack.rb" +# Initialize a stack +# Ruby has no built-in stack class; use an Array as a stack +stack = [] + +# Push elements +stack << 1 +stack << 3 +stack << 2 +stack << 5 +stack << 4 + +# Access the top element +peek = stack.last + +# Pop an element +pop = stack.pop + +# Get the stack size +size = stack.length + +# Check whether the stack is empty +is_empty = stack.empty? +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20stack%0A%20%20%20%20%23%20Python%20has%20no%20built-in%20stack%20class%3B%20use%20a%20list%20as%20a%20stack%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20Push%20elements%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22Stack%3A%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20Access%20the%20top%20element%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22Top%20element%3A%20peek%20%3D%22%2C%20peek%29%0A%0A%20%20%20%20%23%20Pop%20an%20element%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22Popped%20element%3A%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22After%20popping%3A%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20Get%20the%20stack%20size%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22Stack%20size%3A%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20Check%20whether%20the%20stack%20is%20empty%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22Is%20the%20stack%20empty%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_tree/array_representation_of_tree.md b/en/codes/snippets/chapter_tree/array_representation_of_tree.md new file mode 100644 index 000000000..780145981 --- /dev/null +++ b/en/codes/snippets/chapter_tree/array_representation_of_tree.md @@ -0,0 +1,78 @@ + +```python title="" +# Array representation of a binary tree +# Use None for empty positions +tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] +``` + +```cpp title="" +/* Array representation of a binary tree */ +// Use INT_MAX, the maximum int value, for empty positions +vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```java title="" +/* Array representation of a binary tree */ +// Use the wrapper class Integer so that null can mark empty positions +Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; +``` + +```csharp title="" +/* Array representation of a binary tree */ +// Use the nullable type int? so that null can mark empty positions +int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```go title="" +/* Array representation of a binary tree */ +// Use a slice of any so that nil can mark empty positions +tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} +``` + +```swift title="" +/* Array representation of a binary tree */ +// Use the optional type Int? so that nil can mark empty positions +let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` + +```javascript title="" +/* Array representation of a binary tree */ +// Use null for empty positions +let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```typescript title="" +/* Array representation of a binary tree */ +// Use null for empty positions +let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```dart title="" +/* Array representation of a binary tree */ +// Use the nullable type int? so that null can mark empty positions +List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```rust title="" +/* Array representation of a binary tree */ +// Use None for empty positions +let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; +``` + +```c title="" +/* Array representation of a binary tree */ +// Use the maximum int value for empty positions, so node values must not equal INT_MAX +int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```kotlin title="" +/* Array representation of a binary tree */ +// Use null for empty positions +val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) +``` + +```ruby title="" +### Array representation of a binary tree ### +# Use nil for empty positions +tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` diff --git a/en/codes/snippets/chapter_tree/avl_tree.md b/en/codes/snippets/chapter_tree/avl_tree.md new file mode 100644 index 000000000..0d2411084 --- /dev/null +++ b/en/codes/snippets/chapter_tree/avl_tree.md @@ -0,0 +1,182 @@ + +```python title="" +class TreeNode: + """AVL tree node class""" + def __init__(self, val: int): + self.val: int = val # Node value + self.height: int = 0 # Node height + self.left: TreeNode | None = None # Left child reference + self.right: TreeNode | None = None # Right child reference +``` + +```cpp title="" +/* AVL tree node class */ +struct TreeNode { + int val{}; // Node value + int height = 0; // Node height + TreeNode *left{}; // Left child + TreeNode *right{}; // Right child + TreeNode() = default; + explicit TreeNode(int x) : val(x){} +}; +``` + +```java title="" +/* AVL tree node class */ +class TreeNode { + public int val; // Node value + public int height; // Node height + public TreeNode left; // Left child + public TreeNode right; // Right child + public TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* AVL tree node class */ +class TreeNode(int? x) { + public int? val = x; // Node value + public int height; // Node height + public TreeNode? left; // Left child reference + public TreeNode? right; // Right child reference +} +``` + +```go title="" +/* AVL tree node struct */ +type TreeNode struct { + Val int // Node value + Height int // Node height + Left *TreeNode // Left child reference + Right *TreeNode // Right child reference +} +``` + +```swift title="" +/* AVL tree node class */ +class TreeNode { + var val: Int // Node value + var height: Int // Node height + var left: TreeNode? // Left child + var right: TreeNode? // Right child + + init(x: Int) { + val = x + height = 0 + } +} +``` + +```javascript title="" +/* AVL tree node class */ +class TreeNode { + val; // Node value + height; //Node height + left; // Left child pointer + right; // Right child pointer + constructor(val, left, right, height) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* AVL tree node class */ +class TreeNode { + val: number; // Node value + height: number; // Node height + left: TreeNode | null; // Left child pointer + right: TreeNode | null; // Right child pointer + constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```dart title="" +/* AVL tree node class */ +class TreeNode { + int val; // Node value + int height; // Node height + TreeNode? left; // Left child + TreeNode? right; // Right child + TreeNode(this.val, [this.height = 0, this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* AVL tree node struct */ +struct TreeNode { + val: i32, // Node value + height: i32, // Node height + left: Option>>, // Left child + right: Option>>, // Right child +} + +impl TreeNode { + /* Constructor */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + height: 0, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* AVL tree node struct */ +typedef struct TreeNode { + int val; + int height; + struct TreeNode *left; + struct TreeNode *right; +} TreeNode; + +/* Constructor */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* AVL tree node class */ +class TreeNode(val _val: Int) { // Node value + var height: Int = 0 // Node height + var left: TreeNode? = null // Left child + var right: TreeNode? = null // Right child +} +``` + +```ruby title="" +### AVL tree node class ### +class TreeNode + attr_accessor :val # Node value + attr_accessor :height # Node height + attr_accessor :left # Left child reference + attr_accessor :right # Right child reference + + def initialize(val) + @val = val + @height = 0 + end +end +``` diff --git a/en/codes/snippets/chapter_tree/binary_tree.md b/en/codes/snippets/chapter_tree/binary_tree.md new file mode 100644 index 000000000..d67a11547 --- /dev/null +++ b/en/codes/snippets/chapter_tree/binary_tree.md @@ -0,0 +1,502 @@ + +```python title="" +class TreeNode: + """Binary tree node class""" + def __init__(self, val: int): + self.val: int = val # Node value + self.left: TreeNode | None = None # Left child reference + self.right: TreeNode | None = None # Right child reference +``` + +```cpp title="" +/* Binary tree node struct */ +struct TreeNode { + int val; // Node value + TreeNode *left; // Left child pointer + TreeNode *right; // Right child pointer + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; +``` + +```java title="" +/* Binary tree node class */ +class TreeNode { + int val; // Node value + TreeNode left; // Left child reference + TreeNode right; // Right child reference + TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* Binary tree node class */ +class TreeNode(int? x) { + public int? val = x; // Node value + public TreeNode? left; // Left child reference + public TreeNode? right; // Right child reference +} +``` + +```go title="" +/* Binary tree node struct */ +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} +/* Constructor */ +func NewTreeNode(v int) *TreeNode { + return &TreeNode{ + Left: nil, // Left child pointer + Right: nil, // Right child pointer + Val: v, // Node value + } +} +``` + +```swift title="" +/* Binary tree node class */ +class TreeNode { + var val: Int // Node value + var left: TreeNode? // Left child reference + var right: TreeNode? // Right child reference + + init(x: Int) { + val = x + } +} +``` + +```javascript title="" +/* Binary tree node class */ +class TreeNode { + val; // Node value + left; // Left child pointer + right; // Right child pointer + constructor(val, left, right) { + this.val = val === undefined ? 0 : val; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* Binary tree node class */ +class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; // Node value + this.left = left === undefined ? null : left; // Left child reference + this.right = right === undefined ? null : right; // Right child reference + } +} +``` + +```dart title="" +/* Binary tree node class */ +class TreeNode { + int val; // Node value + TreeNode? left; // Left child reference + TreeNode? right; // Right child reference + TreeNode(this.val, [this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* Binary tree node struct */ +struct TreeNode { + val: i32, // Node value + left: Option>>, // Left child reference + right: Option>>, // Right child reference +} + +impl TreeNode { + /* Constructor */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* Binary tree node struct */ +typedef struct TreeNode { + int val; // Node value + int height; // Node height + struct TreeNode *left; // Left child pointer + struct TreeNode *right; // Right child pointer +} TreeNode; + +/* Constructor */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* Binary tree node class */ +class TreeNode(val _val: Int) { // Node value + var left: TreeNode? = null // Left child reference + var right: TreeNode? = null // Right child reference +} +``` + +```ruby title="" +### Binary tree node class ### +class TreeNode + attr_accessor :val # Node value + attr_accessor :left # Left child reference + attr_accessor :right # Right child reference + + def initialize(val) + @val = val + end +end +``` + + +```python title="binary_tree.py" +# Initialize a binary tree +# Initialize nodes +n1 = TreeNode(val=1) +n2 = TreeNode(val=2) +n3 = TreeNode(val=3) +n4 = TreeNode(val=4) +n5 = TreeNode(val=5) +# Connect nodes with references (pointers) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```cpp title="binary_tree.cpp" +/* Initialize a binary tree */ +// Initialize nodes +TreeNode* n1 = new TreeNode(1); +TreeNode* n2 = new TreeNode(2); +TreeNode* n3 = new TreeNode(3); +TreeNode* n4 = new TreeNode(4); +TreeNode* n5 = new TreeNode(5); +// Connect nodes with references (pointers) +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```java title="binary_tree.java" +// Initialize nodes +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// Connect nodes with references (pointers) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```csharp title="binary_tree.cs" +/* Initialize a binary tree */ +// Initialize nodes +TreeNode n1 = new(1); +TreeNode n2 = new(2); +TreeNode n3 = new(3); +TreeNode n4 = new(4); +TreeNode n5 = new(5); +// Connect nodes with references (pointers) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```go title="binary_tree.go" +/* Initialize a binary tree */ +// Initialize nodes +n1 := NewTreeNode(1) +n2 := NewTreeNode(2) +n3 := NewTreeNode(3) +n4 := NewTreeNode(4) +n5 := NewTreeNode(5) +// Connect nodes with references (pointers) +n1.Left = n2 +n1.Right = n3 +n2.Left = n4 +n2.Right = n5 +``` + +```swift title="binary_tree.swift" +// Initialize nodes +let n1 = TreeNode(x: 1) +let n2 = TreeNode(x: 2) +let n3 = TreeNode(x: 3) +let n4 = TreeNode(x: 4) +let n5 = TreeNode(x: 5) +// Connect nodes with references (pointers) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```javascript title="binary_tree.js" +/* Initialize a binary tree */ +// Initialize nodes +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// Connect nodes with references (pointers) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```typescript title="binary_tree.ts" +/* Initialize a binary tree */ +// Initialize nodes +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// Connect nodes with references (pointers) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```dart title="binary_tree.dart" +/* Initialize a binary tree */ +// Initialize nodes +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// Connect nodes with references (pointers) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```rust title="binary_tree.rs" +// Initialize nodes +let n1 = TreeNode::new(1); +let n2 = TreeNode::new(2); +let n3 = TreeNode::new(3); +let n4 = TreeNode::new(4); +let n5 = TreeNode::new(5); +// Connect nodes with references (pointers) +n1.borrow_mut().left = Some(n2.clone()); +n1.borrow_mut().right = Some(n3); +n2.borrow_mut().left = Some(n4); +n2.borrow_mut().right = Some(n5); +``` + +```c title="binary_tree.c" +/* Initialize a binary tree */ +// Initialize nodes +TreeNode *n1 = newTreeNode(1); +TreeNode *n2 = newTreeNode(2); +TreeNode *n3 = newTreeNode(3); +TreeNode *n4 = newTreeNode(4); +TreeNode *n5 = newTreeNode(5); +// Connect nodes with references (pointers) +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```kotlin title="binary_tree.kt" +// Initialize nodes +val n1 = TreeNode(1) +val n2 = TreeNode(2) +val n3 = TreeNode(3) +val n4 = TreeNode(4) +val n5 = TreeNode(5) +// Connect nodes with references (pointers) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```ruby title="binary_tree.rb" +# Initialize a binary tree +# Initialize nodes +n1 = TreeNode.new(1) +n2 = TreeNode.new(2) +n3 = TreeNode.new(3) +n4 = TreeNode.new(4) +n5 = TreeNode.new(5) +# Connect nodes with references (pointers) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22Binary%20tree%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20Left%20child%20reference%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20Right%20child%20reference%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20binary%20tree%0A%20%20%20%20%23%20Initialize%20nodes%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20Connect%20nodes%20with%20references%20%28pointers%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="binary_tree.py" +# Insert and delete a node +p = TreeNode(0) +# Insert node P between n1 and n2 +n1.left = p +p.left = n2 +# Delete node P +n1.left = n2 +``` + +```cpp title="binary_tree.cpp" +/* Insert and delete a node */ +TreeNode* P = new TreeNode(0); +// Insert node P between n1 and n2 +n1->left = P; +P->left = n2; +// Delete node P +n1->left = n2; +// Free the memory +delete P; +``` + +```java title="binary_tree.java" +TreeNode P = new TreeNode(0); +// Insert node P between n1 and n2 +n1.left = P; +P.left = n2; +// Delete node P +n1.left = n2; +``` + +```csharp title="binary_tree.cs" +/* Insert and delete a node */ +TreeNode P = new(0); +// Insert node P between n1 and n2 +n1.left = P; +P.left = n2; +// Delete node P +n1.left = n2; +``` + +```go title="binary_tree.go" +/* Insert and delete a node */ +// Insert node P between n1 and n2 +p := NewTreeNode(0) +n1.Left = p +p.Left = n2 +// Delete node P +n1.Left = n2 +``` + +```swift title="binary_tree.swift" +let P = TreeNode(x: 0) +// Insert node P between n1 and n2 +n1.left = P +P.left = n2 +// Delete node P +n1.left = n2 +``` + +```javascript title="binary_tree.js" +/* Insert and delete a node */ +let P = new TreeNode(0); +// Insert node P between n1 and n2 +n1.left = P; +P.left = n2; +// Delete node P +n1.left = n2; +``` + +```typescript title="binary_tree.ts" +/* Insert and delete a node */ +const P = new TreeNode(0); +// Insert node P between n1 and n2 +n1.left = P; +P.left = n2; +// Delete node P +n1.left = n2; +``` + +```dart title="binary_tree.dart" +/* Insert and delete a node */ +TreeNode P = new TreeNode(0); +// Insert node P between n1 and n2 +n1.left = P; +P.left = n2; +// Delete node P +n1.left = n2; +``` + +```rust title="binary_tree.rs" +let p = TreeNode::new(0); +// Insert node P between n1 and n2 +n1.borrow_mut().left = Some(p.clone()); +p.borrow_mut().left = Some(n2.clone()); +// Delete node p +n1.borrow_mut().left = Some(n2); +``` + +```c title="binary_tree.c" +/* Insert and delete a node */ +TreeNode *P = newTreeNode(0); +// Insert node P between n1 and n2 +n1->left = P; +P->left = n2; +// Delete node P +n1->left = n2; +// Free the memory +free(P); +``` + +```kotlin title="binary_tree.kt" +val P = TreeNode(0) +// Insert node P between n1 and n2 +n1.left = P +P.left = n2 +// Delete node P +n1.left = n2 +``` + +```ruby title="binary_tree.rb" +# Insert and delete a node +_p = TreeNode.new(0) +# Insert node _p between n1 and n2 +n1.left = _p +_p.left = n2 +# Delete the node +n1.left = n2 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22Binary%20tree%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20Left%20child%20reference%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20Right%20child%20reference%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20binary%20tree%0A%20%20%20%20%23%20Initialize%20nodes%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20Connect%20nodes%20with%20references%20%28pointers%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20Insert%20and%20delete%20a%20node%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20Insert%20node%20P%20between%20n1%20and%20n2%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20Delete%20node%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/docs/chapter_array_and_linkedlist/array.md b/en/docs/chapter_array_and_linkedlist/array.md index d1bf76b08..ba12bffd1 100755 --- a/en/docs/chapter_array_and_linkedlist/array.md +++ b/en/docs/chapter_array_and_linkedlist/array.md @@ -10,125 +10,13 @@ An array is a linear data structure that stores elements of the same type We can initialize an array with or without explicit values. When values are not specified, most programming languages initialize the elements to $0$: -=== "Python" - - ```python title="array.py" - # Initialize arrays - arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="array.cpp" - /* Initialize arrays */ - // Stored on the stack - int arr[5] = {}; - int nums[5] = { 1, 3, 2, 5, 4 }; - // Stored on the heap (memory must be freed manually) - int* arr1 = new int[5] {}; - int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="array.java" - /* Initialize arrays */ - int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } - int[] nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "C#" - - ```csharp title="array.cs" - /* Initialize arrays */ - int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] - int[] nums = [1, 3, 2, 5, 4]; - ``` - -=== "Go" - - ```go title="array.go" - /* Initialize arrays */ - var arr [5]int - // In Go, [5]int is an array with a specified length; []int is a slice - // Go array lengths are determined at compile time and must be constants - // To make extend() easier to implement, we treat slices as arrays below - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="array.swift" - /* Initialize arrays */ - let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] - let nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="array.js" - /* Initialize arrays */ - var arr = new Array(5).fill(0); - var nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="array.ts" - /* Initialize arrays */ - let arr: number[] = new Array(5).fill(0); - let nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="array.dart" - /* Initialize arrays */ - List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="array.rs" - /* Initialize arrays */ - let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] - let slice: &[i32] = &[0; 5]; - // In Rust, [i32; 5] is an array with a specified length; &[i32] is a slice - // Rust array lengths are determined at compile time and must be constants - // Vector is Rust's usual dynamic array type - // To make extend() easier to implement, we treat a vector as an array below - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="array.c" - /* Initialize arrays */ - int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } - int nums[5] = { 1, 3, 2, 5, 4 }; - ``` - -=== "Kotlin" - - ```kotlin title="array.kt" - /* Initialize arrays */ - var arr = IntArray(5) // { 0, 0, 0, 0, 0 } - var nums = intArrayOf(1, 3, 2, 5, 4) - ``` - -=== "Ruby" - - ```ruby title="array.rb" - # Initialize arrays - arr = Array.new(5, 0) - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_array +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%23%20Initialize%20arrays%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_array_tutor ### Accessing an element diff --git a/en/docs/chapter_array_and_linkedlist/linked_list.md b/en/docs/chapter_array_and_linkedlist/linked_list.md index 916eb75ff..e036c365d 100755 --- a/en/docs/chapter_array_and_linkedlist/linked_list.md +++ b/en/docs/chapter_array_and_linkedlist/linked_list.md @@ -16,174 +16,9 @@ As shown above, the basic unit of a linked list is a node object. Each no As the code below shows, each `ListNode` stores a reference (pointer) in addition to its value. Thus, **a linked list uses more memory than an array for the same amount of data**. -=== "Python" - - ```python title="" - class ListNode: - """Linked list node class""" - def __init__(self, val: int): - self.val: int = val # Node value - self.next: ListNode | None = None # Reference to the next node - ``` - -=== "C++" - - ```cpp title="" - /* Linked list node structure */ - struct ListNode { - int val; // Node value - ListNode *next; // Pointer to the next node - ListNode(int x) : val(x), next(nullptr) {} // Constructor - }; - ``` - -=== "Java" - - ```java title="" - /* Linked list node class */ - class ListNode { - int val; // Node value - ListNode next; // Reference to the next node - ListNode(int x) { val = x; } // Constructor - } - ``` - -=== "C#" - - ```csharp title="" - /* Linked list node class */ - class ListNode(int x) { // Constructor - int val = x; // Node value - ListNode? next; // Reference to the next node - } - ``` - -=== "Go" - - ```go title="" - /* Linked list node structure */ - type ListNode struct { - Val int // Node value - Next *ListNode // Pointer to the next node - } - - // NewListNode constructor: create a new linked list - func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* Linked list node class */ - class ListNode { - var val: Int // Node value - var next: ListNode? // Reference to the next node - - init(x: Int) { // Constructor - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* Linked list node class */ - class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // Node value - this.next = (next === undefined ? null : next); // Reference to the next node - } - } - ``` - -=== "TS" - - ```typescript title="" - /* Linked list node class */ - class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // Node value - this.next = next === undefined ? null : next; // Reference to the next node - } - } - ``` - -=== "Dart" - - ```dart title="" - /* Linked list node class */ - class ListNode { - int val; // Node value - ListNode? next; // Reference to the next node - ListNode(this.val, [this.next]); // Constructor - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - /* Linked list node class */ - #[derive(Debug)] - struct ListNode { - val: i32, // Node value - next: Option>>, // Pointer to the next node - } - ``` - -=== "C" - - ```c title="" - /* Linked list node structure */ - typedef struct ListNode { - int val; // Node value - struct ListNode *next; // Pointer to the next node - } ListNode; - - /* Constructor */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Linked list node class */ - // Constructor - class ListNode(x: Int) { - val _val: Int = x // Node value - var next: ListNode? = null // Reference to the next node - } - ``` - -=== "Ruby" - - ```ruby title="" - # Linked list node class - class ListNode - attr_accessor :val # Node value - attr_accessor :next # Reference to the next node - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end - end - ``` +```snippet +list_node_class +``` ## Common linked list operations @@ -191,231 +26,13 @@ As the code below shows, each `ListNode` stores a reference (pointer) in additio Building a linked list takes two steps: initialize the node objects, then connect them with references. Afterward, start at the head and follow `next` references to visit every node in order. -=== "Python" - - ```python title="linked_list.py" - # Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 - # Initialize the nodes - n0 = ListNode(1) - n1 = ListNode(3) - n2 = ListNode(2) - n3 = ListNode(5) - n4 = ListNode(4) - # Link the nodes with references - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "C++" - - ```cpp title="linked_list.cpp" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - ListNode* n0 = new ListNode(1); - ListNode* n1 = new ListNode(3); - ListNode* n2 = new ListNode(2); - ListNode* n3 = new ListNode(5); - ListNode* n4 = new ListNode(4); - // Link the nodes with references - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Java" - - ```java title="linked_list.java" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - ListNode n0 = new ListNode(1); - ListNode n1 = new ListNode(3); - ListNode n2 = new ListNode(2); - ListNode n3 = new ListNode(5); - ListNode n4 = new ListNode(4); - // Link the nodes with references - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "C#" - - ```csharp title="linked_list.cs" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - ListNode n0 = new(1); - ListNode n1 = new(3); - ListNode n2 = new(2); - ListNode n3 = new(5); - ListNode n4 = new(4); - // Link the nodes with references - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Go" - - ```go title="linked_list.go" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - n0 := NewListNode(1) - n1 := NewListNode(3) - n2 := NewListNode(2) - n3 := NewListNode(5) - n4 := NewListNode(4) - // Link the nodes with references - n0.Next = n1 - n1.Next = n2 - n2.Next = n3 - n3.Next = n4 - ``` - -=== "Swift" - - ```swift title="linked_list.swift" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - let n0 = ListNode(x: 1) - let n1 = ListNode(x: 3) - let n2 = ListNode(x: 2) - let n3 = ListNode(x: 5) - let n4 = ListNode(x: 4) - // Link the nodes with references - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "JS" - - ```javascript title="linked_list.js" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // Link the nodes with references - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "TS" - - ```typescript title="linked_list.ts" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // Link the nodes with references - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Dart" - - ```dart title="linked_list.dart" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */\ - // Initialize the nodes - ListNode n0 = ListNode(1); - ListNode n1 = ListNode(3); - ListNode n2 = ListNode(2); - ListNode n3 = ListNode(5); - ListNode n4 = ListNode(4); - // Link the nodes with references - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Rust" - - ```rust title="linked_list.rs" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); - let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); - let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); - let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); - let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); - - // Link the nodes with references - n0.borrow_mut().next = Some(n1.clone()); - n1.borrow_mut().next = Some(n2.clone()); - n2.borrow_mut().next = Some(n3.clone()); - n3.borrow_mut().next = Some(n4.clone()); - ``` - -=== "C" - - ```c title="linked_list.c" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - ListNode* n0 = newListNode(1); - ListNode* n1 = newListNode(3); - ListNode* n2 = newListNode(2); - ListNode* n3 = newListNode(5); - ListNode* n4 = newListNode(4); - // Link the nodes with references - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Kotlin" - - ```kotlin title="linked_list.kt" - /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ - // Initialize the nodes - val n0 = ListNode(1) - val n1 = ListNode(3) - val n2 = ListNode(2) - val n3 = ListNode(5) - val n4 = ListNode(4) - // Link the nodes with references - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Ruby" - - ```ruby title="linked_list.rb" - # Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 - # Initialize the nodes - n0 = ListNode.new(1) - n1 = ListNode.new(3) - n2 = ListNode.new(2) - n3 = ListNode.new(5) - n4 = ListNode.new(4) - # Link the nodes with references - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` +```snippet +init_linked_list +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked%20list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20successor%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20the%20linked%20list%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20Initialize%20the%20nodes%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20Link%20the%20nodes%20with%20references%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_linked_list_tutor An array is a single variable, such as `nums`, containing entries `nums[0]`, `nums[1]`, and so on. A linked list consists of separate node objects. **We usually refer to the list by its head node**; for example, the list above can be called `n0`. @@ -482,203 +99,9 @@ The figure below shows three common types. - **Circular linked list**: Connecting a singly linked list's tail to its head forms a circular list. Any node can then be treated as the head. - **Doubly linked list**: Each node stores references (pointers) in both directions, to its successor and predecessor. This makes it more flexible and allows traversal in either direction, at the cost of additional memory. -=== "Python" - - ```python title="" - class ListNode: - """Doubly linked list node class""" - def __init__(self, val: int): - self.val: int = val # Node value - self.next: ListNode | None = None # Reference to the successor - self.prev: ListNode | None = None # Reference to the predecessor - ``` - -=== "C++" - - ```cpp title="" - /* Doubly linked list node structure */ - struct ListNode { - int val; // Node value - ListNode *next; // Pointer to the successor - ListNode *prev; // Pointer to the predecessor - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // Constructor - }; - ``` - -=== "Java" - - ```java title="" - /* Doubly linked list node class */ - class ListNode { - int val; // Node value - ListNode next; // Reference to the successor - ListNode prev; // Reference to the predecessor - ListNode(int x) { val = x; } // Constructor - } - ``` - -=== "C#" - - ```csharp title="" - /* Doubly linked list node class */ - class ListNode(int x) { // Constructor - int val = x; // Node value - ListNode next; // Reference to the successor - ListNode prev; // Reference to the predecessor - } - ``` - -=== "Go" - - ```go title="" - /* Doubly linked list node structure */ - type DoublyListNode struct { - Val int // Node value - Next *DoublyListNode // Pointer to the successor - Prev *DoublyListNode // Pointer to the predecessor - } - - // Initialize a node with NewDoublyListNode - func NewDoublyListNode(val int) *DoublyListNode { - return &DoublyListNode{ - Val: val, - Next: nil, - Prev: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* Doubly linked list node class */ - class ListNode { - var val: Int // Node value - var next: ListNode? // Reference to the successor - var prev: ListNode? // Reference to the predecessor - - init(x: Int) { // Constructor - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* Doubly linked list node class */ - class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // Node value - this.next = next === undefined ? null : next; // Reference to the successor - this.prev = prev === undefined ? null : prev; // Reference to the predecessor - } - } - ``` - -=== "TS" - - ```typescript title="" - /* Doubly linked list node class */ - class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // Node value - this.next = next === undefined ? null : next; // Reference to the successor - this.prev = prev === undefined ? null : prev; // Reference to the predecessor - } - } - ``` - -=== "Dart" - - ```dart title="" - /* Doubly linked list node class */ - class ListNode { - int val; // Node value - ListNode? next; // Reference to the successor - ListNode? prev; // Reference to the predecessor - ListNode(this.val, [this.next, this.prev]); // Constructor - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* Doubly linked list node type */ - #[derive(Debug)] - struct ListNode { - val: i32, // Node value - next: Option>>, // Pointer to the successor - prev: Option>>, // Pointer to the predecessor - } - - /* Constructor */ - impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } - } - ``` - -=== "C" - - ```c title="" - /* Doubly linked list node structure */ - typedef struct ListNode { - int val; // Node value - struct ListNode *next; // Pointer to the successor - struct ListNode *prev; // Pointer to the predecessor - } ListNode; - - /* Constructor */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Doubly linked list node class */ - // Constructor - class ListNode(x: Int) { - val _val: Int = x // Node value - var next: ListNode? = null // Reference to the successor - var prev: ListNode? = null // Reference to the predecessor - } - ``` - -=== "Ruby" - - ```ruby title="" - # Doubly linked list node class - class ListNode - attr_accessor :val # Node value - attr_accessor :next # Reference to the successor - attr_accessor :prev # Reference to the predecessor - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end - end - ``` +```snippet +doubly_list_node_class +``` ![Common types of linked lists](linked_list.assets/linkedlist_common_types.svg) diff --git a/en/docs/chapter_array_and_linkedlist/list.md b/en/docs/chapter_array_and_linkedlist/list.md index 5052ef059..119c49779 100755 --- a/en/docs/chapter_array_and_linkedlist/list.md +++ b/en/docs/chapter_array_and_linkedlist/list.md @@ -17,934 +17,73 @@ A dynamic array solves this problem. It retains the advantages of an arra We usually initialize a list either without elements or with explicit initial values: -=== "Python" - - ```python title="list.py" - # Initialize lists - # Without initial values - nums1: list[int] = [] - # With initial values - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Initialize lists */ - // In C++, vector is the list type used for nums here - // Without initial values - vector nums1; - // With initial values - vector nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="list.java" - /* Initialize lists */ - // Without initial values - List nums1 = new ArrayList<>(); - // With initial values (use Integer[], the boxed counterpart of int[]) - Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; - List nums = new ArrayList<>(Arrays.asList(numbers)); - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Initialize lists */ - // Without initial values - List nums1 = []; - // With initial values - int[] numbers = [1, 3, 2, 5, 4]; - List nums = [.. numbers]; - ``` - -=== "Go" - - ```go title="list_test.go" - /* Initialize lists */ - // Without initial values - nums1 := []int{} - // With initial values - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Initialize lists */ - // Without initial values - let nums1: [Int] = [] - // With initial values - var nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="list.js" - /* Initialize lists */ - // Without initial values - const nums1 = []; - // With initial values - const nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Initialize lists */ - // Without initial values - const nums1: number[] = []; - // With initial values - const nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Initialize lists */ - // Without initial values - List nums1 = []; - // With initial values - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Initialize lists */ - // Without initial values - let nums1: Vec = Vec::new(); - // With initial values - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="list.c" - // C does not provide a built-in dynamic array - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Initialize lists */ - // Without initial values - var nums1 = listOf() - // With initial values - var numbers = arrayOf(1, 3, 2, 5, 4) - var nums = numbers.toMutableList() - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Initialize lists - # Without initial values - nums1 = [] - # With initial values - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_list +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20%23%20Without%20initial%20values%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_list_tutor ### Accessing an element Since the list is based on an array, accessing and updating an element are efficient $O(1)$ operations. -=== "Python" - - ```python title="list.py" - # Access an element - num: int = nums[1] # Access the element at index 1 - - # Update an element - nums[1] = 0 # Set the element at index 1 to 0 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Access an element */ - int num = nums[1]; // Access the element at index 1 - - /* Update an element */ - nums[1] = 0; // Set the element at index 1 to 0 - ``` - -=== "Java" - - ```java title="list.java" - /* Access an element */ - int num = nums.get(1); // Access the element at index 1 - - /* Update an element */ - nums.set(1, 0); // Set the element at index 1 to 0 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Access an element */ - int num = nums[1]; // Access the element at index 1 - - /* Update an element */ - nums[1] = 0; // Set the element at index 1 to 0 - ``` - -=== "Go" - - ```go title="list_test.go" - /* Access an element */ - num := nums[1] // Access the element at index 1 - - /* Update an element */ - nums[1] = 0 // Set the element at index 1 to 0 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Access an element */ - let num = nums[1] // Access the element at index 1 - - /* Update an element */ - nums[1] = 0 // Set the element at index 1 to 0 - ``` - -=== "JS" - - ```javascript title="list.js" - /* Access an element */ - const num = nums[1]; // Access the element at index 1 - - /* Update an element */ - nums[1] = 0; // Set the element at index 1 to 0 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Access an element */ - const num: number = nums[1]; // Access the element at index 1 - - /* Update an element */ - nums[1] = 0; // Set the element at index 1 to 0 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Access an element */ - int num = nums[1]; // Access the element at index 1 - - /* Update an element */ - nums[1] = 0; // Set the element at index 1 to 0 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Access an element */ - let num: i32 = nums[1]; // Access the element at index 1 - /* Update an element */ - nums[1] = 0; // Set the element at index 1 to 0 - ``` - -=== "C" - - ```c title="list.c" - // C does not provide a built-in dynamic array - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Access an element */ - val num = nums[1] // Access the element at index 1 - /* Update an element */ - nums[1] = 0 // Set the element at index 1 to 0 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Access an element - num = nums[1] # Access the element at index 1 - # Update an element - nums[1] = 0 # Set the element at index 1 to 0 - ``` +```snippet +access_element +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20Access%20an%20element%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20Access%20the%20element%20at%20index%201%0A%0A%20%20%20%20%23%20Update%20an%20element%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20Set%20the%20element%20at%20index%201%20to%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor access_element_tutor ### Inserting and removing elements Unlike a fixed array, a list can freely add and remove elements. Appending takes $O(1)$ time, while insertion and removal retain the array's $O(n)$ time complexity. -=== "Python" - - ```python title="list.py" - # Clear the list - nums.clear() - - # Append elements - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - # Insert an element in the middle - nums.insert(3, 6) # Insert 6 at index 3 - - # Remove an element - nums.pop(3) # Remove the element at index 3 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Clear the list */ - nums.clear(); - - /* Append elements */ - nums.push_back(1); - nums.push_back(3); - nums.push_back(2); - nums.push_back(5); - nums.push_back(4); - - /* Insert an element in the middle */ - nums.insert(nums.begin() + 3, 6); // Insert 6 at index 3 - - /* Remove an element */ - nums.erase(nums.begin() + 3); // Remove the element at index 3 - ``` - -=== "Java" - - ```java title="list.java" - /* Clear the list */ - nums.clear(); - - /* Append elements */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* Insert an element in the middle */ - nums.add(3, 6); // Insert 6 at index 3 - - /* Remove an element */ - nums.remove(3); // Remove the element at index 3 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Clear the list */ - nums.Clear(); - - /* Append elements */ - nums.Add(1); - nums.Add(3); - nums.Add(2); - nums.Add(5); - nums.Add(4); - - /* Insert an element in the middle */ - nums.Insert(3, 6); // Insert 6 at index 3 - - /* Remove an element */ - nums.RemoveAt(3); // Remove the element at index 3 - ``` - -=== "Go" - - ```go title="list_test.go" - /* Clear the list */ - nums = nil - - /* Append elements */ - nums = append(nums, 1) - nums = append(nums, 3) - nums = append(nums, 2) - nums = append(nums, 5) - nums = append(nums, 4) - - /* Insert an element in the middle */ - nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert 6 at index 3 - - /* Remove an element */ - nums = append(nums[:3], nums[4:]...) // Remove the element at index 3 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Clear the list */ - nums.removeAll() - - /* Append elements */ - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - /* Insert an element in the middle */ - nums.insert(6, at: 3) // Insert 6 at index 3 - - /* Remove an element */ - nums.remove(at: 3) // Remove the element at index 3 - ``` - -=== "JS" - - ```javascript title="list.js" - /* Clear the list */ - nums.length = 0; - - /* Append elements */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* Insert an element in the middle */ - nums.splice(3, 0, 6); // Insert 6 at index 3 - - /* Remove an element */ - nums.splice(3, 1); // Remove the element at index 3 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Clear the list */ - nums.length = 0; - - /* Append elements */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* Insert an element in the middle */ - nums.splice(3, 0, 6); // Insert 6 at index 3 - - /* Remove an element */ - nums.splice(3, 1); // Remove the element at index 3 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Clear the list */ - nums.clear(); - - /* Append elements */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* Insert an element in the middle */ - nums.insert(3, 6); // Insert 6 at index 3 - - /* Remove an element */ - nums.removeAt(3); // Remove the element at index 3 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Clear the list */ - nums.clear(); - - /* Append elements */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* Insert an element in the middle */ - nums.insert(3, 6); // Insert 6 at index 3 - - /* Remove an element */ - nums.remove(3); // Remove the element at index 3 - ``` - -=== "C" - - ```c title="list.c" - // C does not provide a built-in dynamic array - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Clear the list */ - nums.clear(); - - /* Append elements */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* Insert an element in the middle */ - nums.add(3, 6); // Insert 6 at index 3 - - /* Remove an element */ - nums.remove(3); // Remove the element at index 3 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Clear the list - nums.clear - - # Append elements - nums << 1 - nums << 3 - nums << 2 - nums << 5 - nums << 4 - - # Insert an element in the middle - nums.insert(3, 6) # Insert 6 at index 3 - - # Remove an element - nums.delete_at(3) # Remove the element at index 3 - ``` +```snippet +insert_remove_element +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Clear%20the%20list%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20Append%20elements%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20Insert%20an%20element%20in%20the%20middle%0A%20%20%20%20nums.insert%283%2C%206%29%20%20%23%20Insert%206%20at%20index%203%0A%20%20%20%20%0A%20%20%20%20%23%20Remove%20an%20element%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20Remove%20the%20element%20at%20index%203&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_element_tutor ### Traversing a list Like an array, a list can be traversed by index or by visiting its elements directly. -=== "Python" - - ```python title="list.py" - # Traverse the list by index - count = 0 - for i in range(len(nums)): - count += nums[i] - - # Traverse list elements directly - for num in nums: - count += num - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Traverse the list by index */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums[i]; - } - - /* Traverse list elements directly */ - count = 0; - for (int num : nums) { - count += num; - } - ``` - -=== "Java" - - ```java title="list.java" - /* Traverse the list by index */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums.get(i); - } - - /* Traverse list elements directly */ - for (int num : nums) { - count += num; - } - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Traverse the list by index */ - int count = 0; - for (int i = 0; i < nums.Count; i++) { - count += nums[i]; - } - - /* Traverse list elements directly */ - count = 0; - foreach (int num in nums) { - count += num; - } - ``` - -=== "Go" - - ```go title="list_test.go" - /* Traverse the list by index */ - count := 0 - for i := 0; i < len(nums); i++ { - count += nums[i] - } - - /* Traverse list elements directly */ - count = 0 - for _, num := range nums { - count += num - } - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Traverse the list by index */ - var count = 0 - for i in nums.indices { - count += nums[i] - } - - /* Traverse list elements directly */ - count = 0 - for num in nums { - count += num - } - ``` - -=== "JS" - - ```javascript title="list.js" - /* Traverse the list by index */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* Traverse list elements directly */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Traverse the list by index */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* Traverse list elements directly */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Traverse the list by index */ - int count = 0; - for (var i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* Traverse list elements directly */ - count = 0; - for (var num in nums) { - count += num; - } - ``` - -=== "Rust" - - ```rust title="list.rs" - // Traverse the list by index - let mut _count = 0; - for i in 0..nums.len() { - _count += nums[i]; - } - - // Traverse list elements directly - _count = 0; - for num in &nums { - _count += num; - } - ``` - -=== "C" - - ```c title="list.c" - // C does not provide a built-in dynamic array - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Traverse the list by index */ - var count = 0 - for (i in nums.indices) { - count += nums[i] - } - - /* Traverse list elements directly */ - for (num in nums) { - count += num - } - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Traverse the list by index - count = 0 - for i in 0...nums.length - count += nums[i] - end - - # Traverse list elements directly - count = 0 - for num in nums - count += num - end - ``` +```snippet +iterate_list +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Traverse%20the%20list%20by%20index%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20Traverse%20list%20elements%20directly%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor iterate_list_tutor ### Concatenating lists Given another list `nums1`, we can append its elements to the end of the original list. -=== "Python" - - ```python title="list.py" - # Concatenate two lists - nums1: list[int] = [6, 8, 7, 10, 9] - nums += nums1 # Append nums1 to nums - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Concatenate two lists */ - vector nums1 = { 6, 8, 7, 10, 9 }; - // Append nums1 to nums - nums.insert(nums.end(), nums1.begin(), nums1.end()); - ``` - -=== "Java" - - ```java title="list.java" - /* Concatenate two lists */ - List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); - nums.addAll(nums1); // Append nums1 to nums - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Concatenate two lists */ - List nums1 = [6, 8, 7, 10, 9]; - nums.AddRange(nums1); // Append nums1 to nums - ``` - -=== "Go" - - ```go title="list_test.go" - /* Concatenate two lists */ - nums1 := []int{6, 8, 7, 10, 9} - nums = append(nums, nums1...) // Append nums1 to nums - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Concatenate two lists */ - let nums1 = [6, 8, 7, 10, 9] - nums.append(contentsOf: nums1) // Append nums1 to nums - ``` - -=== "JS" - - ```javascript title="list.js" - /* Concatenate two lists */ - const nums1 = [6, 8, 7, 10, 9]; - nums.push(...nums1); // Append nums1 to nums - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Concatenate two lists */ - const nums1: number[] = [6, 8, 7, 10, 9]; - nums.push(...nums1); // Append nums1 to nums - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Concatenate two lists */ - List nums1 = [6, 8, 7, 10, 9]; - nums.addAll(nums1); // Append nums1 to nums - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Concatenate two lists */ - let nums1: Vec = vec![6, 8, 7, 10, 9]; - nums.extend(nums1); - ``` - -=== "C" - - ```c title="list.c" - // C does not provide a built-in dynamic array - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Concatenate two lists */ - val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() - nums.addAll(nums1) // Append nums1 to nums - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Concatenate two lists - nums1 = [6, 8, 7, 10, 9] - nums += nums1 - ``` +```snippet +concat_list +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Concatenate%20two%20lists%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20Append%20nums1%20to%20nums&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor concat_list_tutor ### Sorting a list Once the list is sorted, we can apply binary search and two-pointer algorithms, which often appear in array problems. -=== "Python" - - ```python title="list.py" - # Sort the list - nums.sort() # After sorting, elements are in ascending order - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Sort the list */ - sort(nums.begin(), nums.end()); // After sorting, elements are in ascending order - ``` - -=== "Java" - - ```java title="list.java" - /* Sort the list */ - Collections.sort(nums); // After sorting, elements are in ascending order - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Sort the list */ - nums.Sort(); // After sorting, elements are in ascending order - ``` - -=== "Go" - - ```go title="list_test.go" - /* Sort the list */ - sort.Ints(nums) // After sorting, elements are in ascending order - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Sort the list */ - nums.sort() // After sorting, elements are in ascending order - ``` - -=== "JS" - - ```javascript title="list.js" - /* Sort the list */ - nums.sort((a, b) => a - b); // After sorting, elements are in ascending order - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Sort the list */ - nums.sort((a, b) => a - b); // After sorting, elements are in ascending order - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Sort the list */ - nums.sort(); // After sorting, elements are in ascending order - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Sort the list */ - nums.sort(); // After sorting, elements are in ascending order - ``` - -=== "C" - - ```c title="list.c" - // C does not provide a built-in dynamic array - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Sort the list */ - nums.sort() // After sorting, elements are in ascending order - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Sort the list - nums = nums.sort { |a, b| a <=> b } # After sorting, elements are in ascending order - ``` +```snippet +sort_list +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Sort%20the%20list%0A%20%20%20%20nums.sort%28%29%20%20%23%20After%20sorting%2C%20elements%20are%20in%20ascending%20order&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor sort_list_tutor ## Implementing a list diff --git a/en/docs/chapter_backtracking/backtracking_algorithm.md b/en/docs/chapter_backtracking/backtracking_algorithm.md index b43dc949d..b2d45c206 100644 --- a/en/docs/chapter_backtracking/backtracking_algorithm.md +++ b/en/docs/chapter_backtracking/backtracking_algorithm.md @@ -95,339 +95,9 @@ We will now extract the core pattern of trying, undoing, and pruning into a more In the following template, `state` is the current problem state, and `choices` contains the choices available from that state: -=== "Python" - - ```python title="" - def backtrack(state: State, choices: list[choice], res: list[state]): - """Backtracking template""" - # Check whether the state is a solution - if is_solution(state): - # Record the solution - record_solution(state, res) - # Stop searching this branch - return - # Try every choice - for choice in choices: - # Prune: check whether the choice is valid - if is_valid(state, choice): - # Try: make the choice and update the state - make_choice(state, choice) - backtrack(state, choices, res) - # Backtrack: undo the choice and restore the previous state - undo_choice(state, choice) - ``` - -=== "C++" - - ```cpp title="" - /* Backtracking template */ - void backtrack(State *state, vector &choices, vector &res) { - // Check whether the state is a solution - if (isSolution(state)) { - // Record the solution - recordSolution(state, res); - // Stop searching this branch - return; - } - // Try every choice - for (Choice choice : choices) { - // Prune: check whether the choice is valid - if (isValid(state, choice)) { - // Try: make the choice and update the state - makeChoice(state, choice); - backtrack(state, choices, res); - // Backtrack: undo the choice and restore the previous state - undoChoice(state, choice); - } - } - } - ``` - -=== "Java" - - ```java title="" - /* Backtracking template */ - void backtrack(State state, List choices, List res) { - // Check whether the state is a solution - if (isSolution(state)) { - // Record the solution - recordSolution(state, res); - // Stop searching this branch - return; - } - // Try every choice - for (Choice choice : choices) { - // Prune: check whether the choice is valid - if (isValid(state, choice)) { - // Try: make the choice and update the state - makeChoice(state, choice); - backtrack(state, choices, res); - // Backtrack: undo the choice and restore the previous state - undoChoice(state, choice); - } - } - } - ``` - -=== "C#" - - ```csharp title="" - /* Backtracking template */ - void Backtrack(State state, List choices, List res) { - // Check whether the state is a solution - if (IsSolution(state)) { - // Record the solution - RecordSolution(state, res); - // Stop searching this branch - return; - } - // Try every choice - foreach (Choice choice in choices) { - // Prune: check whether the choice is valid - if (IsValid(state, choice)) { - // Try: make the choice and update the state - MakeChoice(state, choice); - Backtrack(state, choices, res); - // Backtrack: undo the choice and restore the previous state - UndoChoice(state, choice); - } - } - } - ``` - -=== "Go" - - ```go title="" - /* Backtracking template */ - func backtrack(state *State, choices []Choice, res *[]State) { - // Check whether the state is a solution - if isSolution(state) { - // Record the solution - recordSolution(state, res) - // Stop searching this branch - return - } - // Try every choice - for _, choice := range choices { - // Prune: check whether the choice is valid - if isValid(state, choice) { - // Try: make the choice and update the state - makeChoice(state, choice) - backtrack(state, choices, res) - // Backtrack: undo the choice and restore the previous state - undoChoice(state, choice) - } - } - } - ``` - -=== "Swift" - - ```swift title="" - /* Backtracking template */ - func backtrack(state: inout State, choices: [Choice], res: inout [State]) { - // Check whether the state is a solution - if isSolution(state: state) { - // Record the solution - recordSolution(state: state, res: &res) - // Stop searching this branch - return - } - // Try every choice - for choice in choices { - // Prune: check whether the choice is valid - if isValid(state: state, choice: choice) { - // Try: make the choice and update the state - makeChoice(state: &state, choice: choice) - backtrack(state: &state, choices: choices, res: &res) - // Backtrack: undo the choice and restore the previous state - undoChoice(state: &state, choice: choice) - } - } - } - ``` - -=== "JS" - - ```javascript title="" - /* Backtracking template */ - function backtrack(state, choices, res) { - // Check whether the state is a solution - if (isSolution(state)) { - // Record the solution - recordSolution(state, res); - // Stop searching this branch - return; - } - // Try every choice - for (let choice of choices) { - // Prune: check whether the choice is valid - if (isValid(state, choice)) { - // Try: make the choice and update the state - makeChoice(state, choice); - backtrack(state, choices, res); - // Backtrack: undo the choice and restore the previous state - undoChoice(state, choice); - } - } - } - ``` - -=== "TS" - - ```typescript title="" - /* Backtracking template */ - function backtrack(state: State, choices: Choice[], res: State[]): void { - // Check whether the state is a solution - if (isSolution(state)) { - // Record the solution - recordSolution(state, res); - // Stop searching this branch - return; - } - // Try every choice - for (let choice of choices) { - // Prune: check whether the choice is valid - if (isValid(state, choice)) { - // Try: make the choice and update the state - makeChoice(state, choice); - backtrack(state, choices, res); - // Backtrack: undo the choice and restore the previous state - undoChoice(state, choice); - } - } - } - ``` - -=== "Dart" - - ```dart title="" - /* Backtracking template */ - void backtrack(State state, List, List res) { - // Check whether the state is a solution - if (isSolution(state)) { - // Record the solution - recordSolution(state, res); - // Stop searching this branch - return; - } - // Try every choice - for (Choice choice in choices) { - // Prune: check whether the choice is valid - if (isValid(state, choice)) { - // Try: make the choice and update the state - makeChoice(state, choice); - backtrack(state, choices, res); - // Backtrack: undo the choice and restore the previous state - undoChoice(state, choice); - } - } - } - ``` - -=== "Rust" - - ```rust title="" - /* Backtracking template */ - fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { - // Check whether the state is a solution - if is_solution(state) { - // Record the solution - record_solution(state, res); - // Stop searching this branch - return; - } - // Try every choice - for choice in choices { - // Prune: check whether the choice is valid - if is_valid(state, choice) { - // Try: make the choice and update the state - make_choice(state, choice); - backtrack(state, choices, res); - // Backtrack: undo the choice and restore the previous state - undo_choice(state, choice); - } - } - } - ``` - -=== "C" - - ```c title="" - /* Backtracking template */ - void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { - // Check whether the state is a solution - if (isSolution(state)) { - // Record the solution - recordSolution(state, res, numRes); - // Stop searching this branch - return; - } - // Try every choice - for (int i = 0; i < numChoices; i++) { - // Prune: check whether the choice is valid - if (isValid(state, &choices[i])) { - // Try: make the choice and update the state - makeChoice(state, &choices[i]); - backtrack(state, choices, numChoices, res, numRes); - // Backtrack: undo the choice and restore the previous state - undoChoice(state, &choices[i]); - } - } - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Backtracking template */ - fun backtrack(state: State?, choices: List, res: List?) { - // Check whether the state is a solution - if (isSolution(state)) { - // Record the solution - recordSolution(state, res) - // Stop searching this branch - return - } - // Try every choice - for (choice in choices) { - // Prune: check whether the choice is valid - if (isValid(state, choice)) { - // Try: make the choice and update the state - makeChoice(state, choice) - backtrack(state, choices, res) - // Backtrack: undo the choice and restore the previous state - undoChoice(state, choice) - } - } - } - ``` - -=== "Ruby" - - ```ruby title="" - ### Backtracking template ### - def backtrack(state, choices, res) - # Check whether the state is a solution - if is_solution?(state) - # Record the solution - record_solution(state, res) - return - end - - # Try every choice - for choice in choices - # Prune: check whether the choice is valid - if is_valid?(state, choice) - # Try: make the choice and update the state - make_choice(state, choice) - backtrack(state, choices, res) - # Backtrack: undo the choice and restore the previous state - undo_choice(state, choice) - end - end - end - ``` +```snippet +backtrack_framework +``` Now apply this template to Example 3. The `state` is the current path of visited nodes, `choices` consists of the current node's left and right children, and `res` is the list of paths: diff --git a/en/docs/chapter_computational_complexity/space_complexity.md b/en/docs/chapter_computational_complexity/space_complexity.md index 4e5415cfe..de2b459e5 100644 --- a/en/docs/chapter_computational_complexity/space_complexity.md +++ b/en/docs/chapter_computational_complexity/space_complexity.md @@ -24,342 +24,9 @@ Temporary space can be divided further into three parts. The corresponding code is: -=== "Python" - - ```python title="" - class Node: - """Class""" - def __init__(self, x: int): - self.val: int = x # Node value - self.next: Node | None = None # Reference to the next node - - def function() -> int: - """Function""" - # Perform some operations... - return 0 - - def algorithm(n) -> int: # Input data - A = 0 # Temporary data (constant, conventionally named in uppercase) - b = 0 # Temporary data (variable) - node = Node(0) # Temporary data (object) - c = function() # Stack frame (function call) - return A + b + c # Output data - ``` - -=== "C++" - - ```cpp title="" - /* Structure */ - struct Node { - int val; - Node *next; - Node(int x) : val(x), next(nullptr) {} - }; - - /* Function */ - int func() { - // Perform some operations... - return 0; - } - - int algorithm(int n) { // Input data - const int a = 0; // Temporary data (constant) - int b = 0; // Temporary data (variable) - Node* node = new Node(0); // Temporary data (object) - int c = func(); // Stack frame (function call) - return a + b + c; // Output data - } - ``` - -=== "Java" - - ```java title="" - /* Class */ - class Node { - int val; - Node next; - Node(int x) { val = x; } - } - - /* Function */ - int function() { - // Perform some operations... - return 0; - } - - int algorithm(int n) { // Input data - final int a = 0; // Temporary data (constant) - int b = 0; // Temporary data (variable) - Node node = new Node(0); // Temporary data (object) - int c = function(); // Stack frame (function call) - return a + b + c; // Output data - } - ``` - -=== "C#" - - ```csharp title="" - /* Class */ - class Node(int x) { - int val = x; - Node next; - } - - /* Function */ - int Function() { - // Perform some operations... - return 0; - } - - int Algorithm(int n) { // Input data - const int a = 0; // Temporary data (constant) - int b = 0; // Temporary data (variable) - Node node = new(0); // Temporary data (object) - int c = Function(); // Stack frame (function call) - return a + b + c; // Output data - } - ``` - -=== "Go" - - ```go title="" - /* Structure */ - type node struct { - val int - next *node - } - - /* Create a node structure */ - func newNode(val int) *node { - return &node{val: val} - } - - /* Function */ - func function() int { - // Perform some operations... - return 0 - } - - func algorithm(n int) int { // Input data - const a = 0 // Temporary data (constant) - b := 0 // Temporary data (variable) - newNode(0) // Temporary data (object) - c := function() // Stack frame (function call) - return a + b + c // Output data - } - ``` - -=== "Swift" - - ```swift title="" - /* Class */ - class Node { - var val: Int - var next: Node? - - init(x: Int) { - val = x - } - } - - /* Function */ - func function() -> Int { - // Perform some operations... - return 0 - } - - func algorithm(n: Int) -> Int { // Input data - let a = 0 // Temporary data (constant) - var b = 0 // Temporary data (variable) - let node = Node(x: 0) // Temporary data (object) - let c = function() // Stack frame (function call) - return a + b + c // Output data - } - ``` - -=== "JS" - - ```javascript title="" - /* Class */ - class Node { - val; - next; - constructor(val) { - this.val = val === undefined ? 0 : val; // Node value - this.next = null; // Reference to the next node - } - } - - /* Function */ - function constFunc() { - // Perform some operations - return 0; - } - - function algorithm(n) { // Input data - const a = 0; // Temporary data (constant) - let b = 0; // Temporary data (variable) - const node = new Node(0); // Temporary data (object) - const c = constFunc(); // Stack frame (function call) - return a + b + c; // Output data - } - ``` - -=== "TS" - - ```typescript title="" - /* Class */ - class Node { - val: number; - next: Node | null; - constructor(val?: number) { - this.val = val === undefined ? 0 : val; // Node value - this.next = null; // Reference to the next node - } - } - - /* Function */ - function constFunc(): number { - // Perform some operations - return 0; - } - - function algorithm(n: number): number { // Input data - const a = 0; // Temporary data (constant) - let b = 0; // Temporary data (variable) - const node = new Node(0); // Temporary data (object) - const c = constFunc(); // Stack frame (function call) - return a + b + c; // Output data - } - ``` - -=== "Dart" - - ```dart title="" - /* Class */ - class Node { - int val; - Node next; - Node(this.val, [this.next]); - } - - /* Function */ - int function() { - // Perform some operations... - return 0; - } - - int algorithm(int n) { // Input data - const int a = 0; // Temporary data (constant) - int b = 0; // Temporary data (variable) - Node node = Node(0); // Temporary data (object) - int c = function(); // Stack frame (function call) - return a + b + c; // Output data - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* Structure */ - struct Node { - val: i32, - next: Option>>, - } - - /* Create a Node structure */ - impl Node { - fn new(val: i32) -> Self { - Self { val: val, next: None } - } - } - - /* Function */ - fn function() -> i32 { - // Perform some operations... - return 0; - } - - fn algorithm(n: i32) -> i32 { // Input data - const a: i32 = 0; // Temporary data (constant) - let mut b = 0; // Temporary data (variable) - let node = Node::new(0); // Temporary data (object) - let c = function(); // Stack frame (function call) - return a + b + c; // Output data - } - ``` - -=== "C" - - ```c title="" - /* Function */ - int func() { - // Perform some operations... - return 0; - } - - int algorithm(int n) { // Input data - const int a = 0; // Temporary data (constant) - int b = 0; // Temporary data (variable) - int c = func(); // Stack frame (function call) - return a + b + c; // Output data - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Class */ - class Node(var _val: Int) { - var next: Node? = null - } - - /* Function */ - fun function(): Int { - // Perform some operations... - return 0 - } - - fun algorithm(n: Int): Int { // Input data - val a = 0 // Temporary data (constant) - var b = 0 // Temporary data (variable) - val node = Node(0) // Temporary data (object) - val c = function() // Stack frame (function call) - return a + b + c // Output data - } - ``` - -=== "Ruby" - - ```ruby title="" - ### Class ### - class Node - attr_accessor :val # Node value - attr_accessor :next # Reference to the next node - - def initialize(x) - @val = x - end - end - - ### Function ### - def function - # Perform some operations... - 0 - end - - ### Algorithm ### - def algorithm(n) # Input data - a = 0 # Temporary data (constant) - b = 0 # Temporary data (variable) - node = Node.new(0) # Temporary data (object) - c = function # Stack frame (function call) - a + b + c # Output data - end - ``` +```snippet +space_categories +``` ## Deriving space complexity @@ -372,428 +39,15 @@ In the following code, "worst case" has two meanings. 1. **The worst input**: When $n < 10$, space complexity is $O(1)$. When $n > 10$, initializing `nums` requires $O(n)$ space, so worst-case space complexity is $O(n)$. 2. **Peak memory during execution**: Before the final line, the program uses $O(1)$ space. Initializing `nums` raises usage to $O(n)$, so worst-case space complexity is $O(n)$. -=== "Python" - - ```python title="" - def algorithm(n: int): - a = 0 # O(1) - b = [0] * 10000 # O(1) - if n > 10: - nums = [0] * n # O(n) - ``` - -=== "C++" - - ```cpp title="" - void algorithm(int n) { - int a = 0; // O(1) - vector b(10000); // O(1) - if (n > 10) - vector nums(n); // O(n) - } - ``` - -=== "Java" - - ```java title="" - void algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) - int[] nums = new int[n]; // O(n) - } - ``` - -=== "C#" - - ```csharp title="" - void Algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) { - int[] nums = new int[n]; // O(n) - } - } - ``` - -=== "Go" - - ```go title="" - func algorithm(n int) { - a := 0 // O(1) - b := make([]int, 10000) // O(1) - var nums []int - if n > 10 { - nums := make([]int, n) // O(n) - } - fmt.Println(a, b, nums) - } - ``` - -=== "Swift" - - ```swift title="" - func algorithm(n: Int) { - let a = 0 // O(1) - let b = Array(repeating: 0, count: 10000) // O(1) - if n > 10 { - let nums = Array(repeating: 0, count: n) // O(n) - } - } - ``` - -=== "JS" - - ```javascript title="" - function algorithm(n) { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "TS" - - ```typescript title="" - function algorithm(n: number): void { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "Dart" - - ```dart title="" - void algorithm(int n) { - int a = 0; // O(1) - List b = List.filled(10000, 0); // O(1) - if (n > 10) { - List nums = List.filled(n, 0); // O(n) - } - } - ``` - -=== "Rust" - - ```rust title="" - fn algorithm(n: i32) { - let a = 0; // O(1) - let b = [0; 10000]; // O(1) - if n > 10 { - let nums = vec![0; n as usize]; // O(n) - } - } - ``` - -=== "C" - - ```c title="" - void algorithm(int n) { - int a = 0; // O(1) - int b[10000]; // O(1) - if (n > 10) - int nums[n] = {0}; // O(n) - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun algorithm(n: Int) { - val a = 0 // O(1) - val b = IntArray(10000) // O(1) - if (n > 10) { - val nums = IntArray(n) // O(n) - } - } - ``` - -=== "Ruby" - - ```ruby title="" - def algorithm(n) - a = 0 # O(1) - b = Array.new(10000) # O(1) - nums = Array.new(n) if n > 10 # O(n) - end - ``` +```snippet +worst_case_space +``` **For recursive functions, remember to count stack frames**. Consider the following code: -=== "Python" - - ```python title="" - def function() -> int: - # Perform some operations - return 0 - - def loop(n: int): - """The loop uses O(1) space""" - for _ in range(n): - function() - - def recur(n: int): - """The recursion uses O(n) space""" - if n == 1: - return - return recur(n - 1) - ``` - -=== "C++" - - ```cpp title="" - int func() { - // Perform some operations - return 0; - } - /* The loop uses O(1) space */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* The recursion uses O(n) space */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Java" - - ```java title="" - int function() { - // Perform some operations - return 0; - } - /* The loop uses O(1) space */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* The recursion uses O(n) space */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "C#" - - ```csharp title="" - int Function() { - // Perform some operations - return 0; - } - /* The loop uses O(1) space */ - void Loop(int n) { - for (int i = 0; i < n; i++) { - Function(); - } - } - /* The recursion uses O(n) space */ - int Recur(int n) { - if (n == 1) return 1; - return Recur(n - 1); - } - ``` - -=== "Go" - - ```go title="" - func function() int { - // Perform some operations - return 0 - } - - /* The loop uses O(1) space */ - func loop(n int) { - for i := 0; i < n; i++ { - function() - } - } - - /* The recursion uses O(n) space */ - func recur(n int) { - if n == 1 { - return - } - recur(n - 1) - } - ``` - -=== "Swift" - - ```swift title="" - @discardableResult - func function() -> Int { - // Perform some operations - return 0 - } - - /* The loop uses O(1) space */ - func loop(n: Int) { - for _ in 0 ..< n { - function() - } - } - - /* The recursion uses O(n) space */ - func recur(n: Int) { - if n == 1 { - return - } - recur(n: n - 1) - } - ``` - -=== "JS" - - ```javascript title="" - function constFunc() { - // Perform some operations - return 0; - } - /* The loop uses O(1) space */ - function loop(n) { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* The recursion uses O(n) space */ - function recur(n) { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "TS" - - ```typescript title="" - function constFunc(): number { - // Perform some operations - return 0; - } - /* The loop uses O(1) space */ - function loop(n: number): void { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* The recursion uses O(n) space */ - function recur(n: number): void { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "Dart" - - ```dart title="" - int function() { - // Perform some operations - return 0; - } - /* The loop uses O(1) space */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* The recursion uses O(n) space */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Rust" - - ```rust title="" - fn function() -> i32 { - // Perform some operations - return 0; - } - /* The loop uses O(1) space */ - fn loop(n: i32) { - for i in 0..n { - function(); - } - } - /* The recursion uses O(n) space */ - fn recur(n: i32) { - if n == 1 { - return; - } - recur(n - 1); - } - ``` - -=== "C" - - ```c title="" - int func() { - // Perform some operations - return 0; - } - /* The loop uses O(1) space */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* The recursion uses O(n) space */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun function(): Int { - // Perform some operations - return 0 - } - /* The loop uses O(1) space */ - fun loop(n: Int) { - for (i in 0.. numbers = List.filled(5, 0); - List decimals = List.filled(5, 0.0); - List characters = List.filled(5, 'a'); - List bools = List.filled(5, false); - ``` - -=== "Rust" - - ```rust title="" - // Initialize arrays with different basic data types - let numbers: Vec = vec![0; 5]; - let decimals: Vec = vec![0.0; 5]; - let characters: Vec = vec!['0'; 5]; - let bools: Vec = vec![false; 5]; - ``` - -=== "C" - - ```c title="" - // Initialize arrays with different basic data types - int numbers[10]; - float decimals[10]; - char characters[10]; - bool bools[10]; - ``` - -=== "Kotlin" - - ```kotlin title="" - // Initialize arrays with different basic data types - val numbers = IntArray(5) - val decinals = FloatArray(5) - val characters = CharArray(5) - val bools = BooleanArray(5) - ``` - -=== "Ruby" - - ```ruby title="" - # Ruby arrays can hold different basic data types and object references - data = [0, 0.0, 'a', false, ListNode(0)] - ``` +```snippet +basic_type_arrays +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked%20list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20successor%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20arrays%20with%20different%20basic%20data%20types%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20%2A%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20%2A%205%0A%20%20%20%20%23%20A%20Python%20character%20is%20a%20string%20of%20length%201%0A%20%20%20%20characters%20%3D%20%5B%270%27%5D%20%2A%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20%2A%205%0A%20%20%20%20%23%20Python%20lists%20can%20hold%20different%20basic%20data%20types%20and%20object%20references%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20%27a%27%2C%20False%2C%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor basic_type_arrays_tutor diff --git a/en/docs/chapter_hashing/hash_algorithm.md b/en/docs/chapter_hashing/hash_algorithm.md index 03c9a99ef..d3f19fb9b 100644 --- a/en/docs/chapter_hashing/hash_algorithm.md +++ b/en/docs/chapter_hashing/hash_algorithm.md @@ -113,295 +113,13 @@ Hash-table keys can be integers, floating-point numbers, strings, and other type Built-in hash functions differ in their definitions and implementations across programming languages. -=== "Python" - - ```python title="built_in_hash.py" - num = 3 - hash_num = hash(num) - # The hash of the integer 3 is 3 - - bol = True - hash_bol = hash(bol) - # The hash of the Boolean True is 1 - - dec = 3.14159 - hash_dec = hash(dec) - # The hash of the floating-point number 3.14159 is 326484311674566659 - - str = "Hello 算法" - hash_str = hash(str) - # The hash of the string “Hello 算法” is 4617003410720528961 - - tup = (12836, "小哈") - hash_tup = hash(tup) - # The hash of the tuple (12836, '小哈') is 1029005403108185979 - - obj = ListNode(0) - hash_obj = hash(obj) - # The hash of the node object is 274267521 - ``` - -=== "C++" - - ```cpp title="built_in_hash.cpp" - int num = 3; - size_t hashNum = hash()(num); - // The hash of the integer 3 is 3 - - bool bol = true; - size_t hashBol = hash()(bol); - // The hash of the Boolean 1 is 1 - - double dec = 3.14159; - size_t hashDec = hash()(dec); - // The hash of the floating-point number 3.14159 is 4614256650576692846 - - string str = "Hello 算法"; - size_t hashStr = hash()(str); - // The hash of the string “Hello 算法” is 15466937326284535026 - - // In C++, built-in std::hash() provides hashing only for basic data types - // Hashing for arrays and objects must be implemented separately - ``` - -=== "Java" - - ```java title="built_in_hash.java" - int num = 3; - int hashNum = Integer.hashCode(num); - // The hash of the integer 3 is 3 - - boolean bol = true; - int hashBol = Boolean.hashCode(bol); - // The hash of the Boolean true is 1231 - - double dec = 3.14159; - int hashDec = Double.hashCode(dec); - // The hash of the floating-point number 3.14159 is -1340954729 - - String str = "Hello 算法"; - int hashStr = str.hashCode(); - // The hash of the string “Hello 算法” is -727081396 - - Object[] arr = { 12836, "小哈" }; - int hashTup = Arrays.hashCode(arr); - // The hash of the array [12836, 小哈] is 1151158 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode(); - // The hash of the node object utils.ListNode@7dc5e7b4 is 2110121908 - ``` - -=== "C#" - - ```csharp title="built_in_hash.cs" - int num = 3; - int hashNum = num.GetHashCode(); - // The hash of the integer 3 is 3; - - bool bol = true; - int hashBol = bol.GetHashCode(); - // The hash of the Boolean true is 1; - - double dec = 3.14159; - int hashDec = dec.GetHashCode(); - // The hash of the floating-point number 3.14159 is -1340954729; - - string str = "Hello 算法"; - int hashStr = str.GetHashCode(); - // The hash of the string “Hello 算法” is -586107568; - - object[] arr = [12836, "小哈"]; - int hashTup = arr.GetHashCode(); - // The hash of the array [12836, 小哈] is 42931033; - - ListNode obj = new(0); - int hashObj = obj.GetHashCode(); - // The hash of the node object 0 is 39053774; - ``` - -=== "Go" - - ```go title="built_in_hash.go" - // Go provides no built-in hash-code function - ``` - -=== "Swift" - - ```swift title="built_in_hash.swift" - let num = 3 - let hashNum = num.hashValue - // The hash of the integer 3 is 9047044699613009734 - - let bol = true - let hashBol = bol.hashValue - // The hash of the Boolean true is -4431640247352757451 - - let dec = 3.14159 - let hashDec = dec.hashValue - // The hash of the floating-point number 3.14159 is -2465384235396674631 - - let str = "Hello 算法" - let hashStr = str.hashValue - // The hash of the string “Hello 算法” is -7850626797806988787 - - let arr = [AnyHashable(12836), AnyHashable("小哈")] - let hashTup = arr.hashValue - // The hash of the array [AnyHashable(12836), AnyHashable("小哈")] is -2308633508154532996 - - let obj = ListNode(x: 0) - let hashObj = obj.hashValue - // The hash of the node object utils.ListNode is -2434780518035996159 - ``` - -=== "JS" - - ```javascript title="built_in_hash.js" - // JavaScript provides no built-in hash-code function - ``` - -=== "TS" - - ```typescript title="built_in_hash.ts" - // TypeScript provides no built-in hash-code function - ``` - -=== "Dart" - - ```dart title="built_in_hash.dart" - int num = 3; - int hashNum = num.hashCode; - // The hash of the integer 3 is 34803 - - bool bol = true; - int hashBol = bol.hashCode; - // The hash of the Boolean true is 1231 - - double dec = 3.14159; - int hashDec = dec.hashCode; - // The hash of the floating-point number 3.14159 is 2570631074981783 - - String str = "Hello 算法"; - int hashStr = str.hashCode; - // The hash of the string “Hello 算法” is 468167534 - - List arr = [12836, "小哈"]; - int hashArr = arr.hashCode; - // The hash of the array [12836, 小哈] is 976512528 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode; - // The hash of the node object Instance of 'ListNode' is 1033450432 - ``` - -=== "Rust" - - ```rust title="built_in_hash.rs" - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - - let num = 3; - let mut num_hasher = DefaultHasher::new(); - num.hash(&mut num_hasher); - let hash_num = num_hasher.finish(); - // The hash of the integer 3 is 568126464209439262 - - let bol = true; - let mut bol_hasher = DefaultHasher::new(); - bol.hash(&mut bol_hasher); - let hash_bol = bol_hasher.finish(); - // The hash of the Boolean true is 4952851536318644461 - - let dec: f32 = 3.14159; - let mut dec_hasher = DefaultHasher::new(); - dec.to_bits().hash(&mut dec_hasher); - let hash_dec = dec_hasher.finish(); - // The hash of the floating-point number 3.14159 is 2566941990314602357 - - let str = "Hello 算法"; - let mut str_hasher = DefaultHasher::new(); - str.hash(&mut str_hasher); - let hash_str = str_hasher.finish(); - // The hash of the string “Hello 算法” is 16092673739211250988 - - let arr = (&12836, &"小哈"); - let mut tup_hasher = DefaultHasher::new(); - arr.hash(&mut tup_hasher); - let hash_tup = tup_hasher.finish(); - // The hash of the tuple (12836, "小哈") is 1885128010422702749 - - let node = ListNode::new(42); - let mut hasher = DefaultHasher::new(); - node.borrow().val.hash(&mut hasher); - let hash = hasher.finish(); - // The hash of the node object RefCell { value: ListNode { val: 42, next: None } } is 15387811073369036852 - ``` - -=== "C" - - ```c title="built_in_hash.c" - // C provides no built-in hash-code function - ``` - -=== "Kotlin" - - ```kotlin title="built_in_hash.kt" - val num = 3 - val hashNum = num.hashCode() - // The hash of the integer 3 is 3 - - val bol = true - val hashBol = bol.hashCode() - // The hash of the Boolean true is 1231 - - val dec = 3.14159 - val hashDec = dec.hashCode() - // The hash of the floating-point number 3.14159 is -1340954729 - - val str = "Hello 算法" - val hashStr = str.hashCode() - // The hash of the string “Hello 算法” is -727081396 - - val arr = arrayOf(12836, "小哈") - val hashTup = arr.hashCode() - // The hash of the array [12836, 小哈] is 189568618 - - val obj = ListNode(0) - val hashObj = obj.hashCode() - // The hash of the node object utils.ListNode@1d81eb93 is 495053715 - ``` - -=== "Ruby" - - ```ruby title="built_in_hash.rb" - num = 3 - hash_num = num.hash - # The hash of the integer 3 is -4385856518450339636 - - bol = true - hash_bol = bol.hash - # The hash of the Boolean true is -1617938112149317027 - - dec = 3.14159 - hash_dec = dec.hash - # The hash of the floating-point number 3.14159 is -1479186995943067893 - - str = "Hello 算法" - hash_str = str.hash - # The hash of the string “Hello 算法” is -4075943250025831763 - - tup = [12836, '小哈'] - hash_tup = tup.hash - # The hash of the tuple (12836, '小哈') is 1999544809202288822 - - obj = ListNode.new(0) - hash_obj = obj.hash - # The hash of the node object # is 4302940560806366381 - ``` +```snippet +builtin_hash +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked-list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20next%20node%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20integer%203%20is%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20Boolean%20True%20is%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20floating-point%20number%203.14159%20is%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20string%20%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%20is%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20tuple%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20is%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20node%20object%20%3CListNode%20object%20at%200x1058fd810%3E%20is%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor builtin_hash_tutor In many programming languages, **only immutable objects can serve as hash-table keys**. If a list, a dynamic array, were used as a key, changing its contents would change its hash, making the original value impossible to retrieve from the table. diff --git a/en/docs/chapter_hashing/hash_map.md b/en/docs/chapter_hashing/hash_map.md index 9c9e96d21..9c69cf4fd 100755 --- a/en/docs/chapter_hashing/hash_map.md +++ b/en/docs/chapter_hashing/hash_map.md @@ -26,517 +26,23 @@ Arrays and linked lists also support lookup. The table below compares their effi Common operations include initialization, lookup, adding key-value pairs, and deleting pairs. Examples follow: -=== "Python" - - ```python title="hash_map.py" - # Initialize a hash table - hmap: dict = {} - - # Insertion - # Add key-value pairs (key, value) to the hash table - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - # Lookup - # Look up key in the hash table to obtain value - name: str = hmap[15937] - - # Deletion - # Remove a key-value pair (key, value) from the hash table - hmap.pop(10583) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* Initialize a hash table */ - unordered_map map; - - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - map[12836] = "小哈"; - map[15937] = "小啰"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鸭"; - - /* Lookup */ - // Look up key in the hash table to obtain value - string name = map[15937]; - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - map.erase(10583); - ``` - -=== "Java" - - ```java title="hash_map.java" - /* Initialize a hash table */ - Map map = new HashMap<>(); - - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - map.put(12836, "小哈"); - map.put(15937, "小啰"); - map.put(16750, "小算"); - map.put(13276, "小法"); - map.put(10583, "小鸭"); - - /* Lookup */ - // Look up key in the hash table to obtain value - String name = map.get(15937); - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - map.remove(10583); - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* Initialize a hash table */ - Dictionary map = new() { - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - { 12836, "小哈" }, - { 15937, "小啰" }, - { 16750, "小算" }, - { 13276, "小法" }, - { 10583, "小鸭" } - }; - - /* Lookup */ - // Look up key in the hash table to obtain value - string name = map[15937]; - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - map.Remove(10583); - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* Initialize a hash table */ - hmap := make(map[int]string) - - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - /* Lookup */ - // Look up key in the hash table to obtain value - name := hmap[15937] - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - delete(hmap, 10583) - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* Initialize a hash table */ - var map: [Int: String] = [:] - - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - map[12836] = "小哈" - map[15937] = "小啰" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鸭" - - /* Lookup */ - // Look up key in the hash table to obtain value - let name = map[15937]! - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - map.removeValue(forKey: 10583) - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* Initialize a hash table */ - const map = new Map(); - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - map.set(12836, '小哈'); - map.set(15937, '小啰'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鸭'); - - /* Lookup */ - // Look up key in the hash table to obtain value - let name = map.get(15937); - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - map.delete(10583); - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* Initialize a hash table */ - const map = new Map(); - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - map.set(12836, '小哈'); - map.set(15937, '小啰'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鸭'); - console.info('\nAfter insertion, the hash table is\nKey -> Value'); - console.info(map); - - /* Lookup */ - // Look up key in the hash table to obtain value - let name = map.get(15937); - console.info('\nLooking up student ID 15937 gives the name ' + name); - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - map.delete(10583); - console.info('\nAfter deleting 10583, the hash table is\nKey -> Value'); - console.info(map); - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* Initialize a hash table */ - Map map = {}; - - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - map[12836] = "小哈"; - map[15937] = "小啰"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鸭"; - - /* Lookup */ - // Look up key in the hash table to obtain value - String name = map[15937]; - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - map.remove(10583); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - use std::collections::HashMap; - - /* Initialize a hash table */ - let mut map: HashMap = HashMap::new(); - - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - map.insert(12836, "小哈".to_string()); - map.insert(15937, "小啰".to_string()); - map.insert(16750, "小算".to_string()); - map.insert(13279, "小法".to_string()); - map.insert(10583, "小鸭".to_string()); - - /* Lookup */ - // Look up key in the hash table to obtain value - let _name: Option<&String> = map.get(&15937); - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - let _removed_value: Option = map.remove(&10583); - ``` - -=== "C" - - ```c title="hash_map.c" - // C provides no built-in hash table - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* Initialize a hash table */ - val map = HashMap() - - /* Insertion */ - // Add key-value pairs (key, value) to the hash table - map[12836] = "小哈" - map[15937] = "小啰" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鸭" - - /* Lookup */ - // Look up key in the hash table to obtain value - val name = map[15937] - - /* Deletion */ - // Remove a key-value pair (key, value) from the hash table - map.remove(10583) - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # Initialize a hash table - hmap = {} - - # Insertion - # Add key-value pairs (key, value) to the hash table - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - # Lookup - # Look up key in the hash table to obtain value - name = hmap[15937] - - # Deletion - # Remove a key-value pair (key, value) from the hash table - hmap.delete(10583) - ``` +```snippet +hash_map_operations +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20hash%20table%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20Insertion%0A%20%20%20%20%23%20Add%20key-value%20pairs%20%28key%2C%20value%29%20to%20the%20hash%20table%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20Lookup%0A%20%20%20%20%23%20Look%20up%20key%20in%20the%20hash%20table%20to%20obtain%20value%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Deletion%0A%20%20%20%20%23%20Remove%20a%20key-value%20pair%20%28key%2C%20value%29%20from%20the%20hash%20table%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_operations_tutor There are three common ways to traverse a hash table: visit key-value pairs, keys only, or values only. Examples follow: -=== "Python" - - ```python title="hash_map.py" - # Traverse the hash table - # Traverse key-value pairs: key->value - for key, value in hmap.items(): - print(key, "->", value) - # Traverse keys only: key - for key in hmap.keys(): - print(key) - # Traverse values only: value - for value in hmap.values(): - print(value) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* Traverse the hash table */ - // Traverse key-value pairs: key->value - for (auto kv: map) { - cout << kv.first << " -> " << kv.second << endl; - } - // Use an iterator to traverse key->value pairs - for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; - } - ``` - -=== "Java" - - ```java title="hash_map.java" - /* Traverse the hash table */ - // Traverse key-value pairs: key->value - for (Map.Entry kv: map.entrySet()) { - System.out.println(kv.getKey() + " -> " + kv.getValue()); - } - // Traverse keys only: key - for (int key: map.keySet()) { - System.out.println(key); - } - // Traverse values only: value - for (String val: map.values()) { - System.out.println(val); - } - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* Traverse the hash table */ - // Traverse key-value pairs: Key->Value - foreach (var kv in map) { - Console.WriteLine(kv.Key + " -> " + kv.Value); - } - // Traverse keys only: key - foreach (int key in map.Keys) { - Console.WriteLine(key); - } - // Traverse values only: value - foreach (string val in map.Values) { - Console.WriteLine(val); - } - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* Traverse the hash table */ - // Traverse key-value pairs: key->value - for key, value := range hmap { - fmt.Println(key, "->", value) - } - // Traverse keys only: key - for key := range hmap { - fmt.Println(key) - } - // Traverse values only: value - for _, value := range hmap { - fmt.Println(value) - } - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* Traverse the hash table */ - // Traverse key-value pairs: Key->Value - for (key, value) in map { - print("\(key) -> \(value)") - } - // Traverse keys only: Key - for key in map.keys { - print(key) - } - // Traverse values only: Value - for value in map.values { - print(value) - } - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* Traverse the hash table */ - console.info('\nTraverse key-value pairs: Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\nTraverse keys only: Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\nTraverse values only: Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* Traverse the hash table */ - console.info('\nTraverse key-value pairs: Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\nTraverse keys only: Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\nTraverse values only: Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* Traverse the hash table */ - // Traverse key-value pairs: Key->Value - map.forEach((key, value) { - print('$key -> $value'); - }); - - // Traverse keys only: Key - map.keys.forEach((key) { - print(key); - }); - - // Traverse values only: Value - map.values.forEach((value) { - print(value); - }); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - /* Traverse the hash table */ - // Traverse key-value pairs: Key->Value - for (key, value) in &map { - println!("{key} -> {value}"); - } - - // Traverse keys only: Key - for key in map.keys() { - println!("{key}"); - } - - // Traverse values only: Value - for value in map.values() { - println!("{value}"); - } - ``` - -=== "C" - - ```c title="hash_map.c" - // C provides no built-in hash table - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* Traverse the hash table */ - // Traverse key-value pairs: key->value - for ((key, value) in map) { - println("$key -> $value") - } - // Traverse keys only: key - for (key in map.keys) { - println(key) - } - // Traverse values only: value - for (_val in map.values) { - println(_val) - } - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # Traverse the hash table - # Traverse key-value pairs: key->value - hmap.entries.each { |key, value| puts "#{key} -> #{value}" } - - # Traverse keys only: key - hmap.keys.each { |key| puts key } - - # Traverse values only: value - hmap.values.each { |val| puts val } - ``` +```snippet +hash_map_traversal +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20hash%20table%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20Insertion%0A%20%20%20%20%23%20Add%20key-value%20pairs%20%28key%2C%20value%29%20to%20the%20hash%20table%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20Traverse%20the%20hash%20table%0A%20%20%20%20%23%20Traverse%20key-value%20pairs%3A%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20Traverse%20keys%20only%3A%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20Traverse%20values%20only%3A%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_traversal_tutor ## A simple implementation diff --git a/en/docs/chapter_heap/heap.md b/en/docs/chapter_heap/heap.md index ec2f81acc..cc8b728a8 100644 --- a/en/docs/chapter_heap/heap.md +++ b/en/docs/chapter_heap/heap.md @@ -35,382 +35,13 @@ In practice, use the heap or priority-queue class provided by the language. Just as a sorting algorithm can order values in ascending or descending order, we can switch between min heaps and max heaps by setting a `flag` or changing the `Comparator`: -=== "Python" - - ```python title="heap.py" - # Initialize a min heap - min_heap, flag = [], 1 - # Initialize a max heap - max_heap, flag = [], -1 - - # Python's heapq module implements a min heap by default - # Negate elements before insertion to reverse their order and implement a max heap - # Here, flag = 1 gives a min heap and flag = -1 gives a max heap - - # Insert elements into the heap - heapq.heappush(max_heap, flag * 1) - heapq.heappush(max_heap, flag * 3) - heapq.heappush(max_heap, flag * 2) - heapq.heappush(max_heap, flag * 5) - heapq.heappush(max_heap, flag * 4) - - # Access the root element - peek: int = flag * max_heap[0] # 5 - - # Remove root elements - # Removed elements form a descending sequence - val = flag * heapq.heappop(max_heap) # 5 - val = flag * heapq.heappop(max_heap) # 4 - val = flag * heapq.heappop(max_heap) # 3 - val = flag * heapq.heappop(max_heap) # 2 - val = flag * heapq.heappop(max_heap) # 1 - - # Get the heap size - size: int = len(max_heap) - - # Check whether the heap is empty - is_empty: bool = not max_heap - - # Build a heap from a list - min_heap: list[int] = [1, 3, 2, 5, 4] - heapq.heapify(min_heap) - ``` - -=== "C++" - - ```cpp title="heap.cpp" - /* Initialize a heap */ - // Initialize a min heap - priority_queue, greater> minHeap; - // Initialize a max heap - priority_queue, less> maxHeap; - - /* Insert elements into the heap */ - maxHeap.push(1); - maxHeap.push(3); - maxHeap.push(2); - maxHeap.push(5); - maxHeap.push(4); - - /* Access the root element */ - int peek = maxHeap.top(); // 5 - - /* Remove root elements */ - // Removed elements form a descending sequence - maxHeap.pop(); // 5 - maxHeap.pop(); // 4 - maxHeap.pop(); // 3 - maxHeap.pop(); // 2 - maxHeap.pop(); // 1 - - /* Get the heap size */ - int size = maxHeap.size(); - - /* Check whether the heap is empty */ - bool isEmpty = maxHeap.empty(); - - /* Build a heap from a list */ - vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); - ``` - -=== "Java" - - ```java title="heap.java" - /* Initialize a heap */ - // Initialize a min heap - Queue minHeap = new PriorityQueue<>(); - // Initialize a max heap by changing the Comparator with a lambda expression - Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); - - /* Insert elements into the heap */ - maxHeap.offer(1); - maxHeap.offer(3); - maxHeap.offer(2); - maxHeap.offer(5); - maxHeap.offer(4); - - /* Access the root element */ - int peek = maxHeap.peek(); // 5 - - /* Remove root elements */ - // Removed elements form a descending sequence - peek = maxHeap.poll(); // 5 - peek = maxHeap.poll(); // 4 - peek = maxHeap.poll(); // 3 - peek = maxHeap.poll(); // 2 - peek = maxHeap.poll(); // 1 - - /* Get the heap size */ - int size = maxHeap.size(); - - /* Check whether the heap is empty */ - boolean isEmpty = maxHeap.isEmpty(); - - /* Build a heap from a list */ - minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); - ``` - -=== "C#" - - ```csharp title="heap.cs" - /* Initialize a heap */ - // Initialize a min heap - PriorityQueue minHeap = new(); - // Initialize a max heap by changing the Comparer with a lambda expression - PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); - - /* Insert elements into the heap */ - maxHeap.Enqueue(1, 1); - maxHeap.Enqueue(3, 3); - maxHeap.Enqueue(2, 2); - maxHeap.Enqueue(5, 5); - maxHeap.Enqueue(4, 4); - - /* Access the root element */ - int peek = maxHeap.Peek();//5 - - /* Remove root elements */ - // Removed elements form a descending sequence - peek = maxHeap.Dequeue(); // 5 - peek = maxHeap.Dequeue(); // 4 - peek = maxHeap.Dequeue(); // 3 - peek = maxHeap.Dequeue(); // 2 - peek = maxHeap.Dequeue(); // 1 - - /* Get the heap size */ - int size = maxHeap.Count; - - /* Check whether the heap is empty */ - bool isEmpty = maxHeap.Count == 0; - - /* Build a heap from a list */ - minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); - ``` - -=== "Go" - - ```go title="heap.go" - // In Go, implement heap.Interface to build an integer max heap - // Implementing heap.Interface also requires implementing sort.Interface - type intHeap []any - - // Push implements the heap.Interface method for inserting an element - func (h *intHeap) Push(x any) { - // Push and Pop use pointer receivers - // because they change the slice length as well as its contents. - *h = append(*h, x.(int)) - } - - // Pop implements the heap.Interface method used to remove the root element - func (h *intHeap) Pop() any { - // The element to remove has been placed at the end - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last - } - - // Len implements a sort.Interface method - func (h *intHeap) Len() int { - return len(*h) - } - - // Less implements a sort.Interface method - func (h *intHeap) Less(i, j int) bool { - // For a min heap, change this to a less-than comparison - return (*h)[i].(int) > (*h)[j].(int) - } - - // Swap implements a sort.Interface method - func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] - } - - // Top returns the root element - func (h *intHeap) Top() any { - return (*h)[0] - } - - /* Driver Code */ - func TestHeap(t *testing.T) { - /* Initialize a heap */ - // Initialize a max heap - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* Insert elements into the heap */ - // Call the heap.Interface methods to add elements - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* Access the root element */ - top := maxHeap.Top() - fmt.Printf("The root element is %d\n", top) - - /* Remove root elements */ - // Call the heap.Interface methods to remove elements - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 - - /* Get the heap size */ - size := len(*maxHeap) - fmt.Printf("The heap contains %d elements\n", size) - - /* Check whether the heap is empty */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("Is the heap empty: %t\n", isEmpty) - } - ``` - -=== "Swift" - - ```swift title="heap.swift" - /* Initialize a heap */ - // Swift's Heap type supports both minimum and maximum operations and requires swift-collections - var heap = Heap() - - /* Insert elements into the heap */ - heap.insert(1) - heap.insert(3) - heap.insert(2) - heap.insert(5) - heap.insert(4) - - /* Access the root element */ - var peek = heap.max()! - - /* Remove root elements */ - peek = heap.removeMax() // 5 - peek = heap.removeMax() // 4 - peek = heap.removeMax() // 3 - peek = heap.removeMax() // 2 - peek = heap.removeMax() // 1 - - /* Get the heap size */ - let size = heap.count - - /* Check whether the heap is empty */ - let isEmpty = heap.isEmpty - - /* Build a heap from a list */ - let heap2 = Heap([1, 3, 2, 5, 4]) - ``` - -=== "JS" - - ```javascript title="heap.js" - // JavaScript provides no built-in Heap class - ``` - -=== "TS" - - ```typescript title="heap.ts" - // TypeScript provides no built-in Heap class - ``` - -=== "Dart" - - ```dart title="heap.dart" - // Dart provides no built-in Heap class - ``` - -=== "Rust" - - ```rust title="heap.rs" - use std::collections::BinaryHeap; - use std::cmp::Reverse; - - /* Initialize a heap */ - // Initialize a min heap - let mut min_heap = BinaryHeap::>::new(); - // Initialize a max heap - let mut max_heap = BinaryHeap::new(); - - /* Insert elements into the heap */ - max_heap.push(1); - max_heap.push(3); - max_heap.push(2); - max_heap.push(5); - max_heap.push(4); - - /* Access the root element */ - let peek = max_heap.peek().unwrap(); // 5 - - /* Remove root elements */ - // Removed elements form a descending sequence - let peek = max_heap.pop().unwrap(); // 5 - let peek = max_heap.pop().unwrap(); // 4 - let peek = max_heap.pop().unwrap(); // 3 - let peek = max_heap.pop().unwrap(); // 2 - let peek = max_heap.pop().unwrap(); // 1 - - /* Get the heap size */ - let size = max_heap.len(); - - /* Check whether the heap is empty */ - let is_empty = max_heap.is_empty(); - - /* Build a heap from a list */ - let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); - ``` - -=== "C" - - ```c title="heap.c" - // C provides no built-in Heap class - ``` - -=== "Kotlin" - - ```kotlin title="heap.kt" - /* Initialize a heap */ - // Initialize a min heap - var minHeap = PriorityQueue() - // Initialize a max heap by changing the Comparator with a lambda expression - val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } - - /* Insert elements into the heap */ - maxHeap.offer(1) - maxHeap.offer(3) - maxHeap.offer(2) - maxHeap.offer(5) - maxHeap.offer(4) - - /* Access the root element */ - var peek = maxHeap.peek() // 5 - - /* Remove root elements */ - // Removed elements form a descending sequence - peek = maxHeap.poll() // 5 - peek = maxHeap.poll() // 4 - peek = maxHeap.poll() // 3 - peek = maxHeap.poll() // 2 - peek = maxHeap.poll() // 1 - - /* Get the heap size */ - val size = maxHeap.size - - /* Check whether the heap is empty */ - val isEmpty = maxHeap.isEmpty() - - /* Build a heap from a list */ - minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) - ``` - -=== "Ruby" - - ```ruby title="heap.rb" - # Ruby provides no built-in Heap class - ``` +```snippet +heap_operations +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20min%20heap%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20Initialize%20a%20max%20heap%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%27s%20heapq%20module%20implements%20a%20min%20heap%20by%20default%0A%20%20%20%20%23%20Negate%20elements%20before%20insertion%20to%20reverse%20their%20order%20and%20implement%20a%20max%20heap%0A%20%20%20%20%23%20Here%2C%20flag%20%3D%201%20gives%20a%20min%20heap%20and%20flag%20%3D%20-1%20gives%20a%20max%20heap%0A%20%20%20%20%0A%20%20%20%20%23%20Insert%20elements%20into%20the%20heap%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20Access%20the%20root%20element%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20Remove%20root%20elements%0A%20%20%20%20%23%20Removed%20elements%20form%20a%20descending%20sequence%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20Get%20the%20heap%20size%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20Check%20whether%20the%20heap%20is%20empty%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20Build%20a%20heap%20from%20a%20list%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor heap_operations_tutor ## Implementing a heap diff --git a/en/docs/chapter_preface/suggestions.md b/en/docs/chapter_preface/suggestions.md index 24014dcbd..5c346d72b 100644 --- a/en/docs/chapter_preface/suggestions.md +++ b/en/docs/chapter_preface/suggestions.md @@ -13,170 +13,9 @@ - When terminology differs between programming languages, this book follows Python; for example, it uses `None` to represent a null value. - For a more compact layout, this book sometimes departs from a language's usual commenting conventions. Comments fall into three main categories: heading comments, explanatory comments, and multiline comments. -=== "Python" - - ```python title="" - """Heading comment identifying a function, class, test case, and so on""" - - # Explanatory comment describing the code in detail - - """ - Multiline - comment - """ - ``` - -=== "C++" - - ```cpp title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "Java" - - ```java title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "C#" - - ```csharp title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "Go" - - ```go title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "Swift" - - ```swift title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "JS" - - ```javascript title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "TS" - - ```typescript title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "Dart" - - ```dart title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "Rust" - - ```rust title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - // Multiline - // comment - ``` - -=== "C" - - ```c title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Heading comment identifying a function, class, test case, and so on */ - - // Explanatory comment describing the code in detail - - /** - * Multiline - * comment - */ - ``` - -=== "Ruby" - - ```ruby title="" - ### Heading comment identifying a function, class, test case, and so on ### - - # Explanatory comment describing the code in detail - - # Multiline - # comment - ``` +```snippet +comment_style +``` ## Learn efficiently with animated illustrations diff --git a/en/docs/chapter_stack_and_queue/deque.md b/en/docs/chapter_stack_and_queue/deque.md index 20a47ae8b..ea6dee8bc 100644 --- a/en/docs/chapter_stack_and_queue/deque.md +++ b/en/docs/chapter_stack_and_queue/deque.md @@ -21,371 +21,13 @@ The table below lists common operations. Actual method names depend on the progr Again, we can use a deque class already provided by the programming language: -=== "Python" - - ```python title="deque.py" - from collections import deque - - # Initialize a deque - deq: deque[int] = deque() - - # Enqueue elements - deq.append(2) # Add at the rear - deq.append(5) - deq.append(4) - deq.appendleft(3) # Add at the front - deq.appendleft(1) - - # Access elements - front: int = deq[0] # Front element - rear: int = deq[-1] # Rear element - - # Dequeue elements - pop_front: int = deq.popleft() # Remove the front element - pop_rear: int = deq.pop() # Remove the rear element - - # Get the deque size - size: int = len(deq) - - # Check whether the deque is empty - is_empty: bool = len(deq) == 0 - ``` - -=== "C++" - - ```cpp title="deque.cpp" - /* Initialize a deque */ - deque deque; - - /* Enqueue elements */ - deque.push_back(2); // Add at the rear - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // Add at the front - deque.push_front(1); - - /* Access elements */ - int front = deque.front(); // Front element - int back = deque.back(); // Rear element - - /* Dequeue elements */ - deque.pop_front(); // Remove the front element - deque.pop_back(); // Remove the rear element - - /* Get the deque size */ - int size = deque.size(); - - /* Check whether the deque is empty */ - bool empty = deque.empty(); - ``` - -=== "Java" - - ```java title="deque.java" - /* Initialize a deque */ - Deque deque = new LinkedList<>(); - - /* Enqueue elements */ - deque.offerLast(2); // Add at the rear - deque.offerLast(5); - deque.offerLast(4); - deque.offerFirst(3); // Add at the front - deque.offerFirst(1); - - /* Access elements */ - int peekFirst = deque.peekFirst(); // Front element - int peekLast = deque.peekLast(); // Rear element - - /* Dequeue elements */ - int popFirst = deque.pollFirst(); // Remove the front element - int popLast = deque.pollLast(); // Remove the rear element - - /* Get the deque size */ - int size = deque.size(); - - /* Check whether the deque is empty */ - boolean isEmpty = deque.isEmpty(); - ``` - -=== "C#" - - ```csharp title="deque.cs" - /* Initialize a deque */ - // In C#, use a LinkedList as a deque - LinkedList deque = new(); - - /* Enqueue elements */ - deque.AddLast(2); // Add at the rear - deque.AddLast(5); - deque.AddLast(4); - deque.AddFirst(3); // Add at the front - deque.AddFirst(1); - - /* Access elements */ - int peekFirst = deque.First.Value; // Front element - int peekLast = deque.Last.Value; // Rear element - - /* Dequeue elements */ - deque.RemoveFirst(); // Remove the front element - deque.RemoveLast(); // Remove the rear element - - /* Get the deque size */ - int size = deque.Count; - - /* Check whether the deque is empty */ - bool isEmpty = deque.Count == 0; - ``` - -=== "Go" - - ```go title="deque_test.go" - /* Initialize a deque */ - // In Go, use a list as a deque - deque := list.New() - - /* Enqueue elements */ - deque.PushBack(2) // Add at the rear - deque.PushBack(5) - deque.PushBack(4) - deque.PushFront(3) // Add at the front - deque.PushFront(1) - - /* Access elements */ - front := deque.Front() // Front element - rear := deque.Back() // Rear element - - /* Dequeue elements */ - deque.Remove(front) // Remove the front element - deque.Remove(rear) // Remove the rear element - - /* Get the deque size */ - size := deque.Len() - - /* Check whether the deque is empty */ - isEmpty := deque.Len() == 0 - ``` - -=== "Swift" - - ```swift title="deque.swift" - /* Initialize a deque */ - // Swift has no built-in deque class; use an Array as a deque - var deque: [Int] = [] - - /* Enqueue elements */ - deque.append(2) // Add at the rear - deque.append(5) - deque.append(4) - deque.insert(3, at: 0) // Add at the front - deque.insert(1, at: 0) - - /* Access elements */ - let peekFirst = deque.first! // Front element - let peekLast = deque.last! // Rear element - - /* Dequeue elements */ - // When using an Array, popFirst takes O(n) time - let popFirst = deque.removeFirst() // Remove the front element - let popLast = deque.removeLast() // Remove the rear element - - /* Get the deque size */ - let size = deque.count - - /* Check whether the deque is empty */ - let isEmpty = deque.isEmpty - ``` - -=== "JS" - - ```javascript title="deque.js" - /* Initialize a deque */ - // JavaScript has no built-in deque; use an Array instead - const deque = []; - - /* Enqueue elements */ - deque.push(2); - deque.push(5); - deque.push(4); - // Note that this is an array, so unshift() takes O(n) time - deque.unshift(3); - deque.unshift(1); - - /* Access elements */ - const peekFirst = deque[0]; - const peekLast = deque[deque.length - 1]; - - /* Dequeue elements */ - // Note that this is an array, so shift() takes O(n) time - const popFront = deque.shift(); - const popBack = deque.pop(); - - /* Get the deque size */ - const size = deque.length; - - /* Check whether the deque is empty */ - const isEmpty = size === 0; - ``` - -=== "TS" - - ```typescript title="deque.ts" - /* Initialize a deque */ - // TypeScript has no built-in deque; use an Array instead - const deque: number[] = []; - - /* Enqueue elements */ - deque.push(2); - deque.push(5); - deque.push(4); - // Note that this is an array, so unshift() takes O(n) time - deque.unshift(3); - deque.unshift(1); - - /* Access elements */ - const peekFirst: number = deque[0]; - const peekLast: number = deque[deque.length - 1]; - - /* Dequeue elements */ - // Note that this is an array, so shift() takes O(n) time - const popFront: number = deque.shift() as number; - const popBack: number = deque.pop() as number; - - /* Get the deque size */ - const size: number = deque.length; - - /* Check whether the deque is empty */ - const isEmpty: boolean = size === 0; - ``` - -=== "Dart" - - ```dart title="deque.dart" - /* Initialize a deque */ - // In Dart, Queue is defined as a deque - Queue deque = Queue(); - - /* Enqueue elements */ - deque.addLast(2); // Add at the rear - deque.addLast(5); - deque.addLast(4); - deque.addFirst(3); // Add at the front - deque.addFirst(1); - - /* Access elements */ - int peekFirst = deque.first; // Front element - int peekLast = deque.last; // Rear element - - /* Dequeue elements */ - int popFirst = deque.removeFirst(); // Remove the front element - int popLast = deque.removeLast(); // Remove the rear element - - /* Get the deque size */ - int size = deque.length; - - /* Check whether the deque is empty */ - bool isEmpty = deque.isEmpty; - ``` - -=== "Rust" - - ```rust title="deque.rs" - /* Initialize a deque */ - let mut deque: VecDeque = VecDeque::new(); - - /* Enqueue elements */ - deque.push_back(2); // Add at the rear - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // Add at the front - deque.push_front(1); - - /* Access elements */ - if let Some(front) = deque.front() { // Front element - } - if let Some(rear) = deque.back() { // Rear element - } - - /* Dequeue elements */ - if let Some(pop_front) = deque.pop_front() { // Remove the front element - } - if let Some(pop_rear) = deque.pop_back() { // Remove the rear element - } - - /* Get the deque size */ - let size = deque.len(); - - /* Check whether the deque is empty */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="deque.c" - // C provides no built-in deque - ``` - -=== "Kotlin" - - ```kotlin title="deque.kt" - /* Initialize a deque */ - val deque = LinkedList() - - /* Enqueue elements */ - deque.offerLast(2) // Add at the rear - deque.offerLast(5) - deque.offerLast(4) - deque.offerFirst(3) // Add at the front - deque.offerFirst(1) - - /* Access elements */ - val peekFirst = deque.peekFirst() // Front element - val peekLast = deque.peekLast() // Rear element - - /* Dequeue elements */ - val popFirst = deque.pollFirst() // Remove the front element - val popLast = deque.pollLast() // Remove the rear element - - /* Get the deque size */ - val size = deque.size - - /* Check whether the deque is empty */ - val isEmpty = deque.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="deque.rb" - # Initialize a deque - # Ruby has no built-in deque; use an Array instead - deque = [] - - # Enqueue elements - deque << 2 - deque << 5 - deque << 4 - # Note that this is an array, so Array#unshift takes O(n) time - deque.unshift(3) - deque.unshift(1) - - # Access elements - peek_first = deque.first - peek_last = deque.last - - # Dequeue elements - # Note that this is an array, so Array#shift takes O(n) time - pop_front = deque.shift - pop_back = deque.pop - - # Get the deque size - size = deque.length - - # Check whether the deque is empty - is_empty = size.zero? - ``` +```snippet +deque_operations +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20deque%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20Enqueue%20elements%0A%20%20%20%20deq.append%282%29%20%20%23%20Add%20at%20the%20rear%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20Add%20at%20the%20front%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22Deque%3A%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20Access%20elements%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20Front%20element%0A%20%20%20%20print%28%22Front%20element%3A%20front%20%3D%22%2C%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20Rear%20element%0A%20%20%20%20print%28%22Rear%20element%3A%20rear%20%3D%22%2C%20rear%29%0A%0A%20%20%20%20%23%20Dequeue%20elements%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20Remove%20the%20front%20element%0A%20%20%20%20print%28%22Element%20removed%20from%20the%20front%3A%20pop_front%20%3D%22%2C%20pop_front%29%0A%20%20%20%20print%28%22After%20removing%20from%20the%20front%3A%20deque%20%3D%22%2C%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20Remove%20the%20rear%20element%0A%20%20%20%20print%28%22Element%20removed%20from%20the%20rear%3A%20pop_rear%20%3D%22%2C%20pop_rear%29%0A%20%20%20%20print%28%22After%20removing%20from%20the%20rear%3A%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20Get%20the%20deque%20size%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22Deque%20size%3A%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20Check%20whether%20the%20deque%20is%20empty%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22Is%20the%20deque%20empty%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor deque_operations_tutor ## Implementing a deque * diff --git a/en/docs/chapter_stack_and_queue/queue.md b/en/docs/chapter_stack_and_queue/queue.md index 768365c47..1fb239b44 100755 --- a/en/docs/chapter_stack_and_queue/queue.md +++ b/en/docs/chapter_stack_and_queue/queue.md @@ -20,345 +20,13 @@ The table below lists common operations. Method names vary between programming l We can use a queue class already provided by the programming language: -=== "Python" - - ```python title="queue.py" - from collections import deque - - # Initialize a queue - # In Python, we usually use the deque class as a queue - # Although queue.Queue() is a dedicated queue class, it is less convenient and is not recommended here - que: deque[int] = deque() - - # Enqueue elements - que.append(1) - que.append(3) - que.append(2) - que.append(5) - que.append(4) - - # Access the front element - front: int = que[0] - - # Dequeue an element - pop: int = que.popleft() - - # Get the queue size - size: int = len(que) - - # Check whether the queue is empty - is_empty: bool = len(que) == 0 - ``` - -=== "C++" - - ```cpp title="queue.cpp" - /* Initialize a queue */ - queue queue; - - /* Enqueue elements */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* Access the front element */ - int front = queue.front(); - - /* Dequeue an element */ - queue.pop(); - - /* Get the queue size */ - int size = queue.size(); - - /* Check whether the queue is empty */ - bool empty = queue.empty(); - ``` - -=== "Java" - - ```java title="queue.java" - /* Initialize a queue */ - Queue queue = new LinkedList<>(); - - /* Enqueue elements */ - queue.offer(1); - queue.offer(3); - queue.offer(2); - queue.offer(5); - queue.offer(4); - - /* Access the front element */ - int peek = queue.peek(); - - /* Dequeue an element */ - int pop = queue.poll(); - - /* Get the queue size */ - int size = queue.size(); - - /* Check whether the queue is empty */ - boolean isEmpty = queue.isEmpty(); - ``` - -=== "C#" - - ```csharp title="queue.cs" - /* Initialize a queue */ - Queue queue = new(); - - /* Enqueue elements */ - queue.Enqueue(1); - queue.Enqueue(3); - queue.Enqueue(2); - queue.Enqueue(5); - queue.Enqueue(4); - - /* Access the front element */ - int peek = queue.Peek(); - - /* Dequeue an element */ - int pop = queue.Dequeue(); - - /* Get the queue size */ - int size = queue.Count; - - /* Check whether the queue is empty */ - bool isEmpty = queue.Count == 0; - ``` - -=== "Go" - - ```go title="queue_test.go" - /* Initialize a queue */ - // In Go, use a list as a queue - queue := list.New() - - /* Enqueue elements */ - queue.PushBack(1) - queue.PushBack(3) - queue.PushBack(2) - queue.PushBack(5) - queue.PushBack(4) - - /* Access the front element */ - peek := queue.Front() - - /* Dequeue an element */ - pop := queue.Front() - queue.Remove(pop) - - /* Get the queue size */ - size := queue.Len() - - /* Check whether the queue is empty */ - isEmpty := queue.Len() == 0 - ``` - -=== "Swift" - - ```swift title="queue.swift" - /* Initialize a queue */ - // Swift has no built-in queue class; use an Array as a queue - var queue: [Int] = [] - - /* Enqueue elements */ - queue.append(1) - queue.append(3) - queue.append(2) - queue.append(5) - queue.append(4) - - /* Access the front element */ - let peek = queue.first! - - /* Dequeue an element */ - // Because this is an array, removeFirst takes O(n) time - let pop = queue.removeFirst() - - /* Get the queue size */ - let size = queue.count - - /* Check whether the queue is empty */ - let isEmpty = queue.isEmpty - ``` - -=== "JS" - - ```javascript title="queue.js" - /* Initialize a queue */ - // JavaScript has no built-in queue; use an Array as a queue - const queue = []; - - /* Enqueue elements */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* Access the front element */ - const peek = queue[0]; - - /* Dequeue an element */ - // The underlying structure is an array, so shift() takes O(n) time - const pop = queue.shift(); - - /* Get the queue size */ - const size = queue.length; - - /* Check whether the queue is empty */ - const empty = queue.length === 0; - ``` - -=== "TS" - - ```typescript title="queue.ts" - /* Initialize a queue */ - // TypeScript has no built-in queue; use an Array as a queue - const queue: number[] = []; - - /* Enqueue elements */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* Access the front element */ - const peek = queue[0]; - - /* Dequeue an element */ - // The underlying structure is an array, so shift() takes O(n) time - const pop = queue.shift(); - - /* Get the queue size */ - const size = queue.length; - - /* Check whether the queue is empty */ - const empty = queue.length === 0; - ``` - -=== "Dart" - - ```dart title="queue.dart" - /* Initialize a queue */ - // In Dart, Queue is a deque and can also be used as a queue - Queue queue = Queue(); - - /* Enqueue elements */ - queue.add(1); - queue.add(3); - queue.add(2); - queue.add(5); - queue.add(4); - - /* Access the front element */ - int peek = queue.first; - - /* Dequeue an element */ - int pop = queue.removeFirst(); - - /* Get the queue size */ - int size = queue.length; - - /* Check whether the queue is empty */ - bool isEmpty = queue.isEmpty; - ``` - -=== "Rust" - - ```rust title="queue.rs" - /* Initialize a deque */ - // In Rust, use a deque as an ordinary queue - let mut deque: VecDeque = VecDeque::new(); - - /* Enqueue elements */ - deque.push_back(1); - deque.push_back(3); - deque.push_back(2); - deque.push_back(5); - deque.push_back(4); - - /* Access the front element */ - if let Some(front) = deque.front() { - } - - /* Dequeue an element */ - if let Some(pop) = deque.pop_front() { - } - - /* Get the queue size */ - let size = deque.len(); - - /* Check whether the queue is empty */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="queue.c" - // C provides no built-in queue - ``` - -=== "Kotlin" - - ```kotlin title="queue.kt" - /* Initialize a queue */ - val queue = LinkedList() - - /* Enqueue elements */ - queue.offer(1) - queue.offer(3) - queue.offer(2) - queue.offer(5) - queue.offer(4) - - /* Access the front element */ - val peek = queue.peek() - - /* Dequeue an element */ - val pop = queue.poll() - - /* Get the queue size */ - val size = queue.size - - /* Check whether the queue is empty */ - val isEmpty = queue.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="queue.rb" - # Initialize a queue - # Ruby's built-in Thread::Queue has no peek or traversal methods; use an Array as a queue - queue = [] - - # Enqueue elements - queue.push(1) - queue.push(3) - queue.push(2) - queue.push(5) - queue.push(4) - - # Access the front element of the queue - peek = queue.first - - # Dequeue an element - # Note that this is an array, so Array#shift takes O(n) time - pop = queue.shift - - # Get the queue size - size = queue.length - - # Check whether the queue is empty - is_empty = queue.empty? - ``` +```snippet +queue_operations +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20queue%0A%20%20%20%20%23%20In%20Python%2C%20we%20usually%20use%20the%20deque%20class%20as%20a%20queue%0A%20%20%20%20%23%20Although%20queue.Queue%28%29%20is%20a%20dedicated%20queue%20class%2C%20it%20is%20less%20convenient%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20Enqueue%20elements%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22Queue%3A%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20Access%20the%20front%20element%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22Front%20element%3A%20front%20%3D%22%2C%20front%29%0A%0A%20%20%20%20%23%20Dequeue%20an%20element%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22Dequeued%20element%3A%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22After%20dequeuing%3A%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20Get%20the%20queue%20size%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22Queue%20size%3A%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20Check%20whether%20the%20queue%20is%20empty%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22Is%20the%20queue%20empty%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor queue_operations_tutor ## Implementing a queue diff --git a/en/docs/chapter_stack_and_queue/stack.md b/en/docs/chapter_stack_and_queue/stack.md index cf8e01010..65b25a44a 100755 --- a/en/docs/chapter_stack_and_queue/stack.md +++ b/en/docs/chapter_stack_and_queue/stack.md @@ -22,336 +22,13 @@ The table below lists common operations. Actual method names depend on the progr We can usually use a language's built-in stack class. If no dedicated class is provided, use an array or linked list as a stack and avoid operations unrelated to stack behavior. -=== "Python" - - ```python title="stack.py" - # Initialize a stack - # Python has no built-in stack class; use a list as a stack - stack: list[int] = [] - - # Push elements - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - # Access the top element - peek: int = stack[-1] - - # Pop an element - pop: int = stack.pop() - - # Get the stack size - size: int = len(stack) - - # Check whether the stack is empty - is_empty: bool = len(stack) == 0 - ``` - -=== "C++" - - ```cpp title="stack.cpp" - /* Initialize a stack */ - stack stack; - - /* Push elements */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Access the top element */ - int top = stack.top(); - - /* Pop an element */ - stack.pop(); // No return value - - /* Get the stack size */ - int size = stack.size(); - - /* Check whether the stack is empty */ - bool empty = stack.empty(); - ``` - -=== "Java" - - ```java title="stack.java" - /* Initialize a stack */ - Stack stack = new Stack<>(); - - /* Push elements */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Access the top element */ - int peek = stack.peek(); - - /* Pop an element */ - int pop = stack.pop(); - - /* Get the stack size */ - int size = stack.size(); - - /* Check whether the stack is empty */ - boolean isEmpty = stack.isEmpty(); - ``` - -=== "C#" - - ```csharp title="stack.cs" - /* Initialize a stack */ - Stack stack = new(); - - /* Push elements */ - stack.Push(1); - stack.Push(3); - stack.Push(2); - stack.Push(5); - stack.Push(4); - - /* Access the top element */ - int peek = stack.Peek(); - - /* Pop an element */ - int pop = stack.Pop(); - - /* Get the stack size */ - int size = stack.Count; - - /* Check whether the stack is empty */ - bool isEmpty = stack.Count == 0; - ``` - -=== "Go" - - ```go title="stack_test.go" - /* Initialize a stack */ - // In Go, a slice is recommended for use as a stack - var stack []int - - /* Push elements */ - stack = append(stack, 1) - stack = append(stack, 3) - stack = append(stack, 2) - stack = append(stack, 5) - stack = append(stack, 4) - - /* Access the top element */ - peek := stack[len(stack)-1] - - /* Pop an element */ - pop := stack[len(stack)-1] - stack = stack[:len(stack)-1] - - /* Get the stack size */ - size := len(stack) - - /* Check whether the stack is empty */ - isEmpty := len(stack) == 0 - ``` - -=== "Swift" - - ```swift title="stack.swift" - /* Initialize a stack */ - // Swift has no built-in stack class; use an Array as a stack - var stack: [Int] = [] - - /* Push elements */ - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - /* Access the top element */ - let peek = stack.last! - - /* Pop an element */ - let pop = stack.removeLast() - - /* Get the stack size */ - let size = stack.count - - /* Check whether the stack is empty */ - let isEmpty = stack.isEmpty - ``` - -=== "JS" - - ```javascript title="stack.js" - /* Initialize a stack */ - // JavaScript has no built-in stack class; use an Array as a stack - const stack = []; - - /* Push elements */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Access the top element */ - const peek = stack[stack.length-1]; - - /* Pop an element */ - const pop = stack.pop(); - - /* Get the stack size */ - const size = stack.length; - - /* Check whether the stack is empty */ - const is_empty = stack.length === 0; - ``` - -=== "TS" - - ```typescript title="stack.ts" - /* Initialize a stack */ - // TypeScript has no built-in stack class; use an Array as a stack - const stack: number[] = []; - - /* Push elements */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Access the top element */ - const peek = stack[stack.length - 1]; - - /* Pop an element */ - const pop = stack.pop(); - - /* Get the stack size */ - const size = stack.length; - - /* Check whether the stack is empty */ - const is_empty = stack.length === 0; - ``` - -=== "Dart" - - ```dart title="stack.dart" - /* Initialize a stack */ - // Dart has no built-in stack class; use a List as a stack - List stack = []; - - /* Push elements */ - stack.add(1); - stack.add(3); - stack.add(2); - stack.add(5); - stack.add(4); - - /* Access the top element */ - int peek = stack.last; - - /* Pop an element */ - int pop = stack.removeLast(); - - /* Get the stack size */ - int size = stack.length; - - /* Check whether the stack is empty */ - bool isEmpty = stack.isEmpty; - ``` - -=== "Rust" - - ```rust title="stack.rs" - /* Initialize a stack */ - // Use a Vec as a stack - let mut stack: Vec = Vec::new(); - - /* Push elements */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Access the top element */ - let top = stack.last().unwrap(); - - /* Pop an element */ - let pop = stack.pop().unwrap(); - - /* Get the stack size */ - let size = stack.len(); - - /* Check whether the stack is empty */ - let is_empty = stack.is_empty(); - ``` - -=== "C" - - ```c title="stack.c" - // C provides no built-in stack - ``` - -=== "Kotlin" - - ```kotlin title="stack.kt" - /* Initialize a stack */ - val stack = Stack() - - /* Push elements */ - stack.push(1) - stack.push(3) - stack.push(2) - stack.push(5) - stack.push(4) - - /* Access the top element */ - val peek = stack.peek() - - /* Pop an element */ - val pop = stack.pop() - - /* Get the stack size */ - val size = stack.size - - /* Check whether the stack is empty */ - val isEmpty = stack.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="stack.rb" - # Initialize a stack - # Ruby has no built-in stack class; use an Array as a stack - stack = [] - - # Push elements - stack << 1 - stack << 3 - stack << 2 - stack << 5 - stack << 4 - - # Access the top element - peek = stack.last - - # Pop an element - pop = stack.pop - - # Get the stack size - size = stack.length - - # Check whether the stack is empty - is_empty = stack.empty? - ``` +```snippet +stack_operations +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20stack%0A%20%20%20%20%23%20Python%20has%20no%20built-in%20stack%20class%3B%20use%20a%20list%20as%20a%20stack%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20Push%20elements%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22Stack%3A%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20Access%20the%20top%20element%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22Top%20element%3A%20peek%20%3D%22%2C%20peek%29%0A%0A%20%20%20%20%23%20Pop%20an%20element%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22Popped%20element%3A%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22After%20popping%3A%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20Get%20the%20stack%20size%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22Stack%20size%3A%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20Check%20whether%20the%20stack%20is%20empty%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22Is%20the%20stack%20empty%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor stack_operations_tutor ## Implementing a stack diff --git a/en/docs/chapter_tree/array_representation_of_tree.md b/en/docs/chapter_tree/array_representation_of_tree.md index 9a4bc412a..f4f5bc54a 100644 --- a/en/docs/chapter_tree/array_representation_of_tree.md +++ b/en/docs/chapter_tree/array_representation_of_tree.md @@ -24,109 +24,9 @@ As shown below, the array representation above no longer works for a non-perfect To solve this, **include every `None` position explicitly in the level-order sequence**. The sequence then represents the tree uniquely, as shown below. Example code follows: -=== "Python" - - ```python title="" - # Array representation of a binary tree - # Use None for empty positions - tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] - ``` - -=== "C++" - - ```cpp title="" - /* Array representation of a binary tree */ - // Use INT_MAX, the maximum int value, for empty positions - vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Java" - - ```java title="" - /* Array representation of a binary tree */ - // Use the wrapper class Integer so that null can mark empty positions - Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; - ``` - -=== "C#" - - ```csharp title="" - /* Array representation of a binary tree */ - // Use the nullable type int? so that null can mark empty positions - int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Go" - - ```go title="" - /* Array representation of a binary tree */ - // Use a slice of any so that nil can mark empty positions - tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} - ``` - -=== "Swift" - - ```swift title="" - /* Array representation of a binary tree */ - // Use the optional type Int? so that nil can mark empty positions - let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` - -=== "JS" - - ```javascript title="" - /* Array representation of a binary tree */ - // Use null for empty positions - let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "TS" - - ```typescript title="" - /* Array representation of a binary tree */ - // Use null for empty positions - let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Dart" - - ```dart title="" - /* Array representation of a binary tree */ - // Use the nullable type int? so that null can mark empty positions - List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Rust" - - ```rust title="" - /* Array representation of a binary tree */ - // Use None for empty positions - let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; - ``` - -=== "C" - - ```c title="" - /* Array representation of a binary tree */ - // Use the maximum int value for empty positions, so node values must not equal INT_MAX - int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Array representation of a binary tree */ - // Use null for empty positions - val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) - ``` - -=== "Ruby" - - ```ruby title="" - ### Array representation of a binary tree ### - # Use nil for empty positions - tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` +```snippet +tree_array_representation +``` ![Array representation of an arbitrary binary tree](array_representation_of_tree.assets/array_representation_with_empty.svg) diff --git a/en/docs/chapter_tree/avl_tree.md b/en/docs/chapter_tree/avl_tree.md index 4d4746f18..b5e57cf1a 100644 --- a/en/docs/chapter_tree/avl_tree.md +++ b/en/docs/chapter_tree/avl_tree.md @@ -20,213 +20,9 @@ An AVL tree is both a binary search tree and a balanced binary tree, satisfying AVL operations need node heights, so add a `height` variable to the node class: -=== "Python" - - ```python title="" - class TreeNode: - """AVL tree node class""" - def __init__(self, val: int): - self.val: int = val # Node value - self.height: int = 0 # Node height - self.left: TreeNode | None = None # Left child reference - self.right: TreeNode | None = None # Right child reference - ``` - -=== "C++" - - ```cpp title="" - /* AVL tree node class */ - struct TreeNode { - int val{}; // Node value - int height = 0; // Node height - TreeNode *left{}; // Left child - TreeNode *right{}; // Right child - TreeNode() = default; - explicit TreeNode(int x) : val(x){} - }; - ``` - -=== "Java" - - ```java title="" - /* AVL tree node class */ - class TreeNode { - public int val; // Node value - public int height; // Node height - public TreeNode left; // Left child - public TreeNode right; // Right child - public TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* AVL tree node class */ - class TreeNode(int? x) { - public int? val = x; // Node value - public int height; // Node height - public TreeNode? left; // Left child reference - public TreeNode? right; // Right child reference - } - ``` - -=== "Go" - - ```go title="" - /* AVL tree node struct */ - type TreeNode struct { - Val int // Node value - Height int // Node height - Left *TreeNode // Left child reference - Right *TreeNode // Right child reference - } - ``` - -=== "Swift" - - ```swift title="" - /* AVL tree node class */ - class TreeNode { - var val: Int // Node value - var height: Int // Node height - var left: TreeNode? // Left child - var right: TreeNode? // Right child - - init(x: Int) { - val = x - height = 0 - } - } - ``` - -=== "JS" - - ```javascript title="" - /* AVL tree node class */ - class TreeNode { - val; // Node value - height; //Node height - left; // Left child pointer - right; // Right child pointer - constructor(val, left, right, height) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* AVL tree node class */ - class TreeNode { - val: number; // Node value - height: number; // Node height - left: TreeNode | null; // Left child pointer - right: TreeNode | null; // Right child pointer - constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "Dart" - - ```dart title="" - /* AVL tree node class */ - class TreeNode { - int val; // Node value - int height; // Node height - TreeNode? left; // Left child - TreeNode? right; // Right child - TreeNode(this.val, [this.height = 0, this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* AVL tree node struct */ - struct TreeNode { - val: i32, // Node value - height: i32, // Node height - left: Option>>, // Left child - right: Option>>, // Right child - } - - impl TreeNode { - /* Constructor */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - height: 0, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* AVL tree node struct */ - typedef struct TreeNode { - int val; - int height; - struct TreeNode *left; - struct TreeNode *right; - } TreeNode; - - /* Constructor */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* AVL tree node class */ - class TreeNode(val _val: Int) { // Node value - var height: Int = 0 // Node height - var left: TreeNode? = null // Left child - var right: TreeNode? = null // Right child - } - ``` - -=== "Ruby" - - ```ruby title="" - ### AVL tree node class ### - class TreeNode - attr_accessor :val # Node value - attr_accessor :height # Node height - attr_accessor :left # Left child reference - attr_accessor :right # Right child reference - - def initialize(val) - @val = val - @height = 0 - end - end - ``` +```snippet +avl_tree_node +``` A node's height is the distance to its farthest leaf, measured in edges. A leaf has height $0$, while a missing node has height $-1$. We create two helper functions to retrieve and update a node's height: diff --git a/en/docs/chapter_tree/binary_tree.md b/en/docs/chapter_tree/binary_tree.md index ba25be069..dac65a324 100644 --- a/en/docs/chapter_tree/binary_tree.md +++ b/en/docs/chapter_tree/binary_tree.md @@ -2,204 +2,9 @@ A binary tree is a nonlinear data structure representing relationships between ancestors and descendants. It embodies the divide-and-conquer idea of splitting in two. Like a linked list, it is built from nodes, each containing a value and references to its left and right children. -=== "Python" - - ```python title="" - class TreeNode: - """Binary tree node class""" - def __init__(self, val: int): - self.val: int = val # Node value - self.left: TreeNode | None = None # Left child reference - self.right: TreeNode | None = None # Right child reference - ``` - -=== "C++" - - ```cpp title="" - /* Binary tree node struct */ - struct TreeNode { - int val; // Node value - TreeNode *left; // Left child pointer - TreeNode *right; // Right child pointer - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - }; - ``` - -=== "Java" - - ```java title="" - /* Binary tree node class */ - class TreeNode { - int val; // Node value - TreeNode left; // Left child reference - TreeNode right; // Right child reference - TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* Binary tree node class */ - class TreeNode(int? x) { - public int? val = x; // Node value - public TreeNode? left; // Left child reference - public TreeNode? right; // Right child reference - } - ``` - -=== "Go" - - ```go title="" - /* Binary tree node struct */ - type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode - } - /* Constructor */ - func NewTreeNode(v int) *TreeNode { - return &TreeNode{ - Left: nil, // Left child pointer - Right: nil, // Right child pointer - Val: v, // Node value - } - } - ``` - -=== "Swift" - - ```swift title="" - /* Binary tree node class */ - class TreeNode { - var val: Int // Node value - var left: TreeNode? // Left child reference - var right: TreeNode? // Right child reference - - init(x: Int) { - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* Binary tree node class */ - class TreeNode { - val; // Node value - left; // Left child pointer - right; // Right child pointer - constructor(val, left, right) { - this.val = val === undefined ? 0 : val; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* Binary tree node class */ - class TreeNode { - val: number; - left: TreeNode | null; - right: TreeNode | null; - - constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; // Node value - this.left = left === undefined ? null : left; // Left child reference - this.right = right === undefined ? null : right; // Right child reference - } - } - ``` - -=== "Dart" - - ```dart title="" - /* Binary tree node class */ - class TreeNode { - int val; // Node value - TreeNode? left; // Left child reference - TreeNode? right; // Right child reference - TreeNode(this.val, [this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* Binary tree node struct */ - struct TreeNode { - val: i32, // Node value - left: Option>>, // Left child reference - right: Option>>, // Right child reference - } - - impl TreeNode { - /* Constructor */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* Binary tree node struct */ - typedef struct TreeNode { - int val; // Node value - int height; // Node height - struct TreeNode *left; // Left child pointer - struct TreeNode *right; // Right child pointer - } TreeNode; - - /* Constructor */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Binary tree node class */ - class TreeNode(val _val: Int) { // Node value - var left: TreeNode? = null // Left child reference - var right: TreeNode? = null // Right child reference - } - ``` - -=== "Ruby" - - ```ruby title="" - ### Binary tree node class ### - class TreeNode - attr_accessor :val # Node value - attr_accessor :left # Left child reference - attr_accessor :right # Right child reference - - def initialize(val) - @val = val - end - end - ``` +```snippet +tree_node_class +``` Each node has two references or pointers, one to its left child and one to its right child. The node is their parent. Its left child and all nodes below that child form its left subtree; the right subtree is defined similarly. @@ -232,226 +37,13 @@ The figure below illustrates common binary-tree terminology. As with a linked list, first create the nodes, then connect them with references or pointers. -=== "Python" - - ```python title="binary_tree.py" - # Initialize a binary tree - # Initialize nodes - n1 = TreeNode(val=1) - n2 = TreeNode(val=2) - n3 = TreeNode(val=3) - n4 = TreeNode(val=4) - n5 = TreeNode(val=5) - # Connect nodes with references (pointers) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* Initialize a binary tree */ - // Initialize nodes - TreeNode* n1 = new TreeNode(1); - TreeNode* n2 = new TreeNode(2); - TreeNode* n3 = new TreeNode(3); - TreeNode* n4 = new TreeNode(4); - TreeNode* n5 = new TreeNode(5); - // Connect nodes with references (pointers) - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Java" - - ```java title="binary_tree.java" - // Initialize nodes - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // Connect nodes with references (pointers) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* Initialize a binary tree */ - // Initialize nodes - TreeNode n1 = new(1); - TreeNode n2 = new(2); - TreeNode n3 = new(3); - TreeNode n4 = new(4); - TreeNode n5 = new(5); - // Connect nodes with references (pointers) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* Initialize a binary tree */ - // Initialize nodes - n1 := NewTreeNode(1) - n2 := NewTreeNode(2) - n3 := NewTreeNode(3) - n4 := NewTreeNode(4) - n5 := NewTreeNode(5) - // Connect nodes with references (pointers) - n1.Left = n2 - n1.Right = n3 - n2.Left = n4 - n2.Right = n5 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - // Initialize nodes - let n1 = TreeNode(x: 1) - let n2 = TreeNode(x: 2) - let n3 = TreeNode(x: 3) - let n4 = TreeNode(x: 4) - let n5 = TreeNode(x: 5) - // Connect nodes with references (pointers) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* Initialize a binary tree */ - // Initialize nodes - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // Connect nodes with references (pointers) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* Initialize a binary tree */ - // Initialize nodes - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // Connect nodes with references (pointers) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* Initialize a binary tree */ - // Initialize nodes - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // Connect nodes with references (pointers) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - // Initialize nodes - let n1 = TreeNode::new(1); - let n2 = TreeNode::new(2); - let n3 = TreeNode::new(3); - let n4 = TreeNode::new(4); - let n5 = TreeNode::new(5); - // Connect nodes with references (pointers) - n1.borrow_mut().left = Some(n2.clone()); - n1.borrow_mut().right = Some(n3); - n2.borrow_mut().left = Some(n4); - n2.borrow_mut().right = Some(n5); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* Initialize a binary tree */ - // Initialize nodes - TreeNode *n1 = newTreeNode(1); - TreeNode *n2 = newTreeNode(2); - TreeNode *n3 = newTreeNode(3); - TreeNode *n4 = newTreeNode(4); - TreeNode *n5 = newTreeNode(5); - // Connect nodes with references (pointers) - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - // Initialize nodes - val n1 = TreeNode(1) - val n2 = TreeNode(2) - val n3 = TreeNode(3) - val n4 = TreeNode(4) - val n5 = TreeNode(5) - // Connect nodes with references (pointers) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # Initialize a binary tree - # Initialize nodes - n1 = TreeNode.new(1) - n2 = TreeNode.new(2) - n3 = TreeNode.new(3) - n4 = TreeNode.new(4) - n5 = TreeNode.new(5) - # Connect nodes with references (pointers) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` +```snippet +init_binary_tree +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22Binary%20tree%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20Left%20child%20reference%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20Right%20child%20reference%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20binary%20tree%0A%20%20%20%20%23%20Initialize%20nodes%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20Connect%20nodes%20with%20references%20%28pointers%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_binary_tree_tutor ### Inserting and deleting nodes @@ -459,165 +51,13 @@ As with linked lists, insertion and deletion can be implemented by changing poin ![Inserting and deleting a binary-tree node](binary_tree.assets/binary_tree_add_remove.svg) -=== "Python" - - ```python title="binary_tree.py" - # Insert and delete a node - p = TreeNode(0) - # Insert node P between n1 and n2 - n1.left = p - p.left = n2 - # Delete node P - n1.left = n2 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* Insert and delete a node */ - TreeNode* P = new TreeNode(0); - // Insert node P between n1 and n2 - n1->left = P; - P->left = n2; - // Delete node P - n1->left = n2; - // Free the memory - delete P; - ``` - -=== "Java" - - ```java title="binary_tree.java" - TreeNode P = new TreeNode(0); - // Insert node P between n1 and n2 - n1.left = P; - P.left = n2; - // Delete node P - n1.left = n2; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* Insert and delete a node */ - TreeNode P = new(0); - // Insert node P between n1 and n2 - n1.left = P; - P.left = n2; - // Delete node P - n1.left = n2; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* Insert and delete a node */ - // Insert node P between n1 and n2 - p := NewTreeNode(0) - n1.Left = p - p.Left = n2 - // Delete node P - n1.Left = n2 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - let P = TreeNode(x: 0) - // Insert node P between n1 and n2 - n1.left = P - P.left = n2 - // Delete node P - n1.left = n2 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* Insert and delete a node */ - let P = new TreeNode(0); - // Insert node P between n1 and n2 - n1.left = P; - P.left = n2; - // Delete node P - n1.left = n2; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* Insert and delete a node */ - const P = new TreeNode(0); - // Insert node P between n1 and n2 - n1.left = P; - P.left = n2; - // Delete node P - n1.left = n2; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* Insert and delete a node */ - TreeNode P = new TreeNode(0); - // Insert node P between n1 and n2 - n1.left = P; - P.left = n2; - // Delete node P - n1.left = n2; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - let p = TreeNode::new(0); - // Insert node P between n1 and n2 - n1.borrow_mut().left = Some(p.clone()); - p.borrow_mut().left = Some(n2.clone()); - // Delete node p - n1.borrow_mut().left = Some(n2); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* Insert and delete a node */ - TreeNode *P = newTreeNode(0); - // Insert node P between n1 and n2 - n1->left = P; - P->left = n2; - // Delete node P - n1->left = n2; - // Free the memory - free(P); - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - val P = TreeNode(0) - // Insert node P between n1 and n2 - n1.left = P - P.left = n2 - // Delete node P - n1.left = n2 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # Insert and delete a node - _p = TreeNode.new(0) - # Insert node _p between n1 and n2 - n1.left = _p - _p.left = n2 - # Delete the node - n1.left = n2 - ``` +```snippet +insert_remove_node +``` ??? pythontutor "Visualize execution" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22Binary%20tree%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20Left%20child%20reference%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20Right%20child%20reference%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20binary%20tree%0A%20%20%20%20%23%20Initialize%20nodes%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20Connect%20nodes%20with%20references%20%28pointers%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20Insert%20and%20delete%20a%20node%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20Insert%20node%20P%20between%20n1%20and%20n2%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20Delete%20node%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_node_tutor !!! tip diff --git a/ja/codes/snippets/chapter_array_and_linkedlist/array.md b/ja/codes/snippets/chapter_array_and_linkedlist/array.md new file mode 100644 index 000000000..27d43f0f5 --- /dev/null +++ b/ja/codes/snippets/chapter_array_and_linkedlist/array.md @@ -0,0 +1,93 @@ + +```python title="array.py" +# 配列を初期化 +arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="array.cpp" +/* 配列を初期化 */ +// スタック上に格納 +int arr[5] = {}; +int nums[5] = { 1, 3, 2, 5, 4 }; +// ヒープ上に格納(領域を手動で解放する必要がある) +int* arr1 = new int[5] {}; +int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +``` + +```java title="array.java" +/* 配列を初期化 */ +int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } +int[] nums = { 1, 3, 2, 5, 4 }; +``` + +```csharp title="array.cs" +/* 配列を初期化 */ +int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] +int[] nums = [1, 3, 2, 5, 4]; +``` + +```go title="array.go" +/* 配列を初期化 */ +var arr [5]int +// Go では、長さを指定すると([5]int)配列、指定しないと([]int)スライスになる +// Go の配列はコンパイル時に長さが決まる設計のため、長さには定数しか指定できない +// 容量を拡張する extend() メソッドを実装しやすくするため、以下ではスライス(Slice)を配列(Array)として扱う +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="array.swift" +/* 配列を初期化 */ +let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] +let nums = [1, 3, 2, 5, 4] +``` + +```javascript title="array.js" +/* 配列を初期化 */ +var arr = new Array(5).fill(0); +var nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="array.ts" +/* 配列を初期化 */ +let arr: number[] = new Array(5).fill(0); +let nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="array.dart" +/* 配列を初期化 */ +List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="array.rs" +/* 配列を初期化 */ +let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] +let slice: &[i32] = &[0; 5]; +// Rust では、長さを指定すると([i32; 5])配列、指定しないと(&[i32])スライスになる +// Rust の配列はコンパイル時に長さが決まる設計のため、長さには定数しか指定できない +// Vector は、Rust で通常、動的配列として使う型 +// 容量を拡張する extend() メソッドを実装しやすくするため、以下では vector を配列(array)として扱う +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="array.c" +/* 配列を初期化 */ +int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } +int nums[5] = { 1, 3, 2, 5, 4 }; +``` + +```kotlin title="array.kt" +/* 配列を初期化 */ +var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +var nums = intArrayOf(1, 3, 2, 5, 4) +``` + +```ruby title="array.rb" +# 配列を初期化 +arr = Array.new(5, 0) +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%23%20%E9%85%8D%E5%88%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/ja/codes/snippets/chapter_array_and_linkedlist/linked_list.md new file mode 100644 index 000000000..d0474d6a0 --- /dev/null +++ b/ja/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -0,0 +1,516 @@ + +```python title="" +class ListNode: + """連結リストのノードクラス""" + def __init__(self, val: int): + self.val: int = val # ノードの値 + self.next: ListNode | None = None # 次のノードへの参照 +``` + +```cpp title="" +/* 連結リストのノード構造体 */ +struct ListNode { + int val; // ノードの値 + ListNode *next; // 次のノードへのポインタ + ListNode(int x) : val(x), next(nullptr) {} // コンストラクタ +}; +``` + +```java title="" +/* 連結リストのノードクラス */ +class ListNode { + int val; // ノードの値 + ListNode next; // 次のノードへの参照 + ListNode(int x) { val = x; } // コンストラクタ +} +``` + +```csharp title="" +/* 連結リストのノードクラス */ +class ListNode(int x) { //コンストラクタ + int val = x; // ノードの値 + ListNode? next; // 次のノードへの参照 +} +``` + +```go title="" +/* 連結リストのノード構造体 */ +type ListNode struct { + Val int // ノードの値 + Next *ListNode // 次のノードへのポインタ +} + +// NewListNode コンストラクタで、新しい連結リストを作る +func NewListNode(val int) *ListNode { + return &ListNode{ + Val: val, + Next: nil, + } +} +``` + +```swift title="" +/* 連結リストのノードクラス */ +class ListNode { + var val: Int // ノードの値 + var next: ListNode? // 次のノードへの参照 + + init(x: Int) { // コンストラクタ + val = x + } +} +``` + +```javascript title="" +/* 連結リストのノードクラス */ +class ListNode { + constructor(val, next) { + this.val = (val === undefined ? 0 : val); // ノードの値 + this.next = (next === undefined ? null : next); // 次のノードへの参照 + } +} +``` + +```typescript title="" +/* 連結リストのノードクラス */ +class ListNode { + val: number; + next: ListNode | null; + constructor(val?: number, next?: ListNode | null) { + this.val = val === undefined ? 0 : val; // ノードの値 + this.next = next === undefined ? null : next; // 次のノードへの参照 + } +} +``` + +```dart title="" +/* 連結リストのノードクラス */ +class ListNode { + int val; // ノードの値 + ListNode? next; // 次のノードへの参照 + ListNode(this.val, [this.next]); // コンストラクタ +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; +/* 連結リストのノードクラス */ +#[derive(Debug)] +struct ListNode { + val: i32, // ノードの値 + next: Option>>, // 次のノードへのポインタ +} +``` + +```c title="" +/* 連結リストのノード構造体 */ +typedef struct ListNode { + int val; // ノードの値 + struct ListNode *next; // 次のノードへのポインタ +} ListNode; + +/* コンストラクタ */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + return node; +} +``` + +```kotlin title="" +/* 連結リストのノードクラス */ +// コンストラクタ +class ListNode(x: Int) { + val _val: Int = x // ノードの値 + var next: ListNode? = null // 次のノードへの参照 +} +``` + +```ruby title="" +# 連結リストのノードクラス +class ListNode + attr_accessor :val # ノードの値 + attr_accessor :next # 次のノードへの参照 + + def initialize(val=0, next_node=nil) + @val = val + @next = next_node + end +end +``` + + +```python title="linked_list.py" +# 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 +# 各ノードを初期化 +n0 = ListNode(1) +n1 = ListNode(3) +n2 = ListNode(2) +n3 = ListNode(5) +n4 = ListNode(4) +# ノード間の参照を設定 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```cpp title="linked_list.cpp" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +ListNode* n0 = new ListNode(1); +ListNode* n1 = new ListNode(3); +ListNode* n2 = new ListNode(2); +ListNode* n3 = new ListNode(5); +ListNode* n4 = new ListNode(4); +// ノード間の参照を設定 +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```java title="linked_list.java" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +ListNode n0 = new ListNode(1); +ListNode n1 = new ListNode(3); +ListNode n2 = new ListNode(2); +ListNode n3 = new ListNode(5); +ListNode n4 = new ListNode(4); +// ノード間の参照を設定 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```csharp title="linked_list.cs" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +ListNode n0 = new(1); +ListNode n1 = new(3); +ListNode n2 = new(2); +ListNode n3 = new(5); +ListNode n4 = new(4); +// ノード間の参照を設定 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```go title="linked_list.go" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +n0 := NewListNode(1) +n1 := NewListNode(3) +n2 := NewListNode(2) +n3 := NewListNode(5) +n4 := NewListNode(4) +// ノード間の参照を設定 +n0.Next = n1 +n1.Next = n2 +n2.Next = n3 +n3.Next = n4 +``` + +```swift title="linked_list.swift" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +let n0 = ListNode(x: 1) +let n1 = ListNode(x: 3) +let n2 = ListNode(x: 2) +let n3 = ListNode(x: 5) +let n4 = ListNode(x: 4) +// ノード間の参照を設定 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```javascript title="linked_list.js" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// ノード間の参照を設定 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```typescript title="linked_list.ts" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// ノード間の参照を設定 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```dart title="linked_list.dart" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */\ +// 各ノードを初期化 +ListNode n0 = ListNode(1); +ListNode n1 = ListNode(3); +ListNode n2 = ListNode(2); +ListNode n3 = ListNode(5); +ListNode n4 = ListNode(4); +// ノード間の参照を設定 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```rust title="linked_list.rs" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); +let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); +let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); +let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); +let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); + +// ノード間の参照を設定 +n0.borrow_mut().next = Some(n1.clone()); +n1.borrow_mut().next = Some(n2.clone()); +n2.borrow_mut().next = Some(n3.clone()); +n3.borrow_mut().next = Some(n4.clone()); +``` + +```c title="linked_list.c" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +ListNode* n0 = newListNode(1); +ListNode* n1 = newListNode(3); +ListNode* n2 = newListNode(2); +ListNode* n3 = newListNode(5); +ListNode* n4 = newListNode(4); +// ノード間の参照を設定 +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```kotlin title="linked_list.kt" +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ +// 各ノードを初期化 +val n0 = ListNode(1) +val n1 = ListNode(3) +val n2 = ListNode(2) +val n3 = ListNode(5) +val n4 = ListNode(4) +// ノード間の参照を設定 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```ruby title="linked_list.rb" +# 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 +# 各ノードを初期化 +n0 = ListNode.new(1) +n1 = ListNode.new(3) +n2 = ListNode.new(2) +n3 = ListNode.new(5) +n4 = ListNode.new(4) +# ノード間の参照を設定 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E6%AC%A1%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%20%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E5%90%84%E3%83%8E%E3%83%BC%E3%83%89%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20n0%20%3D%20ListNode(1)%0A%20%20%20%20n1%20%3D%20ListNode(3)%0A%20%20%20%20n2%20%3D%20ListNode(2)%0A%20%20%20%20n3%20%3D%20ListNode(5)%0A%20%20%20%20n4%20%3D%20ListNode(4)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E9%96%93%E3%81%AE%E5%8F%82%E7%85%A7%E3%82%92%E8%A8%AD%E5%AE%9A%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="" +class ListNode: + """双方向連結リストのノードクラス""" + def __init__(self, val: int): + self.val: int = val # ノードの値 + self.next: ListNode | None = None # 後続ノードへの参照 + self.prev: ListNode | None = None # 先行ノードへの参照 +``` + +```cpp title="" +/* 双方向連結リストのノード構造体 */ +struct ListNode { + int val; // ノードの値 + ListNode *next; // 後続ノードへのポインタ + ListNode *prev; // 先行ノードへのポインタ + ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // コンストラクタ +}; +``` + +```java title="" +/* 双方向連結リストのノードクラス */ +class ListNode { + int val; // ノードの値 + ListNode next; // 後続ノードへの参照 + ListNode prev; // 先行ノードへの参照 + ListNode(int x) { val = x; } // コンストラクタ +} +``` + +```csharp title="" +/* 双方向連結リストのノードクラス */ +class ListNode(int x) { // コンストラクタ + int val = x; // ノードの値 + ListNode next; // 後続ノードへの参照 + ListNode prev; // 先行ノードへの参照 +} +``` + +```go title="" +/* 双方向連結リストのノード構造体 */ +type DoublyListNode struct { + Val int // ノードの値 + Next *DoublyListNode // 後続ノードへのポインタ + Prev *DoublyListNode // 先行ノードへのポインタ +} + +// NewDoublyListNode で初期化 +func NewDoublyListNode(val int) *DoublyListNode { + return &DoublyListNode{ + Val: val, + Next: nil, + Prev: nil, + } +} +``` + +```swift title="" +/* 双方向連結リストのノードクラス */ +class ListNode { + var val: Int // ノードの値 + var next: ListNode? // 後続ノードへの参照 + var prev: ListNode? // 先行ノードへの参照 + + init(x: Int) { // コンストラクタ + val = x + } +} +``` + +```javascript title="" +/* 双方向連結リストのノードクラス */ +class ListNode { + constructor(val, next, prev) { + this.val = val === undefined ? 0 : val; // ノードの値 + this.next = next === undefined ? null : next; // 後続ノードへの参照 + this.prev = prev === undefined ? null : prev; // 先行ノードへの参照 + } +} +``` + +```typescript title="" +/* 双方向連結リストのノードクラス */ +class ListNode { + val: number; + next: ListNode | null; + prev: ListNode | null; + constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { + this.val = val === undefined ? 0 : val; // ノードの値 + this.next = next === undefined ? null : next; // 後続ノードへの参照 + this.prev = prev === undefined ? null : prev; // 先行ノードへの参照 + } +} +``` + +```dart title="" +/* 双方向連結リストのノードクラス */ +class ListNode { + int val; // ノードの値 + ListNode? next; // 後続ノードへの参照 + ListNode? prev; // 先行ノードへの参照 + ListNode(this.val, [this.next, this.prev]); // コンストラクタ +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 双方向連結リストのノード型 */ +#[derive(Debug)] +struct ListNode { + val: i32, // ノードの値 + next: Option>>, // 後続ノードへのポインタ + prev: Option>>, // 先行ノードへのポインタ +} + +/* コンストラクタ */ +impl ListNode { + fn new(val: i32) -> Self { + ListNode { + val, + next: None, + prev: None, + } + } +} +``` + +```c title="" +/* 双方向連結リストのノード構造体 */ +typedef struct ListNode { + int val; // ノードの値 + struct ListNode *next; // 後続ノードへのポインタ + struct ListNode *prev; // 先行ノードへのポインタ +} ListNode; + +/* コンストラクタ */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + node->prev = NULL; + return node; +} +``` + +```kotlin title="" +/* 双方向連結リストのノードクラス */ +// コンストラクタ +class ListNode(x: Int) { + val _val: Int = x // ノードの値 + var next: ListNode? = null // 後続ノードへの参照 + var prev: ListNode? = null // 先行ノードへの参照 +} +``` + +```ruby title="" +# 双方向連結リストのノードクラス +class ListNode + attr_accessor :val # ノードの値 + attr_accessor :next # 後続ノードへの参照 + attr_accessor :prev # 先行ノードへの参照 + + def initialize(val=0, next_node=nil, prev_node=nil) + @val = val + @next = next_node + @prev = prev_node + end +end +``` diff --git a/ja/codes/snippets/chapter_array_and_linkedlist/list.md b/ja/codes/snippets/chapter_array_and_linkedlist/list.md new file mode 100644 index 000000000..85bb8823f --- /dev/null +++ b/ja/codes/snippets/chapter_array_and_linkedlist/list.md @@ -0,0 +1,752 @@ + +```python title="list.py" +# リストを初期化 +# 初期値なし +nums1: list[int] = [] +# 初期値あり +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="list.cpp" +/* リストを初期化 */ +// C++ の vector が、本節で扱う nums に相当することに注意 +// 初期値なし +vector nums1; +// 初期値あり +vector nums = { 1, 3, 2, 5, 4 }; +``` + +```java title="list.java" +/* リストを初期化 */ +// 初期値なし +List nums1 = new ArrayList<>(); +// 初期値あり(配列には、int[] に対応するラッパー型の配列 Integer[] を使う必要がある) +Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; +List nums = new ArrayList<>(Arrays.asList(numbers)); +``` + +```csharp title="list.cs" +/* リストを初期化 */ +// 初期値なし +List nums1 = []; +// 初期値あり +int[] numbers = [1, 3, 2, 5, 4]; +List nums = [.. numbers]; +``` + +```go title="list_test.go" +/* リストを初期化 */ +// 初期値なし +nums1 := []int{} +// 初期値あり +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="list.swift" +/* リストを初期化 */ +// 初期値なし +let nums1: [Int] = [] +// 初期値あり +var nums = [1, 3, 2, 5, 4] +``` + +```javascript title="list.js" +/* リストを初期化 */ +// 初期値なし +const nums1 = []; +// 初期値あり +const nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="list.ts" +/* リストを初期化 */ +// 初期値なし +const nums1: number[] = []; +// 初期値あり +const nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="list.dart" +/* リストを初期化 */ +// 初期値なし +List nums1 = []; +// 初期値あり +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="list.rs" +/* リストを初期化 */ +// 初期値なし +let nums1: Vec = Vec::new(); +// 初期値あり +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="list.c" +// C には組み込みの動的配列がない +``` + +```kotlin title="list.kt" +/* リストを初期化 */ +// 初期値なし +var nums1 = listOf() +// 初期値あり +var numbers = arrayOf(1, 3, 2, 5, 4) +var nums = numbers.toMutableList() +``` + +```ruby title="list.rb" +# リストを初期化 +# 初期値なし +nums1 = [] +# 初期値あり +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%AA%E3%81%97%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%82%E3%82%8A%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 要素にアクセス +num: int = nums[1] # インデックス 1 の要素にアクセス + +# 要素を更新 +nums[1] = 0 # インデックス 1 の要素を 0 に更新 +``` + +```cpp title="list.cpp" +/* 要素にアクセス */ +int num = nums[1]; // インデックス 1 の要素にアクセス + +/* 要素を更新 */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新 +``` + +```java title="list.java" +/* 要素にアクセス */ +int num = nums.get(1); // インデックス 1 の要素にアクセス + +/* 要素を更新 */ +nums.set(1, 0); // インデックス 1 の要素を 0 に更新 +``` + +```csharp title="list.cs" +/* 要素にアクセス */ +int num = nums[1]; // インデックス 1 の要素にアクセス + +/* 要素を更新 */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新 +``` + +```go title="list_test.go" +/* 要素にアクセス */ +num := nums[1] // インデックス 1 の要素にアクセス + +/* 要素を更新 */ +nums[1] = 0 // インデックス 1 の要素を 0 に更新 +``` + +```swift title="list.swift" +/* 要素にアクセス */ +let num = nums[1] // インデックス 1 の要素にアクセス + +/* 要素を更新 */ +nums[1] = 0 // インデックス 1 の要素を 0 に更新 +``` + +```javascript title="list.js" +/* 要素にアクセス */ +const num = nums[1]; // インデックス 1 の要素にアクセス + +/* 要素を更新 */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新 +``` + +```typescript title="list.ts" +/* 要素にアクセス */ +const num: number = nums[1]; // インデックス 1 の要素にアクセス + +/* 要素を更新 */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新 +``` + +```dart title="list.dart" +/* 要素にアクセス */ +int num = nums[1]; // インデックス 1 の要素にアクセス + +/* 要素を更新 */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新 +``` + +```rust title="list.rs" +/* 要素にアクセス */ +let num: i32 = nums[1]; // インデックス 1 の要素にアクセス +/* 要素を更新 */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新 +``` + +```c title="list.c" +// C には組み込みの動的配列がない +``` + +```kotlin title="list.kt" +/* 要素にアクセス */ +val num = nums[1] // インデックス 1 の要素にアクセス +/* 要素を更新 */ +nums[1] = 0 // インデックス 1 の要素を 0 に更新 +``` + +```ruby title="list.rb" +# 要素にアクセス +num = nums[1] # インデックス 1 の要素にアクセス +# 要素を更新 +nums[1] = 0 # インデックス 1 の要素を 0 に更新 +``` + + +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%201%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E6%9B%B4%E6%96%B0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%201%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%200%20%E3%81%AB%E6%9B%B4%E6%96%B0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# リストを空にする +nums.clear() + +# 末尾に要素を追加 +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +# 途中に要素を挿入 +nums.insert(3, 6) # インデックス 3 に数値 6 を挿入 + +# 要素を削除 +nums.pop(3) # インデックス 3 の要素を削除 +``` + +```cpp title="list.cpp" +/* リストを空にする */ +nums.clear(); + +/* 末尾に要素を追加 */ +nums.push_back(1); +nums.push_back(3); +nums.push_back(2); +nums.push_back(5); +nums.push_back(4); + +/* 途中に要素を挿入 */ +nums.insert(nums.begin() + 3, 6); // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums.erase(nums.begin() + 3); // インデックス 3 の要素を削除 +``` + +```java title="list.java" +/* リストを空にする */ +nums.clear(); + +/* 末尾に要素を追加 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 途中に要素を挿入 */ +nums.add(3, 6); // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums.remove(3); // インデックス 3 の要素を削除 +``` + +```csharp title="list.cs" +/* リストを空にする */ +nums.Clear(); + +/* 末尾に要素を追加 */ +nums.Add(1); +nums.Add(3); +nums.Add(2); +nums.Add(5); +nums.Add(4); + +/* 途中に要素を挿入 */ +nums.Insert(3, 6); // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums.RemoveAt(3); // インデックス 3 の要素を削除 +``` + +```go title="list_test.go" +/* リストを空にする */ +nums = nil + +/* 末尾に要素を追加 */ +nums = append(nums, 1) +nums = append(nums, 3) +nums = append(nums, 2) +nums = append(nums, 5) +nums = append(nums, 4) + +/* 途中に要素を挿入 */ +nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums = append(nums[:3], nums[4:]...) // インデックス 3 の要素を削除 +``` + +```swift title="list.swift" +/* リストを空にする */ +nums.removeAll() + +/* 末尾に要素を追加 */ +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +/* 途中に要素を挿入 */ +nums.insert(6, at: 3) // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums.remove(at: 3) // インデックス 3 の要素を削除 +``` + +```javascript title="list.js" +/* リストを空にする */ +nums.length = 0; + +/* 末尾に要素を追加 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 途中に要素を挿入 */ +nums.splice(3, 0, 6); // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums.splice(3, 1); // インデックス 3 の要素を削除 +``` + +```typescript title="list.ts" +/* リストを空にする */ +nums.length = 0; + +/* 末尾に要素を追加 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 途中に要素を挿入 */ +nums.splice(3, 0, 6); // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums.splice(3, 1); // インデックス 3 の要素を削除 +``` + +```dart title="list.dart" +/* リストを空にする */ +nums.clear(); + +/* 末尾に要素を追加 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 途中に要素を挿入 */ +nums.insert(3, 6); // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums.removeAt(3); // インデックス 3 の要素を削除 +``` + +```rust title="list.rs" +/* リストを空にする */ +nums.clear(); + +/* 末尾に要素を追加 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 途中に要素を挿入 */ +nums.insert(3, 6); // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums.remove(3); // インデックス 3 の要素を削除 +``` + +```c title="list.c" +// C には組み込みの動的配列がない +``` + +```kotlin title="list.kt" +/* リストを空にする */ +nums.clear(); + +/* 末尾に要素を追加 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 途中に要素を挿入 */ +nums.add(3, 6); // インデックス 3 に数値 6 を挿入 + +/* 要素を削除 */ +nums.remove(3); // インデックス 3 の要素を削除 +``` + +```ruby title="list.rb" +# リストを空にする +nums.clear + +# 末尾に要素を追加 +nums << 1 +nums << 3 +nums << 2 +nums << 5 +nums << 4 + +# 途中に要素を挿入 +nums.insert(3, 6) # インデックス 3 に数値 6 を挿入 + +# 要素を削除 +nums.delete_at(3) # インデックス 3 の要素を削除 +``` + + +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%82%E3%82%8A%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E7%A9%BA%E3%81%AB%E3%81%99%E3%82%8B%0A%20%20%20%20nums.clear()%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%9C%AB%E5%B0%BE%E3%81%AB%E8%A6%81%E7%B4%A0%E3%82%92%E8%BF%BD%E5%8A%A0%0A%20%20%20%20nums.append(1)%0A%20%20%20%20nums.append(3)%0A%20%20%20%20nums.append(2)%0A%20%20%20%20nums.append(5)%0A%20%20%20%20nums.append(4)%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%80%94%E4%B8%AD%E3%81%AB%E8%A6%81%E7%B4%A0%E3%82%92%E6%8C%BF%E5%85%A5%0A%20%20%20%20nums.insert(3%2C%206)%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%203%20%E3%81%AB%E6%95%B0%E5%80%A4%206%20%E3%82%92%E6%8C%BF%E5%85%A5%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E5%89%8A%E9%99%A4%0A%20%20%20%20nums.pop(3)%20%20%20%20%20%20%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%203%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%E5%89%8A%E9%99%A4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# インデックスを使ってリストを走査 +count = 0 +for i in range(len(nums)): + count += nums[i] + +# リストの要素を直接走査 +for num in nums: + count += num +``` + +```cpp title="list.cpp" +/* インデックスを使ってリストを走査 */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums[i]; +} + +/* リストの要素を直接走査 */ +count = 0; +for (int num : nums) { + count += num; +} +``` + +```java title="list.java" +/* インデックスを使ってリストを走査 */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums.get(i); +} + +/* リストの要素を直接走査 */ +for (int num : nums) { + count += num; +} +``` + +```csharp title="list.cs" +/* インデックスを使ってリストを走査 */ +int count = 0; +for (int i = 0; i < nums.Count; i++) { + count += nums[i]; +} + +/* リストの要素を直接走査 */ +count = 0; +foreach (int num in nums) { + count += num; +} +``` + +```go title="list_test.go" +/* インデックスを使ってリストを走査 */ +count := 0 +for i := 0; i < len(nums); i++ { + count += nums[i] +} + +/* リストの要素を直接走査 */ +count = 0 +for _, num := range nums { + count += num +} +``` + +```swift title="list.swift" +/* インデックスを使ってリストを走査 */ +var count = 0 +for i in nums.indices { + count += nums[i] +} + +/* リストの要素を直接走査 */ +count = 0 +for num in nums { + count += num +} +``` + +```javascript title="list.js" +/* インデックスを使ってリストを走査 */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* リストの要素を直接走査 */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```typescript title="list.ts" +/* インデックスを使ってリストを走査 */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* リストの要素を直接走査 */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```dart title="list.dart" +/* インデックスを使ってリストを走査 */ +int count = 0; +for (var i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* リストの要素を直接走査 */ +count = 0; +for (var num in nums) { + count += num; +} +``` + +```rust title="list.rs" +// インデックスを使ってリストを走査 +let mut _count = 0; +for i in 0..nums.len() { + _count += nums[i]; +} + +// リストの要素を直接走査 +_count = 0; +for num in &nums { + _count += num; +} +``` + +```c title="list.c" +// C には組み込みの動的配列がない +``` + +```kotlin title="list.kt" +/* インデックスを使ってリストを走査 */ +var count = 0 +for (i in nums.indices) { + count += nums[i] +} + +/* リストの要素を直接走査 */ +for (num in nums) { + count += num +} +``` + +```ruby title="list.rb" +# インデックスを使ってリストを走査 +count = 0 +for i in 0...nums.length + count += nums[i] +end + +# リストの要素を直接走査 +count = 0 +for num in nums + count += num +end +``` + + +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%A6%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E8%B5%B0%E6%9F%BB%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range(len(nums))%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%E7%9B%B4%E6%8E%A5%E8%B5%B0%E6%9F%BB%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 二つのリストを連結 +nums1: list[int] = [6, 8, 7, 10, 9] +nums += nums1 # リスト nums1 を nums の後ろに連結 +``` + +```cpp title="list.cpp" +/* 二つのリストを連結 */ +vector nums1 = { 6, 8, 7, 10, 9 }; +// リスト nums1 を nums の後ろに連結 +nums.insert(nums.end(), nums1.begin(), nums1.end()); +``` + +```java title="list.java" +/* 二つのリストを連結 */ +List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); +nums.addAll(nums1); // リスト nums1 を nums の後ろに連結 +``` + +```csharp title="list.cs" +/* 二つのリストを連結 */ +List nums1 = [6, 8, 7, 10, 9]; +nums.AddRange(nums1); // リスト nums1 を nums の後ろに連結 +``` + +```go title="list_test.go" +/* 二つのリストを連結 */ +nums1 := []int{6, 8, 7, 10, 9} +nums = append(nums, nums1...) // リスト nums1 を nums の後ろに連結 +``` + +```swift title="list.swift" +/* 二つのリストを連結 */ +let nums1 = [6, 8, 7, 10, 9] +nums.append(contentsOf: nums1) // リスト nums1 を nums の後ろに連結 +``` + +```javascript title="list.js" +/* 二つのリストを連結 */ +const nums1 = [6, 8, 7, 10, 9]; +nums.push(...nums1); // リスト nums1 を nums の後ろに連結 +``` + +```typescript title="list.ts" +/* 二つのリストを連結 */ +const nums1: number[] = [6, 8, 7, 10, 9]; +nums.push(...nums1); // リスト nums1 を nums の後ろに連結 +``` + +```dart title="list.dart" +/* 二つのリストを連結 */ +List nums1 = [6, 8, 7, 10, 9]; +nums.addAll(nums1); // リスト nums1 を nums の後ろに連結 +``` + +```rust title="list.rs" +/* 二つのリストを連結 */ +let nums1: Vec = vec![6, 8, 7, 10, 9]; +nums.extend(nums1); +``` + +```c title="list.c" +// C には組み込みの動的配列がない +``` + +```kotlin title="list.kt" +/* 二つのリストを連結 */ +val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() +nums.addAll(nums1) // リスト nums1 を nums の後ろに連結 +``` + +```ruby title="list.rb" +# 二つのリストを連結 +nums1 = [6, 8, 7, 10, 9] +nums += nums1 +``` + + +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E4%BA%8C%E3%81%A4%E3%81%AE%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E9%80%A3%E7%B5%90%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%20nums1%20%E3%82%92%20nums%20%E3%81%AE%E5%BE%8C%E3%82%8D%E3%81%AB%E9%80%A3%E7%B5%90&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# リストをソート +nums.sort() # ソート後、リストの要素は昇順に並ぶ +``` + +```cpp title="list.cpp" +/* リストをソート */ +sort(nums.begin(), nums.end()); // ソート後、リストの要素は昇順に並ぶ +``` + +```java title="list.java" +/* リストをソート */ +Collections.sort(nums); // ソート後、リストの要素は昇順に並ぶ +``` + +```csharp title="list.cs" +/* リストをソート */ +nums.Sort(); // ソート後、リストの要素は昇順に並ぶ +``` + +```go title="list_test.go" +/* リストをソート */ +sort.Ints(nums) // ソート後、リストの要素は昇順に並ぶ +``` + +```swift title="list.swift" +/* リストをソート */ +nums.sort() // ソート後、リストの要素は昇順に並ぶ +``` + +```javascript title="list.js" +/* リストをソート */ +nums.sort((a, b) => a - b); // ソート後、リストの要素は昇順に並ぶ +``` + +```typescript title="list.ts" +/* リストをソート */ +nums.sort((a, b) => a - b); // ソート後、リストの要素は昇順に並ぶ +``` + +```dart title="list.dart" +/* リストをソート */ +nums.sort(); // ソート後、リストの要素は昇順に並ぶ +``` + +```rust title="list.rs" +/* リストをソート */ +nums.sort(); // ソート後、リストの要素は昇順に並ぶ +``` + +```c title="list.c" +// C には組み込みの動的配列がない +``` + +```kotlin title="list.kt" +/* リストをソート */ +nums.sort() // ソート後、リストの要素は昇順に並ぶ +``` + +```ruby title="list.rb" +# リストをソート +nums = nums.sort { |a, b| a <=> b } # ソート後、リストの要素は昇順に並ぶ +``` + + +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E3%82%BD%E3%83%BC%E3%83%88%0A%20%20%20%20nums.sort()%20%20%23%20%E3%82%BD%E3%83%BC%E3%83%88%E5%BE%8C%E3%81%AF%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E8%A6%81%E7%B4%A0%E3%81%8C%E6%98%87%E9%A0%86%E3%81%AB%E4%B8%A6%E3%81%B6&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_backtracking/backtracking_algorithm.md b/ja/codes/snippets/chapter_backtracking/backtracking_algorithm.md new file mode 100644 index 000000000..a5430a49a --- /dev/null +++ b/ja/codes/snippets/chapter_backtracking/backtracking_algorithm.md @@ -0,0 +1,308 @@ + +```python title="" +def backtrack(state: State, choices: list[choice], res: list[state]): + """バックトラッキングの基本形""" + # 解かどうかを判定 + if is_solution(state): + # 解を記録 + record_solution(state, res) + # これ以上探索しない + return + # すべての選択肢を調べる + for choice in choices: + # 枝刈り:選択が有効かを判定 + if is_valid(state, choice): + # 試行:選択して状態を更新 + make_choice(state, choice) + backtrack(state, choices, res) + # 後戻り:選択を取り消し、前の状態に戻す + undo_choice(state, choice) +``` + +```cpp title="" +/* バックトラッキングの基本形 */ +void backtrack(State *state, vector &choices, vector &res) { + // 解かどうかを判定 + if (isSolution(state)) { + // 解を記録 + recordSolution(state, res); + // これ以上探索しない + return; + } + // すべての選択肢を調べる + for (Choice choice : choices) { + // 枝刈り:選択が有効かを判定 + if (isValid(state, choice)) { + // 試行:選択して状態を更新 + makeChoice(state, choice); + backtrack(state, choices, res); + // 後戻り:選択を取り消し、前の状態に戻す + undoChoice(state, choice); + } + } +} +``` + +```java title="" +/* バックトラッキングの基本形 */ +void backtrack(State state, List choices, List res) { + // 解かどうかを判定 + if (isSolution(state)) { + // 解を記録 + recordSolution(state, res); + // これ以上探索しない + return; + } + // すべての選択肢を調べる + for (Choice choice : choices) { + // 枝刈り:選択が有効かを判定 + if (isValid(state, choice)) { + // 試行:選択して状態を更新 + makeChoice(state, choice); + backtrack(state, choices, res); + // 後戻り:選択を取り消し、前の状態に戻す + undoChoice(state, choice); + } + } +} +``` + +```csharp title="" +/* バックトラッキングの基本形 */ +void Backtrack(State state, List choices, List res) { + // 解かどうかを判定 + if (IsSolution(state)) { + // 解を記録 + RecordSolution(state, res); + // これ以上探索しない + return; + } + // すべての選択肢を調べる + foreach (Choice choice in choices) { + // 枝刈り:選択が有効かを判定 + if (IsValid(state, choice)) { + // 試行:選択して状態を更新 + MakeChoice(state, choice); + Backtrack(state, choices, res); + // 後戻り:選択を取り消し、前の状態に戻す + UndoChoice(state, choice); + } + } +} +``` + +```go title="" +/* バックトラッキングの基本形 */ +func backtrack(state *State, choices []Choice, res *[]State) { + // 解かどうかを判定 + if isSolution(state) { + // 解を記録 + recordSolution(state, res) + // これ以上探索しない + return + } + // すべての選択肢を調べる + for _, choice := range choices { + // 枝刈り:選択が有効かを判定 + if isValid(state, choice) { + // 試行:選択して状態を更新 + makeChoice(state, choice) + backtrack(state, choices, res) + // 後戻り:選択を取り消し、前の状態に戻す + undoChoice(state, choice) + } + } +} +``` + +```swift title="" +/* バックトラッキングの基本形 */ +func backtrack(state: inout State, choices: [Choice], res: inout [State]) { + // 解かどうかを判定 + if isSolution(state: state) { + // 解を記録 + recordSolution(state: state, res: &res) + // これ以上探索しない + return + } + // すべての選択肢を調べる + for choice in choices { + // 枝刈り:選択が有効かを判定 + if isValid(state: state, choice: choice) { + // 試行:選択して状態を更新 + makeChoice(state: &state, choice: choice) + backtrack(state: &state, choices: choices, res: &res) + // 後戻り:選択を取り消し、前の状態に戻す + undoChoice(state: &state, choice: choice) + } + } +} +``` + +```javascript title="" +/* バックトラッキングの基本形 */ +function backtrack(state, choices, res) { + // 解かどうかを判定 + if (isSolution(state)) { + // 解を記録 + recordSolution(state, res); + // これ以上探索しない + return; + } + // すべての選択肢を調べる + for (let choice of choices) { + // 枝刈り:選択が有効かを判定 + if (isValid(state, choice)) { + // 試行:選択して状態を更新 + makeChoice(state, choice); + backtrack(state, choices, res); + // 後戻り:選択を取り消し、前の状態に戻す + undoChoice(state, choice); + } + } +} +``` + +```typescript title="" +/* バックトラッキングの基本形 */ +function backtrack(state: State, choices: Choice[], res: State[]): void { + // 解かどうかを判定 + if (isSolution(state)) { + // 解を記録 + recordSolution(state, res); + // これ以上探索しない + return; + } + // すべての選択肢を調べる + for (let choice of choices) { + // 枝刈り:選択が有効かを判定 + if (isValid(state, choice)) { + // 試行:選択して状態を更新 + makeChoice(state, choice); + backtrack(state, choices, res); + // 後戻り:選択を取り消し、前の状態に戻す + undoChoice(state, choice); + } + } +} +``` + +```dart title="" +/* バックトラッキングの基本形 */ +void backtrack(State state, List, List res) { + // 解かどうかを判定 + if (isSolution(state)) { + // 解を記録 + recordSolution(state, res); + // これ以上探索しない + return; + } + // すべての選択肢を調べる + for (Choice choice in choices) { + // 枝刈り:選択が有効かを判定 + if (isValid(state, choice)) { + // 試行:選択して状態を更新 + makeChoice(state, choice); + backtrack(state, choices, res); + // 後戻り:選択を取り消し、前の状態に戻す + undoChoice(state, choice); + } + } +} +``` + +```rust title="" +/* バックトラッキングの基本形 */ +fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { + // 解かどうかを判定 + if is_solution(state) { + // 解を記録 + record_solution(state, res); + // これ以上探索しない + return; + } + // すべての選択肢を調べる + for choice in choices { + // 枝刈り:選択が有効かを判定 + if is_valid(state, choice) { + // 試行:選択して状態を更新 + make_choice(state, choice); + backtrack(state, choices, res); + // 後戻り:選択を取り消し、前の状態に戻す + undo_choice(state, choice); + } + } +} +``` + +```c title="" +/* バックトラッキングの基本形 */ +void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { + // 解かどうかを判定 + if (isSolution(state)) { + // 解を記録 + recordSolution(state, res, numRes); + // これ以上探索しない + return; + } + // すべての選択肢を調べる + for (int i = 0; i < numChoices; i++) { + // 枝刈り:選択が有効かを判定 + if (isValid(state, &choices[i])) { + // 試行:選択して状態を更新 + makeChoice(state, &choices[i]); + backtrack(state, choices, numChoices, res, numRes); + // 後戻り:選択を取り消し、前の状態に戻す + undoChoice(state, &choices[i]); + } + } +} +``` + +```kotlin title="" +/* バックトラッキングの基本形 */ +fun backtrack(state: State?, choices: List, res: List?) { + // 解かどうかを判定 + if (isSolution(state)) { + // 解を記録 + recordSolution(state, res) + // これ以上探索しない + return + } + // すべての選択肢を調べる + for (choice in choices) { + // 枝刈り:選択が有効かを判定 + if (isValid(state, choice)) { + // 試行:選択して状態を更新 + makeChoice(state, choice) + backtrack(state, choices, res) + // 後戻り:選択を取り消し、前の状態に戻す + undoChoice(state, choice) + } + } +} +``` + +```ruby title="" +### バックトラッキングの基本形 ### +def backtrack(state, choices, res) + # 解かどうかを判定 + if is_solution?(state) + # 解を記録 + record_solution(state, res) + return + end + + # すべての選択肢を調べる + for choice in choices + # 枝刈り:選択が有効かを判定 + if is_valid?(state, choice) + # 試行:選択して状態を更新 + make_choice(state, choice) + backtrack(state, choices, res) + # 後戻り:選択を取り消し、前の状態に戻す + undo_choice(state, choice) + end + end +end +``` diff --git a/ja/codes/snippets/chapter_computational_complexity/space_complexity.md b/ja/codes/snippets/chapter_computational_complexity/space_complexity.md new file mode 100644 index 000000000..ba2668605 --- /dev/null +++ b/ja/codes/snippets/chapter_computational_complexity/space_complexity.md @@ -0,0 +1,682 @@ + +```python title="" +class Node: + """クラス""" + def __init__(self, x: int): + self.val: int = x # ノードの値 + self.next: Node | None = None # 次のノードへの参照 + +def function() -> int: + """関数""" + # 何らかの処理を実行... + return 0 + +def algorithm(n) -> int: # 入力データ + A = 0 # 一時データ(定数、通常は大文字で表す) + b = 0 # 一時データ(変数) + node = Node(0) # 一時データ(オブジェクト) + c = function() # スタックフレーム(関数呼び出し) + return A + b + c # 出力データ +``` + +```cpp title="" +/* 構造体 */ +struct Node { + int val; + Node *next; + Node(int x) : val(x), next(nullptr) {} +}; + +/* 関数 */ +int func() { + // 何らかの処理を実行... + return 0; +} + +int algorithm(int n) { // 入力データ + const int a = 0; // 一時データ(定数) + int b = 0; // 一時データ(変数) + Node* node = new Node(0); // 一時データ(オブジェクト) + int c = func(); // スタックフレーム(関数呼び出し) + return a + b + c; // 出力データ +} +``` + +```java title="" +/* クラス */ +class Node { + int val; + Node next; + Node(int x) { val = x; } +} + +/* 関数 */ +int function() { + // 何らかの処理を実行... + return 0; +} + +int algorithm(int n) { // 入力データ + final int a = 0; // 一時データ(定数) + int b = 0; // 一時データ(変数) + Node node = new Node(0); // 一時データ(オブジェクト) + int c = function(); // スタックフレーム(関数呼び出し) + return a + b + c; // 出力データ +} +``` + +```csharp title="" +/* クラス */ +class Node(int x) { + int val = x; + Node next; +} + +/* 関数 */ +int Function() { + // 何らかの処理を実行... + return 0; +} + +int Algorithm(int n) { // 入力データ + const int a = 0; // 一時データ(定数) + int b = 0; // 一時データ(変数) + Node node = new(0); // 一時データ(オブジェクト) + int c = Function(); // スタックフレーム(関数呼び出し) + return a + b + c; // 出力データ +} +``` + +```go title="" +/* 構造体 */ +type node struct { + val int + next *node +} + +/* node 構造体を作成 */ +func newNode(val int) *node { + return &node{val: val} +} + +/* 関数 */ +func function() int { + // 何らかの処理を実行... + return 0 +} + +func algorithm(n int) int { // 入力データ + const a = 0 // 一時データ(定数) + b := 0 // 一時データ(変数) + newNode(0) // 一時データ(オブジェクト) + c := function() // スタックフレーム(関数呼び出し) + return a + b + c // 出力データ +} +``` + +```swift title="" +/* クラス */ +class Node { + var val: Int + var next: Node? + + init(x: Int) { + val = x + } +} + +/* 関数 */ +func function() -> Int { + // 何らかの処理を実行... + return 0 +} + +func algorithm(n: Int) -> Int { // 入力データ + let a = 0 // 一時データ(定数) + var b = 0 // 一時データ(変数) + let node = Node(x: 0) // 一時データ(オブジェクト) + let c = function() // スタックフレーム(関数呼び出し) + return a + b + c // 出力データ +} +``` + +```javascript title="" +/* クラス */ +class Node { + val; + next; + constructor(val) { + this.val = val === undefined ? 0 : val; // ノードの値 + this.next = null; // 次のノードへの参照 + } +} + +/* 関数 */ +function constFunc() { + // 何らかの処理を実行 + return 0; +} + +function algorithm(n) { // 入力データ + const a = 0; // 一時データ(定数) + let b = 0; // 一時データ(変数) + const node = new Node(0); // 一時データ(オブジェクト) + const c = constFunc(); // スタックフレーム(関数呼び出し) + return a + b + c; // 出力データ +} +``` + +```typescript title="" +/* クラス */ +class Node { + val: number; + next: Node | null; + constructor(val?: number) { + this.val = val === undefined ? 0 : val; // ノードの値 + this.next = null; // 次のノードへの参照 + } +} + +/* 関数 */ +function constFunc(): number { + // 何らかの処理を実行 + return 0; +} + +function algorithm(n: number): number { // 入力データ + const a = 0; // 一時データ(定数) + let b = 0; // 一時データ(変数) + const node = new Node(0); // 一時データ(オブジェクト) + const c = constFunc(); // スタックフレーム(関数呼び出し) + return a + b + c; // 出力データ +} +``` + +```dart title="" +/* クラス */ +class Node { + int val; + Node next; + Node(this.val, [this.next]); +} + +/* 関数 */ +int function() { + // 何らかの処理を実行... + return 0; +} + +int algorithm(int n) { // 入力データ + const int a = 0; // 一時データ(定数) + int b = 0; // 一時データ(変数) + Node node = Node(0); // 一時データ(オブジェクト) + int c = function(); // スタックフレーム(関数呼び出し) + return a + b + c; // 出力データ +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 構造体 */ +struct Node { + val: i32, + next: Option>>, +} + +/* Node 構造体を作成 */ +impl Node { + fn new(val: i32) -> Self { + Self { val: val, next: None } + } +} + +/* 関数 */ +fn function() -> i32 { + // 何らかの処理を実行... + return 0; +} + +fn algorithm(n: i32) -> i32 { // 入力データ + const a: i32 = 0; // 一時データ(定数) + let mut b = 0; // 一時データ(変数) + let node = Node::new(0); // 一時データ(オブジェクト) + let c = function(); // スタックフレーム(関数呼び出し) + return a + b + c; // 出力データ +} +``` + +```c title="" +/* 関数 */ +int func() { + // 何らかの処理を実行... + return 0; +} + +int algorithm(int n) { // 入力データ + const int a = 0; // 一時データ(定数) + int b = 0; // 一時データ(変数) + int c = func(); // スタックフレーム(関数呼び出し) + return a + b + c; // 出力データ +} +``` + +```kotlin title="" +/* クラス */ +class Node(var _val: Int) { + var next: Node? = null +} + +/* 関数 */ +fun function(): Int { + // 何らかの処理を実行... + return 0 +} + +fun algorithm(n: Int): Int { // 入力データ + val a = 0 // 一時データ(定数) + var b = 0 // 一時データ(変数) + val node = Node(0) // 一時データ(オブジェクト) + val c = function() // スタックフレーム(関数呼び出し) + return a + b + c // 出力データ +} +``` + +```ruby title="" +### クラス ### +class Node + attr_accessor :val # ノードの値 + attr_accessor :next # 次のノードへの参照 + + def initialize(x) + @val = x + end +end + +### 関数 ### +def function + # 何らかの処理を実行... + 0 +end + +### アルゴリズム ### +def algorithm(n) # 入力データ + a = 0 # 一時データ(定数) + b = 0 # 一時データ(変数) + node = Node.new(0) # 一時データ(オブジェクト) + c = function # スタックフレーム(関数呼び出し) + a + b + c # 出力データ +end +``` + + +```python title="" +def algorithm(n: int): + a = 0 # O(1) + b = [0] * 10000 # O(1) + if n > 10: + nums = [0] * n # O(n) +``` + +```cpp title="" +void algorithm(int n) { + int a = 0; // O(1) + vector b(10000); // O(1) + if (n > 10) + vector nums(n); // O(n) +} +``` + +```java title="" +void algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) + int[] nums = new int[n]; // O(n) +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) { + int[] nums = new int[n]; // O(n) + } +} +``` + +```go title="" +func algorithm(n int) { + a := 0 // O(1) + b := make([]int, 10000) // O(1) + var nums []int + if n > 10 { + nums := make([]int, n) // O(n) + } + fmt.Println(a, b, nums) +} +``` + +```swift title="" +func algorithm(n: Int) { + let a = 0 // O(1) + let b = Array(repeating: 0, count: 10000) // O(1) + if n > 10 { + let nums = Array(repeating: 0, count: n) // O(n) + } +} +``` + +```javascript title="" +function algorithm(n) { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 0; // O(1) + List b = List.filled(10000, 0); // O(1) + if (n > 10) { + List nums = List.filled(n, 0); // O(n) + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let a = 0; // O(1) + let b = [0; 10000]; // O(1) + if n > 10 { + let nums = vec![0; n as usize]; // O(n) + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 0; // O(1) + int b[10000]; // O(1) + if (n > 10) + int nums[n] = {0}; // O(n) +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + val a = 0 // O(1) + val b = IntArray(10000) // O(1) + if (n > 10) { + val nums = IntArray(n) // O(n) + } +} +``` + +```ruby title="" +def algorithm(n) + a = 0 # O(1) + b = Array.new(10000) # O(1) + nums = Array.new(n) if n > 10 # O(n) +end +``` + + +```python title="" +def function() -> int: + # 何らかの処理を実行 + return 0 + +def loop(n: int): + """ループの空間計算量は O(1)""" + for _ in range(n): + function() + +def recur(n: int): + """再帰の空間計算量は O(n)""" + if n == 1: + return + return recur(n - 1) +``` + +```cpp title="" +int func() { + // 何らかの処理を実行 + return 0; +} +/* ループの空間計算量は O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* 再帰の空間計算量は O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```java title="" +int function() { + // 何らかの処理を実行 + return 0; +} +/* ループの空間計算量は O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* 再帰の空間計算量は O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```csharp title="" +int Function() { + // 何らかの処理を実行 + return 0; +} +/* ループの空間計算量は O(1) */ +void Loop(int n) { + for (int i = 0; i < n; i++) { + Function(); + } +} +/* 再帰の空間計算量は O(n) */ +int Recur(int n) { + if (n == 1) return 1; + return Recur(n - 1); +} +``` + +```go title="" +func function() int { + // 何らかの処理を実行 + return 0 +} + +/* ループの空間計算量は O(1) */ +func loop(n int) { + for i := 0; i < n; i++ { + function() + } +} + +/* 再帰の空間計算量は O(n) */ +func recur(n int) { + if n == 1 { + return + } + recur(n - 1) +} +``` + +```swift title="" +@discardableResult +func function() -> Int { + // 何らかの処理を実行 + return 0 +} + +/* ループの空間計算量は O(1) */ +func loop(n: Int) { + for _ in 0 ..< n { + function() + } +} + +/* 再帰の空間計算量は O(n) */ +func recur(n: Int) { + if n == 1 { + return + } + recur(n: n - 1) +} +``` + +```javascript title="" +function constFunc() { + // 何らかの処理を実行 + return 0; +} +/* ループの空間計算量は O(1) */ +function loop(n) { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* 再帰の空間計算量は O(n) */ +function recur(n) { + if (n === 1) return; + return recur(n - 1); +} +``` + +```typescript title="" +function constFunc(): number { + // 何らかの処理を実行 + return 0; +} +/* ループの空間計算量は O(1) */ +function loop(n: number): void { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* 再帰の空間計算量は O(n) */ +function recur(n: number): void { + if (n === 1) return; + return recur(n - 1); +} +``` + +```dart title="" +int function() { + // 何らかの処理を実行 + return 0; +} +/* ループの空間計算量は O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* 再帰の空間計算量は O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```rust title="" +fn function() -> i32 { + // 何らかの処理を実行 + return 0; +} +/* ループの空間計算量は O(1) */ +fn loop(n: i32) { + for i in 0..n { + function(); + } +} +/* 再帰の空間計算量は O(n) */ +fn recur(n: i32) { + if n == 1 { + return; + } + recur(n - 1); +} +``` + +```c title="" +int func() { + // 何らかの処理を実行 + return 0; +} +/* ループの空間計算量は O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* 再帰の空間計算量は O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```kotlin title="" +fun function(): Int { + // 何らかの処理を実行 + return 0 +} +/* ループの空間計算量は O(1) */ +fun loop(n: Int) { + for (i in 0.. +```python title="" +# ある実行環境において +def algorithm(n: int): + a = 2 # 1 ns + a = a + 1 # 1 ns + a = a * 2 # 10 ns + # n 回繰り返す + for _ in range(n): # 1 ns + print(0) # 5 ns +``` + +```cpp title="" +// ある実行環境において +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n 回繰り返す + for (int i = 0; i < n; i++) { // 1 ns + cout << 0 << endl; // 5 ns + } +} +``` + +```java title="" +// ある実行環境において +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n 回繰り返す + for (int i = 0; i < n; i++) { // 1 ns + System.out.println(0); // 5 ns + } +} +``` + +```csharp title="" +// ある実行環境において +void Algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n 回繰り返す + for (int i = 0; i < n; i++) { // 1 ns + Console.WriteLine(0); // 5 ns + } +} +``` + +```go title="" +// ある実行環境において +func algorithm(n int) { + a := 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // n 回繰り返す + for i := 0; i < n; i++ { // 1 ns + fmt.Println(a) // 5 ns + } +} +``` + +```swift title="" +// ある実行環境において +func algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // n 回繰り返す + for _ in 0 ..< n { // 1 ns + print(0) // 5 ns + } +} +``` + +```javascript title="" +// ある実行環境において +function algorithm(n) { + var a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n 回繰り返す + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```typescript title="" +// ある実行環境において +function algorithm(n: number): void { + var a: number = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n 回繰り返す + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```dart title="" +// ある実行環境において +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n 回繰り返す + for (int i = 0; i < n; i++) { // 1 ns + print(0); // 5 ns + } +} +``` + +```rust title="" +// ある実行環境において +fn algorithm(n: i32) { + let mut a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n 回繰り返す + for _ in 0..n { // 1 ns + println!("{}", 0); // 5 ns + } +} +``` + +```c title="" +// ある実行環境において +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n 回繰り返す + for (int i = 0; i < n; i++) { // 1 ns + printf("%d", 0); // 5 ns + } +} +``` + +```kotlin title="" +// ある実行環境において +fun algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // n 回繰り返す + for (i in 0.. +```python title="" +# アルゴリズム A の時間計算量:定数のオーダー +def algorithm_A(n: int): + print(0) +# アルゴリズム B の時間計算量:線形のオーダー +def algorithm_B(n: int): + for _ in range(n): + print(0) +# アルゴリズム C の時間計算量:定数のオーダー +def algorithm_C(n: int): + for _ in range(1000000): + print(0) +``` + +```cpp title="" +// アルゴリズム A の時間計算量:定数のオーダー +void algorithm_A(int n) { + cout << 0 << endl; +} +// アルゴリズム B の時間計算量:線形のオーダー +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + cout << 0 << endl; + } +} +// アルゴリズム C の時間計算量:定数のオーダー +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + cout << 0 << endl; + } +} +``` + +```java title="" +// アルゴリズム A の時間計算量:定数のオーダー +void algorithm_A(int n) { + System.out.println(0); +} +// アルゴリズム B の時間計算量:線形のオーダー +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + System.out.println(0); + } +} +// アルゴリズム C の時間計算量:定数のオーダー +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + System.out.println(0); + } +} +``` + +```csharp title="" +// アルゴリズム A の時間計算量:定数のオーダー +void AlgorithmA(int n) { + Console.WriteLine(0); +} +// アルゴリズム B の時間計算量:線形のオーダー +void AlgorithmB(int n) { + for (int i = 0; i < n; i++) { + Console.WriteLine(0); + } +} +// アルゴリズム C の時間計算量:定数のオーダー +void AlgorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + Console.WriteLine(0); + } +} +``` + +```go title="" +// アルゴリズム A の時間計算量:定数のオーダー +func algorithm_A(n int) { + fmt.Println(0) +} +// アルゴリズム B の時間計算量:線形のオーダー +func algorithm_B(n int) { + for i := 0; i < n; i++ { + fmt.Println(0) + } +} +// アルゴリズム C の時間計算量:定数のオーダー +func algorithm_C(n int) { + for i := 0; i < 1000000; i++ { + fmt.Println(0) + } +} +``` + +```swift title="" +// アルゴリズム A の時間計算量:定数のオーダー +func algorithmA(n: Int) { + print(0) +} + +// アルゴリズム B の時間計算量:線形のオーダー +func algorithmB(n: Int) { + for _ in 0 ..< n { + print(0) + } +} + +// アルゴリズム C の時間計算量:定数のオーダー +func algorithmC(n: Int) { + for _ in 0 ..< 1_000_000 { + print(0) + } +} +``` + +```javascript title="" +// アルゴリズム A の時間計算量:定数のオーダー +function algorithm_A(n) { + console.log(0); +} +// アルゴリズム B の時間計算量:線形のオーダー +function algorithm_B(n) { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// アルゴリズム C の時間計算量:定数のオーダー +function algorithm_C(n) { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} + +``` + +```typescript title="" +// アルゴリズム A の時間計算量:定数のオーダー +function algorithm_A(n: number): void { + console.log(0); +} +// アルゴリズム B の時間計算量:線形のオーダー +function algorithm_B(n: number): void { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// アルゴリズム C の時間計算量:定数のオーダー +function algorithm_C(n: number): void { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} +``` + +```dart title="" +// アルゴリズム A の時間計算量:定数のオーダー +void algorithmA(int n) { + print(0); +} +// アルゴリズム B の時間計算量:線形のオーダー +void algorithmB(int n) { + for (int i = 0; i < n; i++) { + print(0); + } +} +// アルゴリズム C の時間計算量:定数のオーダー +void algorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + print(0); + } +} +``` + +```rust title="" +// アルゴリズム A の時間計算量:定数のオーダー +fn algorithm_A(n: i32) { + println!("{}", 0); +} +// アルゴリズム B の時間計算量:線形のオーダー +fn algorithm_B(n: i32) { + for _ in 0..n { + println!("{}", 0); + } +} +// アルゴリズム C の時間計算量:定数のオーダー +fn algorithm_C(n: i32) { + for _ in 0..1000000 { + println!("{}", 0); + } +} +``` + +```c title="" +// アルゴリズム A の時間計算量:定数のオーダー +void algorithm_A(int n) { + printf("%d", 0); +} +// アルゴリズム B の時間計算量:線形のオーダー +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + printf("%d", 0); + } +} +// アルゴリズム C の時間計算量:定数のオーダー +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + printf("%d", 0); + } +} +``` + +```kotlin title="" +// アルゴリズム A の時間計算量:定数のオーダー +fun algoritm_A(n: Int) { + println(0) +} +// アルゴリズム B の時間計算量:線形のオーダー +fun algorithm_B(n: Int) { + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +1 + a = a + 1 # +1 + a = a * 2 # +1 + # n 回繰り返す + for i in range(n): # +1 + print(0) # +1 +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n 回繰り返す + for (int i = 0; i < n; i++) { // +1(毎回 i ++ を実行) + cout << 0 << endl; // +1 + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n 回繰り返す + for (int i = 0; i < n; i++) { // +1(毎回 i ++ を実行) + System.out.println(0); // +1 + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n 回繰り返す + for (int i = 0; i < n; i++) { // +1(毎回 i ++ を実行) + Console.WriteLine(0); // +1 + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // n 回繰り返す + for i := 0; i < n; i++ { // +1 + fmt.Println(a) // +1 + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // n 回繰り返す + for _ in 0 ..< n { // +1 + print(0) // +1 + } +} +``` + +```javascript title="" +function algorithm(n) { + var a = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // n 回繰り返す + for(let i = 0; i < n; i++){ // +1(毎回 i ++ を実行) + console.log(0); // +1 + } +} +``` + +```typescript title="" +function algorithm(n: number): void{ + var a: number = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // n 回繰り返す + for(let i = 0; i < n; i++){ // +1(毎回 i ++ を実行) + console.log(0); // +1 + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n 回繰り返す + for (int i = 0; i < n; i++) { // +1(毎回 i ++ を実行) + print(0); // +1 + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + + // n 回繰り返す + for _ in 0..n { // +1(毎回 i ++ を実行) + println!("{}", 0); // +1 + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n 回繰り返す + for (int i = 0; i < n; i++) { // +1(毎回 i ++ を実行) + printf("%d", 0); // +1 + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // n 回繰り返す + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +0(工夫 1) + a = a + n # +0(工夫 1) + # +n(工夫 2) + for i in range(5 * n + 1): + print(0) + # +n*n(工夫 3) + for i in range(2 * n): + for j in range(n + 1): + print(0) +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +0(工夫 1) + a = a + n; // +0(工夫 1) + // +n(工夫 2) + for (int i = 0; i < 5 * n + 1; i++) { + cout << 0 << endl; + } + // +n*n(工夫 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + cout << 0 << endl; + } + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +0(工夫 1) + a = a + n; // +0(工夫 1) + // +n(工夫 2) + for (int i = 0; i < 5 * n + 1; i++) { + System.out.println(0); + } + // +n*n(工夫 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + System.out.println(0); + } + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +0(工夫 1) + a = a + n; // +0(工夫 1) + // +n(工夫 2) + for (int i = 0; i < 5 * n + 1; i++) { + Console.WriteLine(0); + } + // +n*n(工夫 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + Console.WriteLine(0); + } + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +0(工夫 1) + a = a + n // +0(工夫 1) + // +n(工夫 2) + for i := 0; i < 5 * n + 1; i++ { + fmt.Println(0) + } + // +n*n(工夫 3) + for i := 0; i < 2 * n; i++ { + for j := 0; j < n + 1; j++ { + fmt.Println(0) + } + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +0(工夫 1) + a = a + n // +0(工夫 1) + // +n(工夫 2) + for _ in 0 ..< (5 * n + 1) { + print(0) + } + // +n*n(工夫 3) + for _ in 0 ..< (2 * n) { + for _ in 0 ..< (n + 1) { + print(0) + } + } +} +``` + +```javascript title="" +function algorithm(n) { + let a = 1; // +0(工夫 1) + a = a + n; // +0(工夫 1) + // +n(工夫 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n(工夫 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + let a = 1; // +0(工夫 1) + a = a + n; // +0(工夫 1) + // +n(工夫 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n(工夫 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +0(工夫 1) + a = a + n; // +0(工夫 1) + // +n(工夫 2) + for (int i = 0; i < 5 * n + 1; i++) { + print(0); + } + // +n*n(工夫 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + print(0); + } + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +0(工夫 1) + a = a + n; // +0(工夫 1) + + // +n(工夫 2) + for i in 0..(5 * n + 1) { + println!("{}", 0); + } + + // +n*n(工夫 3) + for i in 0..(2 * n) { + for j in 0..(n + 1) { + println!("{}", 0); + } + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +0(工夫 1) + a = a + n; // +0(工夫 1) + // +n(工夫 2) + for (int i = 0; i < 5 * n + 1; i++) { + printf("%d", 0); + } + // +n*n(工夫 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + printf("%d", 0); + } + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +0(工夫 1) + a = a + n // +0(工夫 1) + // +n(工夫 2) + for (i in 0..<5 * n + 1) { + println(0) + } + // +n*n(工夫 3) + for (i in 0..<2 * n) { + for (j in 0.. +```python title="" +# さまざまな基本データ型で配列を初期化 +numbers: list[int] = [0] * 5 +decimals: list[float] = [0.0] * 5 +# Python の文字は、実際には長さ 1 の文字列 +characters: list[str] = ['0'] * 5 +bools: list[bool] = [False] * 5 +# Python のリストには、さまざまな基本データ型やオブジェクトへの参照を自由に格納できる +data = [0, 0.0, 'a', False, ListNode(0)] +``` + +```cpp title="" +// さまざまな基本データ型で配列を初期化 +int numbers[5]; +float decimals[5]; +char characters[5]; +bool bools[5]; +``` + +```java title="" +// さまざまな基本データ型で配列を初期化 +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +boolean[] bools = new boolean[5]; +``` + +```csharp title="" +// さまざまな基本データ型で配列を初期化 +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +bool[] bools = new bool[5]; +``` + +```go title="" +// さまざまな基本データ型で配列を初期化 +var numbers = [5]int{} +var decimals = [5]float64{} +var characters = [5]byte{} +var bools = [5]bool{} +``` + +```swift title="" +// さまざまな基本データ型で配列を初期化 +let numbers = Array(repeating: 0, count: 5) +let decimals = Array(repeating: 0.0, count: 5) +let characters: [Character] = Array(repeating: "a", count: 5) +let bools = Array(repeating: false, count: 5) +``` + +```javascript title="" +// JavaScript の配列には、さまざまな基本データ型やオブジェクトを自由に格納できる +const array = [0, 0.0, 'a', false]; +``` + +```typescript title="" +// さまざまな基本データ型で配列を初期化 +const numbers: number[] = []; +const characters: string[] = []; +const bools: boolean[] = []; +``` + +```dart title="" +// さまざまな基本データ型で配列を初期化 +List numbers = List.filled(5, 0); +List decimals = List.filled(5, 0.0); +List characters = List.filled(5, 'a'); +List bools = List.filled(5, false); +``` + +```rust title="" +// さまざまな基本データ型で配列を初期化 +let numbers: Vec = vec![0; 5]; +let decimals: Vec = vec![0.0; 5]; +let characters: Vec = vec!['0'; 5]; +let bools: Vec = vec![false; 5]; +``` + +```c title="" +// さまざまな基本データ型で配列を初期化 +int numbers[10]; +float decimals[10]; +char characters[10]; +bool bools[10]; +``` + +```kotlin title="" +// さまざまな基本データ型で配列を初期化 +val numbers = IntArray(5) +val decinals = FloatArray(5) +val characters = CharArray(5) +val bools = BooleanArray(5) +``` + +```ruby title="" +# Ruby のリストには、さまざまな基本データ型やオブジェクトへの参照を自由に格納できる +data = [0, 0.0, 'a', false, ListNode(0)] +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E6%AC%A1%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%81%95%E3%81%BE%E3%81%96%E3%81%BE%E3%81%AA%E5%9F%BA%E6%9C%AC%E3%83%87%E3%83%BC%E3%82%BF%E5%9E%8B%E3%81%A7%E9%85%8D%E5%88%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20*%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20*%205%0A%20%20%20%20%23%20Python%20%E3%81%AE%E6%96%87%E5%AD%97%E3%81%AF%E3%80%81%E5%AE%9F%E9%9A%9B%E3%81%AB%E3%81%AF%E9%95%B7%E3%81%95%201%20%E3%81%AE%E6%96%87%E5%AD%97%E5%88%97%0A%20%20%20%20characters%20%3D%20%5B'0'%5D%20*%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20*%205%0A%20%20%20%20%23%20Python%20%E3%81%AE%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AB%E3%81%AF%E3%80%81%E3%81%95%E3%81%BE%E3%81%96%E3%81%BE%E3%81%AA%E5%9F%BA%E6%9C%AC%E3%83%87%E3%83%BC%E3%82%BF%E5%9E%8B%E3%82%84%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%E3%82%92%E8%87%AA%E7%94%B1%E3%81%AB%E6%A0%BC%E7%B4%8D%E3%81%A7%E3%81%8D%E3%82%8B%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20'a'%2C%20False%2C%20ListNode(0)%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_hashing/hash_algorithm.md b/ja/codes/snippets/chapter_hashing/hash_algorithm.md new file mode 100644 index 000000000..ce7ccbdc1 --- /dev/null +++ b/ja/codes/snippets/chapter_hashing/hash_algorithm.md @@ -0,0 +1,263 @@ + +```python title="built_in_hash.py" +num = 3 +hash_num = hash(num) +# 整数 3 のハッシュ値は 3 + +bol = True +hash_bol = hash(bol) +# 真偽値 True のハッシュ値は 1 + +dec = 3.14159 +hash_dec = hash(dec) +# 小数 3.14159 のハッシュ値は 326484311674566659 + +str = "Hello 算法" +hash_str = hash(str) +# 文字列「Hello 算法」のハッシュ値は 4617003410720528961 + +tup = (12836, "小哈") +hash_tup = hash(tup) +# タプル (12836, '小哈') のハッシュ値は 1029005403108185979 + +obj = ListNode(0) +hash_obj = hash(obj) +# ノードオブジェクト のハッシュ値は 274267521 +``` + +```cpp title="built_in_hash.cpp" +int num = 3; +size_t hashNum = hash()(num); +// 整数 3 のハッシュ値は 3 + +bool bol = true; +size_t hashBol = hash()(bol); +// 真偽値 1 のハッシュ値は 1 + +double dec = 3.14159; +size_t hashDec = hash()(dec); +// 小数 3.14159 のハッシュ値は 4614256650576692846 + +string str = "Hello 算法"; +size_t hashStr = hash()(str); +// 文字列「Hello 算法」のハッシュ値は 15466937326284535026 + +// C++ の組み込み std::hash() は基本データ型のハッシュ値計算のみを提供する +// 配列やオブジェクトのハッシュ値計算は自分で実装する +``` + +```java title="built_in_hash.java" +int num = 3; +int hashNum = Integer.hashCode(num); +// 整数 3 のハッシュ値は 3 + +boolean bol = true; +int hashBol = Boolean.hashCode(bol); +// 真偽値 true のハッシュ値は 1231 + +double dec = 3.14159; +int hashDec = Double.hashCode(dec); +// 小数 3.14159 のハッシュ値は -1340954729 + +String str = "Hello 算法"; +int hashStr = str.hashCode(); +// 文字列「Hello 算法」のハッシュ値は -727081396 + +Object[] arr = { 12836, "小哈" }; +int hashTup = Arrays.hashCode(arr); +// 配列 [12836, 小哈] のハッシュ値は 1151158 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode(); +// ノードオブジェクト utils.ListNode@7dc5e7b4 のハッシュ値は 2110121908 +``` + +```csharp title="built_in_hash.cs" +int num = 3; +int hashNum = num.GetHashCode(); +// 整数 3 のハッシュ値は 3; + +bool bol = true; +int hashBol = bol.GetHashCode(); +// 真偽値 true のハッシュ値は 1; + +double dec = 3.14159; +int hashDec = dec.GetHashCode(); +// 小数 3.14159 のハッシュ値は -1340954729; + +string str = "Hello 算法"; +int hashStr = str.GetHashCode(); +// 文字列「Hello 算法」のハッシュ値は -586107568; + +object[] arr = [12836, "小哈"]; +int hashTup = arr.GetHashCode(); +// 配列 [12836, 小哈] のハッシュ値は 42931033; + +ListNode obj = new(0); +int hashObj = obj.GetHashCode(); +// ノードオブジェクト 0 のハッシュ値は 39053774; +``` + +```go title="built_in_hash.go" +// Go には組み込みの hash code 関数がない +``` + +```swift title="built_in_hash.swift" +let num = 3 +let hashNum = num.hashValue +// 整数 3 のハッシュ値は 9047044699613009734 + +let bol = true +let hashBol = bol.hashValue +// 真偽値 true のハッシュ値は -4431640247352757451 + +let dec = 3.14159 +let hashDec = dec.hashValue +// 小数 3.14159 のハッシュ値は -2465384235396674631 + +let str = "Hello 算法" +let hashStr = str.hashValue +// 文字列「Hello 算法」のハッシュ値は -7850626797806988787 + +let arr = [AnyHashable(12836), AnyHashable("小哈")] +let hashTup = arr.hashValue +// 配列 [AnyHashable(12836), AnyHashable("小哈")] のハッシュ値は -2308633508154532996 + +let obj = ListNode(x: 0) +let hashObj = obj.hashValue +// ノードオブジェクト utils.ListNode のハッシュ値は -2434780518035996159 +``` + +```javascript title="built_in_hash.js" +// JavaScript には組み込みの hash code 関数がない +``` + +```typescript title="built_in_hash.ts" +// TypeScript には組み込みの hash code 関数がない +``` + +```dart title="built_in_hash.dart" +int num = 3; +int hashNum = num.hashCode; +// 整数 3 のハッシュ値は 34803 + +bool bol = true; +int hashBol = bol.hashCode; +// 真偽値 true のハッシュ値は 1231 + +double dec = 3.14159; +int hashDec = dec.hashCode; +// 小数 3.14159 のハッシュ値は 2570631074981783 + +String str = "Hello 算法"; +int hashStr = str.hashCode; +// 文字列「Hello 算法」のハッシュ値は 468167534 + +List arr = [12836, "小哈"]; +int hashArr = arr.hashCode; +// 配列 [12836, 小哈] のハッシュ値は 976512528 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode; +// ノードオブジェクト Instance of 'ListNode' のハッシュ値は 1033450432 +``` + +```rust title="built_in_hash.rs" +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +let num = 3; +let mut num_hasher = DefaultHasher::new(); +num.hash(&mut num_hasher); +let hash_num = num_hasher.finish(); +// 整数 3 のハッシュ値は 568126464209439262 + +let bol = true; +let mut bol_hasher = DefaultHasher::new(); +bol.hash(&mut bol_hasher); +let hash_bol = bol_hasher.finish(); +// 真偽値 true のハッシュ値は 4952851536318644461 + +let dec: f32 = 3.14159; +let mut dec_hasher = DefaultHasher::new(); +dec.to_bits().hash(&mut dec_hasher); +let hash_dec = dec_hasher.finish(); +// 小数 3.14159 のハッシュ値は 2566941990314602357 + +let str = "Hello 算法"; +let mut str_hasher = DefaultHasher::new(); +str.hash(&mut str_hasher); +let hash_str = str_hasher.finish(); +// 文字列「Hello 算法」のハッシュ値は 16092673739211250988 + +let arr = (&12836, &"小哈"); +let mut tup_hasher = DefaultHasher::new(); +arr.hash(&mut tup_hasher); +let hash_tup = tup_hasher.finish(); +// タプル (12836, "小哈") のハッシュ値は 1885128010422702749 + +let node = ListNode::new(42); +let mut hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut hasher); +let hash = hasher.finish(); +// ノードオブジェクト RefCell { value: ListNode { val: 42, next: None } } のハッシュ値は 15387811073369036852 +``` + +```c title="built_in_hash.c" +// C には組み込みの hash code 関数がない +``` + +```kotlin title="built_in_hash.kt" +val num = 3 +val hashNum = num.hashCode() +// 整数 3 のハッシュ値は 3 + +val bol = true +val hashBol = bol.hashCode() +// 真偽値 true のハッシュ値は 1231 + +val dec = 3.14159 +val hashDec = dec.hashCode() +// 小数 3.14159 のハッシュ値は -1340954729 + +val str = "Hello 算法" +val hashStr = str.hashCode() +// 文字列「Hello 算法」のハッシュ値は -727081396 + +val arr = arrayOf(12836, "小哈") +val hashTup = arr.hashCode() +// 配列 [12836, 小哈] のハッシュ値は 189568618 + +val obj = ListNode(0) +val hashObj = obj.hashCode() +// ノードオブジェクト utils.ListNode@1d81eb93 のハッシュ値は 495053715 +``` + +```ruby title="built_in_hash.rb" +num = 3 +hash_num = num.hash +# 整数 3 のハッシュ値は -4385856518450339636 + +bol = true +hash_bol = bol.hash +# 真偽値 true のハッシュ値は -1617938112149317027 + +dec = 3.14159 +hash_dec = dec.hash +# 小数 3.14159 のハッシュ値は -1479186995943067893 + +str = "Hello 算法" +hash_str = str.hash +# 文字列「Hello 算法」のハッシュ値は -4075943250025831763 + +tup = [12836, '小哈'] +hash_tup = tup.hash +# タプル (12836, '小哈') のハッシュ値は 1999544809202288822 + +obj = ListNode.new(0) +hash_obj = obj.hash +# ノードオブジェクト # のハッシュ値は 4302940560806366381 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E6%AC%A1%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash(num)%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash(bol)%0A%20%20%20%20%23%20%E7%9C%9F%E5%81%BD%E5%80%A4%20True%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash(dec)%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash(str)%0A%20%20%20%20%23%20%E6%96%87%E5%AD%97%E5%88%97%E3%80%8CHello%20%E7%AE%97%E6%B3%95%E3%80%8D%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20(12836%2C%20%22%E5%B0%8F%E5%93%88%22)%0A%20%20%20%20hash_tup%20%3D%20hash(tup)%0A%20%20%20%20%23%20%E3%82%BF%E3%83%97%E3%83%AB%20(12836%2C%20'%E5%B0%8F%E5%93%88')%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode(0)%0A%20%20%20%20hash_obj%20%3D%20hash(obj)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%20%3CListNode%20object%20at%200x1058fd810%3E%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_hashing/hash_map.md b/ja/codes/snippets/chapter_hashing/hash_map.md new file mode 100644 index 000000000..5b13ebcec --- /dev/null +++ b/ja/codes/snippets/chapter_hashing/hash_map.md @@ -0,0 +1,457 @@ + +```python title="hash_map.py" +# ハッシュテーブルを初期化 +hmap: dict = {} + +# 追加操作 +# ハッシュテーブルにペア (key, value) を追加 +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +# 照会操作 +# キー key を入力して値 value を取得 +name: str = hmap[15937] + +# 削除操作 +# ハッシュテーブルからペア (key, value) を削除 +hmap.pop(10583) +``` + +```cpp title="hash_map.cpp" +/* ハッシュテーブルを初期化 */ +unordered_map map; + +/* 追加操作 */ +// ハッシュテーブルにペア (key, value) を追加 +map[12836] = "小哈"; +map[15937] = "小啰"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鸭"; + +/* 照会操作 */ +// キー key を入力して値 value を取得 +string name = map[15937]; + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +map.erase(10583); +``` + +```java title="hash_map.java" +/* ハッシュテーブルを初期化 */ +Map map = new HashMap<>(); + +/* 追加操作 */ +// ハッシュテーブルにペア (key, value) を追加 +map.put(12836, "小哈"); +map.put(15937, "小啰"); +map.put(16750, "小算"); +map.put(13276, "小法"); +map.put(10583, "小鸭"); + +/* 照会操作 */ +// キー key を入力して値 value を取得 +String name = map.get(15937); + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +map.remove(10583); +``` + +```csharp title="hash_map.cs" +/* ハッシュテーブルを初期化 */ +Dictionary map = new() { + /* 追加操作 */ + // ハッシュテーブルにペア (key, value) を追加 + { 12836, "小哈" }, + { 15937, "小啰" }, + { 16750, "小算" }, + { 13276, "小法" }, + { 10583, "小鸭" } +}; + +/* 照会操作 */ +// キー key を入力して値 value を取得 +string name = map[15937]; + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +map.Remove(10583); +``` + +```go title="hash_map_test.go" +/* ハッシュテーブルを初期化 */ +hmap := make(map[int]string) + +/* 追加操作 */ +// ハッシュテーブルにペア (key, value) を追加 +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +/* 照会操作 */ +// キー key を入力して値 value を取得 +name := hmap[15937] + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +delete(hmap, 10583) +``` + +```swift title="hash_map.swift" +/* ハッシュテーブルを初期化 */ +var map: [Int: String] = [:] + +/* 追加操作 */ +// ハッシュテーブルにペア (key, value) を追加 +map[12836] = "小哈" +map[15937] = "小啰" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鸭" + +/* 照会操作 */ +// キー key を入力して値 value を取得 +let name = map[15937]! + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +map.removeValue(forKey: 10583) +``` + +```javascript title="hash_map.js" +/* ハッシュテーブルを初期化 */ +const map = new Map(); +/* 追加操作 */ +// ハッシュテーブルにペア (key, value) を追加 +map.set(12836, '小哈'); +map.set(15937, '小啰'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鸭'); + +/* 照会操作 */ +// キー key を入力して値 value を取得 +let name = map.get(15937); + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +map.delete(10583); +``` + +```typescript title="hash_map.ts" +/* ハッシュテーブルを初期化 */ +const map = new Map(); +/* 追加操作 */ +// ハッシュテーブルにペア (key, value) を追加 +map.set(12836, '小哈'); +map.set(15937, '小啰'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鸭'); +console.info('\n追加後のハッシュテーブルは\nKey -> Value'); +console.info(map); + +/* 照会操作 */ +// キー key を入力して値 value を取得 +let name = map.get(15937); +console.info('\n学籍番号 15937 を入力して得た名前は ' + name); + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +map.delete(10583); +console.info('\n10583 を削除した後のハッシュテーブルは\nKey -> Value'); +console.info(map); +``` + +```dart title="hash_map.dart" +/* ハッシュテーブルを初期化 */ +Map map = {}; + +/* 追加操作 */ +// ハッシュテーブルにペア (key, value) を追加 +map[12836] = "小哈"; +map[15937] = "小啰"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鸭"; + +/* 照会操作 */ +// キー key を入力して値 value を取得 +String name = map[15937]; + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +map.remove(10583); +``` + +```rust title="hash_map.rs" +use std::collections::HashMap; + +/* ハッシュテーブルを初期化 */ +let mut map: HashMap = HashMap::new(); + +/* 追加操作 */ +// ハッシュテーブルにペア (key, value) を追加 +map.insert(12836, "小哈".to_string()); +map.insert(15937, "小啰".to_string()); +map.insert(16750, "小算".to_string()); +map.insert(13279, "小法".to_string()); +map.insert(10583, "小鸭".to_string()); + +/* 照会操作 */ +// キー key を入力して値 value を取得 +let _name: Option<&String> = map.get(&15937); + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +let _removed_value: Option = map.remove(&10583); +``` + +```c title="hash_map.c" +// C には組み込みのハッシュテーブルがない +``` + +```kotlin title="hash_map.kt" +/* ハッシュテーブルを初期化 */ +val map = HashMap() + +/* 追加操作 */ +// ハッシュテーブルにペア (key, value) を追加 +map[12836] = "小哈" +map[15937] = "小啰" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鸭" + +/* 照会操作 */ +// キー key を入力して値 value を取得 +val name = map[15937] + +/* 削除操作 */ +// ハッシュテーブルからペア (key, value) を削除 +map.remove(10583) +``` + +```ruby title="hash_map.rb" +# ハッシュテーブルを初期化 +hmap = {} + +# 追加操作 +# ハッシュテーブルにペア (key, value) を追加 +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +# 照会操作 +# キー key を入力して値 value を取得 +name = hmap[15937] + +# 削除操作 +# ハッシュテーブルからペア (key, value) を削除 +hmap.delete(10583) +``` + + +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BF%BD%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%81%AB%E3%83%9A%E3%82%A2%20(key%2C%20value)%20%E3%82%92%E8%BF%BD%E5%8A%A0%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%85%A7%E4%BC%9A%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%20key%20%E3%82%92%E5%85%A5%E5%8A%9B%E3%81%97%E3%81%A6%E5%80%A4%20value%20%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%89%8A%E9%99%A4%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%81%8B%E3%82%89%E3%83%9A%E3%82%A2%20(key%2C%20value)%20%E3%82%92%E5%89%8A%E9%99%A4%0A%20%20%20%20hmap.pop(10583)&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="hash_map.py" +# ハッシュテーブルを走査 +# キーと値のペアを走査 key->value +for key, value in hmap.items(): + print(key, "->", value) +# キーだけを走査 key +for key in hmap.keys(): + print(key) +# 値だけを走査 value +for value in hmap.values(): + print(value) +``` + +```cpp title="hash_map.cpp" +/* ハッシュテーブルを走査 */ +// キーと値のペアを走査 key->value +for (auto kv: map) { + cout << kv.first << " -> " << kv.second << endl; +} +// イテレータで走査 key->value +for (auto iter = map.begin(); iter != map.end(); iter++) { + cout << iter->first << "->" << iter->second << endl; +} +``` + +```java title="hash_map.java" +/* ハッシュテーブルを走査 */ +// キーと値のペアを走査 key->value +for (Map.Entry kv: map.entrySet()) { + System.out.println(kv.getKey() + " -> " + kv.getValue()); +} +// キーだけを走査 key +for (int key: map.keySet()) { + System.out.println(key); +} +// 値だけを走査 value +for (String val: map.values()) { + System.out.println(val); +} +``` + +```csharp title="hash_map.cs" +/* ハッシュテーブルを走査 */ +// キーと値のペアを走査 Key->Value +foreach (var kv in map) { + Console.WriteLine(kv.Key + " -> " + kv.Value); +} +// キーだけを走査 key +foreach (int key in map.Keys) { + Console.WriteLine(key); +} +// 値だけを走査 value +foreach (string val in map.Values) { + Console.WriteLine(val); +} +``` + +```go title="hash_map_test.go" +/* ハッシュテーブルを走査 */ +// キーと値のペアを走査 key->value +for key, value := range hmap { + fmt.Println(key, "->", value) +} +// キーだけを走査 key +for key := range hmap { + fmt.Println(key) +} +// 値だけを走査 value +for _, value := range hmap { + fmt.Println(value) +} +``` + +```swift title="hash_map.swift" +/* ハッシュテーブルを走査 */ +// キーと値のペアを走査 Key->Value +for (key, value) in map { + print("\(key) -> \(value)") +} +// キーだけを走査 Key +for key in map.keys { + print(key) +} +// 値だけを走査 Value +for value in map.values { + print(value) +} +``` + +```javascript title="hash_map.js" +/* ハッシュテーブルを走査 */ +console.info('\nキーと値のペアを走査 Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\nキーだけを走査 Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\n値だけを走査 Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```typescript title="hash_map.ts" +/* ハッシュテーブルを走査 */ +console.info('\nキーと値のペアを走査 Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\nキーだけを走査 Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\n値だけを走査 Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```dart title="hash_map.dart" +/* ハッシュテーブルを走査 */ +// キーと値のペアを走査 Key->Value +map.forEach((key, value) { + print('$key -> $value'); +}); + +// キーだけを走査 Key +map.keys.forEach((key) { + print(key); +}); + +// 値だけを走査 Value +map.values.forEach((value) { + print(value); +}); +``` + +```rust title="hash_map.rs" +/* ハッシュテーブルを走査 */ +// キーと値のペアを走査 Key->Value +for (key, value) in &map { + println!("{key} -> {value}"); +} + +// キーだけを走査 Key +for key in map.keys() { + println!("{key}"); +} + +// 値だけを走査 Value +for value in map.values() { + println!("{value}"); +} +``` + +```c title="hash_map.c" +// C には組み込みのハッシュテーブルがない +``` + +```kotlin title="hash_map.kt" +/* ハッシュテーブルを走査 */ +// キーと値のペアを走査 key->value +for ((key, value) in map) { + println("$key -> $value") +} +// キーだけを走査 key +for (key in map.keys) { + println(key) +} +// 値だけを走査 value +for (_val in map.values) { + println(_val) +} +``` + +```ruby title="hash_map.rb" +# ハッシュテーブルを走査 +# キーと値のペアを走査 key->value +hmap.entries.each { |key, value| puts "#{key} -> #{value}" } + +# キーだけを走査 key +hmap.keys.each { |key| puts key } + +# 値だけを走査 value +hmap.values.each { |val| puts val } +``` + + +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BF%BD%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%81%AB%E3%83%9A%E3%82%A2%20(key%2C%20value)%20%E3%82%92%E8%BF%BD%E5%8A%A0%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E8%B5%B0%E6%9F%BB%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%E3%81%A8%E5%80%A4%E3%81%AE%E3%83%9A%E3%82%A2%E3%82%92%E8%B5%B0%E6%9F%BB%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items()%3A%0A%20%20%20%20%20%20%20%20print(key%2C%20%22-%3E%22%2C%20value)%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%E3%81%A0%E3%81%91%E3%82%92%E8%B5%B0%E6%9F%BB%20key%0A%20%20%20%20for%20key%20in%20hmap.keys()%3A%0A%20%20%20%20%20%20%20%20print(key)%0A%20%20%20%20%23%20%E5%80%A4%E3%81%A0%E3%81%91%E3%82%92%E8%B5%B0%E6%9F%BB%20value%0A%20%20%20%20for%20value%20in%20hmap.values()%3A%0A%20%20%20%20%20%20%20%20print(value)&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_heap/heap.md b/ja/codes/snippets/chapter_heap/heap.md new file mode 100644 index 000000000..26dfab83b --- /dev/null +++ b/ja/codes/snippets/chapter_heap/heap.md @@ -0,0 +1,350 @@ + +```python title="heap.py" +# 最小ヒープを初期化 +min_heap, flag = [], 1 +# 最大ヒープを初期化 +max_heap, flag = [], -1 + +# Python の heapq モジュールはデフォルトで最小ヒープを実装する +# 要素の符号を反転してから挿入すると、大小関係が逆転し最大ヒープを実現できる +# この例では flag = 1 が最小ヒープ、flag = -1 が最大ヒープに対応する + +# 要素をヒープに挿入 +heapq.heappush(max_heap, flag * 1) +heapq.heappush(max_heap, flag * 3) +heapq.heappush(max_heap, flag * 2) +heapq.heappush(max_heap, flag * 5) +heapq.heappush(max_heap, flag * 4) + +# ヒープの先頭要素を取得 +peek: int = flag * max_heap[0] # 5 + +# ヒープの先頭要素を取り出す +# 取り出した要素は降順の列になる +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 + +# ヒープの要素数を取得 +size: int = len(max_heap) + +# ヒープが空かどうかを判定 +is_empty: bool = not max_heap + +# リストを入力してヒープを構築 +min_heap: list[int] = [1, 3, 2, 5, 4] +heapq.heapify(min_heap) +``` + +```cpp title="heap.cpp" +/* ヒープを初期化 */ +// 最小ヒープを初期化 +priority_queue, greater> minHeap; +// 最大ヒープを初期化 +priority_queue, less> maxHeap; + +/* 要素をヒープに挿入 */ +maxHeap.push(1); +maxHeap.push(3); +maxHeap.push(2); +maxHeap.push(5); +maxHeap.push(4); + +/* ヒープの先頭要素を取得 */ +int peek = maxHeap.top(); // 5 + +/* ヒープの先頭要素を取り出す */ +// 取り出した要素は降順の列になる +maxHeap.pop(); // 5 +maxHeap.pop(); // 4 +maxHeap.pop(); // 3 +maxHeap.pop(); // 2 +maxHeap.pop(); // 1 + +/* ヒープの要素数を取得 */ +int size = maxHeap.size(); + +/* ヒープが空かどうかを判定 */ +bool isEmpty = maxHeap.empty(); + +/* リストを入力してヒープを構築 */ +vector input{1, 3, 2, 5, 4}; +priority_queue, greater> minHeap(input.begin(), input.end()); +``` + +```java title="heap.java" +/* ヒープを初期化 */ +// 最小ヒープを初期化 +Queue minHeap = new PriorityQueue<>(); +// 最大ヒープを初期化(ラムダ式で Comparator を変更する) +Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + +/* 要素をヒープに挿入 */ +maxHeap.offer(1); +maxHeap.offer(3); +maxHeap.offer(2); +maxHeap.offer(5); +maxHeap.offer(4); + +/* ヒープの先頭要素を取得 */ +int peek = maxHeap.peek(); // 5 + +/* ヒープの先頭要素を取り出す */ +// 取り出した要素は降順の列になる +peek = maxHeap.poll(); // 5 +peek = maxHeap.poll(); // 4 +peek = maxHeap.poll(); // 3 +peek = maxHeap.poll(); // 2 +peek = maxHeap.poll(); // 1 + +/* ヒープの要素数を取得 */ +int size = maxHeap.size(); + +/* ヒープが空かどうかを判定 */ +boolean isEmpty = maxHeap.isEmpty(); + +/* リストを入力してヒープを構築 */ +minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +``` + +```csharp title="heap.cs" +/* ヒープを初期化 */ +// 最小ヒープを初期化 +PriorityQueue minHeap = new(); +// 最大ヒープを初期化(ラムダ式で Comparer を変更する) +PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + +/* 要素をヒープに挿入 */ +maxHeap.Enqueue(1, 1); +maxHeap.Enqueue(3, 3); +maxHeap.Enqueue(2, 2); +maxHeap.Enqueue(5, 5); +maxHeap.Enqueue(4, 4); + +/* ヒープの先頭要素を取得 */ +int peek = maxHeap.Peek();//5 + +/* ヒープの先頭要素を取り出す */ +// 取り出した要素は降順の列になる +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 + +/* ヒープの要素数を取得 */ +int size = maxHeap.Count; + +/* ヒープが空かどうかを判定 */ +bool isEmpty = maxHeap.Count == 0; + +/* リストを入力してヒープを構築 */ +minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +``` + +```go title="heap.go" +// Go では heap.Interface を実装して整数の最大ヒープを構築できる +// heap.Interface の実装には sort.Interface の実装も必要 +type intHeap []any + +// Push は heap.Interface のメソッドで、ヒープへの挿入を実装する +func (h *intHeap) Push(x any) { + // Push と Pop はポインタレシーバーを引数として使う + // スライスの内容だけでなく長さも変更するため + *h = append(*h, x.(int)) +} + +// Pop は heap.Interface のメソッドで、先頭要素の取り出しを実装する +func (h *intHeap) Pop() any { + // 取り出す要素は末尾に格納されている + last := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return last +} + +// Len は sort.Interface のメソッド +func (h *intHeap) Len() int { + return len(*h) +} + +// Less は sort.Interface のメソッド +func (h *intHeap) Less(i, j int) bool { + // 最小ヒープを実装する場合は、小なり記号に変更する + return (*h)[i].(int) > (*h)[j].(int) +} + +// Swap は sort.Interface のメソッド +func (h *intHeap) Swap(i, j int) { + (*h)[i], (*h)[j] = (*h)[j], (*h)[i] +} + +// Top ヒープの先頭要素を取得 +func (h *intHeap) Top() any { + return (*h)[0] +} + +/* 実行用コード */ +func TestHeap(t *testing.T) { + /* ヒープを初期化 */ + // 最大ヒープを初期化 + maxHeap := &intHeap{} + heap.Init(maxHeap) + /* 要素をヒープに挿入 */ + // heap.Interface のメソッドを呼んで要素を追加 + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 4) + heap.Push(maxHeap, 5) + + /* ヒープの先頭要素を取得 */ + top := maxHeap.Top() + fmt.Printf("ヒープの先頭要素は %d\n", top) + + /* ヒープの先頭要素を取り出す */ + // heap.Interface のメソッドを呼んで要素を削除 + heap.Pop(maxHeap) // 5 + heap.Pop(maxHeap) // 4 + heap.Pop(maxHeap) // 3 + heap.Pop(maxHeap) // 2 + heap.Pop(maxHeap) // 1 + + /* ヒープの要素数を取得 */ + size := len(*maxHeap) + fmt.Printf("ヒープの要素数は %d\n", size) + + /* ヒープが空かどうかを判定 */ + isEmpty := len(*maxHeap) == 0 + fmt.Printf("ヒープは空か %t\n", isEmpty) +} +``` + +```swift title="heap.swift" +/* ヒープを初期化 */ +// Swift の Heap 型は最大ヒープと最小ヒープの両方に対応し、swift-collections の導入が必要 +var heap = Heap() + +/* 要素をヒープに挿入 */ +heap.insert(1) +heap.insert(3) +heap.insert(2) +heap.insert(5) +heap.insert(4) + +/* ヒープの先頭要素を取得 */ +var peek = heap.max()! + +/* ヒープの先頭要素を取り出す */ +peek = heap.removeMax() // 5 +peek = heap.removeMax() // 4 +peek = heap.removeMax() // 3 +peek = heap.removeMax() // 2 +peek = heap.removeMax() // 1 + +/* ヒープの要素数を取得 */ +let size = heap.count + +/* ヒープが空かどうかを判定 */ +let isEmpty = heap.isEmpty + +/* リストを入力してヒープを構築 */ +let heap2 = Heap([1, 3, 2, 5, 4]) +``` + +```javascript title="heap.js" +// JavaScript には組み込みの Heap クラスがない +``` + +```typescript title="heap.ts" +// TypeScript には組み込みの Heap クラスがない +``` + +```dart title="heap.dart" +// Dart には組み込みの Heap クラスがない +``` + +```rust title="heap.rs" +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +/* ヒープを初期化 */ +// 最小ヒープを初期化 +let mut min_heap = BinaryHeap::>::new(); +// 最大ヒープを初期化 +let mut max_heap = BinaryHeap::new(); + +/* 要素をヒープに挿入 */ +max_heap.push(1); +max_heap.push(3); +max_heap.push(2); +max_heap.push(5); +max_heap.push(4); + +/* ヒープの先頭要素を取得 */ +let peek = max_heap.peek().unwrap(); // 5 + +/* ヒープの先頭要素を取り出す */ +// 取り出した要素は降順の列になる +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 + +/* ヒープの要素数を取得 */ +let size = max_heap.len(); + +/* ヒープが空かどうかを判定 */ +let is_empty = max_heap.is_empty(); + +/* リストを入力してヒープを構築 */ +let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +``` + +```c title="heap.c" +// C には組み込みの Heap クラスがない +``` + +```kotlin title="heap.kt" +/* ヒープを初期化 */ +// 最小ヒープを初期化 +var minHeap = PriorityQueue() +// 最大ヒープを初期化(ラムダ式で Comparator を変更する) +val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + +/* 要素をヒープに挿入 */ +maxHeap.offer(1) +maxHeap.offer(3) +maxHeap.offer(2) +maxHeap.offer(5) +maxHeap.offer(4) + +/* ヒープの先頭要素を取得 */ +var peek = maxHeap.peek() // 5 + +/* ヒープの先頭要素を取り出す */ +// 取り出した要素は降順の列になる +peek = maxHeap.poll() // 5 +peek = maxHeap.poll() // 4 +peek = maxHeap.poll() // 3 +peek = maxHeap.poll() // 2 +peek = maxHeap.poll() // 1 + +/* ヒープの要素数を取得 */ +val size = maxHeap.size + +/* ヒープが空かどうかを判定 */ +val isEmpty = maxHeap.isEmpty() + +/* リストを入力してヒープを構築 */ +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +``` + +```ruby title="heap.rb" +# Ruby には組み込みの Heap クラスがない +``` + + +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E3%81%AE%20heapq%20%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AF%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88%E3%81%A7%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%AE%9F%E8%A3%85%E3%81%99%E3%82%8B%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AE%E7%AC%A6%E5%8F%B7%E3%82%92%E5%8F%8D%E8%BB%A2%E3%81%97%E3%81%A6%E3%81%8B%E3%82%89%E6%8C%BF%E5%85%A5%E3%81%99%E3%82%8B%E3%81%A8%E3%80%81%E5%A4%A7%E5%B0%8F%E9%96%A2%E4%BF%82%E3%81%8C%E9%80%86%E8%BB%A2%E3%81%97%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%AE%9F%E7%8F%BE%E3%81%A7%E3%81%8D%E3%82%8B%0A%20%20%20%20%23%20%E3%81%93%E3%81%AE%E4%BE%8B%E3%81%A7%E3%81%AF%20flag%20%3D%201%20%E3%81%8C%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%80%81flag%20%3D%20-1%20%E3%81%8C%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%81%AB%E5%AF%BE%E5%BF%9C%E3%81%99%E3%82%8B%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%92%E3%83%BC%E3%83%97%E3%81%AB%E6%8C%BF%E5%85%A5%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%201)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%203)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%202)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%205)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%204)%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20peek%20%3D%20flag%20*%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%99%0A%20%20%20%20%23%20%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%E3%81%AF%E9%99%8D%E9%A0%86%E3%81%AE%E5%88%97%E3%81%AB%E3%81%AA%E3%82%8B%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%205%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%204%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%203%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%202%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E8%A6%81%E7%B4%A0%E6%95%B0%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(max_heap)%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%8C%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%85%A5%E5%8A%9B%E3%81%97%E3%81%A6%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E6%A7%8B%E7%AF%89%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify(min_heap)&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_preface/suggestions.md b/ja/codes/snippets/chapter_preface/suggestions.md new file mode 100644 index 000000000..d448b751e --- /dev/null +++ b/ja/codes/snippets/chapter_preface/suggestions.md @@ -0,0 +1,139 @@ + +```python title="" +"""見出しコメント:関数、クラス、テストケースなどを示す""" + +# 内容コメント:コードを詳しく説明する + +""" +複数行の +コメント +""" +``` + +```cpp title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```java title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```csharp title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```go title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```swift title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```javascript title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```typescript title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```dart title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```rust title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +// 複数行の +// コメント +``` + +```c title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```kotlin title="" +/* 見出しコメント:関数、クラス、テストケースなどを示す */ + +// 内容コメント:コードを詳しく説明する + +/** + * 複数行の + * コメント + */ +``` + +```ruby title="" +### 見出しコメント:関数、クラス、テストケースなどを示す ### + +# 内容コメント:コードを詳しく説明する + +# 複数行の +# コメント +``` diff --git a/ja/codes/snippets/chapter_stack_and_queue/deque.md b/ja/codes/snippets/chapter_stack_and_queue/deque.md new file mode 100644 index 000000000..15056280a --- /dev/null +++ b/ja/codes/snippets/chapter_stack_and_queue/deque.md @@ -0,0 +1,339 @@ + +```python title="deque.py" +from collections import deque + +# 両端キューを初期化 +deq: deque[int] = deque() + +# 要素をエンキュー +deq.append(2) # 末尾に追加 +deq.append(5) +deq.append(4) +deq.appendleft(3) # 先頭に追加 +deq.appendleft(1) + +# 要素にアクセス +front: int = deq[0] # 先頭要素 +rear: int = deq[-1] # 末尾要素 + +# 要素をデキュー +pop_front: int = deq.popleft() # 先頭要素を取り出す +pop_rear: int = deq.pop() # 末尾要素を取り出す + +# 両端キューの長さを取得 +size: int = len(deq) + +# 両端キューが空かどうかを判定 +is_empty: bool = len(deq) == 0 +``` + +```cpp title="deque.cpp" +/* 両端キューを初期化 */ +deque deque; + +/* 要素をエンキュー */ +deque.push_back(2); // 末尾に追加 +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // 先頭に追加 +deque.push_front(1); + +/* 要素にアクセス */ +int front = deque.front(); // 先頭要素 +int back = deque.back(); // 末尾要素 + +/* 要素をデキュー */ +deque.pop_front(); // 先頭要素を取り出す +deque.pop_back(); // 末尾要素を取り出す + +/* 両端キューの長さを取得 */ +int size = deque.size(); + +/* 両端キューが空かどうかを判定 */ +bool empty = deque.empty(); +``` + +```java title="deque.java" +/* 両端キューを初期化 */ +Deque deque = new LinkedList<>(); + +/* 要素をエンキュー */ +deque.offerLast(2); // 末尾に追加 +deque.offerLast(5); +deque.offerLast(4); +deque.offerFirst(3); // 先頭に追加 +deque.offerFirst(1); + +/* 要素にアクセス */ +int peekFirst = deque.peekFirst(); // 先頭要素 +int peekLast = deque.peekLast(); // 末尾要素 + +/* 要素をデキュー */ +int popFirst = deque.pollFirst(); // 先頭要素を取り出す +int popLast = deque.pollLast(); // 末尾要素を取り出す + +/* 両端キューの長さを取得 */ +int size = deque.size(); + +/* 両端キューが空かどうかを判定 */ +boolean isEmpty = deque.isEmpty(); +``` + +```csharp title="deque.cs" +/* 両端キューを初期化 */ +// C# では LinkedList を両端キューとして使う +LinkedList deque = new(); + +/* 要素をエンキュー */ +deque.AddLast(2); // 末尾に追加 +deque.AddLast(5); +deque.AddLast(4); +deque.AddFirst(3); // 先頭に追加 +deque.AddFirst(1); + +/* 要素にアクセス */ +int peekFirst = deque.First.Value; // 先頭要素 +int peekLast = deque.Last.Value; // 末尾要素 + +/* 要素をデキュー */ +deque.RemoveFirst(); // 先頭要素を取り出す +deque.RemoveLast(); // 末尾要素を取り出す + +/* 両端キューの長さを取得 */ +int size = deque.Count; + +/* 両端キューが空かどうかを判定 */ +bool isEmpty = deque.Count == 0; +``` + +```go title="deque_test.go" +/* 両端キューを初期化 */ +// Go では list を両端キューとして使う +deque := list.New() + +/* 要素をエンキュー */ +deque.PushBack(2) // 末尾に追加 +deque.PushBack(5) +deque.PushBack(4) +deque.PushFront(3) // 先頭に追加 +deque.PushFront(1) + +/* 要素にアクセス */ +front := deque.Front() // 先頭要素 +rear := deque.Back() // 末尾要素 + +/* 要素をデキュー */ +deque.Remove(front) // 先頭要素を取り出す +deque.Remove(rear) // 末尾要素を取り出す + +/* 両端キューの長さを取得 */ +size := deque.Len() + +/* 両端キューが空かどうかを判定 */ +isEmpty := deque.Len() == 0 +``` + +```swift title="deque.swift" +/* 両端キューを初期化 */ +// Swift には組み込みの両端キュークラスがないため、Array を両端キューとして使える +var deque: [Int] = [] + +/* 要素をエンキュー */ +deque.append(2) // 末尾に追加 +deque.append(5) +deque.append(4) +deque.insert(3, at: 0) // 先頭に追加 +deque.insert(1, at: 0) + +/* 要素にアクセス */ +let peekFirst = deque.first! // 先頭要素 +let peekLast = deque.last! // 末尾要素 + +/* 要素をデキュー */ +// Array で代用する場合、popFirst の計算量は O(n) +let popFirst = deque.removeFirst() // 先頭要素を取り出す +let popLast = deque.removeLast() // 末尾要素を取り出す + +/* 両端キューの長さを取得 */ +let size = deque.count + +/* 両端キューが空かどうかを判定 */ +let isEmpty = deque.isEmpty +``` + +```javascript title="deque.js" +/* 両端キューを初期化 */ +// JavaScript には組み込みの両端キューがないため、Array で代用する必要がある +const deque = []; + +/* 要素をエンキュー */ +deque.push(2); +deque.push(5); +deque.push(4); +// 配列なので unshift() の時間計算量は O(n) であることに注意 +deque.unshift(3); +deque.unshift(1); + +/* 要素にアクセス */ +const peekFirst = deque[0]; +const peekLast = deque[deque.length - 1]; + +/* 要素をデキュー */ +// 配列なので shift() の時間計算量は O(n) であることに注意 +const popFront = deque.shift(); +const popBack = deque.pop(); + +/* 両端キューの長さを取得 */ +const size = deque.length; + +/* 両端キューが空かどうかを判定 */ +const isEmpty = size === 0; +``` + +```typescript title="deque.ts" +/* 両端キューを初期化 */ +// TypeScript には組み込みの両端キューがないため、Array で代用する必要がある +const deque: number[] = []; + +/* 要素をエンキュー */ +deque.push(2); +deque.push(5); +deque.push(4); +// 配列なので unshift() の時間計算量は O(n) であることに注意 +deque.unshift(3); +deque.unshift(1); + +/* 要素にアクセス */ +const peekFirst: number = deque[0]; +const peekLast: number = deque[deque.length - 1]; + +/* 要素をデキュー */ +// 配列なので shift() の時間計算量は O(n) であることに注意 +const popFront: number = deque.shift() as number; +const popBack: number = deque.pop() as number; + +/* 両端キューの長さを取得 */ +const size: number = deque.length; + +/* 両端キューが空かどうかを判定 */ +const isEmpty: boolean = size === 0; +``` + +```dart title="deque.dart" +/* 両端キューを初期化 */ +// Dart では Queue は両端キューとして定義されている +Queue deque = Queue(); + +/* 要素をエンキュー */ +deque.addLast(2); // 末尾に追加 +deque.addLast(5); +deque.addLast(4); +deque.addFirst(3); // 先頭に追加 +deque.addFirst(1); + +/* 要素にアクセス */ +int peekFirst = deque.first; // 先頭要素 +int peekLast = deque.last; // 末尾要素 + +/* 要素をデキュー */ +int popFirst = deque.removeFirst(); // 先頭要素を取り出す +int popLast = deque.removeLast(); // 末尾要素を取り出す + +/* 両端キューの長さを取得 */ +int size = deque.length; + +/* 両端キューが空かどうかを判定 */ +bool isEmpty = deque.isEmpty; +``` + +```rust title="deque.rs" +/* 両端キューを初期化 */ +let mut deque: VecDeque = VecDeque::new(); + +/* 要素をエンキュー */ +deque.push_back(2); // 末尾に追加 +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // 先頭に追加 +deque.push_front(1); + +/* 要素にアクセス */ +if let Some(front) = deque.front() { // 先頭要素 +} +if let Some(rear) = deque.back() { // 末尾要素 +} + +/* 要素をデキュー */ +if let Some(pop_front) = deque.pop_front() { // 先頭要素を取り出す +} +if let Some(pop_rear) = deque.pop_back() { // 末尾要素を取り出す +} + +/* 両端キューの長さを取得 */ +let size = deque.len(); + +/* 両端キューが空かどうかを判定 */ +let is_empty = deque.is_empty(); +``` + +```c title="deque.c" +// C には組み込みの両端キューがない +``` + +```kotlin title="deque.kt" +/* 両端キューを初期化 */ +val deque = LinkedList() + +/* 要素をエンキュー */ +deque.offerLast(2) // 末尾に追加 +deque.offerLast(5) +deque.offerLast(4) +deque.offerFirst(3) // 先頭に追加 +deque.offerFirst(1) + +/* 要素にアクセス */ +val peekFirst = deque.peekFirst() // 先頭要素 +val peekLast = deque.peekLast() // 末尾要素 + +/* 要素をデキュー */ +val popFirst = deque.pollFirst() // 先頭要素を取り出す +val popLast = deque.pollLast() // 末尾要素を取り出す + +/* 両端キューの長さを取得 */ +val size = deque.size + +/* 両端キューが空かどうかを判定 */ +val isEmpty = deque.isEmpty() +``` + +```ruby title="deque.rb" +# 両端キューを初期化 +# Ruby には組み込みの両端キューがないため、Array で代用する必要がある +deque = [] + +# 要素をエンキュー +deque << 2 +deque << 5 +deque << 4 +# 配列なので Array#unshift の時間計算量は O(n) であることに注意 +deque.unshift(3) +deque.unshift(1) + +# 要素にアクセス +peek_first = deque.first +peek_last = deque.last + +# 要素をデキュー +# 配列なので Array#shift の時間計算量は O(n) であることに注意 +pop_front = deque.shift +pop_back = deque.pop + +# 両端キューの長さを取得 +size = deque.length + +# 両端キューが空かどうかを判定 +is_empty = size.zero? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20deq%20%3D%20deque()%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%82%A8%E3%83%B3%E3%82%AD%E3%83%A5%E3%83%BC%0A%20%20%20%20deq.append(2)%20%20%23%20%E6%9C%AB%E5%B0%BE%E3%81%AB%E8%BF%BD%E5%8A%A0%0A%20%20%20%20deq.append(5)%0A%20%20%20%20deq.append(4)%0A%20%20%20%20deq.appendleft(3)%20%20%23%20%E5%85%88%E9%A0%AD%E3%81%AB%E8%BF%BD%E5%8A%A0%0A%20%20%20%20deq.appendleft(1)%0A%20%20%20%20print(%22%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%20deque%20%3D%22%2C%20deq)%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%0A%20%20%20%20print(%22%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%20front%20%3D%22%2C%20front)%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%E6%9C%AB%E5%B0%BE%E8%A6%81%E7%B4%A0%0A%20%20%20%20print(%22%E6%9C%AB%E5%B0%BE%E8%A6%81%E7%B4%A0%20rear%20%3D%22%2C%20rear)%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%87%E3%82%AD%E3%83%A5%E3%83%BC%0A%20%20%20%20pop_front%20%3D%20deq.popleft()%20%20%23%20%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%99%0A%20%20%20%20print(%22%E5%85%88%E9%A0%AD%E3%81%8B%E3%82%89%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%20%20pop_front%20%3D%22%2C%20pop_front)%0A%20%20%20%20print(%22%E5%85%88%E9%A0%AD%E3%81%8B%E3%82%89%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E5%BE%8C%E3%81%AE%20deque%20%3D%22%2C%20deq)%0A%20%20%20%20pop_rear%20%3D%20deq.pop()%20%20%23%20%E6%9C%AB%E5%B0%BE%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%99%0A%20%20%20%20print(%22%E6%9C%AB%E5%B0%BE%E3%81%8B%E3%82%89%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%20%20pop_rear%20%3D%22%2C%20pop_rear)%0A%20%20%20%20print(%22%E6%9C%AB%E5%B0%BE%E3%81%8B%E3%82%89%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E5%BE%8C%E3%81%AE%20deque%20%3D%22%2C%20deq)%0A%0A%20%20%20%20%23%20%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AE%E9%95%B7%E3%81%95%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(deq)%0A%20%20%20%20print(%22%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AE%E9%95%B7%E3%81%95%20size%20%3D%22%2C%20size)%0A%0A%20%20%20%20%23%20%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%8C%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20len(deq)%20%3D%3D%200%0A%20%20%20%20print(%22%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AF%E7%A9%BA%E3%81%8B%20%3D%22%2C%20is_empty)&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_stack_and_queue/queue.md b/ja/codes/snippets/chapter_stack_and_queue/queue.md new file mode 100644 index 000000000..99eec9684 --- /dev/null +++ b/ja/codes/snippets/chapter_stack_and_queue/queue.md @@ -0,0 +1,313 @@ + +```python title="queue.py" +from collections import deque + +# キューを初期化 +# Python では通常、両端キュークラス deque をキューとして使う +# queue.Queue() は本来のキュークラスだが、使いにくいため推奨しない +que: deque[int] = deque() + +# 要素をエンキュー +que.append(1) +que.append(3) +que.append(2) +que.append(5) +que.append(4) + +# 先頭要素にアクセス +front: int = que[0] + +# 要素をデキュー +pop: int = que.popleft() + +# キューの長さを取得 +size: int = len(que) + +# キューが空かどうかを判定 +is_empty: bool = len(que) == 0 +``` + +```cpp title="queue.cpp" +/* キューを初期化 */ +queue queue; + +/* 要素をエンキュー */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 先頭要素にアクセス */ +int front = queue.front(); + +/* 要素をデキュー */ +queue.pop(); + +/* キューの長さを取得 */ +int size = queue.size(); + +/* キューが空かどうかを判定 */ +bool empty = queue.empty(); +``` + +```java title="queue.java" +/* キューを初期化 */ +Queue queue = new LinkedList<>(); + +/* 要素をエンキュー */ +queue.offer(1); +queue.offer(3); +queue.offer(2); +queue.offer(5); +queue.offer(4); + +/* 先頭要素にアクセス */ +int peek = queue.peek(); + +/* 要素をデキュー */ +int pop = queue.poll(); + +/* キューの長さを取得 */ +int size = queue.size(); + +/* キューが空かどうかを判定 */ +boolean isEmpty = queue.isEmpty(); +``` + +```csharp title="queue.cs" +/* キューを初期化 */ +Queue queue = new(); + +/* 要素をエンキュー */ +queue.Enqueue(1); +queue.Enqueue(3); +queue.Enqueue(2); +queue.Enqueue(5); +queue.Enqueue(4); + +/* 先頭要素にアクセス */ +int peek = queue.Peek(); + +/* 要素をデキュー */ +int pop = queue.Dequeue(); + +/* キューの長さを取得 */ +int size = queue.Count; + +/* キューが空かどうかを判定 */ +bool isEmpty = queue.Count == 0; +``` + +```go title="queue_test.go" +/* キューを初期化 */ +// Go では list をキューとして使う +queue := list.New() + +/* 要素をエンキュー */ +queue.PushBack(1) +queue.PushBack(3) +queue.PushBack(2) +queue.PushBack(5) +queue.PushBack(4) + +/* 先頭要素にアクセス */ +peek := queue.Front() + +/* 要素をデキュー */ +pop := queue.Front() +queue.Remove(pop) + +/* キューの長さを取得 */ +size := queue.Len() + +/* キューが空かどうかを判定 */ +isEmpty := queue.Len() == 0 +``` + +```swift title="queue.swift" +/* キューを初期化 */ +// Swift には組み込みのキュークラスがないため、Array をキューとして使える +var queue: [Int] = [] + +/* 要素をエンキュー */ +queue.append(1) +queue.append(3) +queue.append(2) +queue.append(5) +queue.append(4) + +/* 先頭要素にアクセス */ +let peek = queue.first! + +/* 要素をデキュー */ +// 配列なので removeFirst の計算量は O(n) +let pop = queue.removeFirst() + +/* キューの長さを取得 */ +let size = queue.count + +/* キューが空かどうかを判定 */ +let isEmpty = queue.isEmpty +``` + +```javascript title="queue.js" +/* キューを初期化 */ +// JavaScript には組み込みのキューがないため、Array をキューとして使える +const queue = []; + +/* 要素をエンキュー */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 先頭要素にアクセス */ +const peek = queue[0]; + +/* 要素をデキュー */ +// 内部が配列なので shift() の時間計算量は O(n) +const pop = queue.shift(); + +/* キューの長さを取得 */ +const size = queue.length; + +/* キューが空かどうかを判定 */ +const empty = queue.length === 0; +``` + +```typescript title="queue.ts" +/* キューを初期化 */ +// TypeScript には組み込みのキューがないため、Array をキューとして使える +const queue: number[] = []; + +/* 要素をエンキュー */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 先頭要素にアクセス */ +const peek = queue[0]; + +/* 要素をデキュー */ +// 内部が配列なので shift() の時間計算量は O(n) +const pop = queue.shift(); + +/* キューの長さを取得 */ +const size = queue.length; + +/* キューが空かどうかを判定 */ +const empty = queue.length === 0; +``` + +```dart title="queue.dart" +/* キューを初期化 */ +// Dart の Queue は両端キューであり、通常のキューとしても使える +Queue queue = Queue(); + +/* 要素をエンキュー */ +queue.add(1); +queue.add(3); +queue.add(2); +queue.add(5); +queue.add(4); + +/* 先頭要素にアクセス */ +int peek = queue.first; + +/* 要素をデキュー */ +int pop = queue.removeFirst(); + +/* キューの長さを取得 */ +int size = queue.length; + +/* キューが空かどうかを判定 */ +bool isEmpty = queue.isEmpty; +``` + +```rust title="queue.rs" +/* 両端キューを初期化 */ +// Rust では両端キューを通常のキューとして使う +let mut deque: VecDeque = VecDeque::new(); + +/* 要素をエンキュー */ +deque.push_back(1); +deque.push_back(3); +deque.push_back(2); +deque.push_back(5); +deque.push_back(4); + +/* 先頭要素にアクセス */ +if let Some(front) = deque.front() { +} + +/* 要素をデキュー */ +if let Some(pop) = deque.pop_front() { +} + +/* キューの長さを取得 */ +let size = deque.len(); + +/* キューが空かどうかを判定 */ +let is_empty = deque.is_empty(); +``` + +```c title="queue.c" +// C には組み込みのキューがない +``` + +```kotlin title="queue.kt" +/* キューを初期化 */ +val queue = LinkedList() + +/* 要素をエンキュー */ +queue.offer(1) +queue.offer(3) +queue.offer(2) +queue.offer(5) +queue.offer(4) + +/* 先頭要素にアクセス */ +val peek = queue.peek() + +/* 要素をデキュー */ +val pop = queue.poll() + +/* キューの長さを取得 */ +val size = queue.size + +/* キューが空かどうかを判定 */ +val isEmpty = queue.isEmpty() +``` + +```ruby title="queue.rb" +# キューを初期化 +# Ruby の組み込みキュー(Thread::Queue)には peek や走査のメソッドがないため、Array をキューとして使える +queue = [] + +# 要素をエンキュー +queue.push(1) +queue.push(3) +queue.push(2) +queue.push(5) +queue.push(4) + +# キューの要素にアクセス +peek = queue.first + +# 要素をデキュー +# 配列なので Array#shift の時間計算量は O(n) であることに注意 +pop = queue.shift + +# キューの長さを取得 +size = queue.length + +# キューが空かどうかを判定 +is_empty = queue.empty? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%82%AD%E3%83%A5%E3%83%BC%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20Python%20%E3%81%A7%E3%81%AF%E9%80%9A%E5%B8%B8%E3%80%81%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%82%AF%E3%83%A9%E3%82%B9%20deque%20%E3%82%92%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%A8%E3%81%97%E3%81%A6%E4%BD%BF%E3%81%86%0A%20%20%20%20%23%20queue.Queue()%20%E3%81%AF%E6%9C%AC%E6%9D%A5%E3%81%AE%E3%82%AD%E3%83%A5%E3%83%BC%E3%82%AF%E3%83%A9%E3%82%B9%E3%81%A0%E3%81%8C%E3%80%81%E4%BD%BF%E3%81%84%E3%81%AB%E3%81%8F%E3%81%84%0A%20%20%20%20que%20%3D%20deque()%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%82%A8%E3%83%B3%E3%82%AD%E3%83%A5%E3%83%BC%0A%20%20%20%20que.append(1)%0A%20%20%20%20que.append(3)%0A%20%20%20%20que.append(2)%0A%20%20%20%20que.append(5)%0A%20%20%20%20que.append(4)%0A%20%20%20%20print(%22%E3%82%AD%E3%83%A5%E3%83%BC%20que%20%3D%22%2C%20que)%0A%0A%20%20%20%20%23%20%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print(%22%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%20front%20%3D%22%2C%20front)%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%87%E3%82%AD%E3%83%A5%E3%83%BC%0A%20%20%20%20pop%20%3D%20que.popleft()%0A%20%20%20%20print(%22%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%20pop%20%3D%22%2C%20pop)%0A%20%20%20%20print(%22%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E5%BE%8C%E3%81%AE%20que%20%3D%22%2C%20que)%0A%0A%20%20%20%20%23%20%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AE%E9%95%B7%E3%81%95%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(que)%0A%20%20%20%20print(%22%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AE%E9%95%B7%E3%81%95%20size%20%3D%22%2C%20size)%0A%0A%20%20%20%20%23%20%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%8C%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20len(que)%20%3D%3D%200%0A%20%20%20%20print(%22%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AF%E7%A9%BA%E3%81%8B%20%3D%22%2C%20is_empty)&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_stack_and_queue/stack.md b/ja/codes/snippets/chapter_stack_and_queue/stack.md new file mode 100644 index 000000000..55e0080cd --- /dev/null +++ b/ja/codes/snippets/chapter_stack_and_queue/stack.md @@ -0,0 +1,304 @@ + +```python title="stack.py" +# スタックを初期化 +# Python には組み込みのスタッククラスがないため、list をスタックとして使える +stack: list[int] = [] + +# 要素をプッシュ +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +# スタックの先頭要素にアクセス +peek: int = stack[-1] + +# 要素をポップ +pop: int = stack.pop() + +# スタックの長さを取得 +size: int = len(stack) + +# 空かどうかを判定 +is_empty: bool = len(stack) == 0 +``` + +```cpp title="stack.cpp" +/* スタックを初期化 */ +stack stack; + +/* 要素をプッシュ */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* スタックの先頭要素にアクセス */ +int top = stack.top(); + +/* 要素をポップ */ +stack.pop(); // 戻り値なし + +/* スタックの長さを取得 */ +int size = stack.size(); + +/* 空かどうかを判定 */ +bool empty = stack.empty(); +``` + +```java title="stack.java" +/* スタックを初期化 */ +Stack stack = new Stack<>(); + +/* 要素をプッシュ */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* スタックの先頭要素にアクセス */ +int peek = stack.peek(); + +/* 要素をポップ */ +int pop = stack.pop(); + +/* スタックの長さを取得 */ +int size = stack.size(); + +/* 空かどうかを判定 */ +boolean isEmpty = stack.isEmpty(); +``` + +```csharp title="stack.cs" +/* スタックを初期化 */ +Stack stack = new(); + +/* 要素をプッシュ */ +stack.Push(1); +stack.Push(3); +stack.Push(2); +stack.Push(5); +stack.Push(4); + +/* スタックの先頭要素にアクセス */ +int peek = stack.Peek(); + +/* 要素をポップ */ +int pop = stack.Pop(); + +/* スタックの長さを取得 */ +int size = stack.Count; + +/* 空かどうかを判定 */ +bool isEmpty = stack.Count == 0; +``` + +```go title="stack_test.go" +/* スタックを初期化 */ +// Go では Slice をスタックとして使うことを推奨 +var stack []int + +/* 要素をプッシュ */ +stack = append(stack, 1) +stack = append(stack, 3) +stack = append(stack, 2) +stack = append(stack, 5) +stack = append(stack, 4) + +/* スタックの先頭要素にアクセス */ +peek := stack[len(stack)-1] + +/* 要素をポップ */ +pop := stack[len(stack)-1] +stack = stack[:len(stack)-1] + +/* スタックの長さを取得 */ +size := len(stack) + +/* 空かどうかを判定 */ +isEmpty := len(stack) == 0 +``` + +```swift title="stack.swift" +/* スタックを初期化 */ +// Swift には組み込みのスタッククラスがないため、Array をスタックとして使える +var stack: [Int] = [] + +/* 要素をプッシュ */ +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +/* スタックの先頭要素にアクセス */ +let peek = stack.last! + +/* 要素をポップ */ +let pop = stack.removeLast() + +/* スタックの長さを取得 */ +let size = stack.count + +/* 空かどうかを判定 */ +let isEmpty = stack.isEmpty +``` + +```javascript title="stack.js" +/* スタックを初期化 */ +// JavaScript には組み込みのスタッククラスがないため、Array をスタックとして使える +const stack = []; + +/* 要素をプッシュ */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* スタックの先頭要素にアクセス */ +const peek = stack[stack.length-1]; + +/* 要素をポップ */ +const pop = stack.pop(); + +/* スタックの長さを取得 */ +const size = stack.length; + +/* 空かどうかを判定 */ +const is_empty = stack.length === 0; +``` + +```typescript title="stack.ts" +/* スタックを初期化 */ +// TypeScript には組み込みのスタッククラスがないため、Array をスタックとして使える +const stack: number[] = []; + +/* 要素をプッシュ */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* スタックの先頭要素にアクセス */ +const peek = stack[stack.length - 1]; + +/* 要素をポップ */ +const pop = stack.pop(); + +/* スタックの長さを取得 */ +const size = stack.length; + +/* 空かどうかを判定 */ +const is_empty = stack.length === 0; +``` + +```dart title="stack.dart" +/* スタックを初期化 */ +// Dart には組み込みのスタッククラスがないため、List をスタックとして使える +List stack = []; + +/* 要素をプッシュ */ +stack.add(1); +stack.add(3); +stack.add(2); +stack.add(5); +stack.add(4); + +/* スタックの先頭要素にアクセス */ +int peek = stack.last; + +/* 要素をポップ */ +int pop = stack.removeLast(); + +/* スタックの長さを取得 */ +int size = stack.length; + +/* 空かどうかを判定 */ +bool isEmpty = stack.isEmpty; +``` + +```rust title="stack.rs" +/* スタックを初期化 */ +// Vec をスタックとして使う +let mut stack: Vec = Vec::new(); + +/* 要素をプッシュ */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* スタックの先頭要素にアクセス */ +let top = stack.last().unwrap(); + +/* 要素をポップ */ +let pop = stack.pop().unwrap(); + +/* スタックの長さを取得 */ +let size = stack.len(); + +/* 空かどうかを判定 */ +let is_empty = stack.is_empty(); +``` + +```c title="stack.c" +// C には組み込みのスタックがない +``` + +```kotlin title="stack.kt" +/* スタックを初期化 */ +val stack = Stack() + +/* 要素をプッシュ */ +stack.push(1) +stack.push(3) +stack.push(2) +stack.push(5) +stack.push(4) + +/* スタックの先頭要素にアクセス */ +val peek = stack.peek() + +/* 要素をポップ */ +val pop = stack.pop() + +/* スタックの長さを取得 */ +val size = stack.size + +/* 空かどうかを判定 */ +val isEmpty = stack.isEmpty() +``` + +```ruby title="stack.rb" +# スタックを初期化 +# Ruby には組み込みのスタッククラスがないため、Array をスタックとして使える +stack = [] + +# 要素をプッシュ +stack << 1 +stack << 3 +stack << 2 +stack << 5 +stack << 4 + +# スタックの先頭要素にアクセス +peek = stack.last + +# 要素をポップ +pop = stack.pop + +# スタックの長さを取得 +size = stack.length + +# 空かどうかを判定 +is_empty = stack.empty? +``` + + +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20Python%20%E3%81%AB%E3%81%AF%E7%B5%84%E3%81%BF%E8%BE%BC%E3%81%BF%E3%81%AE%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%82%AF%E3%83%A9%E3%82%B9%E3%81%8C%E3%81%AA%E3%81%84%E3%81%9F%E3%82%81%E3%80%81list%20%E3%82%92%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%A8%E3%81%97%E3%81%A6%E4%BD%BF%E3%81%88%E3%82%8B%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%97%E3%83%83%E3%82%B7%E3%83%A5%0A%20%20%20%20stack.append(1)%0A%20%20%20%20stack.append(3)%0A%20%20%20%20stack.append(2)%0A%20%20%20%20stack.append(5)%0A%20%20%20%20stack.append(4)%0A%20%20%20%20print(%22%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%20stack%20%3D%22%2C%20stack)%0A%0A%20%20%20%20%23%20%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print(%22%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%20peek%20%3D%22%2C%20peek)%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%9D%E3%83%83%E3%83%97%0A%20%20%20%20pop%20%3D%20stack.pop()%0A%20%20%20%20print(%22%E3%83%9D%E3%83%83%E3%83%97%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%20pop%20%3D%22%2C%20pop)%0A%20%20%20%20print(%22%E3%83%9D%E3%83%83%E3%83%97%E3%81%97%E3%81%9F%E5%BE%8C%E3%81%AE%20stack%20%3D%22%2C%20stack)%0A%0A%20%20%20%20%23%20%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AE%E9%95%B7%E3%81%95%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(stack)%0A%20%20%20%20print(%22%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AE%E9%95%B7%E3%81%95%20size%20%3D%22%2C%20size)%0A%0A%20%20%20%20%23%20%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20len(stack)%20%3D%3D%200%0A%20%20%20%20print(%22%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AF%E7%A9%BA%E3%81%8B%20%3D%22%2C%20is_empty)&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_tree/array_representation_of_tree.md b/ja/codes/snippets/chapter_tree/array_representation_of_tree.md new file mode 100644 index 000000000..b1048ccb9 --- /dev/null +++ b/ja/codes/snippets/chapter_tree/array_representation_of_tree.md @@ -0,0 +1,78 @@ + +```python title="" +# 二分木の配列表現 +# None で空の位置を表す +tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] +``` + +```cpp title="" +/* 二分木の配列表現 */ +// int の最大値 INT_MAX で空の位置を示す +vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```java title="" +/* 二分木の配列表現 */ +// int のラッパークラス Integer を使うと、null で空の位置を示せる +Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; +``` + +```csharp title="" +/* 二分木の配列表現 */ +// null 許容型 int? を使うと、null で空の位置を示せる +int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```go title="" +/* 二分木の配列表現 */ +// any 型のスライスを使うと、nil で空の位置を示せる +tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} +``` + +```swift title="" +/* 二分木の配列表現 */ +// オプショナル型 Int? を使うと、nil で空の位置を示せる +let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` + +```javascript title="" +/* 二分木の配列表現 */ +// null で空の位置を表す +let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```typescript title="" +/* 二分木の配列表現 */ +// null で空の位置を表す +let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```dart title="" +/* 二分木の配列表現 */ +// null 許容型 int? を使うと、null で空の位置を示せる +List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```rust title="" +/* 二分木の配列表現 */ +// None で空の位置を示す +let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; +``` + +```c title="" +/* 二分木の配列表現 */ +// int の最大値で空の位置を示すため、ノードの値に INT_MAX は使えない +int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```kotlin title="" +/* 二分木の配列表現 */ +// null で空の位置を表す +val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) +``` + +```ruby title="" +### 二分木の配列表現 ### +# nil で空の位置を表す +tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` diff --git a/ja/codes/snippets/chapter_tree/avl_tree.md b/ja/codes/snippets/chapter_tree/avl_tree.md new file mode 100644 index 000000000..f46ceefcf --- /dev/null +++ b/ja/codes/snippets/chapter_tree/avl_tree.md @@ -0,0 +1,182 @@ + +```python title="" +class TreeNode: + """AVL 木のノードクラス""" + def __init__(self, val: int): + self.val: int = val # ノードの値 + self.height: int = 0 # ノードの高さ + self.left: TreeNode | None = None # 左の子への参照 + self.right: TreeNode | None = None # 右の子への参照 +``` + +```cpp title="" +/* AVL 木のノードクラス */ +struct TreeNode { + int val{}; // ノードの値 + int height = 0; // ノードの高さ + TreeNode *left{}; // 左の子 + TreeNode *right{}; // 右の子 + TreeNode() = default; + explicit TreeNode(int x) : val(x){} +}; +``` + +```java title="" +/* AVL 木のノードクラス */ +class TreeNode { + public int val; // ノードの値 + public int height; // ノードの高さ + public TreeNode left; // 左の子 + public TreeNode right; // 右の子 + public TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* AVL 木のノードクラス */ +class TreeNode(int? x) { + public int? val = x; // ノードの値 + public int height; // ノードの高さ + public TreeNode? left; // 左の子への参照 + public TreeNode? right; // 右の子への参照 +} +``` + +```go title="" +/* AVL 木のノード構造体 */ +type TreeNode struct { + Val int // ノードの値 + Height int // ノードの高さ + Left *TreeNode // 左の子への参照 + Right *TreeNode // 右の子への参照 +} +``` + +```swift title="" +/* AVL 木のノードクラス */ +class TreeNode { + var val: Int // ノードの値 + var height: Int // ノードの高さ + var left: TreeNode? // 左の子 + var right: TreeNode? // 右の子 + + init(x: Int) { + val = x + height = 0 + } +} +``` + +```javascript title="" +/* AVL 木のノードクラス */ +class TreeNode { + val; // ノードの値 + height; //ノードの高さ + left; // 左の子へのポインタ + right; // 右の子へのポインタ + constructor(val, left, right, height) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* AVL 木のノードクラス */ +class TreeNode { + val: number; // ノードの値 + height: number; // ノードの高さ + left: TreeNode | null; // 左の子へのポインタ + right: TreeNode | null; // 右の子へのポインタ + constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```dart title="" +/* AVL 木のノードクラス */ +class TreeNode { + int val; // ノードの値 + int height; // ノードの高さ + TreeNode? left; // 左の子 + TreeNode? right; // 右の子 + TreeNode(this.val, [this.height = 0, this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* AVL 木のノード構造体 */ +struct TreeNode { + val: i32, // ノードの値 + height: i32, // ノードの高さ + left: Option>>, // 左の子 + right: Option>>, // 右の子 +} + +impl TreeNode { + /* コンストラクタ */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + height: 0, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* AVL 木のノード構造体 */ +typedef struct TreeNode { + int val; + int height; + struct TreeNode *left; + struct TreeNode *right; +} TreeNode; + +/* コンストラクタ */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* AVL 木のノードクラス */ +class TreeNode(val _val: Int) { // ノードの値 + var height: Int = 0 // ノードの高さ + var left: TreeNode? = null // 左の子 + var right: TreeNode? = null // 右の子 +} +``` + +```ruby title="" +### AVL 木のノードクラス ### +class TreeNode + attr_accessor :val # ノードの値 + attr_accessor :height # ノードの高さ + attr_accessor :left # 左の子への参照 + attr_accessor :right # 右の子への参照 + + def initialize(val) + @val = val + @height = 0 + end +end +``` diff --git a/ja/codes/snippets/chapter_tree/binary_tree.md b/ja/codes/snippets/chapter_tree/binary_tree.md new file mode 100644 index 000000000..ecf40ac45 --- /dev/null +++ b/ja/codes/snippets/chapter_tree/binary_tree.md @@ -0,0 +1,502 @@ + +```python title="" +class TreeNode: + """二分木のノードクラス""" + def __init__(self, val: int): + self.val: int = val # ノードの値 + self.left: TreeNode | None = None # 左の子への参照 + self.right: TreeNode | None = None # 右の子への参照 +``` + +```cpp title="" +/* 二分木のノード構造体 */ +struct TreeNode { + int val; // ノードの値 + TreeNode *left; // 左の子へのポインタ + TreeNode *right; // 右の子へのポインタ + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; +``` + +```java title="" +/* 二分木のノードクラス */ +class TreeNode { + int val; // ノードの値 + TreeNode left; // 左の子への参照 + TreeNode right; // 右の子への参照 + TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* 二分木のノードクラス */ +class TreeNode(int? x) { + public int? val = x; // ノードの値 + public TreeNode? left; // 左の子への参照 + public TreeNode? right; // 右の子への参照 +} +``` + +```go title="" +/* 二分木のノード構造体 */ +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} +/* コンストラクタ */ +func NewTreeNode(v int) *TreeNode { + return &TreeNode{ + Left: nil, // 左の子へのポインタ + Right: nil, // 右の子へのポインタ + Val: v, // ノードの値 + } +} +``` + +```swift title="" +/* 二分木のノードクラス */ +class TreeNode { + var val: Int // ノードの値 + var left: TreeNode? // 左の子への参照 + var right: TreeNode? // 右の子への参照 + + init(x: Int) { + val = x + } +} +``` + +```javascript title="" +/* 二分木のノードクラス */ +class TreeNode { + val; // ノードの値 + left; // 左の子へのポインタ + right; // 右の子へのポインタ + constructor(val, left, right) { + this.val = val === undefined ? 0 : val; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* 二分木のノードクラス */ +class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; // ノードの値 + this.left = left === undefined ? null : left; // 左の子への参照 + this.right = right === undefined ? null : right; // 右の子への参照 + } +} +``` + +```dart title="" +/* 二分木のノードクラス */ +class TreeNode { + int val; // ノードの値 + TreeNode? left; // 左の子への参照 + TreeNode? right; // 右の子への参照 + TreeNode(this.val, [this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 二分木のノード構造体 */ +struct TreeNode { + val: i32, // ノードの値 + left: Option>>, // 左の子への参照 + right: Option>>, // 右の子への参照 +} + +impl TreeNode { + /* コンストラクタ */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* 二分木のノード構造体 */ +typedef struct TreeNode { + int val; // ノードの値 + int height; // ノードの高さ + struct TreeNode *left; // 左の子へのポインタ + struct TreeNode *right; // 右の子へのポインタ +} TreeNode; + +/* コンストラクタ */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* 二分木のノードクラス */ +class TreeNode(val _val: Int) { // ノードの値 + var left: TreeNode? = null // 左の子への参照 + var right: TreeNode? = null // 右の子への参照 +} +``` + +```ruby title="" +### 二分木のノードクラス ### +class TreeNode + attr_accessor :val # ノードの値 + attr_accessor :left # 左の子への参照 + attr_accessor :right # 右の子への参照 + + def initialize(val) + @val = val + end +end +``` + + +```python title="binary_tree.py" +# 二分木を初期化 +# ノードを初期化 +n1 = TreeNode(val=1) +n2 = TreeNode(val=2) +n3 = TreeNode(val=3) +n4 = TreeNode(val=4) +n5 = TreeNode(val=5) +# ノード間の参照(ポインタ)をつなぐ +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```cpp title="binary_tree.cpp" +/* 二分木を初期化 */ +// ノードを初期化 +TreeNode* n1 = new TreeNode(1); +TreeNode* n2 = new TreeNode(2); +TreeNode* n3 = new TreeNode(3); +TreeNode* n4 = new TreeNode(4); +TreeNode* n5 = new TreeNode(5); +// ノード間の参照(ポインタ)をつなぐ +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```java title="binary_tree.java" +// ノードを初期化 +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// ノード間の参照(ポインタ)をつなぐ +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```csharp title="binary_tree.cs" +/* 二分木を初期化 */ +// ノードを初期化 +TreeNode n1 = new(1); +TreeNode n2 = new(2); +TreeNode n3 = new(3); +TreeNode n4 = new(4); +TreeNode n5 = new(5); +// ノード間の参照(ポインタ)をつなぐ +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```go title="binary_tree.go" +/* 二分木を初期化 */ +// ノードを初期化 +n1 := NewTreeNode(1) +n2 := NewTreeNode(2) +n3 := NewTreeNode(3) +n4 := NewTreeNode(4) +n5 := NewTreeNode(5) +// ノード間の参照(ポインタ)をつなぐ +n1.Left = n2 +n1.Right = n3 +n2.Left = n4 +n2.Right = n5 +``` + +```swift title="binary_tree.swift" +// ノードを初期化 +let n1 = TreeNode(x: 1) +let n2 = TreeNode(x: 2) +let n3 = TreeNode(x: 3) +let n4 = TreeNode(x: 4) +let n5 = TreeNode(x: 5) +// ノード間の参照(ポインタ)をつなぐ +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```javascript title="binary_tree.js" +/* 二分木を初期化 */ +// ノードを初期化 +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// ノード間の参照(ポインタ)をつなぐ +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```typescript title="binary_tree.ts" +/* 二分木を初期化 */ +// ノードを初期化 +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// ノード間の参照(ポインタ)をつなぐ +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```dart title="binary_tree.dart" +/* 二分木を初期化 */ +// ノードを初期化 +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// ノード間の参照(ポインタ)をつなぐ +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```rust title="binary_tree.rs" +// ノードを初期化 +let n1 = TreeNode::new(1); +let n2 = TreeNode::new(2); +let n3 = TreeNode::new(3); +let n4 = TreeNode::new(4); +let n5 = TreeNode::new(5); +// ノード間の参照(ポインタ)をつなぐ +n1.borrow_mut().left = Some(n2.clone()); +n1.borrow_mut().right = Some(n3); +n2.borrow_mut().left = Some(n4); +n2.borrow_mut().right = Some(n5); +``` + +```c title="binary_tree.c" +/* 二分木を初期化 */ +// ノードを初期化 +TreeNode *n1 = newTreeNode(1); +TreeNode *n2 = newTreeNode(2); +TreeNode *n3 = newTreeNode(3); +TreeNode *n4 = newTreeNode(4); +TreeNode *n5 = newTreeNode(5); +// ノード間の参照(ポインタ)をつなぐ +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```kotlin title="binary_tree.kt" +// ノードを初期化 +val n1 = TreeNode(1) +val n2 = TreeNode(2) +val n3 = TreeNode(3) +val n4 = TreeNode(4) +val n5 = TreeNode(5) +// ノード間の参照(ポインタ)をつなぐ +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```ruby title="binary_tree.rb" +# 二分木を初期化 +# ノードを初期化 +n1 = TreeNode.new(1) +n2 = TreeNode.new(2) +n3 = TreeNode.new(3) +n4 = TreeNode.new(4) +n5 = TreeNode.new(5) +# ノード間の参照(ポインタ)をつなぐ +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9C%A8%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9C%A8%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20n1%20%3D%20TreeNode(val%3D1)%0A%20%20%20%20n2%20%3D%20TreeNode(val%3D2)%0A%20%20%20%20n3%20%3D%20TreeNode(val%3D3)%0A%20%20%20%20n4%20%3D%20TreeNode(val%3D4)%0A%20%20%20%20n5%20%3D%20TreeNode(val%3D5)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E9%96%93%E3%81%AE%E5%8F%82%E7%85%A7%EF%BC%88%E3%83%9D%E3%82%A4%E3%83%B3%E3%82%BF%EF%BC%89%E3%82%92%E3%81%A4%E3%81%AA%E3%81%90%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="binary_tree.py" +# ノードの挿入と削除 +p = TreeNode(0) +# n1 -> n2 の間にノード P を挿入 +n1.left = p +p.left = n2 +# ノード P を削除 +n1.left = n2 +``` + +```cpp title="binary_tree.cpp" +/* ノードの挿入と削除 */ +TreeNode* P = new TreeNode(0); +// n1 -> n2 の間にノード P を挿入 +n1->left = P; +P->left = n2; +// ノード P を削除 +n1->left = n2; +// メモリを解放 +delete P; +``` + +```java title="binary_tree.java" +TreeNode P = new TreeNode(0); +// n1 -> n2 の間にノード P を挿入 +n1.left = P; +P.left = n2; +// ノード P を削除 +n1.left = n2; +``` + +```csharp title="binary_tree.cs" +/* ノードの挿入と削除 */ +TreeNode P = new(0); +// n1 -> n2 の間にノード P を挿入 +n1.left = P; +P.left = n2; +// ノード P を削除 +n1.left = n2; +``` + +```go title="binary_tree.go" +/* ノードの挿入と削除 */ +// n1 -> n2 の間にノード P を挿入 +p := NewTreeNode(0) +n1.Left = p +p.Left = n2 +// ノード P を削除 +n1.Left = n2 +``` + +```swift title="binary_tree.swift" +let P = TreeNode(x: 0) +// n1 -> n2 の間にノード P を挿入 +n1.left = P +P.left = n2 +// ノード P を削除 +n1.left = n2 +``` + +```javascript title="binary_tree.js" +/* ノードの挿入と削除 */ +let P = new TreeNode(0); +// n1 -> n2 の間にノード P を挿入 +n1.left = P; +P.left = n2; +// ノード P を削除 +n1.left = n2; +``` + +```typescript title="binary_tree.ts" +/* ノードの挿入と削除 */ +const P = new TreeNode(0); +// n1 -> n2 の間にノード P を挿入 +n1.left = P; +P.left = n2; +// ノード P を削除 +n1.left = n2; +``` + +```dart title="binary_tree.dart" +/* ノードの挿入と削除 */ +TreeNode P = new TreeNode(0); +// n1 -> n2 の間にノード P を挿入 +n1.left = P; +P.left = n2; +// ノード P を削除 +n1.left = n2; +``` + +```rust title="binary_tree.rs" +let p = TreeNode::new(0); +// n1 -> n2 の間にノード P を挿入 +n1.borrow_mut().left = Some(p.clone()); +p.borrow_mut().left = Some(n2.clone()); +// ノード p を削除 +n1.borrow_mut().left = Some(n2); +``` + +```c title="binary_tree.c" +/* ノードの挿入と削除 */ +TreeNode *P = newTreeNode(0); +// n1 -> n2 の間にノード P を挿入 +n1->left = P; +P->left = n2; +// ノード P を削除 +n1->left = n2; +// メモリを解放 +free(P); +``` + +```kotlin title="binary_tree.kt" +val P = TreeNode(0) +// n1 -> n2 の間にノード P を挿入 +n1.left = P +P.left = n2 +// ノード P を削除 +n1.left = n2 +``` + +```ruby title="binary_tree.rb" +# ノードの挿入と削除 +_p = TreeNode.new(0) +# n1 -> n2 の間にノード _p を挿入 +n1.left = _p +_p.left = n2 +# ノードを削除 +n1.left = n2 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9C%A8%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9C%A8%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20n1%20%3D%20TreeNode(val%3D1)%0A%20%20%20%20n2%20%3D%20TreeNode(val%3D2)%0A%20%20%20%20n3%20%3D%20TreeNode(val%3D3)%0A%20%20%20%20n4%20%3D%20TreeNode(val%3D4)%0A%20%20%20%20n5%20%3D%20TreeNode(val%3D5)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E9%96%93%E3%81%AE%E5%8F%82%E7%85%A7%EF%BC%88%E3%83%9D%E3%82%A4%E3%83%B3%E3%82%BF%EF%BC%89%E3%82%92%E3%81%A4%E3%81%AA%E3%81%90%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E6%8C%BF%E5%85%A5%E3%81%A8%E5%89%8A%E9%99%A4%0A%20%20%20%20p%20%3D%20TreeNode(0)%0A%20%20%20%20%23%20n1%20-%3E%20n2%20%E3%81%AE%E9%96%93%E3%81%AB%E3%83%8E%E3%83%BC%E3%83%89%20P%20%E3%82%92%E6%8C%BF%E5%85%A5%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%20P%20%E3%82%92%E5%89%8A%E9%99%A4%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/docs/chapter_array_and_linkedlist/array.md b/ja/docs/chapter_array_and_linkedlist/array.md index c67ab2197..384ce8295 100644 --- a/ja/docs/chapter_array_and_linkedlist/array.md +++ b/ja/docs/chapter_array_and_linkedlist/array.md @@ -10,125 +10,13 @@ 配列の初期化には、初期値を指定しない方法と、初期値を指定する方法があり、必要に応じて選べます。初期値を指定しない場合、多くのプログラミング言語では要素が $0$ で初期化されます。 -=== "Python" - - ```python title="array.py" - # 配列を初期化 - arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="array.cpp" - /* 配列を初期化 */ - // スタック上に格納 - int arr[5] = {}; - int nums[5] = { 1, 3, 2, 5, 4 }; - // ヒープ上に格納(領域を手動で解放する必要がある) - int* arr1 = new int[5] {}; - int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="array.java" - /* 配列を初期化 */ - int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } - int[] nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "C#" - - ```csharp title="array.cs" - /* 配列を初期化 */ - int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] - int[] nums = [1, 3, 2, 5, 4]; - ``` - -=== "Go" - - ```go title="array.go" - /* 配列を初期化 */ - var arr [5]int - // Go では、長さを指定すると([5]int)配列、指定しないと([]int)スライスになる - // Go の配列はコンパイル時に長さが決まる設計のため、長さには定数しか指定できない - // 容量を拡張する extend() メソッドを実装しやすくするため、以下ではスライス(Slice)を配列(Array)として扱う - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="array.swift" - /* 配列を初期化 */ - let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] - let nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="array.js" - /* 配列を初期化 */ - var arr = new Array(5).fill(0); - var nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="array.ts" - /* 配列を初期化 */ - let arr: number[] = new Array(5).fill(0); - let nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="array.dart" - /* 配列を初期化 */ - List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="array.rs" - /* 配列を初期化 */ - let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] - let slice: &[i32] = &[0; 5]; - // Rust では、長さを指定すると([i32; 5])配列、指定しないと(&[i32])スライスになる - // Rust の配列はコンパイル時に長さが決まる設計のため、長さには定数しか指定できない - // Vector は、Rust で通常、動的配列として使う型 - // 容量を拡張する extend() メソッドを実装しやすくするため、以下では vector を配列(array)として扱う - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="array.c" - /* 配列を初期化 */ - int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } - int nums[5] = { 1, 3, 2, 5, 4 }; - ``` - -=== "Kotlin" - - ```kotlin title="array.kt" - /* 配列を初期化 */ - var arr = IntArray(5) // { 0, 0, 0, 0, 0 } - var nums = intArrayOf(1, 3, 2, 5, 4) - ``` - -=== "Ruby" - - ```ruby title="array.rb" - # 配列を初期化 - arr = Array.new(5, 0) - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_array +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%23%20%E9%85%8D%E5%88%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_array_tutor ### 要素へのアクセス diff --git a/ja/docs/chapter_array_and_linkedlist/linked_list.md b/ja/docs/chapter_array_and_linkedlist/linked_list.md index 466c24723..2d9ece209 100644 --- a/ja/docs/chapter_array_and_linkedlist/linked_list.md +++ b/ja/docs/chapter_array_and_linkedlist/linked_list.md @@ -16,174 +16,9 @@ 次のコードのように、連結リストのノード `ListNode` は、値に加えて参照(ポインタ)も保存する必要があります。そのため、同じデータ量なら、**連結リストは配列より多くのメモリを使います**。 -=== "Python" - - ```python title="" - class ListNode: - """連結リストのノードクラス""" - def __init__(self, val: int): - self.val: int = val # ノードの値 - self.next: ListNode | None = None # 次のノードへの参照 - ``` - -=== "C++" - - ```cpp title="" - /* 連結リストのノード構造体 */ - struct ListNode { - int val; // ノードの値 - ListNode *next; // 次のノードへのポインタ - ListNode(int x) : val(x), next(nullptr) {} // コンストラクタ - }; - ``` - -=== "Java" - - ```java title="" - /* 連結リストのノードクラス */ - class ListNode { - int val; // ノードの値 - ListNode next; // 次のノードへの参照 - ListNode(int x) { val = x; } // コンストラクタ - } - ``` - -=== "C#" - - ```csharp title="" - /* 連結リストのノードクラス */ - class ListNode(int x) { //コンストラクタ - int val = x; // ノードの値 - ListNode? next; // 次のノードへの参照 - } - ``` - -=== "Go" - - ```go title="" - /* 連結リストのノード構造体 */ - type ListNode struct { - Val int // ノードの値 - Next *ListNode // 次のノードへのポインタ - } - - // NewListNode コンストラクタで、新しい連結リストを作る - func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 連結リストのノードクラス */ - class ListNode { - var val: Int // ノードの値 - var next: ListNode? // 次のノードへの参照 - - init(x: Int) { // コンストラクタ - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 連結リストのノードクラス */ - class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // ノードの値 - this.next = (next === undefined ? null : next); // 次のノードへの参照 - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 連結リストのノードクラス */ - class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.next = next === undefined ? null : next; // 次のノードへの参照 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 連結リストのノードクラス */ - class ListNode { - int val; // ノードの値 - ListNode? next; // 次のノードへの参照 - ListNode(this.val, [this.next]); // コンストラクタ - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - /* 連結リストのノードクラス */ - #[derive(Debug)] - struct ListNode { - val: i32, // ノードの値 - next: Option>>, // 次のノードへのポインタ - } - ``` - -=== "C" - - ```c title="" - /* 連結リストのノード構造体 */ - typedef struct ListNode { - int val; // ノードの値 - struct ListNode *next; // 次のノードへのポインタ - } ListNode; - - /* コンストラクタ */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 連結リストのノードクラス */ - // コンストラクタ - class ListNode(x: Int) { - val _val: Int = x // ノードの値 - var next: ListNode? = null // 次のノードへの参照 - } - ``` - -=== "Ruby" - - ```ruby title="" - # 連結リストのノードクラス - class ListNode - attr_accessor :val # ノードの値 - attr_accessor :next # 次のノードへの参照 - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end - end - ``` +```snippet +list_node_class +``` ## 連結リストの主な操作 @@ -191,231 +26,13 @@ 連結リストは二つの手順で作ります。まず各ノードオブジェクトを初期化し、次にノード間の参照関係を構築します。初期化後は、先頭ノードから `next` の参照をたどり、すべてのノードを順に訪問できます。 -=== "Python" - - ```python title="linked_list.py" - # 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 - # 各ノードを初期化 - n0 = ListNode(1) - n1 = ListNode(3) - n2 = ListNode(2) - n3 = ListNode(5) - n4 = ListNode(4) - # ノード間の参照を設定 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "C++" - - ```cpp title="linked_list.cpp" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - ListNode* n0 = new ListNode(1); - ListNode* n1 = new ListNode(3); - ListNode* n2 = new ListNode(2); - ListNode* n3 = new ListNode(5); - ListNode* n4 = new ListNode(4); - // ノード間の参照を設定 - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Java" - - ```java title="linked_list.java" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - ListNode n0 = new ListNode(1); - ListNode n1 = new ListNode(3); - ListNode n2 = new ListNode(2); - ListNode n3 = new ListNode(5); - ListNode n4 = new ListNode(4); - // ノード間の参照を設定 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "C#" - - ```csharp title="linked_list.cs" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - ListNode n0 = new(1); - ListNode n1 = new(3); - ListNode n2 = new(2); - ListNode n3 = new(5); - ListNode n4 = new(4); - // ノード間の参照を設定 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Go" - - ```go title="linked_list.go" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - n0 := NewListNode(1) - n1 := NewListNode(3) - n2 := NewListNode(2) - n3 := NewListNode(5) - n4 := NewListNode(4) - // ノード間の参照を設定 - n0.Next = n1 - n1.Next = n2 - n2.Next = n3 - n3.Next = n4 - ``` - -=== "Swift" - - ```swift title="linked_list.swift" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - let n0 = ListNode(x: 1) - let n1 = ListNode(x: 3) - let n2 = ListNode(x: 2) - let n3 = ListNode(x: 5) - let n4 = ListNode(x: 4) - // ノード間の参照を設定 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "JS" - - ```javascript title="linked_list.js" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // ノード間の参照を設定 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "TS" - - ```typescript title="linked_list.ts" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // ノード間の参照を設定 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Dart" - - ```dart title="linked_list.dart" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */\ - // 各ノードを初期化 - ListNode n0 = ListNode(1); - ListNode n1 = ListNode(3); - ListNode n2 = ListNode(2); - ListNode n3 = ListNode(5); - ListNode n4 = ListNode(4); - // ノード間の参照を設定 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Rust" - - ```rust title="linked_list.rs" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); - let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); - let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); - let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); - let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); - - // ノード間の参照を設定 - n0.borrow_mut().next = Some(n1.clone()); - n1.borrow_mut().next = Some(n2.clone()); - n2.borrow_mut().next = Some(n3.clone()); - n3.borrow_mut().next = Some(n4.clone()); - ``` - -=== "C" - - ```c title="linked_list.c" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - ListNode* n0 = newListNode(1); - ListNode* n1 = newListNode(3); - ListNode* n2 = newListNode(2); - ListNode* n3 = newListNode(5); - ListNode* n4 = newListNode(4); - // ノード間の参照を設定 - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Kotlin" - - ```kotlin title="linked_list.kt" - /* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ - // 各ノードを初期化 - val n0 = ListNode(1) - val n1 = ListNode(3) - val n2 = ListNode(2) - val n3 = ListNode(5) - val n4 = ListNode(4) - // ノード間の参照を設定 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Ruby" - - ```ruby title="linked_list.rb" - # 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 - # 各ノードを初期化 - n0 = ListNode.new(1) - n1 = ListNode.new(3) - n2 = ListNode.new(2) - n3 = ListNode.new(5) - n4 = ListNode.new(4) - # ノード間の参照を設定 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` +```snippet +init_linked_list +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E6%AC%A1%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%20%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E5%90%84%E3%83%8E%E3%83%BC%E3%83%89%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20n0%20%3D%20ListNode(1)%0A%20%20%20%20n1%20%3D%20ListNode(3)%0A%20%20%20%20n2%20%3D%20ListNode(2)%0A%20%20%20%20n3%20%3D%20ListNode(5)%0A%20%20%20%20n4%20%3D%20ListNode(4)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E9%96%93%E3%81%AE%E5%8F%82%E7%85%A7%E3%82%92%E8%A8%AD%E5%AE%9A%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_linked_list_tutor 配列は全体で一つの変数です。たとえば配列 `nums` は、`nums[0]` や `nums[1]` などの要素を含みます。一方、連結リストは複数の独立したノードオブジェクトからなります。**通常は先頭ノードで連結リスト全体を表します**。たとえば、上のコードの連結リストは、連結リスト `n0` と呼べます。 @@ -482,203 +99,9 @@ - **循環連結リスト**:単方向連結リストの末尾ノードを先頭ノードに向け、末尾と先頭をつなぐと、循環連結リストになります。循環連結リストでは、任意のノードを先頭とみなせます。 - **双方向連結リスト**:単方向連結リストと異なり、両方向の参照を記録します。ノードには、後続ノード(次のノード)と先行ノード(前のノード)の両方への参照(ポインタ)を持たせます。単方向連結リストより柔軟で、どちらの方向にも走査できますが、その分メモリ使用量も増えます。 -=== "Python" - - ```python title="" - class ListNode: - """双方向連結リストのノードクラス""" - def __init__(self, val: int): - self.val: int = val # ノードの値 - self.next: ListNode | None = None # 後続ノードへの参照 - self.prev: ListNode | None = None # 先行ノードへの参照 - ``` - -=== "C++" - - ```cpp title="" - /* 双方向連結リストのノード構造体 */ - struct ListNode { - int val; // ノードの値 - ListNode *next; // 後続ノードへのポインタ - ListNode *prev; // 先行ノードへのポインタ - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // コンストラクタ - }; - ``` - -=== "Java" - - ```java title="" - /* 双方向連結リストのノードクラス */ - class ListNode { - int val; // ノードの値 - ListNode next; // 後続ノードへの参照 - ListNode prev; // 先行ノードへの参照 - ListNode(int x) { val = x; } // コンストラクタ - } - ``` - -=== "C#" - - ```csharp title="" - /* 双方向連結リストのノードクラス */ - class ListNode(int x) { // コンストラクタ - int val = x; // ノードの値 - ListNode next; // 後続ノードへの参照 - ListNode prev; // 先行ノードへの参照 - } - ``` - -=== "Go" - - ```go title="" - /* 双方向連結リストのノード構造体 */ - type DoublyListNode struct { - Val int // ノードの値 - Next *DoublyListNode // 後続ノードへのポインタ - Prev *DoublyListNode // 先行ノードへのポインタ - } - - // NewDoublyListNode で初期化 - func NewDoublyListNode(val int) *DoublyListNode { - return &DoublyListNode{ - Val: val, - Next: nil, - Prev: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 双方向連結リストのノードクラス */ - class ListNode { - var val: Int // ノードの値 - var next: ListNode? // 後続ノードへの参照 - var prev: ListNode? // 先行ノードへの参照 - - init(x: Int) { // コンストラクタ - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 双方向連結リストのノードクラス */ - class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.next = next === undefined ? null : next; // 後続ノードへの参照 - this.prev = prev === undefined ? null : prev; // 先行ノードへの参照 - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 双方向連結リストのノードクラス */ - class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.next = next === undefined ? null : next; // 後続ノードへの参照 - this.prev = prev === undefined ? null : prev; // 先行ノードへの参照 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 双方向連結リストのノードクラス */ - class ListNode { - int val; // ノードの値 - ListNode? next; // 後続ノードへの参照 - ListNode? prev; // 先行ノードへの参照 - ListNode(this.val, [this.next, this.prev]); // コンストラクタ - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 双方向連結リストのノード型 */ - #[derive(Debug)] - struct ListNode { - val: i32, // ノードの値 - next: Option>>, // 後続ノードへのポインタ - prev: Option>>, // 先行ノードへのポインタ - } - - /* コンストラクタ */ - impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } - } - ``` - -=== "C" - - ```c title="" - /* 双方向連結リストのノード構造体 */ - typedef struct ListNode { - int val; // ノードの値 - struct ListNode *next; // 後続ノードへのポインタ - struct ListNode *prev; // 先行ノードへのポインタ - } ListNode; - - /* コンストラクタ */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 双方向連結リストのノードクラス */ - // コンストラクタ - class ListNode(x: Int) { - val _val: Int = x // ノードの値 - var next: ListNode? = null // 後続ノードへの参照 - var prev: ListNode? = null // 先行ノードへの参照 - } - ``` - -=== "Ruby" - - ```ruby title="" - # 双方向連結リストのノードクラス - class ListNode - attr_accessor :val # ノードの値 - attr_accessor :next # 後続ノードへの参照 - attr_accessor :prev # 先行ノードへの参照 - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end - end - ``` +```snippet +doubly_list_node_class +``` ![連結リストの主な種類](linked_list.assets/linkedlist_common_types.svg) diff --git a/ja/docs/chapter_array_and_linkedlist/list.md b/ja/docs/chapter_array_and_linkedlist/list.md index 4d5fa66a6..1bd36c60c 100644 --- a/ja/docs/chapter_array_and_linkedlist/list.md +++ b/ja/docs/chapter_array_and_linkedlist/list.md @@ -17,934 +17,73 @@ 通常は、「初期値なし」と「初期値あり」の二つの方法で初期化します。 -=== "Python" - - ```python title="list.py" - # リストを初期化 - # 初期値なし - nums1: list[int] = [] - # 初期値あり - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* リストを初期化 */ - // C++ の vector が、本節で扱う nums に相当することに注意 - // 初期値なし - vector nums1; - // 初期値あり - vector nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="list.java" - /* リストを初期化 */ - // 初期値なし - List nums1 = new ArrayList<>(); - // 初期値あり(配列には、int[] に対応するラッパー型の配列 Integer[] を使う必要がある) - Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; - List nums = new ArrayList<>(Arrays.asList(numbers)); - ``` - -=== "C#" - - ```csharp title="list.cs" - /* リストを初期化 */ - // 初期値なし - List nums1 = []; - // 初期値あり - int[] numbers = [1, 3, 2, 5, 4]; - List nums = [.. numbers]; - ``` - -=== "Go" - - ```go title="list_test.go" - /* リストを初期化 */ - // 初期値なし - nums1 := []int{} - // 初期値あり - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="list.swift" - /* リストを初期化 */ - // 初期値なし - let nums1: [Int] = [] - // 初期値あり - var nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="list.js" - /* リストを初期化 */ - // 初期値なし - const nums1 = []; - // 初期値あり - const nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="list.ts" - /* リストを初期化 */ - // 初期値なし - const nums1: number[] = []; - // 初期値あり - const nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="list.dart" - /* リストを初期化 */ - // 初期値なし - List nums1 = []; - // 初期値あり - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="list.rs" - /* リストを初期化 */ - // 初期値なし - let nums1: Vec = Vec::new(); - // 初期値あり - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="list.c" - // C には組み込みの動的配列がない - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* リストを初期化 */ - // 初期値なし - var nums1 = listOf() - // 初期値あり - var numbers = arrayOf(1, 3, 2, 5, 4) - var nums = numbers.toMutableList() - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # リストを初期化 - # 初期値なし - nums1 = [] - # 初期値あり - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_list +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%AA%E3%81%97%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%82%E3%82%8A%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_list_tutor ### 要素へのアクセス リストの実体は配列なので、要素へのアクセスと更新を $O(1)$ 時間で行え、非常に効率的です。 -=== "Python" - - ```python title="list.py" - # 要素にアクセス - num: int = nums[1] # インデックス 1 の要素にアクセス - - # 要素を更新 - nums[1] = 0 # インデックス 1 の要素を 0 に更新 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 要素にアクセス */ - int num = nums[1]; // インデックス 1 の要素にアクセス - - /* 要素を更新 */ - nums[1] = 0; // インデックス 1 の要素を 0 に更新 - ``` - -=== "Java" - - ```java title="list.java" - /* 要素にアクセス */ - int num = nums.get(1); // インデックス 1 の要素にアクセス - - /* 要素を更新 */ - nums.set(1, 0); // インデックス 1 の要素を 0 に更新 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 要素にアクセス */ - int num = nums[1]; // インデックス 1 の要素にアクセス - - /* 要素を更新 */ - nums[1] = 0; // インデックス 1 の要素を 0 に更新 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 要素にアクセス */ - num := nums[1] // インデックス 1 の要素にアクセス - - /* 要素を更新 */ - nums[1] = 0 // インデックス 1 の要素を 0 に更新 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 要素にアクセス */ - let num = nums[1] // インデックス 1 の要素にアクセス - - /* 要素を更新 */ - nums[1] = 0 // インデックス 1 の要素を 0 に更新 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 要素にアクセス */ - const num = nums[1]; // インデックス 1 の要素にアクセス - - /* 要素を更新 */ - nums[1] = 0; // インデックス 1 の要素を 0 に更新 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 要素にアクセス */ - const num: number = nums[1]; // インデックス 1 の要素にアクセス - - /* 要素を更新 */ - nums[1] = 0; // インデックス 1 の要素を 0 に更新 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 要素にアクセス */ - int num = nums[1]; // インデックス 1 の要素にアクセス - - /* 要素を更新 */ - nums[1] = 0; // インデックス 1 の要素を 0 に更新 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 要素にアクセス */ - let num: i32 = nums[1]; // インデックス 1 の要素にアクセス - /* 要素を更新 */ - nums[1] = 0; // インデックス 1 の要素を 0 に更新 - ``` - -=== "C" - - ```c title="list.c" - // C には組み込みの動的配列がない - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 要素にアクセス */ - val num = nums[1] // インデックス 1 の要素にアクセス - /* 要素を更新 */ - nums[1] = 0 // インデックス 1 の要素を 0 に更新 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 要素にアクセス - num = nums[1] # インデックス 1 の要素にアクセス - # 要素を更新 - nums[1] = 0 # インデックス 1 の要素を 0 に更新 - ``` +```snippet +access_element +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%201%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E6%9B%B4%E6%96%B0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%201%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%200%20%E3%81%AB%E6%9B%B4%E6%96%B0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor access_element_tutor ### 要素の挿入と削除 配列と比べて、リストは自由に要素を追加・削除できます。末尾への追加の時間計算量は $O(1)$ ですが、要素の挿入と削除の効率は配列と同じで、時間計算量は $O(n)$ です。 -=== "Python" - - ```python title="list.py" - # リストを空にする - nums.clear() - - # 末尾に要素を追加 - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - # 途中に要素を挿入 - nums.insert(3, 6) # インデックス 3 に数値 6 を挿入 - - # 要素を削除 - nums.pop(3) # インデックス 3 の要素を削除 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* リストを空にする */ - nums.clear(); - - /* 末尾に要素を追加 */ - nums.push_back(1); - nums.push_back(3); - nums.push_back(2); - nums.push_back(5); - nums.push_back(4); - - /* 途中に要素を挿入 */ - nums.insert(nums.begin() + 3, 6); // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums.erase(nums.begin() + 3); // インデックス 3 の要素を削除 - ``` - -=== "Java" - - ```java title="list.java" - /* リストを空にする */ - nums.clear(); - - /* 末尾に要素を追加 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 途中に要素を挿入 */ - nums.add(3, 6); // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums.remove(3); // インデックス 3 の要素を削除 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* リストを空にする */ - nums.Clear(); - - /* 末尾に要素を追加 */ - nums.Add(1); - nums.Add(3); - nums.Add(2); - nums.Add(5); - nums.Add(4); - - /* 途中に要素を挿入 */ - nums.Insert(3, 6); // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums.RemoveAt(3); // インデックス 3 の要素を削除 - ``` - -=== "Go" - - ```go title="list_test.go" - /* リストを空にする */ - nums = nil - - /* 末尾に要素を追加 */ - nums = append(nums, 1) - nums = append(nums, 3) - nums = append(nums, 2) - nums = append(nums, 5) - nums = append(nums, 4) - - /* 途中に要素を挿入 */ - nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums = append(nums[:3], nums[4:]...) // インデックス 3 の要素を削除 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* リストを空にする */ - nums.removeAll() - - /* 末尾に要素を追加 */ - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - /* 途中に要素を挿入 */ - nums.insert(6, at: 3) // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums.remove(at: 3) // インデックス 3 の要素を削除 - ``` - -=== "JS" - - ```javascript title="list.js" - /* リストを空にする */ - nums.length = 0; - - /* 末尾に要素を追加 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 途中に要素を挿入 */ - nums.splice(3, 0, 6); // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums.splice(3, 1); // インデックス 3 の要素を削除 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* リストを空にする */ - nums.length = 0; - - /* 末尾に要素を追加 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 途中に要素を挿入 */ - nums.splice(3, 0, 6); // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums.splice(3, 1); // インデックス 3 の要素を削除 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* リストを空にする */ - nums.clear(); - - /* 末尾に要素を追加 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 途中に要素を挿入 */ - nums.insert(3, 6); // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums.removeAt(3); // インデックス 3 の要素を削除 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* リストを空にする */ - nums.clear(); - - /* 末尾に要素を追加 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 途中に要素を挿入 */ - nums.insert(3, 6); // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums.remove(3); // インデックス 3 の要素を削除 - ``` - -=== "C" - - ```c title="list.c" - // C には組み込みの動的配列がない - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* リストを空にする */ - nums.clear(); - - /* 末尾に要素を追加 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 途中に要素を挿入 */ - nums.add(3, 6); // インデックス 3 に数値 6 を挿入 - - /* 要素を削除 */ - nums.remove(3); // インデックス 3 の要素を削除 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # リストを空にする - nums.clear - - # 末尾に要素を追加 - nums << 1 - nums << 3 - nums << 2 - nums << 5 - nums << 4 - - # 途中に要素を挿入 - nums.insert(3, 6) # インデックス 3 に数値 6 を挿入 - - # 要素を削除 - nums.delete_at(3) # インデックス 3 の要素を削除 - ``` +```snippet +insert_remove_element +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%82%E3%82%8A%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E7%A9%BA%E3%81%AB%E3%81%99%E3%82%8B%0A%20%20%20%20nums.clear()%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%9C%AB%E5%B0%BE%E3%81%AB%E8%A6%81%E7%B4%A0%E3%82%92%E8%BF%BD%E5%8A%A0%0A%20%20%20%20nums.append(1)%0A%20%20%20%20nums.append(3)%0A%20%20%20%20nums.append(2)%0A%20%20%20%20nums.append(5)%0A%20%20%20%20nums.append(4)%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%80%94%E4%B8%AD%E3%81%AB%E8%A6%81%E7%B4%A0%E3%82%92%E6%8C%BF%E5%85%A5%0A%20%20%20%20nums.insert(3%2C%206)%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%203%20%E3%81%AB%E6%95%B0%E5%80%A4%206%20%E3%82%92%E6%8C%BF%E5%85%A5%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E5%89%8A%E9%99%A4%0A%20%20%20%20nums.pop(3)%20%20%20%20%20%20%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%203%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%E5%89%8A%E9%99%A4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_element_tutor ### リストの走査 配列と同様に、インデックスを使って走査することも、各要素を直接取り出して走査することもできます。 -=== "Python" - - ```python title="list.py" - # インデックスを使ってリストを走査 - count = 0 - for i in range(len(nums)): - count += nums[i] - - # リストの要素を直接走査 - for num in nums: - count += num - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* インデックスを使ってリストを走査 */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums[i]; - } - - /* リストの要素を直接走査 */ - count = 0; - for (int num : nums) { - count += num; - } - ``` - -=== "Java" - - ```java title="list.java" - /* インデックスを使ってリストを走査 */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums.get(i); - } - - /* リストの要素を直接走査 */ - for (int num : nums) { - count += num; - } - ``` - -=== "C#" - - ```csharp title="list.cs" - /* インデックスを使ってリストを走査 */ - int count = 0; - for (int i = 0; i < nums.Count; i++) { - count += nums[i]; - } - - /* リストの要素を直接走査 */ - count = 0; - foreach (int num in nums) { - count += num; - } - ``` - -=== "Go" - - ```go title="list_test.go" - /* インデックスを使ってリストを走査 */ - count := 0 - for i := 0; i < len(nums); i++ { - count += nums[i] - } - - /* リストの要素を直接走査 */ - count = 0 - for _, num := range nums { - count += num - } - ``` - -=== "Swift" - - ```swift title="list.swift" - /* インデックスを使ってリストを走査 */ - var count = 0 - for i in nums.indices { - count += nums[i] - } - - /* リストの要素を直接走査 */ - count = 0 - for num in nums { - count += num - } - ``` - -=== "JS" - - ```javascript title="list.js" - /* インデックスを使ってリストを走査 */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* リストの要素を直接走査 */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "TS" - - ```typescript title="list.ts" - /* インデックスを使ってリストを走査 */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* リストの要素を直接走査 */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "Dart" - - ```dart title="list.dart" - /* インデックスを使ってリストを走査 */ - int count = 0; - for (var i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* リストの要素を直接走査 */ - count = 0; - for (var num in nums) { - count += num; - } - ``` - -=== "Rust" - - ```rust title="list.rs" - // インデックスを使ってリストを走査 - let mut _count = 0; - for i in 0..nums.len() { - _count += nums[i]; - } - - // リストの要素を直接走査 - _count = 0; - for num in &nums { - _count += num; - } - ``` - -=== "C" - - ```c title="list.c" - // C には組み込みの動的配列がない - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* インデックスを使ってリストを走査 */ - var count = 0 - for (i in nums.indices) { - count += nums[i] - } - - /* リストの要素を直接走査 */ - for (num in nums) { - count += num - } - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # インデックスを使ってリストを走査 - count = 0 - for i in 0...nums.length - count += nums[i] - end - - # リストの要素を直接走査 - count = 0 - for num in nums - count += num - end - ``` +```snippet +iterate_list +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%A6%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E8%B5%B0%E6%9F%BB%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range(len(nums))%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%E7%9B%B4%E6%8E%A5%E8%B5%B0%E6%9F%BB%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor iterate_list_tutor ### リストの連結 新しいリスト `nums1` を、元のリストの末尾につなげられます。 -=== "Python" - - ```python title="list.py" - # 二つのリストを連結 - nums1: list[int] = [6, 8, 7, 10, 9] - nums += nums1 # リスト nums1 を nums の後ろに連結 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 二つのリストを連結 */ - vector nums1 = { 6, 8, 7, 10, 9 }; - // リスト nums1 を nums の後ろに連結 - nums.insert(nums.end(), nums1.begin(), nums1.end()); - ``` - -=== "Java" - - ```java title="list.java" - /* 二つのリストを連結 */ - List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); - nums.addAll(nums1); // リスト nums1 を nums の後ろに連結 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 二つのリストを連結 */ - List nums1 = [6, 8, 7, 10, 9]; - nums.AddRange(nums1); // リスト nums1 を nums の後ろに連結 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 二つのリストを連結 */ - nums1 := []int{6, 8, 7, 10, 9} - nums = append(nums, nums1...) // リスト nums1 を nums の後ろに連結 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 二つのリストを連結 */ - let nums1 = [6, 8, 7, 10, 9] - nums.append(contentsOf: nums1) // リスト nums1 を nums の後ろに連結 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 二つのリストを連結 */ - const nums1 = [6, 8, 7, 10, 9]; - nums.push(...nums1); // リスト nums1 を nums の後ろに連結 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 二つのリストを連結 */ - const nums1: number[] = [6, 8, 7, 10, 9]; - nums.push(...nums1); // リスト nums1 を nums の後ろに連結 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 二つのリストを連結 */ - List nums1 = [6, 8, 7, 10, 9]; - nums.addAll(nums1); // リスト nums1 を nums の後ろに連結 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 二つのリストを連結 */ - let nums1: Vec = vec![6, 8, 7, 10, 9]; - nums.extend(nums1); - ``` - -=== "C" - - ```c title="list.c" - // C には組み込みの動的配列がない - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 二つのリストを連結 */ - val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() - nums.addAll(nums1) // リスト nums1 を nums の後ろに連結 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 二つのリストを連結 - nums1 = [6, 8, 7, 10, 9] - nums += nums1 - ``` +```snippet +concat_list +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E4%BA%8C%E3%81%A4%E3%81%AE%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E9%80%A3%E7%B5%90%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%20nums1%20%E3%82%92%20nums%20%E3%81%AE%E5%BE%8C%E3%82%8D%E3%81%AB%E9%80%A3%E7%B5%90&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor concat_list_tutor ### リストのソート リストをソートすると、配列を扱うアルゴリズムの問題でよく問われる「二分探索」や「二つのポインタを使う」アルゴリズムを利用できます。 -=== "Python" - - ```python title="list.py" - # リストをソート - nums.sort() # ソート後、リストの要素は昇順に並ぶ - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* リストをソート */ - sort(nums.begin(), nums.end()); // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "Java" - - ```java title="list.java" - /* リストをソート */ - Collections.sort(nums); // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "C#" - - ```csharp title="list.cs" - /* リストをソート */ - nums.Sort(); // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "Go" - - ```go title="list_test.go" - /* リストをソート */ - sort.Ints(nums) // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "Swift" - - ```swift title="list.swift" - /* リストをソート */ - nums.sort() // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "JS" - - ```javascript title="list.js" - /* リストをソート */ - nums.sort((a, b) => a - b); // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "TS" - - ```typescript title="list.ts" - /* リストをソート */ - nums.sort((a, b) => a - b); // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "Dart" - - ```dart title="list.dart" - /* リストをソート */ - nums.sort(); // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "Rust" - - ```rust title="list.rs" - /* リストをソート */ - nums.sort(); // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "C" - - ```c title="list.c" - // C には組み込みの動的配列がない - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* リストをソート */ - nums.sort() // ソート後、リストの要素は昇順に並ぶ - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # リストをソート - nums = nums.sort { |a, b| a <=> b } # ソート後、リストの要素は昇順に並ぶ - ``` +```snippet +sort_list +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E3%82%BD%E3%83%BC%E3%83%88%0A%20%20%20%20nums.sort()%20%20%23%20%E3%82%BD%E3%83%BC%E3%83%88%E5%BE%8C%E3%81%AF%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E8%A6%81%E7%B4%A0%E3%81%8C%E6%98%87%E9%A0%86%E3%81%AB%E4%B8%A6%E3%81%B6&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor sort_list_tutor ## リストの実装 diff --git a/ja/docs/chapter_backtracking/backtracking_algorithm.md b/ja/docs/chapter_backtracking/backtracking_algorithm.md index 0f26d1735..b7d49f5db 100644 --- a/ja/docs/chapter_backtracking/backtracking_algorithm.md +++ b/ja/docs/chapter_backtracking/backtracking_algorithm.md @@ -95,339 +95,9 @@ 次の基本形では、`state` が問題の現在の状態を、`choices` がその状態で取れる選択肢を表します。 -=== "Python" - - ```python title="" - def backtrack(state: State, choices: list[choice], res: list[state]): - """バックトラッキングの基本形""" - # 解かどうかを判定 - if is_solution(state): - # 解を記録 - record_solution(state, res) - # これ以上探索しない - return - # すべての選択肢を調べる - for choice in choices: - # 枝刈り:選択が有効かを判定 - if is_valid(state, choice): - # 試行:選択して状態を更新 - make_choice(state, choice) - backtrack(state, choices, res) - # 後戻り:選択を取り消し、前の状態に戻す - undo_choice(state, choice) - ``` - -=== "C++" - - ```cpp title="" - /* バックトラッキングの基本形 */ - void backtrack(State *state, vector &choices, vector &res) { - // 解かどうかを判定 - if (isSolution(state)) { - // 解を記録 - recordSolution(state, res); - // これ以上探索しない - return; - } - // すべての選択肢を調べる - for (Choice choice : choices) { - // 枝刈り:選択が有効かを判定 - if (isValid(state, choice)) { - // 試行:選択して状態を更新 - makeChoice(state, choice); - backtrack(state, choices, res); - // 後戻り:選択を取り消し、前の状態に戻す - undoChoice(state, choice); - } - } - } - ``` - -=== "Java" - - ```java title="" - /* バックトラッキングの基本形 */ - void backtrack(State state, List choices, List res) { - // 解かどうかを判定 - if (isSolution(state)) { - // 解を記録 - recordSolution(state, res); - // これ以上探索しない - return; - } - // すべての選択肢を調べる - for (Choice choice : choices) { - // 枝刈り:選択が有効かを判定 - if (isValid(state, choice)) { - // 試行:選択して状態を更新 - makeChoice(state, choice); - backtrack(state, choices, res); - // 後戻り:選択を取り消し、前の状態に戻す - undoChoice(state, choice); - } - } - } - ``` - -=== "C#" - - ```csharp title="" - /* バックトラッキングの基本形 */ - void Backtrack(State state, List choices, List res) { - // 解かどうかを判定 - if (IsSolution(state)) { - // 解を記録 - RecordSolution(state, res); - // これ以上探索しない - return; - } - // すべての選択肢を調べる - foreach (Choice choice in choices) { - // 枝刈り:選択が有効かを判定 - if (IsValid(state, choice)) { - // 試行:選択して状態を更新 - MakeChoice(state, choice); - Backtrack(state, choices, res); - // 後戻り:選択を取り消し、前の状態に戻す - UndoChoice(state, choice); - } - } - } - ``` - -=== "Go" - - ```go title="" - /* バックトラッキングの基本形 */ - func backtrack(state *State, choices []Choice, res *[]State) { - // 解かどうかを判定 - if isSolution(state) { - // 解を記録 - recordSolution(state, res) - // これ以上探索しない - return - } - // すべての選択肢を調べる - for _, choice := range choices { - // 枝刈り:選択が有効かを判定 - if isValid(state, choice) { - // 試行:選択して状態を更新 - makeChoice(state, choice) - backtrack(state, choices, res) - // 後戻り:選択を取り消し、前の状態に戻す - undoChoice(state, choice) - } - } - } - ``` - -=== "Swift" - - ```swift title="" - /* バックトラッキングの基本形 */ - func backtrack(state: inout State, choices: [Choice], res: inout [State]) { - // 解かどうかを判定 - if isSolution(state: state) { - // 解を記録 - recordSolution(state: state, res: &res) - // これ以上探索しない - return - } - // すべての選択肢を調べる - for choice in choices { - // 枝刈り:選択が有効かを判定 - if isValid(state: state, choice: choice) { - // 試行:選択して状態を更新 - makeChoice(state: &state, choice: choice) - backtrack(state: &state, choices: choices, res: &res) - // 後戻り:選択を取り消し、前の状態に戻す - undoChoice(state: &state, choice: choice) - } - } - } - ``` - -=== "JS" - - ```javascript title="" - /* バックトラッキングの基本形 */ - function backtrack(state, choices, res) { - // 解かどうかを判定 - if (isSolution(state)) { - // 解を記録 - recordSolution(state, res); - // これ以上探索しない - return; - } - // すべての選択肢を調べる - for (let choice of choices) { - // 枝刈り:選択が有効かを判定 - if (isValid(state, choice)) { - // 試行:選択して状態を更新 - makeChoice(state, choice); - backtrack(state, choices, res); - // 後戻り:選択を取り消し、前の状態に戻す - undoChoice(state, choice); - } - } - } - ``` - -=== "TS" - - ```typescript title="" - /* バックトラッキングの基本形 */ - function backtrack(state: State, choices: Choice[], res: State[]): void { - // 解かどうかを判定 - if (isSolution(state)) { - // 解を記録 - recordSolution(state, res); - // これ以上探索しない - return; - } - // すべての選択肢を調べる - for (let choice of choices) { - // 枝刈り:選択が有効かを判定 - if (isValid(state, choice)) { - // 試行:選択して状態を更新 - makeChoice(state, choice); - backtrack(state, choices, res); - // 後戻り:選択を取り消し、前の状態に戻す - undoChoice(state, choice); - } - } - } - ``` - -=== "Dart" - - ```dart title="" - /* バックトラッキングの基本形 */ - void backtrack(State state, List, List res) { - // 解かどうかを判定 - if (isSolution(state)) { - // 解を記録 - recordSolution(state, res); - // これ以上探索しない - return; - } - // すべての選択肢を調べる - for (Choice choice in choices) { - // 枝刈り:選択が有効かを判定 - if (isValid(state, choice)) { - // 試行:選択して状態を更新 - makeChoice(state, choice); - backtrack(state, choices, res); - // 後戻り:選択を取り消し、前の状態に戻す - undoChoice(state, choice); - } - } - } - ``` - -=== "Rust" - - ```rust title="" - /* バックトラッキングの基本形 */ - fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { - // 解かどうかを判定 - if is_solution(state) { - // 解を記録 - record_solution(state, res); - // これ以上探索しない - return; - } - // すべての選択肢を調べる - for choice in choices { - // 枝刈り:選択が有効かを判定 - if is_valid(state, choice) { - // 試行:選択して状態を更新 - make_choice(state, choice); - backtrack(state, choices, res); - // 後戻り:選択を取り消し、前の状態に戻す - undo_choice(state, choice); - } - } - } - ``` - -=== "C" - - ```c title="" - /* バックトラッキングの基本形 */ - void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { - // 解かどうかを判定 - if (isSolution(state)) { - // 解を記録 - recordSolution(state, res, numRes); - // これ以上探索しない - return; - } - // すべての選択肢を調べる - for (int i = 0; i < numChoices; i++) { - // 枝刈り:選択が有効かを判定 - if (isValid(state, &choices[i])) { - // 試行:選択して状態を更新 - makeChoice(state, &choices[i]); - backtrack(state, choices, numChoices, res, numRes); - // 後戻り:選択を取り消し、前の状態に戻す - undoChoice(state, &choices[i]); - } - } - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* バックトラッキングの基本形 */ - fun backtrack(state: State?, choices: List, res: List?) { - // 解かどうかを判定 - if (isSolution(state)) { - // 解を記録 - recordSolution(state, res) - // これ以上探索しない - return - } - // すべての選択肢を調べる - for (choice in choices) { - // 枝刈り:選択が有効かを判定 - if (isValid(state, choice)) { - // 試行:選択して状態を更新 - makeChoice(state, choice) - backtrack(state, choices, res) - // 後戻り:選択を取り消し、前の状態に戻す - undoChoice(state, choice) - } - } - } - ``` - -=== "Ruby" - - ```ruby title="" - ### バックトラッキングの基本形 ### - def backtrack(state, choices, res) - # 解かどうかを判定 - if is_solution?(state) - # 解を記録 - record_solution(state, res) - return - end - - # すべての選択肢を調べる - for choice in choices - # 枝刈り:選択が有効かを判定 - if is_valid?(state, choice) - # 試行:選択して状態を更新 - make_choice(state, choice) - backtrack(state, choices, res) - # 後戻り:選択を取り消し、前の状態に戻す - undo_choice(state, choice) - end - end - end - ``` +```snippet +backtrack_framework +``` 次に、この基本形を使って例題 3 を解きます。状態 `state` はノードをたどった経路、選択肢 `choices` は現在のノードの左右の子ノード、結果 `res` は経路のリストです。 diff --git a/ja/docs/chapter_computational_complexity/space_complexity.md b/ja/docs/chapter_computational_complexity/space_complexity.md index 5b6639e3f..e4750ee42 100644 --- a/ja/docs/chapter_computational_complexity/space_complexity.md +++ b/ja/docs/chapter_computational_complexity/space_complexity.md @@ -24,342 +24,9 @@ 関連するコードを次に示します。 -=== "Python" - - ```python title="" - class Node: - """クラス""" - def __init__(self, x: int): - self.val: int = x # ノードの値 - self.next: Node | None = None # 次のノードへの参照 - - def function() -> int: - """関数""" - # 何らかの処理を実行... - return 0 - - def algorithm(n) -> int: # 入力データ - A = 0 # 一時データ(定数、通常は大文字で表す) - b = 0 # 一時データ(変数) - node = Node(0) # 一時データ(オブジェクト) - c = function() # スタックフレーム(関数呼び出し) - return A + b + c # 出力データ - ``` - -=== "C++" - - ```cpp title="" - /* 構造体 */ - struct Node { - int val; - Node *next; - Node(int x) : val(x), next(nullptr) {} - }; - - /* 関数 */ - int func() { - // 何らかの処理を実行... - return 0; - } - - int algorithm(int n) { // 入力データ - const int a = 0; // 一時データ(定数) - int b = 0; // 一時データ(変数) - Node* node = new Node(0); // 一時データ(オブジェクト) - int c = func(); // スタックフレーム(関数呼び出し) - return a + b + c; // 出力データ - } - ``` - -=== "Java" - - ```java title="" - /* クラス */ - class Node { - int val; - Node next; - Node(int x) { val = x; } - } - - /* 関数 */ - int function() { - // 何らかの処理を実行... - return 0; - } - - int algorithm(int n) { // 入力データ - final int a = 0; // 一時データ(定数) - int b = 0; // 一時データ(変数) - Node node = new Node(0); // 一時データ(オブジェクト) - int c = function(); // スタックフレーム(関数呼び出し) - return a + b + c; // 出力データ - } - ``` - -=== "C#" - - ```csharp title="" - /* クラス */ - class Node(int x) { - int val = x; - Node next; - } - - /* 関数 */ - int Function() { - // 何らかの処理を実行... - return 0; - } - - int Algorithm(int n) { // 入力データ - const int a = 0; // 一時データ(定数) - int b = 0; // 一時データ(変数) - Node node = new(0); // 一時データ(オブジェクト) - int c = Function(); // スタックフレーム(関数呼び出し) - return a + b + c; // 出力データ - } - ``` - -=== "Go" - - ```go title="" - /* 構造体 */ - type node struct { - val int - next *node - } - - /* node 構造体を作成 */ - func newNode(val int) *node { - return &node{val: val} - } - - /* 関数 */ - func function() int { - // 何らかの処理を実行... - return 0 - } - - func algorithm(n int) int { // 入力データ - const a = 0 // 一時データ(定数) - b := 0 // 一時データ(変数) - newNode(0) // 一時データ(オブジェクト) - c := function() // スタックフレーム(関数呼び出し) - return a + b + c // 出力データ - } - ``` - -=== "Swift" - - ```swift title="" - /* クラス */ - class Node { - var val: Int - var next: Node? - - init(x: Int) { - val = x - } - } - - /* 関数 */ - func function() -> Int { - // 何らかの処理を実行... - return 0 - } - - func algorithm(n: Int) -> Int { // 入力データ - let a = 0 // 一時データ(定数) - var b = 0 // 一時データ(変数) - let node = Node(x: 0) // 一時データ(オブジェクト) - let c = function() // スタックフレーム(関数呼び出し) - return a + b + c // 出力データ - } - ``` - -=== "JS" - - ```javascript title="" - /* クラス */ - class Node { - val; - next; - constructor(val) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.next = null; // 次のノードへの参照 - } - } - - /* 関数 */ - function constFunc() { - // 何らかの処理を実行 - return 0; - } - - function algorithm(n) { // 入力データ - const a = 0; // 一時データ(定数) - let b = 0; // 一時データ(変数) - const node = new Node(0); // 一時データ(オブジェクト) - const c = constFunc(); // スタックフレーム(関数呼び出し) - return a + b + c; // 出力データ - } - ``` - -=== "TS" - - ```typescript title="" - /* クラス */ - class Node { - val: number; - next: Node | null; - constructor(val?: number) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.next = null; // 次のノードへの参照 - } - } - - /* 関数 */ - function constFunc(): number { - // 何らかの処理を実行 - return 0; - } - - function algorithm(n: number): number { // 入力データ - const a = 0; // 一時データ(定数) - let b = 0; // 一時データ(変数) - const node = new Node(0); // 一時データ(オブジェクト) - const c = constFunc(); // スタックフレーム(関数呼び出し) - return a + b + c; // 出力データ - } - ``` - -=== "Dart" - - ```dart title="" - /* クラス */ - class Node { - int val; - Node next; - Node(this.val, [this.next]); - } - - /* 関数 */ - int function() { - // 何らかの処理を実行... - return 0; - } - - int algorithm(int n) { // 入力データ - const int a = 0; // 一時データ(定数) - int b = 0; // 一時データ(変数) - Node node = Node(0); // 一時データ(オブジェクト) - int c = function(); // スタックフレーム(関数呼び出し) - return a + b + c; // 出力データ - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 構造体 */ - struct Node { - val: i32, - next: Option>>, - } - - /* Node 構造体を作成 */ - impl Node { - fn new(val: i32) -> Self { - Self { val: val, next: None } - } - } - - /* 関数 */ - fn function() -> i32 { - // 何らかの処理を実行... - return 0; - } - - fn algorithm(n: i32) -> i32 { // 入力データ - const a: i32 = 0; // 一時データ(定数) - let mut b = 0; // 一時データ(変数) - let node = Node::new(0); // 一時データ(オブジェクト) - let c = function(); // スタックフレーム(関数呼び出し) - return a + b + c; // 出力データ - } - ``` - -=== "C" - - ```c title="" - /* 関数 */ - int func() { - // 何らかの処理を実行... - return 0; - } - - int algorithm(int n) { // 入力データ - const int a = 0; // 一時データ(定数) - int b = 0; // 一時データ(変数) - int c = func(); // スタックフレーム(関数呼び出し) - return a + b + c; // 出力データ - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* クラス */ - class Node(var _val: Int) { - var next: Node? = null - } - - /* 関数 */ - fun function(): Int { - // 何らかの処理を実行... - return 0 - } - - fun algorithm(n: Int): Int { // 入力データ - val a = 0 // 一時データ(定数) - var b = 0 // 一時データ(変数) - val node = Node(0) // 一時データ(オブジェクト) - val c = function() // スタックフレーム(関数呼び出し) - return a + b + c // 出力データ - } - ``` - -=== "Ruby" - - ```ruby title="" - ### クラス ### - class Node - attr_accessor :val # ノードの値 - attr_accessor :next # 次のノードへの参照 - - def initialize(x) - @val = x - end - end - - ### 関数 ### - def function - # 何らかの処理を実行... - 0 - end - - ### アルゴリズム ### - def algorithm(n) # 入力データ - a = 0 # 一時データ(定数) - b = 0 # 一時データ(変数) - node = Node.new(0) # 一時データ(オブジェクト) - c = function # スタックフレーム(関数呼び出し) - a + b + c # 出力データ - end - ``` +```snippet +space_categories +``` ## 見積もり方 @@ -372,428 +39,15 @@ 1. **最悪の入力を基準にする**:$n < 10$ なら $O(1)$ ですが、$n > 10$ なら配列 `nums` が $O(n)$ の空間を使うため、最悪空間計算量は $O(n)$ です。 2. **実行中の最大メモリ使用量を基準にする**:たとえば、最後の行の実行前は $O(1)$ ですが、配列 `nums` を初期化すると $O(n)$ の空間を使うため、最悪空間計算量は $O(n)$ です。 -=== "Python" - - ```python title="" - def algorithm(n: int): - a = 0 # O(1) - b = [0] * 10000 # O(1) - if n > 10: - nums = [0] * n # O(n) - ``` - -=== "C++" - - ```cpp title="" - void algorithm(int n) { - int a = 0; // O(1) - vector b(10000); // O(1) - if (n > 10) - vector nums(n); // O(n) - } - ``` - -=== "Java" - - ```java title="" - void algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) - int[] nums = new int[n]; // O(n) - } - ``` - -=== "C#" - - ```csharp title="" - void Algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) { - int[] nums = new int[n]; // O(n) - } - } - ``` - -=== "Go" - - ```go title="" - func algorithm(n int) { - a := 0 // O(1) - b := make([]int, 10000) // O(1) - var nums []int - if n > 10 { - nums := make([]int, n) // O(n) - } - fmt.Println(a, b, nums) - } - ``` - -=== "Swift" - - ```swift title="" - func algorithm(n: Int) { - let a = 0 // O(1) - let b = Array(repeating: 0, count: 10000) // O(1) - if n > 10 { - let nums = Array(repeating: 0, count: n) // O(n) - } - } - ``` - -=== "JS" - - ```javascript title="" - function algorithm(n) { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "TS" - - ```typescript title="" - function algorithm(n: number): void { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "Dart" - - ```dart title="" - void algorithm(int n) { - int a = 0; // O(1) - List b = List.filled(10000, 0); // O(1) - if (n > 10) { - List nums = List.filled(n, 0); // O(n) - } - } - ``` - -=== "Rust" - - ```rust title="" - fn algorithm(n: i32) { - let a = 0; // O(1) - let b = [0; 10000]; // O(1) - if n > 10 { - let nums = vec![0; n as usize]; // O(n) - } - } - ``` - -=== "C" - - ```c title="" - void algorithm(int n) { - int a = 0; // O(1) - int b[10000]; // O(1) - if (n > 10) - int nums[n] = {0}; // O(n) - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun algorithm(n: Int) { - val a = 0 // O(1) - val b = IntArray(10000) // O(1) - if (n > 10) { - val nums = IntArray(n) // O(n) - } - } - ``` - -=== "Ruby" - - ```ruby title="" - def algorithm(n) - a = 0 # O(1) - b = Array.new(10000) # O(1) - nums = Array.new(n) if n > 10 # O(n) - end - ``` +```snippet +worst_case_space +``` **再帰関数では、スタックフレームを数え忘れないよう注意が必要です**。次のコードを見てください。 -=== "Python" - - ```python title="" - def function() -> int: - # 何らかの処理を実行 - return 0 - - def loop(n: int): - """ループの空間計算量は O(1)""" - for _ in range(n): - function() - - def recur(n: int): - """再帰の空間計算量は O(n)""" - if n == 1: - return - return recur(n - 1) - ``` - -=== "C++" - - ```cpp title="" - int func() { - // 何らかの処理を実行 - return 0; - } - /* ループの空間計算量は O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* 再帰の空間計算量は O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Java" - - ```java title="" - int function() { - // 何らかの処理を実行 - return 0; - } - /* ループの空間計算量は O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* 再帰の空間計算量は O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "C#" - - ```csharp title="" - int Function() { - // 何らかの処理を実行 - return 0; - } - /* ループの空間計算量は O(1) */ - void Loop(int n) { - for (int i = 0; i < n; i++) { - Function(); - } - } - /* 再帰の空間計算量は O(n) */ - int Recur(int n) { - if (n == 1) return 1; - return Recur(n - 1); - } - ``` - -=== "Go" - - ```go title="" - func function() int { - // 何らかの処理を実行 - return 0 - } - - /* ループの空間計算量は O(1) */ - func loop(n int) { - for i := 0; i < n; i++ { - function() - } - } - - /* 再帰の空間計算量は O(n) */ - func recur(n int) { - if n == 1 { - return - } - recur(n - 1) - } - ``` - -=== "Swift" - - ```swift title="" - @discardableResult - func function() -> Int { - // 何らかの処理を実行 - return 0 - } - - /* ループの空間計算量は O(1) */ - func loop(n: Int) { - for _ in 0 ..< n { - function() - } - } - - /* 再帰の空間計算量は O(n) */ - func recur(n: Int) { - if n == 1 { - return - } - recur(n: n - 1) - } - ``` - -=== "JS" - - ```javascript title="" - function constFunc() { - // 何らかの処理を実行 - return 0; - } - /* ループの空間計算量は O(1) */ - function loop(n) { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* 再帰の空間計算量は O(n) */ - function recur(n) { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "TS" - - ```typescript title="" - function constFunc(): number { - // 何らかの処理を実行 - return 0; - } - /* ループの空間計算量は O(1) */ - function loop(n: number): void { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* 再帰の空間計算量は O(n) */ - function recur(n: number): void { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "Dart" - - ```dart title="" - int function() { - // 何らかの処理を実行 - return 0; - } - /* ループの空間計算量は O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* 再帰の空間計算量は O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Rust" - - ```rust title="" - fn function() -> i32 { - // 何らかの処理を実行 - return 0; - } - /* ループの空間計算量は O(1) */ - fn loop(n: i32) { - for i in 0..n { - function(); - } - } - /* 再帰の空間計算量は O(n) */ - fn recur(n: i32) { - if n == 1 { - return; - } - recur(n - 1); - } - ``` - -=== "C" - - ```c title="" - int func() { - // 何らかの処理を実行 - return 0; - } - /* ループの空間計算量は O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* 再帰の空間計算量は O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun function(): Int { - // 何らかの処理を実行 - return 0 - } - /* ループの空間計算量は O(1) */ - fun loop(n: Int) { - for (i in 0.. numbers = List.filled(5, 0); - List decimals = List.filled(5, 0.0); - List characters = List.filled(5, 'a'); - List bools = List.filled(5, false); - ``` - -=== "Rust" - - ```rust title="" - // さまざまな基本データ型で配列を初期化 - let numbers: Vec = vec![0; 5]; - let decimals: Vec = vec![0.0; 5]; - let characters: Vec = vec!['0'; 5]; - let bools: Vec = vec![false; 5]; - ``` - -=== "C" - - ```c title="" - // さまざまな基本データ型で配列を初期化 - int numbers[10]; - float decimals[10]; - char characters[10]; - bool bools[10]; - ``` - -=== "Kotlin" - - ```kotlin title="" - // さまざまな基本データ型で配列を初期化 - val numbers = IntArray(5) - val decinals = FloatArray(5) - val characters = CharArray(5) - val bools = BooleanArray(5) - ``` - -=== "Ruby" - - ```ruby title="" - # Ruby のリストには、さまざまな基本データ型やオブジェクトへの参照を自由に格納できる - data = [0, 0.0, 'a', false, ListNode(0)] - ``` +```snippet +basic_type_arrays +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E6%AC%A1%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%81%95%E3%81%BE%E3%81%96%E3%81%BE%E3%81%AA%E5%9F%BA%E6%9C%AC%E3%83%87%E3%83%BC%E3%82%BF%E5%9E%8B%E3%81%A7%E9%85%8D%E5%88%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20*%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20*%205%0A%20%20%20%20%23%20Python%20%E3%81%AE%E6%96%87%E5%AD%97%E3%81%AF%E3%80%81%E5%AE%9F%E9%9A%9B%E3%81%AB%E3%81%AF%E9%95%B7%E3%81%95%201%20%E3%81%AE%E6%96%87%E5%AD%97%E5%88%97%0A%20%20%20%20characters%20%3D%20%5B'0'%5D%20*%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20*%205%0A%20%20%20%20%23%20Python%20%E3%81%AE%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AB%E3%81%AF%E3%80%81%E3%81%95%E3%81%BE%E3%81%96%E3%81%BE%E3%81%AA%E5%9F%BA%E6%9C%AC%E3%83%87%E3%83%BC%E3%82%BF%E5%9E%8B%E3%82%84%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%E3%82%92%E8%87%AA%E7%94%B1%E3%81%AB%E6%A0%BC%E7%B4%8D%E3%81%A7%E3%81%8D%E3%82%8B%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20'a'%2C%20False%2C%20ListNode(0)%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor basic_type_arrays_tutor diff --git a/ja/docs/chapter_hashing/hash_algorithm.md b/ja/docs/chapter_hashing/hash_algorithm.md index a3be638df..8f611bbec 100644 --- a/ja/docs/chapter_hashing/hash_algorithm.md +++ b/ja/docs/chapter_hashing/hash_algorithm.md @@ -113,295 +113,13 @@ $$ 組み込みのハッシュ値計算関数の定義や方法は、言語ごとに異なります。 -=== "Python" - - ```python title="built_in_hash.py" - num = 3 - hash_num = hash(num) - # 整数 3 のハッシュ値は 3 - - bol = True - hash_bol = hash(bol) - # 真偽値 True のハッシュ値は 1 - - dec = 3.14159 - hash_dec = hash(dec) - # 小数 3.14159 のハッシュ値は 326484311674566659 - - str = "Hello 算法" - hash_str = hash(str) - # 文字列「Hello 算法」のハッシュ値は 4617003410720528961 - - tup = (12836, "小哈") - hash_tup = hash(tup) - # タプル (12836, '小哈') のハッシュ値は 1029005403108185979 - - obj = ListNode(0) - hash_obj = hash(obj) - # ノードオブジェクト のハッシュ値は 274267521 - ``` - -=== "C++" - - ```cpp title="built_in_hash.cpp" - int num = 3; - size_t hashNum = hash()(num); - // 整数 3 のハッシュ値は 3 - - bool bol = true; - size_t hashBol = hash()(bol); - // 真偽値 1 のハッシュ値は 1 - - double dec = 3.14159; - size_t hashDec = hash()(dec); - // 小数 3.14159 のハッシュ値は 4614256650576692846 - - string str = "Hello 算法"; - size_t hashStr = hash()(str); - // 文字列「Hello 算法」のハッシュ値は 15466937326284535026 - - // C++ の組み込み std::hash() は基本データ型のハッシュ値計算のみを提供する - // 配列やオブジェクトのハッシュ値計算は自分で実装する - ``` - -=== "Java" - - ```java title="built_in_hash.java" - int num = 3; - int hashNum = Integer.hashCode(num); - // 整数 3 のハッシュ値は 3 - - boolean bol = true; - int hashBol = Boolean.hashCode(bol); - // 真偽値 true のハッシュ値は 1231 - - double dec = 3.14159; - int hashDec = Double.hashCode(dec); - // 小数 3.14159 のハッシュ値は -1340954729 - - String str = "Hello 算法"; - int hashStr = str.hashCode(); - // 文字列「Hello 算法」のハッシュ値は -727081396 - - Object[] arr = { 12836, "小哈" }; - int hashTup = Arrays.hashCode(arr); - // 配列 [12836, 小哈] のハッシュ値は 1151158 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode(); - // ノードオブジェクト utils.ListNode@7dc5e7b4 のハッシュ値は 2110121908 - ``` - -=== "C#" - - ```csharp title="built_in_hash.cs" - int num = 3; - int hashNum = num.GetHashCode(); - // 整数 3 のハッシュ値は 3; - - bool bol = true; - int hashBol = bol.GetHashCode(); - // 真偽値 true のハッシュ値は 1; - - double dec = 3.14159; - int hashDec = dec.GetHashCode(); - // 小数 3.14159 のハッシュ値は -1340954729; - - string str = "Hello 算法"; - int hashStr = str.GetHashCode(); - // 文字列「Hello 算法」のハッシュ値は -586107568; - - object[] arr = [12836, "小哈"]; - int hashTup = arr.GetHashCode(); - // 配列 [12836, 小哈] のハッシュ値は 42931033; - - ListNode obj = new(0); - int hashObj = obj.GetHashCode(); - // ノードオブジェクト 0 のハッシュ値は 39053774; - ``` - -=== "Go" - - ```go title="built_in_hash.go" - // Go には組み込みの hash code 関数がない - ``` - -=== "Swift" - - ```swift title="built_in_hash.swift" - let num = 3 - let hashNum = num.hashValue - // 整数 3 のハッシュ値は 9047044699613009734 - - let bol = true - let hashBol = bol.hashValue - // 真偽値 true のハッシュ値は -4431640247352757451 - - let dec = 3.14159 - let hashDec = dec.hashValue - // 小数 3.14159 のハッシュ値は -2465384235396674631 - - let str = "Hello 算法" - let hashStr = str.hashValue - // 文字列「Hello 算法」のハッシュ値は -7850626797806988787 - - let arr = [AnyHashable(12836), AnyHashable("小哈")] - let hashTup = arr.hashValue - // 配列 [AnyHashable(12836), AnyHashable("小哈")] のハッシュ値は -2308633508154532996 - - let obj = ListNode(x: 0) - let hashObj = obj.hashValue - // ノードオブジェクト utils.ListNode のハッシュ値は -2434780518035996159 - ``` - -=== "JS" - - ```javascript title="built_in_hash.js" - // JavaScript には組み込みの hash code 関数がない - ``` - -=== "TS" - - ```typescript title="built_in_hash.ts" - // TypeScript には組み込みの hash code 関数がない - ``` - -=== "Dart" - - ```dart title="built_in_hash.dart" - int num = 3; - int hashNum = num.hashCode; - // 整数 3 のハッシュ値は 34803 - - bool bol = true; - int hashBol = bol.hashCode; - // 真偽値 true のハッシュ値は 1231 - - double dec = 3.14159; - int hashDec = dec.hashCode; - // 小数 3.14159 のハッシュ値は 2570631074981783 - - String str = "Hello 算法"; - int hashStr = str.hashCode; - // 文字列「Hello 算法」のハッシュ値は 468167534 - - List arr = [12836, "小哈"]; - int hashArr = arr.hashCode; - // 配列 [12836, 小哈] のハッシュ値は 976512528 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode; - // ノードオブジェクト Instance of 'ListNode' のハッシュ値は 1033450432 - ``` - -=== "Rust" - - ```rust title="built_in_hash.rs" - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - - let num = 3; - let mut num_hasher = DefaultHasher::new(); - num.hash(&mut num_hasher); - let hash_num = num_hasher.finish(); - // 整数 3 のハッシュ値は 568126464209439262 - - let bol = true; - let mut bol_hasher = DefaultHasher::new(); - bol.hash(&mut bol_hasher); - let hash_bol = bol_hasher.finish(); - // 真偽値 true のハッシュ値は 4952851536318644461 - - let dec: f32 = 3.14159; - let mut dec_hasher = DefaultHasher::new(); - dec.to_bits().hash(&mut dec_hasher); - let hash_dec = dec_hasher.finish(); - // 小数 3.14159 のハッシュ値は 2566941990314602357 - - let str = "Hello 算法"; - let mut str_hasher = DefaultHasher::new(); - str.hash(&mut str_hasher); - let hash_str = str_hasher.finish(); - // 文字列「Hello 算法」のハッシュ値は 16092673739211250988 - - let arr = (&12836, &"小哈"); - let mut tup_hasher = DefaultHasher::new(); - arr.hash(&mut tup_hasher); - let hash_tup = tup_hasher.finish(); - // タプル (12836, "小哈") のハッシュ値は 1885128010422702749 - - let node = ListNode::new(42); - let mut hasher = DefaultHasher::new(); - node.borrow().val.hash(&mut hasher); - let hash = hasher.finish(); - // ノードオブジェクト RefCell { value: ListNode { val: 42, next: None } } のハッシュ値は 15387811073369036852 - ``` - -=== "C" - - ```c title="built_in_hash.c" - // C には組み込みの hash code 関数がない - ``` - -=== "Kotlin" - - ```kotlin title="built_in_hash.kt" - val num = 3 - val hashNum = num.hashCode() - // 整数 3 のハッシュ値は 3 - - val bol = true - val hashBol = bol.hashCode() - // 真偽値 true のハッシュ値は 1231 - - val dec = 3.14159 - val hashDec = dec.hashCode() - // 小数 3.14159 のハッシュ値は -1340954729 - - val str = "Hello 算法" - val hashStr = str.hashCode() - // 文字列「Hello 算法」のハッシュ値は -727081396 - - val arr = arrayOf(12836, "小哈") - val hashTup = arr.hashCode() - // 配列 [12836, 小哈] のハッシュ値は 189568618 - - val obj = ListNode(0) - val hashObj = obj.hashCode() - // ノードオブジェクト utils.ListNode@1d81eb93 のハッシュ値は 495053715 - ``` - -=== "Ruby" - - ```ruby title="built_in_hash.rb" - num = 3 - hash_num = num.hash - # 整数 3 のハッシュ値は -4385856518450339636 - - bol = true - hash_bol = bol.hash - # 真偽値 true のハッシュ値は -1617938112149317027 - - dec = 3.14159 - hash_dec = dec.hash - # 小数 3.14159 のハッシュ値は -1479186995943067893 - - str = "Hello 算法" - hash_str = str.hash - # 文字列「Hello 算法」のハッシュ値は -4075943250025831763 - - tup = [12836, '小哈'] - hash_tup = tup.hash - # タプル (12836, '小哈') のハッシュ値は 1999544809202288822 - - obj = ListNode.new(0) - hash_obj = obj.hash - # ノードオブジェクト # のハッシュ値は 4302940560806366381 - ``` +```snippet +builtin_hash +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E6%AC%A1%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash(num)%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash(bol)%0A%20%20%20%20%23%20%E7%9C%9F%E5%81%BD%E5%80%A4%20True%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash(dec)%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash(str)%0A%20%20%20%20%23%20%E6%96%87%E5%AD%97%E5%88%97%E3%80%8CHello%20%E7%AE%97%E6%B3%95%E3%80%8D%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20(12836%2C%20%22%E5%B0%8F%E5%93%88%22)%0A%20%20%20%20hash_tup%20%3D%20hash(tup)%0A%20%20%20%20%23%20%E3%82%BF%E3%83%97%E3%83%AB%20(12836%2C%20'%E5%B0%8F%E5%93%88')%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode(0)%0A%20%20%20%20hash_obj%20%3D%20hash(obj)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%20%3CListNode%20object%20at%200x1058fd810%3E%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor builtin_hash_tutor 多くの言語では、**不変オブジェクトだけがハッシュテーブルの `key` になれます**。リスト(動的配列)を `key` にすると、内容の変化とともにハッシュ値も変わり、元の `value` を照会できなくなります。 diff --git a/ja/docs/chapter_hashing/hash_map.md b/ja/docs/chapter_hashing/hash_map.md index 30e5dc387..d638d4f1f 100644 --- a/ja/docs/chapter_hashing/hash_map.md +++ b/ja/docs/chapter_hashing/hash_map.md @@ -26,517 +26,23 @@ 主な操作には、初期化、照会、キーと値のペアの追加や削除などがあります。コード例を示します。 -=== "Python" - - ```python title="hash_map.py" - # ハッシュテーブルを初期化 - hmap: dict = {} - - # 追加操作 - # ハッシュテーブルにペア (key, value) を追加 - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - # 照会操作 - # キー key を入力して値 value を取得 - name: str = hmap[15937] - - # 削除操作 - # ハッシュテーブルからペア (key, value) を削除 - hmap.pop(10583) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* ハッシュテーブルを初期化 */ - unordered_map map; - - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - map[12836] = "小哈"; - map[15937] = "小啰"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鸭"; - - /* 照会操作 */ - // キー key を入力して値 value を取得 - string name = map[15937]; - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - map.erase(10583); - ``` - -=== "Java" - - ```java title="hash_map.java" - /* ハッシュテーブルを初期化 */ - Map map = new HashMap<>(); - - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - map.put(12836, "小哈"); - map.put(15937, "小啰"); - map.put(16750, "小算"); - map.put(13276, "小法"); - map.put(10583, "小鸭"); - - /* 照会操作 */ - // キー key を入力して値 value を取得 - String name = map.get(15937); - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - map.remove(10583); - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* ハッシュテーブルを初期化 */ - Dictionary map = new() { - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - { 12836, "小哈" }, - { 15937, "小啰" }, - { 16750, "小算" }, - { 13276, "小法" }, - { 10583, "小鸭" } - }; - - /* 照会操作 */ - // キー key を入力して値 value を取得 - string name = map[15937]; - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - map.Remove(10583); - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* ハッシュテーブルを初期化 */ - hmap := make(map[int]string) - - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - /* 照会操作 */ - // キー key を入力して値 value を取得 - name := hmap[15937] - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - delete(hmap, 10583) - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* ハッシュテーブルを初期化 */ - var map: [Int: String] = [:] - - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - map[12836] = "小哈" - map[15937] = "小啰" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鸭" - - /* 照会操作 */ - // キー key を入力して値 value を取得 - let name = map[15937]! - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - map.removeValue(forKey: 10583) - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* ハッシュテーブルを初期化 */ - const map = new Map(); - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - map.set(12836, '小哈'); - map.set(15937, '小啰'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鸭'); - - /* 照会操作 */ - // キー key を入力して値 value を取得 - let name = map.get(15937); - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - map.delete(10583); - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* ハッシュテーブルを初期化 */ - const map = new Map(); - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - map.set(12836, '小哈'); - map.set(15937, '小啰'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鸭'); - console.info('\n追加後のハッシュテーブルは\nKey -> Value'); - console.info(map); - - /* 照会操作 */ - // キー key を入力して値 value を取得 - let name = map.get(15937); - console.info('\n学籍番号 15937 を入力して得た名前は ' + name); - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - map.delete(10583); - console.info('\n10583 を削除した後のハッシュテーブルは\nKey -> Value'); - console.info(map); - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* ハッシュテーブルを初期化 */ - Map map = {}; - - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - map[12836] = "小哈"; - map[15937] = "小啰"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鸭"; - - /* 照会操作 */ - // キー key を入力して値 value を取得 - String name = map[15937]; - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - map.remove(10583); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - use std::collections::HashMap; - - /* ハッシュテーブルを初期化 */ - let mut map: HashMap = HashMap::new(); - - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - map.insert(12836, "小哈".to_string()); - map.insert(15937, "小啰".to_string()); - map.insert(16750, "小算".to_string()); - map.insert(13279, "小法".to_string()); - map.insert(10583, "小鸭".to_string()); - - /* 照会操作 */ - // キー key を入力して値 value を取得 - let _name: Option<&String> = map.get(&15937); - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - let _removed_value: Option = map.remove(&10583); - ``` - -=== "C" - - ```c title="hash_map.c" - // C には組み込みのハッシュテーブルがない - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* ハッシュテーブルを初期化 */ - val map = HashMap() - - /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 - map[12836] = "小哈" - map[15937] = "小啰" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鸭" - - /* 照会操作 */ - // キー key を入力して値 value を取得 - val name = map[15937] - - /* 削除操作 */ - // ハッシュテーブルからペア (key, value) を削除 - map.remove(10583) - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # ハッシュテーブルを初期化 - hmap = {} - - # 追加操作 - # ハッシュテーブルにペア (key, value) を追加 - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - # 照会操作 - # キー key を入力して値 value を取得 - name = hmap[15937] - - # 削除操作 - # ハッシュテーブルからペア (key, value) を削除 - hmap.delete(10583) - ``` +```snippet +hash_map_operations +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BF%BD%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%81%AB%E3%83%9A%E3%82%A2%20(key%2C%20value)%20%E3%82%92%E8%BF%BD%E5%8A%A0%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%85%A7%E4%BC%9A%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%20key%20%E3%82%92%E5%85%A5%E5%8A%9B%E3%81%97%E3%81%A6%E5%80%A4%20value%20%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%89%8A%E9%99%A4%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%81%8B%E3%82%89%E3%83%9A%E3%82%A2%20(key%2C%20value)%20%E3%82%92%E5%89%8A%E9%99%A4%0A%20%20%20%20hmap.pop(10583)&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_operations_tutor ハッシュテーブルの主な走査方法は、キーと値のペアの走査、キーだけの走査、値だけの走査の三つです。コード例を示します。 -=== "Python" - - ```python title="hash_map.py" - # ハッシュテーブルを走査 - # キーと値のペアを走査 key->value - for key, value in hmap.items(): - print(key, "->", value) - # キーだけを走査 key - for key in hmap.keys(): - print(key) - # 値だけを走査 value - for value in hmap.values(): - print(value) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* ハッシュテーブルを走査 */ - // キーと値のペアを走査 key->value - for (auto kv: map) { - cout << kv.first << " -> " << kv.second << endl; - } - // イテレータで走査 key->value - for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; - } - ``` - -=== "Java" - - ```java title="hash_map.java" - /* ハッシュテーブルを走査 */ - // キーと値のペアを走査 key->value - for (Map.Entry kv: map.entrySet()) { - System.out.println(kv.getKey() + " -> " + kv.getValue()); - } - // キーだけを走査 key - for (int key: map.keySet()) { - System.out.println(key); - } - // 値だけを走査 value - for (String val: map.values()) { - System.out.println(val); - } - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* ハッシュテーブルを走査 */ - // キーと値のペアを走査 Key->Value - foreach (var kv in map) { - Console.WriteLine(kv.Key + " -> " + kv.Value); - } - // キーだけを走査 key - foreach (int key in map.Keys) { - Console.WriteLine(key); - } - // 値だけを走査 value - foreach (string val in map.Values) { - Console.WriteLine(val); - } - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* ハッシュテーブルを走査 */ - // キーと値のペアを走査 key->value - for key, value := range hmap { - fmt.Println(key, "->", value) - } - // キーだけを走査 key - for key := range hmap { - fmt.Println(key) - } - // 値だけを走査 value - for _, value := range hmap { - fmt.Println(value) - } - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* ハッシュテーブルを走査 */ - // キーと値のペアを走査 Key->Value - for (key, value) in map { - print("\(key) -> \(value)") - } - // キーだけを走査 Key - for key in map.keys { - print(key) - } - // 値だけを走査 Value - for value in map.values { - print(value) - } - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* ハッシュテーブルを走査 */ - console.info('\nキーと値のペアを走査 Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\nキーだけを走査 Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\n値だけを走査 Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* ハッシュテーブルを走査 */ - console.info('\nキーと値のペアを走査 Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\nキーだけを走査 Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\n値だけを走査 Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* ハッシュテーブルを走査 */ - // キーと値のペアを走査 Key->Value - map.forEach((key, value) { - print('$key -> $value'); - }); - - // キーだけを走査 Key - map.keys.forEach((key) { - print(key); - }); - - // 値だけを走査 Value - map.values.forEach((value) { - print(value); - }); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - /* ハッシュテーブルを走査 */ - // キーと値のペアを走査 Key->Value - for (key, value) in &map { - println!("{key} -> {value}"); - } - - // キーだけを走査 Key - for key in map.keys() { - println!("{key}"); - } - - // 値だけを走査 Value - for value in map.values() { - println!("{value}"); - } - ``` - -=== "C" - - ```c title="hash_map.c" - // C には組み込みのハッシュテーブルがない - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* ハッシュテーブルを走査 */ - // キーと値のペアを走査 key->value - for ((key, value) in map) { - println("$key -> $value") - } - // キーだけを走査 key - for (key in map.keys) { - println(key) - } - // 値だけを走査 value - for (_val in map.values) { - println(_val) - } - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # ハッシュテーブルを走査 - # キーと値のペアを走査 key->value - hmap.entries.each { |key, value| puts "#{key} -> #{value}" } - - # キーだけを走査 key - hmap.keys.each { |key| puts key } - - # 値だけを走査 value - hmap.values.each { |val| puts val } - ``` +```snippet +hash_map_traversal +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BF%BD%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%81%AB%E3%83%9A%E3%82%A2%20(key%2C%20value)%20%E3%82%92%E8%BF%BD%E5%8A%A0%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E8%B5%B0%E6%9F%BB%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%E3%81%A8%E5%80%A4%E3%81%AE%E3%83%9A%E3%82%A2%E3%82%92%E8%B5%B0%E6%9F%BB%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items()%3A%0A%20%20%20%20%20%20%20%20print(key%2C%20%22-%3E%22%2C%20value)%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%E3%81%A0%E3%81%91%E3%82%92%E8%B5%B0%E6%9F%BB%20key%0A%20%20%20%20for%20key%20in%20hmap.keys()%3A%0A%20%20%20%20%20%20%20%20print(key)%0A%20%20%20%20%23%20%E5%80%A4%E3%81%A0%E3%81%91%E3%82%92%E8%B5%B0%E6%9F%BB%20value%0A%20%20%20%20for%20value%20in%20hmap.values()%3A%0A%20%20%20%20%20%20%20%20print(value)&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_traversal_tutor ## ハッシュテーブルの単純な実装 diff --git a/ja/docs/chapter_heap/heap.md b/ja/docs/chapter_heap/heap.md index 5a12236a8..bc59ee60a 100644 --- a/ja/docs/chapter_heap/heap.md +++ b/ja/docs/chapter_heap/heap.md @@ -35,382 +35,13 @@ ソートで昇順と降順を切り替えるように、`flag` の設定や `Comparator` の変更によって、最小ヒープと最大ヒープを切り替えられます。コードは次のとおりです。 -=== "Python" - - ```python title="heap.py" - # 最小ヒープを初期化 - min_heap, flag = [], 1 - # 最大ヒープを初期化 - max_heap, flag = [], -1 - - # Python の heapq モジュールはデフォルトで最小ヒープを実装する - # 要素の符号を反転してから挿入すると、大小関係が逆転し最大ヒープを実現できる - # この例では flag = 1 が最小ヒープ、flag = -1 が最大ヒープに対応する - - # 要素をヒープに挿入 - heapq.heappush(max_heap, flag * 1) - heapq.heappush(max_heap, flag * 3) - heapq.heappush(max_heap, flag * 2) - heapq.heappush(max_heap, flag * 5) - heapq.heappush(max_heap, flag * 4) - - # ヒープの先頭要素を取得 - peek: int = flag * max_heap[0] # 5 - - # ヒープの先頭要素を取り出す - # 取り出した要素は降順の列になる - val = flag * heapq.heappop(max_heap) # 5 - val = flag * heapq.heappop(max_heap) # 4 - val = flag * heapq.heappop(max_heap) # 3 - val = flag * heapq.heappop(max_heap) # 2 - val = flag * heapq.heappop(max_heap) # 1 - - # ヒープの要素数を取得 - size: int = len(max_heap) - - # ヒープが空かどうかを判定 - is_empty: bool = not max_heap - - # リストを入力してヒープを構築 - min_heap: list[int] = [1, 3, 2, 5, 4] - heapq.heapify(min_heap) - ``` - -=== "C++" - - ```cpp title="heap.cpp" - /* ヒープを初期化 */ - // 最小ヒープを初期化 - priority_queue, greater> minHeap; - // 最大ヒープを初期化 - priority_queue, less> maxHeap; - - /* 要素をヒープに挿入 */ - maxHeap.push(1); - maxHeap.push(3); - maxHeap.push(2); - maxHeap.push(5); - maxHeap.push(4); - - /* ヒープの先頭要素を取得 */ - int peek = maxHeap.top(); // 5 - - /* ヒープの先頭要素を取り出す */ - // 取り出した要素は降順の列になる - maxHeap.pop(); // 5 - maxHeap.pop(); // 4 - maxHeap.pop(); // 3 - maxHeap.pop(); // 2 - maxHeap.pop(); // 1 - - /* ヒープの要素数を取得 */ - int size = maxHeap.size(); - - /* ヒープが空かどうかを判定 */ - bool isEmpty = maxHeap.empty(); - - /* リストを入力してヒープを構築 */ - vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); - ``` - -=== "Java" - - ```java title="heap.java" - /* ヒープを初期化 */ - // 最小ヒープを初期化 - Queue minHeap = new PriorityQueue<>(); - // 最大ヒープを初期化(ラムダ式で Comparator を変更する) - Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); - - /* 要素をヒープに挿入 */ - maxHeap.offer(1); - maxHeap.offer(3); - maxHeap.offer(2); - maxHeap.offer(5); - maxHeap.offer(4); - - /* ヒープの先頭要素を取得 */ - int peek = maxHeap.peek(); // 5 - - /* ヒープの先頭要素を取り出す */ - // 取り出した要素は降順の列になる - peek = maxHeap.poll(); // 5 - peek = maxHeap.poll(); // 4 - peek = maxHeap.poll(); // 3 - peek = maxHeap.poll(); // 2 - peek = maxHeap.poll(); // 1 - - /* ヒープの要素数を取得 */ - int size = maxHeap.size(); - - /* ヒープが空かどうかを判定 */ - boolean isEmpty = maxHeap.isEmpty(); - - /* リストを入力してヒープを構築 */ - minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); - ``` - -=== "C#" - - ```csharp title="heap.cs" - /* ヒープを初期化 */ - // 最小ヒープを初期化 - PriorityQueue minHeap = new(); - // 最大ヒープを初期化(ラムダ式で Comparer を変更する) - PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); - - /* 要素をヒープに挿入 */ - maxHeap.Enqueue(1, 1); - maxHeap.Enqueue(3, 3); - maxHeap.Enqueue(2, 2); - maxHeap.Enqueue(5, 5); - maxHeap.Enqueue(4, 4); - - /* ヒープの先頭要素を取得 */ - int peek = maxHeap.Peek();//5 - - /* ヒープの先頭要素を取り出す */ - // 取り出した要素は降順の列になる - peek = maxHeap.Dequeue(); // 5 - peek = maxHeap.Dequeue(); // 4 - peek = maxHeap.Dequeue(); // 3 - peek = maxHeap.Dequeue(); // 2 - peek = maxHeap.Dequeue(); // 1 - - /* ヒープの要素数を取得 */ - int size = maxHeap.Count; - - /* ヒープが空かどうかを判定 */ - bool isEmpty = maxHeap.Count == 0; - - /* リストを入力してヒープを構築 */ - minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); - ``` - -=== "Go" - - ```go title="heap.go" - // Go では heap.Interface を実装して整数の最大ヒープを構築できる - // heap.Interface の実装には sort.Interface の実装も必要 - type intHeap []any - - // Push は heap.Interface のメソッドで、ヒープへの挿入を実装する - func (h *intHeap) Push(x any) { - // Push と Pop はポインタレシーバーを引数として使う - // スライスの内容だけでなく長さも変更するため - *h = append(*h, x.(int)) - } - - // Pop は heap.Interface のメソッドで、先頭要素の取り出しを実装する - func (h *intHeap) Pop() any { - // 取り出す要素は末尾に格納されている - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last - } - - // Len は sort.Interface のメソッド - func (h *intHeap) Len() int { - return len(*h) - } - - // Less は sort.Interface のメソッド - func (h *intHeap) Less(i, j int) bool { - // 最小ヒープを実装する場合は、小なり記号に変更する - return (*h)[i].(int) > (*h)[j].(int) - } - - // Swap は sort.Interface のメソッド - func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] - } - - // Top ヒープの先頭要素を取得 - func (h *intHeap) Top() any { - return (*h)[0] - } - - /* 実行用コード */ - func TestHeap(t *testing.T) { - /* ヒープを初期化 */ - // 最大ヒープを初期化 - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* 要素をヒープに挿入 */ - // heap.Interface のメソッドを呼んで要素を追加 - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* ヒープの先頭要素を取得 */ - top := maxHeap.Top() - fmt.Printf("ヒープの先頭要素は %d\n", top) - - /* ヒープの先頭要素を取り出す */ - // heap.Interface のメソッドを呼んで要素を削除 - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 - - /* ヒープの要素数を取得 */ - size := len(*maxHeap) - fmt.Printf("ヒープの要素数は %d\n", size) - - /* ヒープが空かどうかを判定 */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("ヒープは空か %t\n", isEmpty) - } - ``` - -=== "Swift" - - ```swift title="heap.swift" - /* ヒープを初期化 */ - // Swift の Heap 型は最大ヒープと最小ヒープの両方に対応し、swift-collections の導入が必要 - var heap = Heap() - - /* 要素をヒープに挿入 */ - heap.insert(1) - heap.insert(3) - heap.insert(2) - heap.insert(5) - heap.insert(4) - - /* ヒープの先頭要素を取得 */ - var peek = heap.max()! - - /* ヒープの先頭要素を取り出す */ - peek = heap.removeMax() // 5 - peek = heap.removeMax() // 4 - peek = heap.removeMax() // 3 - peek = heap.removeMax() // 2 - peek = heap.removeMax() // 1 - - /* ヒープの要素数を取得 */ - let size = heap.count - - /* ヒープが空かどうかを判定 */ - let isEmpty = heap.isEmpty - - /* リストを入力してヒープを構築 */ - let heap2 = Heap([1, 3, 2, 5, 4]) - ``` - -=== "JS" - - ```javascript title="heap.js" - // JavaScript には組み込みの Heap クラスがない - ``` - -=== "TS" - - ```typescript title="heap.ts" - // TypeScript には組み込みの Heap クラスがない - ``` - -=== "Dart" - - ```dart title="heap.dart" - // Dart には組み込みの Heap クラスがない - ``` - -=== "Rust" - - ```rust title="heap.rs" - use std::collections::BinaryHeap; - use std::cmp::Reverse; - - /* ヒープを初期化 */ - // 最小ヒープを初期化 - let mut min_heap = BinaryHeap::>::new(); - // 最大ヒープを初期化 - let mut max_heap = BinaryHeap::new(); - - /* 要素をヒープに挿入 */ - max_heap.push(1); - max_heap.push(3); - max_heap.push(2); - max_heap.push(5); - max_heap.push(4); - - /* ヒープの先頭要素を取得 */ - let peek = max_heap.peek().unwrap(); // 5 - - /* ヒープの先頭要素を取り出す */ - // 取り出した要素は降順の列になる - let peek = max_heap.pop().unwrap(); // 5 - let peek = max_heap.pop().unwrap(); // 4 - let peek = max_heap.pop().unwrap(); // 3 - let peek = max_heap.pop().unwrap(); // 2 - let peek = max_heap.pop().unwrap(); // 1 - - /* ヒープの要素数を取得 */ - let size = max_heap.len(); - - /* ヒープが空かどうかを判定 */ - let is_empty = max_heap.is_empty(); - - /* リストを入力してヒープを構築 */ - let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); - ``` - -=== "C" - - ```c title="heap.c" - // C には組み込みの Heap クラスがない - ``` - -=== "Kotlin" - - ```kotlin title="heap.kt" - /* ヒープを初期化 */ - // 最小ヒープを初期化 - var minHeap = PriorityQueue() - // 最大ヒープを初期化(ラムダ式で Comparator を変更する) - val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } - - /* 要素をヒープに挿入 */ - maxHeap.offer(1) - maxHeap.offer(3) - maxHeap.offer(2) - maxHeap.offer(5) - maxHeap.offer(4) - - /* ヒープの先頭要素を取得 */ - var peek = maxHeap.peek() // 5 - - /* ヒープの先頭要素を取り出す */ - // 取り出した要素は降順の列になる - peek = maxHeap.poll() // 5 - peek = maxHeap.poll() // 4 - peek = maxHeap.poll() // 3 - peek = maxHeap.poll() // 2 - peek = maxHeap.poll() // 1 - - /* ヒープの要素数を取得 */ - val size = maxHeap.size - - /* ヒープが空かどうかを判定 */ - val isEmpty = maxHeap.isEmpty() - - /* リストを入力してヒープを構築 */ - minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) - ``` - -=== "Ruby" - - ```ruby title="heap.rb" - # Ruby には組み込みの Heap クラスがない - ``` +```snippet +heap_operations +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E3%81%AE%20heapq%20%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AF%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88%E3%81%A7%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%AE%9F%E8%A3%85%E3%81%99%E3%82%8B%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AE%E7%AC%A6%E5%8F%B7%E3%82%92%E5%8F%8D%E8%BB%A2%E3%81%97%E3%81%A6%E3%81%8B%E3%82%89%E6%8C%BF%E5%85%A5%E3%81%99%E3%82%8B%E3%81%A8%E3%80%81%E5%A4%A7%E5%B0%8F%E9%96%A2%E4%BF%82%E3%81%8C%E9%80%86%E8%BB%A2%E3%81%97%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%AE%9F%E7%8F%BE%E3%81%A7%E3%81%8D%E3%82%8B%0A%20%20%20%20%23%20%E3%81%93%E3%81%AE%E4%BE%8B%E3%81%A7%E3%81%AF%20flag%20%3D%201%20%E3%81%8C%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%80%81flag%20%3D%20-1%20%E3%81%8C%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%81%AB%E5%AF%BE%E5%BF%9C%E3%81%99%E3%82%8B%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%92%E3%83%BC%E3%83%97%E3%81%AB%E6%8C%BF%E5%85%A5%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%201)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%203)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%202)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%205)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%204)%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20peek%20%3D%20flag%20*%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%99%0A%20%20%20%20%23%20%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%E3%81%AF%E9%99%8D%E9%A0%86%E3%81%AE%E5%88%97%E3%81%AB%E3%81%AA%E3%82%8B%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%205%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%204%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%203%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%202%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E8%A6%81%E7%B4%A0%E6%95%B0%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(max_heap)%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%8C%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%85%A5%E5%8A%9B%E3%81%97%E3%81%A6%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E6%A7%8B%E7%AF%89%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify(min_heap)&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor heap_operations_tutor ## ヒープの実装 diff --git a/ja/docs/chapter_preface/suggestions.md b/ja/docs/chapter_preface/suggestions.md index d3b5a757f..0475e99c3 100644 --- a/ja/docs/chapter_preface/suggestions.md +++ b/ja/docs/chapter_preface/suggestions.md @@ -13,170 +13,9 @@ - 言語によって呼び方が異なる場合、本書では Python に合わせます。例えば、「空」を表すには `None` を使います。 - 本書では、コンパクトなレイアウトを優先し、言語のコメント規約に一部従っていません。コメントは主に、見出しコメント、内容コメント、複数行コメントの三種類に分かれます。 -=== "Python" - - ```python title="" - """見出しコメント:関数、クラス、テストケースなどを示す""" - - # 内容コメント:コードを詳しく説明する - - """ - 複数行の - コメント - """ - ``` - -=== "C++" - - ```cpp title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "Java" - - ```java title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "C#" - - ```csharp title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "Go" - - ```go title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "Swift" - - ```swift title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "JS" - - ```javascript title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "TS" - - ```typescript title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "Dart" - - ```dart title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "Rust" - - ```rust title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - // 複数行の - // コメント - ``` - -=== "C" - - ```c title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 見出しコメント:関数、クラス、テストケースなどを示す */ - - // 内容コメント:コードを詳しく説明する - - /** - * 複数行の - * コメント - */ - ``` - -=== "Ruby" - - ```ruby title="" - ### 見出しコメント:関数、クラス、テストケースなどを示す ### - - # 内容コメント:コードを詳しく説明する - - # 複数行の - # コメント - ``` +```snippet +comment_style +``` ## アニメーション図解で効率よく学ぶ diff --git a/ja/docs/chapter_stack_and_queue/deque.md b/ja/docs/chapter_stack_and_queue/deque.md index a01426931..4483e11e8 100644 --- a/ja/docs/chapter_stack_and_queue/deque.md +++ b/ja/docs/chapter_stack_and_queue/deque.md @@ -21,371 +21,13 @@ 同様に、言語が用意する両端キュークラスをそのまま利用できます。 -=== "Python" - - ```python title="deque.py" - from collections import deque - - # 両端キューを初期化 - deq: deque[int] = deque() - - # 要素をエンキュー - deq.append(2) # 末尾に追加 - deq.append(5) - deq.append(4) - deq.appendleft(3) # 先頭に追加 - deq.appendleft(1) - - # 要素にアクセス - front: int = deq[0] # 先頭要素 - rear: int = deq[-1] # 末尾要素 - - # 要素をデキュー - pop_front: int = deq.popleft() # 先頭要素を取り出す - pop_rear: int = deq.pop() # 末尾要素を取り出す - - # 両端キューの長さを取得 - size: int = len(deq) - - # 両端キューが空かどうかを判定 - is_empty: bool = len(deq) == 0 - ``` - -=== "C++" - - ```cpp title="deque.cpp" - /* 両端キューを初期化 */ - deque deque; - - /* 要素をエンキュー */ - deque.push_back(2); // 末尾に追加 - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // 先頭に追加 - deque.push_front(1); - - /* 要素にアクセス */ - int front = deque.front(); // 先頭要素 - int back = deque.back(); // 末尾要素 - - /* 要素をデキュー */ - deque.pop_front(); // 先頭要素を取り出す - deque.pop_back(); // 末尾要素を取り出す - - /* 両端キューの長さを取得 */ - int size = deque.size(); - - /* 両端キューが空かどうかを判定 */ - bool empty = deque.empty(); - ``` - -=== "Java" - - ```java title="deque.java" - /* 両端キューを初期化 */ - Deque deque = new LinkedList<>(); - - /* 要素をエンキュー */ - deque.offerLast(2); // 末尾に追加 - deque.offerLast(5); - deque.offerLast(4); - deque.offerFirst(3); // 先頭に追加 - deque.offerFirst(1); - - /* 要素にアクセス */ - int peekFirst = deque.peekFirst(); // 先頭要素 - int peekLast = deque.peekLast(); // 末尾要素 - - /* 要素をデキュー */ - int popFirst = deque.pollFirst(); // 先頭要素を取り出す - int popLast = deque.pollLast(); // 末尾要素を取り出す - - /* 両端キューの長さを取得 */ - int size = deque.size(); - - /* 両端キューが空かどうかを判定 */ - boolean isEmpty = deque.isEmpty(); - ``` - -=== "C#" - - ```csharp title="deque.cs" - /* 両端キューを初期化 */ - // C# では LinkedList を両端キューとして使う - LinkedList deque = new(); - - /* 要素をエンキュー */ - deque.AddLast(2); // 末尾に追加 - deque.AddLast(5); - deque.AddLast(4); - deque.AddFirst(3); // 先頭に追加 - deque.AddFirst(1); - - /* 要素にアクセス */ - int peekFirst = deque.First.Value; // 先頭要素 - int peekLast = deque.Last.Value; // 末尾要素 - - /* 要素をデキュー */ - deque.RemoveFirst(); // 先頭要素を取り出す - deque.RemoveLast(); // 末尾要素を取り出す - - /* 両端キューの長さを取得 */ - int size = deque.Count; - - /* 両端キューが空かどうかを判定 */ - bool isEmpty = deque.Count == 0; - ``` - -=== "Go" - - ```go title="deque_test.go" - /* 両端キューを初期化 */ - // Go では list を両端キューとして使う - deque := list.New() - - /* 要素をエンキュー */ - deque.PushBack(2) // 末尾に追加 - deque.PushBack(5) - deque.PushBack(4) - deque.PushFront(3) // 先頭に追加 - deque.PushFront(1) - - /* 要素にアクセス */ - front := deque.Front() // 先頭要素 - rear := deque.Back() // 末尾要素 - - /* 要素をデキュー */ - deque.Remove(front) // 先頭要素を取り出す - deque.Remove(rear) // 末尾要素を取り出す - - /* 両端キューの長さを取得 */ - size := deque.Len() - - /* 両端キューが空かどうかを判定 */ - isEmpty := deque.Len() == 0 - ``` - -=== "Swift" - - ```swift title="deque.swift" - /* 両端キューを初期化 */ - // Swift には組み込みの両端キュークラスがないため、Array を両端キューとして使える - var deque: [Int] = [] - - /* 要素をエンキュー */ - deque.append(2) // 末尾に追加 - deque.append(5) - deque.append(4) - deque.insert(3, at: 0) // 先頭に追加 - deque.insert(1, at: 0) - - /* 要素にアクセス */ - let peekFirst = deque.first! // 先頭要素 - let peekLast = deque.last! // 末尾要素 - - /* 要素をデキュー */ - // Array で代用する場合、popFirst の計算量は O(n) - let popFirst = deque.removeFirst() // 先頭要素を取り出す - let popLast = deque.removeLast() // 末尾要素を取り出す - - /* 両端キューの長さを取得 */ - let size = deque.count - - /* 両端キューが空かどうかを判定 */ - let isEmpty = deque.isEmpty - ``` - -=== "JS" - - ```javascript title="deque.js" - /* 両端キューを初期化 */ - // JavaScript には組み込みの両端キューがないため、Array で代用する必要がある - const deque = []; - - /* 要素をエンキュー */ - deque.push(2); - deque.push(5); - deque.push(4); - // 配列なので unshift() の時間計算量は O(n) であることに注意 - deque.unshift(3); - deque.unshift(1); - - /* 要素にアクセス */ - const peekFirst = deque[0]; - const peekLast = deque[deque.length - 1]; - - /* 要素をデキュー */ - // 配列なので shift() の時間計算量は O(n) であることに注意 - const popFront = deque.shift(); - const popBack = deque.pop(); - - /* 両端キューの長さを取得 */ - const size = deque.length; - - /* 両端キューが空かどうかを判定 */ - const isEmpty = size === 0; - ``` - -=== "TS" - - ```typescript title="deque.ts" - /* 両端キューを初期化 */ - // TypeScript には組み込みの両端キューがないため、Array で代用する必要がある - const deque: number[] = []; - - /* 要素をエンキュー */ - deque.push(2); - deque.push(5); - deque.push(4); - // 配列なので unshift() の時間計算量は O(n) であることに注意 - deque.unshift(3); - deque.unshift(1); - - /* 要素にアクセス */ - const peekFirst: number = deque[0]; - const peekLast: number = deque[deque.length - 1]; - - /* 要素をデキュー */ - // 配列なので shift() の時間計算量は O(n) であることに注意 - const popFront: number = deque.shift() as number; - const popBack: number = deque.pop() as number; - - /* 両端キューの長さを取得 */ - const size: number = deque.length; - - /* 両端キューが空かどうかを判定 */ - const isEmpty: boolean = size === 0; - ``` - -=== "Dart" - - ```dart title="deque.dart" - /* 両端キューを初期化 */ - // Dart では Queue は両端キューとして定義されている - Queue deque = Queue(); - - /* 要素をエンキュー */ - deque.addLast(2); // 末尾に追加 - deque.addLast(5); - deque.addLast(4); - deque.addFirst(3); // 先頭に追加 - deque.addFirst(1); - - /* 要素にアクセス */ - int peekFirst = deque.first; // 先頭要素 - int peekLast = deque.last; // 末尾要素 - - /* 要素をデキュー */ - int popFirst = deque.removeFirst(); // 先頭要素を取り出す - int popLast = deque.removeLast(); // 末尾要素を取り出す - - /* 両端キューの長さを取得 */ - int size = deque.length; - - /* 両端キューが空かどうかを判定 */ - bool isEmpty = deque.isEmpty; - ``` - -=== "Rust" - - ```rust title="deque.rs" - /* 両端キューを初期化 */ - let mut deque: VecDeque = VecDeque::new(); - - /* 要素をエンキュー */ - deque.push_back(2); // 末尾に追加 - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // 先頭に追加 - deque.push_front(1); - - /* 要素にアクセス */ - if let Some(front) = deque.front() { // 先頭要素 - } - if let Some(rear) = deque.back() { // 末尾要素 - } - - /* 要素をデキュー */ - if let Some(pop_front) = deque.pop_front() { // 先頭要素を取り出す - } - if let Some(pop_rear) = deque.pop_back() { // 末尾要素を取り出す - } - - /* 両端キューの長さを取得 */ - let size = deque.len(); - - /* 両端キューが空かどうかを判定 */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="deque.c" - // C には組み込みの両端キューがない - ``` - -=== "Kotlin" - - ```kotlin title="deque.kt" - /* 両端キューを初期化 */ - val deque = LinkedList() - - /* 要素をエンキュー */ - deque.offerLast(2) // 末尾に追加 - deque.offerLast(5) - deque.offerLast(4) - deque.offerFirst(3) // 先頭に追加 - deque.offerFirst(1) - - /* 要素にアクセス */ - val peekFirst = deque.peekFirst() // 先頭要素 - val peekLast = deque.peekLast() // 末尾要素 - - /* 要素をデキュー */ - val popFirst = deque.pollFirst() // 先頭要素を取り出す - val popLast = deque.pollLast() // 末尾要素を取り出す - - /* 両端キューの長さを取得 */ - val size = deque.size - - /* 両端キューが空かどうかを判定 */ - val isEmpty = deque.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="deque.rb" - # 両端キューを初期化 - # Ruby には組み込みの両端キューがないため、Array で代用する必要がある - deque = [] - - # 要素をエンキュー - deque << 2 - deque << 5 - deque << 4 - # 配列なので Array#unshift の時間計算量は O(n) であることに注意 - deque.unshift(3) - deque.unshift(1) - - # 要素にアクセス - peek_first = deque.first - peek_last = deque.last - - # 要素をデキュー - # 配列なので Array#shift の時間計算量は O(n) であることに注意 - pop_front = deque.shift - pop_back = deque.pop - - # 両端キューの長さを取得 - size = deque.length - - # 両端キューが空かどうかを判定 - is_empty = size.zero? - ``` +```snippet +deque_operations +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20deq%20%3D%20deque()%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%82%A8%E3%83%B3%E3%82%AD%E3%83%A5%E3%83%BC%0A%20%20%20%20deq.append(2)%20%20%23%20%E6%9C%AB%E5%B0%BE%E3%81%AB%E8%BF%BD%E5%8A%A0%0A%20%20%20%20deq.append(5)%0A%20%20%20%20deq.append(4)%0A%20%20%20%20deq.appendleft(3)%20%20%23%20%E5%85%88%E9%A0%AD%E3%81%AB%E8%BF%BD%E5%8A%A0%0A%20%20%20%20deq.appendleft(1)%0A%20%20%20%20print(%22%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%20deque%20%3D%22%2C%20deq)%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%0A%20%20%20%20print(%22%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%20front%20%3D%22%2C%20front)%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%E6%9C%AB%E5%B0%BE%E8%A6%81%E7%B4%A0%0A%20%20%20%20print(%22%E6%9C%AB%E5%B0%BE%E8%A6%81%E7%B4%A0%20rear%20%3D%22%2C%20rear)%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%87%E3%82%AD%E3%83%A5%E3%83%BC%0A%20%20%20%20pop_front%20%3D%20deq.popleft()%20%20%23%20%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%99%0A%20%20%20%20print(%22%E5%85%88%E9%A0%AD%E3%81%8B%E3%82%89%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%20%20pop_front%20%3D%22%2C%20pop_front)%0A%20%20%20%20print(%22%E5%85%88%E9%A0%AD%E3%81%8B%E3%82%89%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E5%BE%8C%E3%81%AE%20deque%20%3D%22%2C%20deq)%0A%20%20%20%20pop_rear%20%3D%20deq.pop()%20%20%23%20%E6%9C%AB%E5%B0%BE%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%99%0A%20%20%20%20print(%22%E6%9C%AB%E5%B0%BE%E3%81%8B%E3%82%89%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%20%20pop_rear%20%3D%22%2C%20pop_rear)%0A%20%20%20%20print(%22%E6%9C%AB%E5%B0%BE%E3%81%8B%E3%82%89%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E5%BE%8C%E3%81%AE%20deque%20%3D%22%2C%20deq)%0A%0A%20%20%20%20%23%20%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AE%E9%95%B7%E3%81%95%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(deq)%0A%20%20%20%20print(%22%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AE%E9%95%B7%E3%81%95%20size%20%3D%22%2C%20size)%0A%0A%20%20%20%20%23%20%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%8C%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20len(deq)%20%3D%3D%200%0A%20%20%20%20print(%22%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AF%E7%A9%BA%E3%81%8B%20%3D%22%2C%20is_empty)&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor deque_operations_tutor ## 両端キューの実装 * diff --git a/ja/docs/chapter_stack_and_queue/queue.md b/ja/docs/chapter_stack_and_queue/queue.md index e21928003..bd975f001 100644 --- a/ja/docs/chapter_stack_and_queue/queue.md +++ b/ja/docs/chapter_stack_and_queue/queue.md @@ -20,345 +20,13 @@ 言語が用意するキュークラスを、そのまま利用できます。 -=== "Python" - - ```python title="queue.py" - from collections import deque - - # キューを初期化 - # Python では通常、両端キュークラス deque をキューとして使う - # queue.Queue() は本来のキュークラスだが、使いにくいため推奨しない - que: deque[int] = deque() - - # 要素をエンキュー - que.append(1) - que.append(3) - que.append(2) - que.append(5) - que.append(4) - - # 先頭要素にアクセス - front: int = que[0] - - # 要素をデキュー - pop: int = que.popleft() - - # キューの長さを取得 - size: int = len(que) - - # キューが空かどうかを判定 - is_empty: bool = len(que) == 0 - ``` - -=== "C++" - - ```cpp title="queue.cpp" - /* キューを初期化 */ - queue queue; - - /* 要素をエンキュー */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 先頭要素にアクセス */ - int front = queue.front(); - - /* 要素をデキュー */ - queue.pop(); - - /* キューの長さを取得 */ - int size = queue.size(); - - /* キューが空かどうかを判定 */ - bool empty = queue.empty(); - ``` - -=== "Java" - - ```java title="queue.java" - /* キューを初期化 */ - Queue queue = new LinkedList<>(); - - /* 要素をエンキュー */ - queue.offer(1); - queue.offer(3); - queue.offer(2); - queue.offer(5); - queue.offer(4); - - /* 先頭要素にアクセス */ - int peek = queue.peek(); - - /* 要素をデキュー */ - int pop = queue.poll(); - - /* キューの長さを取得 */ - int size = queue.size(); - - /* キューが空かどうかを判定 */ - boolean isEmpty = queue.isEmpty(); - ``` - -=== "C#" - - ```csharp title="queue.cs" - /* キューを初期化 */ - Queue queue = new(); - - /* 要素をエンキュー */ - queue.Enqueue(1); - queue.Enqueue(3); - queue.Enqueue(2); - queue.Enqueue(5); - queue.Enqueue(4); - - /* 先頭要素にアクセス */ - int peek = queue.Peek(); - - /* 要素をデキュー */ - int pop = queue.Dequeue(); - - /* キューの長さを取得 */ - int size = queue.Count; - - /* キューが空かどうかを判定 */ - bool isEmpty = queue.Count == 0; - ``` - -=== "Go" - - ```go title="queue_test.go" - /* キューを初期化 */ - // Go では list をキューとして使う - queue := list.New() - - /* 要素をエンキュー */ - queue.PushBack(1) - queue.PushBack(3) - queue.PushBack(2) - queue.PushBack(5) - queue.PushBack(4) - - /* 先頭要素にアクセス */ - peek := queue.Front() - - /* 要素をデキュー */ - pop := queue.Front() - queue.Remove(pop) - - /* キューの長さを取得 */ - size := queue.Len() - - /* キューが空かどうかを判定 */ - isEmpty := queue.Len() == 0 - ``` - -=== "Swift" - - ```swift title="queue.swift" - /* キューを初期化 */ - // Swift には組み込みのキュークラスがないため、Array をキューとして使える - var queue: [Int] = [] - - /* 要素をエンキュー */ - queue.append(1) - queue.append(3) - queue.append(2) - queue.append(5) - queue.append(4) - - /* 先頭要素にアクセス */ - let peek = queue.first! - - /* 要素をデキュー */ - // 配列なので removeFirst の計算量は O(n) - let pop = queue.removeFirst() - - /* キューの長さを取得 */ - let size = queue.count - - /* キューが空かどうかを判定 */ - let isEmpty = queue.isEmpty - ``` - -=== "JS" - - ```javascript title="queue.js" - /* キューを初期化 */ - // JavaScript には組み込みのキューがないため、Array をキューとして使える - const queue = []; - - /* 要素をエンキュー */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 先頭要素にアクセス */ - const peek = queue[0]; - - /* 要素をデキュー */ - // 内部が配列なので shift() の時間計算量は O(n) - const pop = queue.shift(); - - /* キューの長さを取得 */ - const size = queue.length; - - /* キューが空かどうかを判定 */ - const empty = queue.length === 0; - ``` - -=== "TS" - - ```typescript title="queue.ts" - /* キューを初期化 */ - // TypeScript には組み込みのキューがないため、Array をキューとして使える - const queue: number[] = []; - - /* 要素をエンキュー */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 先頭要素にアクセス */ - const peek = queue[0]; - - /* 要素をデキュー */ - // 内部が配列なので shift() の時間計算量は O(n) - const pop = queue.shift(); - - /* キューの長さを取得 */ - const size = queue.length; - - /* キューが空かどうかを判定 */ - const empty = queue.length === 0; - ``` - -=== "Dart" - - ```dart title="queue.dart" - /* キューを初期化 */ - // Dart の Queue は両端キューであり、通常のキューとしても使える - Queue queue = Queue(); - - /* 要素をエンキュー */ - queue.add(1); - queue.add(3); - queue.add(2); - queue.add(5); - queue.add(4); - - /* 先頭要素にアクセス */ - int peek = queue.first; - - /* 要素をデキュー */ - int pop = queue.removeFirst(); - - /* キューの長さを取得 */ - int size = queue.length; - - /* キューが空かどうかを判定 */ - bool isEmpty = queue.isEmpty; - ``` - -=== "Rust" - - ```rust title="queue.rs" - /* 両端キューを初期化 */ - // Rust では両端キューを通常のキューとして使う - let mut deque: VecDeque = VecDeque::new(); - - /* 要素をエンキュー */ - deque.push_back(1); - deque.push_back(3); - deque.push_back(2); - deque.push_back(5); - deque.push_back(4); - - /* 先頭要素にアクセス */ - if let Some(front) = deque.front() { - } - - /* 要素をデキュー */ - if let Some(pop) = deque.pop_front() { - } - - /* キューの長さを取得 */ - let size = deque.len(); - - /* キューが空かどうかを判定 */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="queue.c" - // C には組み込みのキューがない - ``` - -=== "Kotlin" - - ```kotlin title="queue.kt" - /* キューを初期化 */ - val queue = LinkedList() - - /* 要素をエンキュー */ - queue.offer(1) - queue.offer(3) - queue.offer(2) - queue.offer(5) - queue.offer(4) - - /* 先頭要素にアクセス */ - val peek = queue.peek() - - /* 要素をデキュー */ - val pop = queue.poll() - - /* キューの長さを取得 */ - val size = queue.size - - /* キューが空かどうかを判定 */ - val isEmpty = queue.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="queue.rb" - # キューを初期化 - # Ruby の組み込みキュー(Thread::Queue)には peek や走査のメソッドがないため、Array をキューとして使える - queue = [] - - # 要素をエンキュー - queue.push(1) - queue.push(3) - queue.push(2) - queue.push(5) - queue.push(4) - - # キューの要素にアクセス - peek = queue.first - - # 要素をデキュー - # 配列なので Array#shift の時間計算量は O(n) であることに注意 - pop = queue.shift - - # キューの長さを取得 - size = queue.length - - # キューが空かどうかを判定 - is_empty = queue.empty? - ``` +```snippet +queue_operations +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%82%AD%E3%83%A5%E3%83%BC%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20Python%20%E3%81%A7%E3%81%AF%E9%80%9A%E5%B8%B8%E3%80%81%E4%B8%A1%E7%AB%AF%E3%82%AD%E3%83%A5%E3%83%BC%E3%82%AF%E3%83%A9%E3%82%B9%20deque%20%E3%82%92%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%A8%E3%81%97%E3%81%A6%E4%BD%BF%E3%81%86%0A%20%20%20%20%23%20queue.Queue()%20%E3%81%AF%E6%9C%AC%E6%9D%A5%E3%81%AE%E3%82%AD%E3%83%A5%E3%83%BC%E3%82%AF%E3%83%A9%E3%82%B9%E3%81%A0%E3%81%8C%E3%80%81%E4%BD%BF%E3%81%84%E3%81%AB%E3%81%8F%E3%81%84%0A%20%20%20%20que%20%3D%20deque()%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%82%A8%E3%83%B3%E3%82%AD%E3%83%A5%E3%83%BC%0A%20%20%20%20que.append(1)%0A%20%20%20%20que.append(3)%0A%20%20%20%20que.append(2)%0A%20%20%20%20que.append(5)%0A%20%20%20%20que.append(4)%0A%20%20%20%20print(%22%E3%82%AD%E3%83%A5%E3%83%BC%20que%20%3D%22%2C%20que)%0A%0A%20%20%20%20%23%20%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print(%22%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%20front%20%3D%22%2C%20front)%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%87%E3%82%AD%E3%83%A5%E3%83%BC%0A%20%20%20%20pop%20%3D%20que.popleft()%0A%20%20%20%20print(%22%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%20pop%20%3D%22%2C%20pop)%0A%20%20%20%20print(%22%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E5%BE%8C%E3%81%AE%20que%20%3D%22%2C%20que)%0A%0A%20%20%20%20%23%20%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AE%E9%95%B7%E3%81%95%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(que)%0A%20%20%20%20print(%22%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AE%E9%95%B7%E3%81%95%20size%20%3D%22%2C%20size)%0A%0A%20%20%20%20%23%20%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%8C%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20len(que)%20%3D%3D%200%0A%20%20%20%20print(%22%E3%82%AD%E3%83%A5%E3%83%BC%E3%81%AF%E7%A9%BA%E3%81%8B%20%3D%22%2C%20is_empty)&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor queue_operations_tutor ## キューの実装 diff --git a/ja/docs/chapter_stack_and_queue/stack.md b/ja/docs/chapter_stack_and_queue/stack.md index bbb2aea1f..812bb9b07 100644 --- a/ja/docs/chapter_stack_and_queue/stack.md +++ b/ja/docs/chapter_stack_and_queue/stack.md @@ -22,336 +22,13 @@ 通常は、言語に組み込まれたスタッククラスをそのまま使えます。専用クラスがない言語では、配列や連結リストをスタックとして使い、スタックに関係しない操作をプログラムの論理上使わないようにします。 -=== "Python" - - ```python title="stack.py" - # スタックを初期化 - # Python には組み込みのスタッククラスがないため、list をスタックとして使える - stack: list[int] = [] - - # 要素をプッシュ - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - # スタックの先頭要素にアクセス - peek: int = stack[-1] - - # 要素をポップ - pop: int = stack.pop() - - # スタックの長さを取得 - size: int = len(stack) - - # 空かどうかを判定 - is_empty: bool = len(stack) == 0 - ``` - -=== "C++" - - ```cpp title="stack.cpp" - /* スタックを初期化 */ - stack stack; - - /* 要素をプッシュ */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* スタックの先頭要素にアクセス */ - int top = stack.top(); - - /* 要素をポップ */ - stack.pop(); // 戻り値なし - - /* スタックの長さを取得 */ - int size = stack.size(); - - /* 空かどうかを判定 */ - bool empty = stack.empty(); - ``` - -=== "Java" - - ```java title="stack.java" - /* スタックを初期化 */ - Stack stack = new Stack<>(); - - /* 要素をプッシュ */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* スタックの先頭要素にアクセス */ - int peek = stack.peek(); - - /* 要素をポップ */ - int pop = stack.pop(); - - /* スタックの長さを取得 */ - int size = stack.size(); - - /* 空かどうかを判定 */ - boolean isEmpty = stack.isEmpty(); - ``` - -=== "C#" - - ```csharp title="stack.cs" - /* スタックを初期化 */ - Stack stack = new(); - - /* 要素をプッシュ */ - stack.Push(1); - stack.Push(3); - stack.Push(2); - stack.Push(5); - stack.Push(4); - - /* スタックの先頭要素にアクセス */ - int peek = stack.Peek(); - - /* 要素をポップ */ - int pop = stack.Pop(); - - /* スタックの長さを取得 */ - int size = stack.Count; - - /* 空かどうかを判定 */ - bool isEmpty = stack.Count == 0; - ``` - -=== "Go" - - ```go title="stack_test.go" - /* スタックを初期化 */ - // Go では Slice をスタックとして使うことを推奨 - var stack []int - - /* 要素をプッシュ */ - stack = append(stack, 1) - stack = append(stack, 3) - stack = append(stack, 2) - stack = append(stack, 5) - stack = append(stack, 4) - - /* スタックの先頭要素にアクセス */ - peek := stack[len(stack)-1] - - /* 要素をポップ */ - pop := stack[len(stack)-1] - stack = stack[:len(stack)-1] - - /* スタックの長さを取得 */ - size := len(stack) - - /* 空かどうかを判定 */ - isEmpty := len(stack) == 0 - ``` - -=== "Swift" - - ```swift title="stack.swift" - /* スタックを初期化 */ - // Swift には組み込みのスタッククラスがないため、Array をスタックとして使える - var stack: [Int] = [] - - /* 要素をプッシュ */ - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - /* スタックの先頭要素にアクセス */ - let peek = stack.last! - - /* 要素をポップ */ - let pop = stack.removeLast() - - /* スタックの長さを取得 */ - let size = stack.count - - /* 空かどうかを判定 */ - let isEmpty = stack.isEmpty - ``` - -=== "JS" - - ```javascript title="stack.js" - /* スタックを初期化 */ - // JavaScript には組み込みのスタッククラスがないため、Array をスタックとして使える - const stack = []; - - /* 要素をプッシュ */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* スタックの先頭要素にアクセス */ - const peek = stack[stack.length-1]; - - /* 要素をポップ */ - const pop = stack.pop(); - - /* スタックの長さを取得 */ - const size = stack.length; - - /* 空かどうかを判定 */ - const is_empty = stack.length === 0; - ``` - -=== "TS" - - ```typescript title="stack.ts" - /* スタックを初期化 */ - // TypeScript には組み込みのスタッククラスがないため、Array をスタックとして使える - const stack: number[] = []; - - /* 要素をプッシュ */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* スタックの先頭要素にアクセス */ - const peek = stack[stack.length - 1]; - - /* 要素をポップ */ - const pop = stack.pop(); - - /* スタックの長さを取得 */ - const size = stack.length; - - /* 空かどうかを判定 */ - const is_empty = stack.length === 0; - ``` - -=== "Dart" - - ```dart title="stack.dart" - /* スタックを初期化 */ - // Dart には組み込みのスタッククラスがないため、List をスタックとして使える - List stack = []; - - /* 要素をプッシュ */ - stack.add(1); - stack.add(3); - stack.add(2); - stack.add(5); - stack.add(4); - - /* スタックの先頭要素にアクセス */ - int peek = stack.last; - - /* 要素をポップ */ - int pop = stack.removeLast(); - - /* スタックの長さを取得 */ - int size = stack.length; - - /* 空かどうかを判定 */ - bool isEmpty = stack.isEmpty; - ``` - -=== "Rust" - - ```rust title="stack.rs" - /* スタックを初期化 */ - // Vec をスタックとして使う - let mut stack: Vec = Vec::new(); - - /* 要素をプッシュ */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* スタックの先頭要素にアクセス */ - let top = stack.last().unwrap(); - - /* 要素をポップ */ - let pop = stack.pop().unwrap(); - - /* スタックの長さを取得 */ - let size = stack.len(); - - /* 空かどうかを判定 */ - let is_empty = stack.is_empty(); - ``` - -=== "C" - - ```c title="stack.c" - // C には組み込みのスタックがない - ``` - -=== "Kotlin" - - ```kotlin title="stack.kt" - /* スタックを初期化 */ - val stack = Stack() - - /* 要素をプッシュ */ - stack.push(1) - stack.push(3) - stack.push(2) - stack.push(5) - stack.push(4) - - /* スタックの先頭要素にアクセス */ - val peek = stack.peek() - - /* 要素をポップ */ - val pop = stack.pop() - - /* スタックの長さを取得 */ - val size = stack.size - - /* 空かどうかを判定 */ - val isEmpty = stack.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="stack.rb" - # スタックを初期化 - # Ruby には組み込みのスタッククラスがないため、Array をスタックとして使える - stack = [] - - # 要素をプッシュ - stack << 1 - stack << 3 - stack << 2 - stack << 5 - stack << 4 - - # スタックの先頭要素にアクセス - peek = stack.last - - # 要素をポップ - pop = stack.pop - - # スタックの長さを取得 - size = stack.length - - # 空かどうかを判定 - is_empty = stack.empty? - ``` +```snippet +stack_operations +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20Python%20%E3%81%AB%E3%81%AF%E7%B5%84%E3%81%BF%E8%BE%BC%E3%81%BF%E3%81%AE%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%82%AF%E3%83%A9%E3%82%B9%E3%81%8C%E3%81%AA%E3%81%84%E3%81%9F%E3%82%81%E3%80%81list%20%E3%82%92%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%A8%E3%81%97%E3%81%A6%E4%BD%BF%E3%81%88%E3%82%8B%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%97%E3%83%83%E3%82%B7%E3%83%A5%0A%20%20%20%20stack.append(1)%0A%20%20%20%20stack.append(3)%0A%20%20%20%20stack.append(2)%0A%20%20%20%20stack.append(5)%0A%20%20%20%20stack.append(4)%0A%20%20%20%20print(%22%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%20stack%20%3D%22%2C%20stack)%0A%0A%20%20%20%20%23%20%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print(%22%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%20peek%20%3D%22%2C%20peek)%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%9D%E3%83%83%E3%83%97%0A%20%20%20%20pop%20%3D%20stack.pop()%0A%20%20%20%20print(%22%E3%83%9D%E3%83%83%E3%83%97%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%20pop%20%3D%22%2C%20pop)%0A%20%20%20%20print(%22%E3%83%9D%E3%83%83%E3%83%97%E3%81%97%E3%81%9F%E5%BE%8C%E3%81%AE%20stack%20%3D%22%2C%20stack)%0A%0A%20%20%20%20%23%20%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AE%E9%95%B7%E3%81%95%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(stack)%0A%20%20%20%20print(%22%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AE%E9%95%B7%E3%81%95%20size%20%3D%22%2C%20size)%0A%0A%20%20%20%20%23%20%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20len(stack)%20%3D%3D%200%0A%20%20%20%20print(%22%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF%E3%81%AF%E7%A9%BA%E3%81%8B%20%3D%22%2C%20is_empty)&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor stack_operations_tutor ## スタックの実装 diff --git a/ja/docs/chapter_tree/array_representation_of_tree.md b/ja/docs/chapter_tree/array_representation_of_tree.md index 4686c1b08..10ca20a17 100644 --- a/ja/docs/chapter_tree/array_representation_of_tree.md +++ b/ja/docs/chapter_tree/array_representation_of_tree.md @@ -24,109 +24,9 @@ 解決するには、**レベル順の列にすべての `None` を明示的に書き込みます**。下図のように、これで二分木を一意に表せます。コード例を示します。 -=== "Python" - - ```python title="" - # 二分木の配列表現 - # None で空の位置を表す - tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] - ``` - -=== "C++" - - ```cpp title="" - /* 二分木の配列表現 */ - // int の最大値 INT_MAX で空の位置を示す - vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Java" - - ```java title="" - /* 二分木の配列表現 */ - // int のラッパークラス Integer を使うと、null で空の位置を示せる - Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; - ``` - -=== "C#" - - ```csharp title="" - /* 二分木の配列表現 */ - // null 許容型 int? を使うと、null で空の位置を示せる - int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Go" - - ```go title="" - /* 二分木の配列表現 */ - // any 型のスライスを使うと、nil で空の位置を示せる - tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} - ``` - -=== "Swift" - - ```swift title="" - /* 二分木の配列表現 */ - // オプショナル型 Int? を使うと、nil で空の位置を示せる - let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` - -=== "JS" - - ```javascript title="" - /* 二分木の配列表現 */ - // null で空の位置を表す - let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "TS" - - ```typescript title="" - /* 二分木の配列表現 */ - // null で空の位置を表す - let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Dart" - - ```dart title="" - /* 二分木の配列表現 */ - // null 許容型 int? を使うと、null で空の位置を示せる - List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Rust" - - ```rust title="" - /* 二分木の配列表現 */ - // None で空の位置を示す - let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; - ``` - -=== "C" - - ```c title="" - /* 二分木の配列表現 */ - // int の最大値で空の位置を示すため、ノードの値に INT_MAX は使えない - int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 二分木の配列表現 */ - // null で空の位置を表す - val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) - ``` - -=== "Ruby" - - ```ruby title="" - ### 二分木の配列表現 ### - # nil で空の位置を表す - tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` +```snippet +tree_array_representation +``` ![任意の二分木の配列表現](array_representation_of_tree.assets/array_representation_with_empty.svg) diff --git a/ja/docs/chapter_tree/avl_tree.md b/ja/docs/chapter_tree/avl_tree.md index 14feed078..c0387082e 100644 --- a/ja/docs/chapter_tree/avl_tree.md +++ b/ja/docs/chapter_tree/avl_tree.md @@ -20,213 +20,9 @@ AVL 木は二分探索木であると同時に平衡二分木でもあり、両 AVL 木の操作ではノードの高さが必要なので、ノードクラスに変数 `height` を追加します。 -=== "Python" - - ```python title="" - class TreeNode: - """AVL 木のノードクラス""" - def __init__(self, val: int): - self.val: int = val # ノードの値 - self.height: int = 0 # ノードの高さ - self.left: TreeNode | None = None # 左の子への参照 - self.right: TreeNode | None = None # 右の子への参照 - ``` - -=== "C++" - - ```cpp title="" - /* AVL 木のノードクラス */ - struct TreeNode { - int val{}; // ノードの値 - int height = 0; // ノードの高さ - TreeNode *left{}; // 左の子 - TreeNode *right{}; // 右の子 - TreeNode() = default; - explicit TreeNode(int x) : val(x){} - }; - ``` - -=== "Java" - - ```java title="" - /* AVL 木のノードクラス */ - class TreeNode { - public int val; // ノードの値 - public int height; // ノードの高さ - public TreeNode left; // 左の子 - public TreeNode right; // 右の子 - public TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* AVL 木のノードクラス */ - class TreeNode(int? x) { - public int? val = x; // ノードの値 - public int height; // ノードの高さ - public TreeNode? left; // 左の子への参照 - public TreeNode? right; // 右の子への参照 - } - ``` - -=== "Go" - - ```go title="" - /* AVL 木のノード構造体 */ - type TreeNode struct { - Val int // ノードの値 - Height int // ノードの高さ - Left *TreeNode // 左の子への参照 - Right *TreeNode // 右の子への参照 - } - ``` - -=== "Swift" - - ```swift title="" - /* AVL 木のノードクラス */ - class TreeNode { - var val: Int // ノードの値 - var height: Int // ノードの高さ - var left: TreeNode? // 左の子 - var right: TreeNode? // 右の子 - - init(x: Int) { - val = x - height = 0 - } - } - ``` - -=== "JS" - - ```javascript title="" - /* AVL 木のノードクラス */ - class TreeNode { - val; // ノードの値 - height; //ノードの高さ - left; // 左の子へのポインタ - right; // 右の子へのポインタ - constructor(val, left, right, height) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* AVL 木のノードクラス */ - class TreeNode { - val: number; // ノードの値 - height: number; // ノードの高さ - left: TreeNode | null; // 左の子へのポインタ - right: TreeNode | null; // 右の子へのポインタ - constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "Dart" - - ```dart title="" - /* AVL 木のノードクラス */ - class TreeNode { - int val; // ノードの値 - int height; // ノードの高さ - TreeNode? left; // 左の子 - TreeNode? right; // 右の子 - TreeNode(this.val, [this.height = 0, this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* AVL 木のノード構造体 */ - struct TreeNode { - val: i32, // ノードの値 - height: i32, // ノードの高さ - left: Option>>, // 左の子 - right: Option>>, // 右の子 - } - - impl TreeNode { - /* コンストラクタ */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - height: 0, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* AVL 木のノード構造体 */ - typedef struct TreeNode { - int val; - int height; - struct TreeNode *left; - struct TreeNode *right; - } TreeNode; - - /* コンストラクタ */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* AVL 木のノードクラス */ - class TreeNode(val _val: Int) { // ノードの値 - var height: Int = 0 // ノードの高さ - var left: TreeNode? = null // 左の子 - var right: TreeNode? = null // 右の子 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### AVL 木のノードクラス ### - class TreeNode - attr_accessor :val # ノードの値 - attr_accessor :height # ノードの高さ - attr_accessor :left # 左の子への参照 - attr_accessor :right # 右の子への参照 - - def initialize(val) - @val = val - @height = 0 - end - end - ``` +```snippet +avl_tree_node +``` 「ノードの高さ」は、そのノードから最も遠い葉までの距離、つまり通る辺の数です。葉の高さは $0$、空のノードの高さは $-1$ であることに、特に注意してください。高さの取得と更新を行う二つの補助関数を作ります。 diff --git a/ja/docs/chapter_tree/binary_tree.md b/ja/docs/chapter_tree/binary_tree.md index 34049c4b3..0f9a2c26a 100644 --- a/ja/docs/chapter_tree/binary_tree.md +++ b/ja/docs/chapter_tree/binary_tree.md @@ -2,204 +2,9 @@ 二分木(binary tree)は、「祖先」と「子孫」の派生関係を表す非線形データ構造で、「一つを二つに分ける」という分割統治の論理を体現しています。連結リストと同様、基本単位はノードで、各ノードには値、左の子への参照、右の子への参照が含まれます。 -=== "Python" - - ```python title="" - class TreeNode: - """二分木のノードクラス""" - def __init__(self, val: int): - self.val: int = val # ノードの値 - self.left: TreeNode | None = None # 左の子への参照 - self.right: TreeNode | None = None # 右の子への参照 - ``` - -=== "C++" - - ```cpp title="" - /* 二分木のノード構造体 */ - struct TreeNode { - int val; // ノードの値 - TreeNode *left; // 左の子へのポインタ - TreeNode *right; // 右の子へのポインタ - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - }; - ``` - -=== "Java" - - ```java title="" - /* 二分木のノードクラス */ - class TreeNode { - int val; // ノードの値 - TreeNode left; // 左の子への参照 - TreeNode right; // 右の子への参照 - TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* 二分木のノードクラス */ - class TreeNode(int? x) { - public int? val = x; // ノードの値 - public TreeNode? left; // 左の子への参照 - public TreeNode? right; // 右の子への参照 - } - ``` - -=== "Go" - - ```go title="" - /* 二分木のノード構造体 */ - type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode - } - /* コンストラクタ */ - func NewTreeNode(v int) *TreeNode { - return &TreeNode{ - Left: nil, // 左の子へのポインタ - Right: nil, // 右の子へのポインタ - Val: v, // ノードの値 - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 二分木のノードクラス */ - class TreeNode { - var val: Int // ノードの値 - var left: TreeNode? // 左の子への参照 - var right: TreeNode? // 右の子への参照 - - init(x: Int) { - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 二分木のノードクラス */ - class TreeNode { - val; // ノードの値 - left; // 左の子へのポインタ - right; // 右の子へのポインタ - constructor(val, left, right) { - this.val = val === undefined ? 0 : val; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 二分木のノードクラス */ - class TreeNode { - val: number; - left: TreeNode | null; - right: TreeNode | null; - - constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.left = left === undefined ? null : left; // 左の子への参照 - this.right = right === undefined ? null : right; // 右の子への参照 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 二分木のノードクラス */ - class TreeNode { - int val; // ノードの値 - TreeNode? left; // 左の子への参照 - TreeNode? right; // 右の子への参照 - TreeNode(this.val, [this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 二分木のノード構造体 */ - struct TreeNode { - val: i32, // ノードの値 - left: Option>>, // 左の子への参照 - right: Option>>, // 右の子への参照 - } - - impl TreeNode { - /* コンストラクタ */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* 二分木のノード構造体 */ - typedef struct TreeNode { - int val; // ノードの値 - int height; // ノードの高さ - struct TreeNode *left; // 左の子へのポインタ - struct TreeNode *right; // 右の子へのポインタ - } TreeNode; - - /* コンストラクタ */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 二分木のノードクラス */ - class TreeNode(val _val: Int) { // ノードの値 - var left: TreeNode? = null // 左の子への参照 - var right: TreeNode? = null // 右の子への参照 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 二分木のノードクラス ### - class TreeNode - attr_accessor :val # ノードの値 - attr_accessor :left # 左の子への参照 - attr_accessor :right # 右の子への参照 - - def initialize(val) - @val = val - end - end - ``` +```snippet +tree_node_class +``` 各ノードは二つの参照(ポインタ)を持ち、それぞれ左の子ノード(left-child node)と右の子ノード(right-child node)を指します。そのノードは、二つの子の親ノード(parent node)と呼ばれます。あるノードの左の子とその下のノードが作る木を左部分木(left subtree)と呼び、同様に右部分木(right subtree)も定義できます。 @@ -232,226 +37,13 @@ 連結リストと同じく、まずノードを初期化し、次に参照(ポインタ)をつなぎます。 -=== "Python" - - ```python title="binary_tree.py" - # 二分木を初期化 - # ノードを初期化 - n1 = TreeNode(val=1) - n2 = TreeNode(val=2) - n3 = TreeNode(val=3) - n4 = TreeNode(val=4) - n5 = TreeNode(val=5) - # ノード間の参照(ポインタ)をつなぐ - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* 二分木を初期化 */ - // ノードを初期化 - TreeNode* n1 = new TreeNode(1); - TreeNode* n2 = new TreeNode(2); - TreeNode* n3 = new TreeNode(3); - TreeNode* n4 = new TreeNode(4); - TreeNode* n5 = new TreeNode(5); - // ノード間の参照(ポインタ)をつなぐ - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Java" - - ```java title="binary_tree.java" - // ノードを初期化 - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // ノード間の参照(ポインタ)をつなぐ - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* 二分木を初期化 */ - // ノードを初期化 - TreeNode n1 = new(1); - TreeNode n2 = new(2); - TreeNode n3 = new(3); - TreeNode n4 = new(4); - TreeNode n5 = new(5); - // ノード間の参照(ポインタ)をつなぐ - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* 二分木を初期化 */ - // ノードを初期化 - n1 := NewTreeNode(1) - n2 := NewTreeNode(2) - n3 := NewTreeNode(3) - n4 := NewTreeNode(4) - n5 := NewTreeNode(5) - // ノード間の参照(ポインタ)をつなぐ - n1.Left = n2 - n1.Right = n3 - n2.Left = n4 - n2.Right = n5 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - // ノードを初期化 - let n1 = TreeNode(x: 1) - let n2 = TreeNode(x: 2) - let n3 = TreeNode(x: 3) - let n4 = TreeNode(x: 4) - let n5 = TreeNode(x: 5) - // ノード間の参照(ポインタ)をつなぐ - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* 二分木を初期化 */ - // ノードを初期化 - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // ノード間の参照(ポインタ)をつなぐ - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* 二分木を初期化 */ - // ノードを初期化 - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // ノード間の参照(ポインタ)をつなぐ - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* 二分木を初期化 */ - // ノードを初期化 - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // ノード間の参照(ポインタ)をつなぐ - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - // ノードを初期化 - let n1 = TreeNode::new(1); - let n2 = TreeNode::new(2); - let n3 = TreeNode::new(3); - let n4 = TreeNode::new(4); - let n5 = TreeNode::new(5); - // ノード間の参照(ポインタ)をつなぐ - n1.borrow_mut().left = Some(n2.clone()); - n1.borrow_mut().right = Some(n3); - n2.borrow_mut().left = Some(n4); - n2.borrow_mut().right = Some(n5); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* 二分木を初期化 */ - // ノードを初期化 - TreeNode *n1 = newTreeNode(1); - TreeNode *n2 = newTreeNode(2); - TreeNode *n3 = newTreeNode(3); - TreeNode *n4 = newTreeNode(4); - TreeNode *n5 = newTreeNode(5); - // ノード間の参照(ポインタ)をつなぐ - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - // ノードを初期化 - val n1 = TreeNode(1) - val n2 = TreeNode(2) - val n3 = TreeNode(3) - val n4 = TreeNode(4) - val n5 = TreeNode(5) - // ノード間の参照(ポインタ)をつなぐ - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # 二分木を初期化 - # ノードを初期化 - n1 = TreeNode.new(1) - n2 = TreeNode.new(2) - n3 = TreeNode.new(3) - n4 = TreeNode.new(4) - n5 = TreeNode.new(5) - # ノード間の参照(ポインタ)をつなぐ - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` +```snippet +init_binary_tree +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9C%A8%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9C%A8%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20n1%20%3D%20TreeNode(val%3D1)%0A%20%20%20%20n2%20%3D%20TreeNode(val%3D2)%0A%20%20%20%20n3%20%3D%20TreeNode(val%3D3)%0A%20%20%20%20n4%20%3D%20TreeNode(val%3D4)%0A%20%20%20%20n5%20%3D%20TreeNode(val%3D5)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E9%96%93%E3%81%AE%E5%8F%82%E7%85%A7%EF%BC%88%E3%83%9D%E3%82%A4%E3%83%B3%E3%82%BF%EF%BC%89%E3%82%92%E3%81%A4%E3%81%AA%E3%81%90%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_binary_tree_tutor ### ノードの挿入と削除 @@ -459,165 +51,13 @@ ![二分木でのノードの挿入と削除](binary_tree.assets/binary_tree_add_remove.svg) -=== "Python" - - ```python title="binary_tree.py" - # ノードの挿入と削除 - p = TreeNode(0) - # n1 -> n2 の間にノード P を挿入 - n1.left = p - p.left = n2 - # ノード P を削除 - n1.left = n2 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* ノードの挿入と削除 */ - TreeNode* P = new TreeNode(0); - // n1 -> n2 の間にノード P を挿入 - n1->left = P; - P->left = n2; - // ノード P を削除 - n1->left = n2; - // メモリを解放 - delete P; - ``` - -=== "Java" - - ```java title="binary_tree.java" - TreeNode P = new TreeNode(0); - // n1 -> n2 の間にノード P を挿入 - n1.left = P; - P.left = n2; - // ノード P を削除 - n1.left = n2; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* ノードの挿入と削除 */ - TreeNode P = new(0); - // n1 -> n2 の間にノード P を挿入 - n1.left = P; - P.left = n2; - // ノード P を削除 - n1.left = n2; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* ノードの挿入と削除 */ - // n1 -> n2 の間にノード P を挿入 - p := NewTreeNode(0) - n1.Left = p - p.Left = n2 - // ノード P を削除 - n1.Left = n2 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - let P = TreeNode(x: 0) - // n1 -> n2 の間にノード P を挿入 - n1.left = P - P.left = n2 - // ノード P を削除 - n1.left = n2 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* ノードの挿入と削除 */ - let P = new TreeNode(0); - // n1 -> n2 の間にノード P を挿入 - n1.left = P; - P.left = n2; - // ノード P を削除 - n1.left = n2; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* ノードの挿入と削除 */ - const P = new TreeNode(0); - // n1 -> n2 の間にノード P を挿入 - n1.left = P; - P.left = n2; - // ノード P を削除 - n1.left = n2; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* ノードの挿入と削除 */ - TreeNode P = new TreeNode(0); - // n1 -> n2 の間にノード P を挿入 - n1.left = P; - P.left = n2; - // ノード P を削除 - n1.left = n2; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - let p = TreeNode::new(0); - // n1 -> n2 の間にノード P を挿入 - n1.borrow_mut().left = Some(p.clone()); - p.borrow_mut().left = Some(n2.clone()); - // ノード p を削除 - n1.borrow_mut().left = Some(n2); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* ノードの挿入と削除 */ - TreeNode *P = newTreeNode(0); - // n1 -> n2 の間にノード P を挿入 - n1->left = P; - P->left = n2; - // ノード P を削除 - n1->left = n2; - // メモリを解放 - free(P); - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - val P = TreeNode(0) - // n1 -> n2 の間にノード P を挿入 - n1.left = P - P.left = n2 - // ノード P を削除 - n1.left = n2 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # ノードの挿入と削除 - _p = TreeNode.new(0) - # n1 -> n2 の間にノード _p を挿入 - n1.left = _p - _p.left = n2 - # ノードを削除 - n1.left = n2 - ``` +```snippet +insert_remove_node +``` ??? pythontutor "実行の可視化" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9C%A8%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9C%A8%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20n1%20%3D%20TreeNode(val%3D1)%0A%20%20%20%20n2%20%3D%20TreeNode(val%3D2)%0A%20%20%20%20n3%20%3D%20TreeNode(val%3D3)%0A%20%20%20%20n4%20%3D%20TreeNode(val%3D4)%0A%20%20%20%20n5%20%3D%20TreeNode(val%3D5)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E9%96%93%E3%81%AE%E5%8F%82%E7%85%A7%EF%BC%88%E3%83%9D%E3%82%A4%E3%83%B3%E3%82%BF%EF%BC%89%E3%82%92%E3%81%A4%E3%81%AA%E3%81%90%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E6%8C%BF%E5%85%A5%E3%81%A8%E5%89%8A%E9%99%A4%0A%20%20%20%20p%20%3D%20TreeNode(0)%0A%20%20%20%20%23%20n1%20-%3E%20n2%20%E3%81%AE%E9%96%93%E3%81%AB%E3%83%8E%E3%83%BC%E3%83%89%20P%20%E3%82%92%E6%8C%BF%E5%85%A5%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%20P%20%E3%82%92%E5%89%8A%E9%99%A4%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_node_tutor !!! tip diff --git a/ko/codes/snippets/chapter_array_and_linkedlist/array.md b/ko/codes/snippets/chapter_array_and_linkedlist/array.md new file mode 100644 index 000000000..7ef9a8b6f --- /dev/null +++ b/ko/codes/snippets/chapter_array_and_linkedlist/array.md @@ -0,0 +1,93 @@ + +```python title="array.py" +# 배열 초기화 +arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="array.cpp" +/* 배열 초기화 */ +// 스택에 저장 +int arr[5] = {}; +int nums[5] = { 1, 3, 2, 5, 4 }; +// 힙에 저장(공간을 직접 해제해야 함) +int* arr1 = new int[5] {}; +int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +``` + +```java title="array.java" +/* 배열 초기화 */ +int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } +int[] nums = { 1, 3, 2, 5, 4 }; +``` + +```csharp title="array.cs" +/* 배열 초기화 */ +int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] +int[] nums = [1, 3, 2, 5, 4]; +``` + +```go title="array.go" +/* 배열 초기화 */ +var arr [5]int +// Go에서 길이를 지정하면([5]int) 배열이고, 지정하지 않으면([]int) 슬라이스다 +// Go 배열의 길이는 컴파일 시 결정되도록 설계되었으므로 상수로만 길이를 지정할 수 있다 +// 용량 확장 메서드 extend()를 쉽게 구현하기 위해 아래에서는 슬라이스(Slice)를 배열(Array)로 간주한다 +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="array.swift" +/* 배열 초기화 */ +let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] +let nums = [1, 3, 2, 5, 4] +``` + +```javascript title="array.js" +/* 배열 초기화 */ +var arr = new Array(5).fill(0); +var nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="array.ts" +/* 배열 초기화 */ +let arr: number[] = new Array(5).fill(0); +let nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="array.dart" +/* 배열 초기화 */ +List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="array.rs" +/* 배열 초기화 */ +let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] +let slice: &[i32] = &[0; 5]; +// Rust에서 길이를 지정하면([i32; 5]) 배열이고, 지정하지 않으면(&[i32]) 슬라이스다 +// Rust 배열의 길이는 컴파일 시 결정되도록 설계되었으므로 상수로만 길이를 지정할 수 있다 +// Vector는 Rust에서 일반적으로 동적 배열로 사용하는 자료형이다 +// 용량 확장 메서드 extend()를 쉽게 구현하기 위해 아래에서는 vector를 배열(array)로 간주한다 +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="array.c" +/* 배열 초기화 */ +int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } +int nums[5] = { 1, 3, 2, 5, 4 }; +``` + +```kotlin title="array.kt" +/* 배열 초기화 */ +var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +var nums = intArrayOf(1, 3, 2, 5, 4) +``` + +```ruby title="array.rb" +# 배열 초기화 +arr = Array.new(5, 0) +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%23%20%EB%B0%B0%EC%97%B4%20%EC%B4%88%EA%B8%B0%ED%99%94%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/ko/codes/snippets/chapter_array_and_linkedlist/linked_list.md new file mode 100644 index 000000000..3d24c437a --- /dev/null +++ b/ko/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -0,0 +1,516 @@ + +```python title="" +class ListNode: + """연결 리스트 노드 클래스""" + def __init__(self, val: int): + self.val: int = val # 노드 값 + self.next: ListNode | None = None # 다음 노드를 가리키는 참조 +``` + +```cpp title="" +/* 연결 리스트 노드 구조체 */ +struct ListNode { + int val; // 노드 값 + ListNode *next; // 다음 노드를 가리키는 포인터 + ListNode(int x) : val(x), next(nullptr) {} // 생성자 +}; +``` + +```java title="" +/* 연결 리스트 노드 클래스 */ +class ListNode { + int val; // 노드 값 + ListNode next; // 다음 노드를 가리키는 참조 + ListNode(int x) { val = x; } // 생성자 +} +``` + +```csharp title="" +/* 연결 리스트 노드 클래스 */ +class ListNode(int x) { //생성자 + int val = x; // 노드 값 + ListNode? next; // 다음 노드를 가리키는 참조 +} +``` + +```go title="" +/* 연결 리스트 노드 구조체 */ +type ListNode struct { + Val int // 노드 값 + Next *ListNode // 다음 노드를 가리키는 포인터 +} + +// NewListNode 생성자: 새 연결 리스트 생성 +func NewListNode(val int) *ListNode { + return &ListNode{ + Val: val, + Next: nil, + } +} +``` + +```swift title="" +/* 연결 리스트 노드 클래스 */ +class ListNode { + var val: Int // 노드 값 + var next: ListNode? // 다음 노드를 가리키는 참조 + + init(x: Int) { // 생성자 + val = x + } +} +``` + +```javascript title="" +/* 연결 리스트 노드 클래스 */ +class ListNode { + constructor(val, next) { + this.val = (val === undefined ? 0 : val); // 노드 값 + this.next = (next === undefined ? null : next); // 다음 노드를 가리키는 참조 + } +} +``` + +```typescript title="" +/* 연결 리스트 노드 클래스 */ +class ListNode { + val: number; + next: ListNode | null; + constructor(val?: number, next?: ListNode | null) { + this.val = val === undefined ? 0 : val; // 노드 값 + this.next = next === undefined ? null : next; // 다음 노드를 가리키는 참조 + } +} +``` + +```dart title="" +/* 연결 리스트 노드 클래스 */ +class ListNode { + int val; // 노드 값 + ListNode? next; // 다음 노드를 가리키는 참조 + ListNode(this.val, [this.next]); // 생성자 +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; +/* 연결 리스트 노드 클래스 */ +#[derive(Debug)] +struct ListNode { + val: i32, // 노드 값 + next: Option>>, // 다음 노드를 가리키는 포인터 +} +``` + +```c title="" +/* 연결 리스트 노드 구조체 */ +typedef struct ListNode { + int val; // 노드 값 + struct ListNode *next; // 다음 노드를 가리키는 포인터 +} ListNode; + +/* 생성자 */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + return node; +} +``` + +```kotlin title="" +/* 연결 리스트 노드 클래스 */ +// 생성자 +class ListNode(x: Int) { + val _val: Int = x // 노드 값 + var next: ListNode? = null // 다음 노드를 가리키는 참조 +} +``` + +```ruby title="" +# 연결 리스트 노드 클래스 +class ListNode + attr_accessor :val # 노드 값 + attr_accessor :next # 다음 노드를 가리키는 참조 + + def initialize(val=0, next_node=nil) + @val = val + @next = next_node + end +end +``` + + +```python title="linked_list.py" +# 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 +# 각 노드 초기화 +n0 = ListNode(1) +n1 = ListNode(3) +n2 = ListNode(2) +n3 = ListNode(5) +n4 = ListNode(4) +# 노드 사이의 참조 설정 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```cpp title="linked_list.cpp" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +ListNode* n0 = new ListNode(1); +ListNode* n1 = new ListNode(3); +ListNode* n2 = new ListNode(2); +ListNode* n3 = new ListNode(5); +ListNode* n4 = new ListNode(4); +// 노드 사이의 참조 설정 +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```java title="linked_list.java" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +ListNode n0 = new ListNode(1); +ListNode n1 = new ListNode(3); +ListNode n2 = new ListNode(2); +ListNode n3 = new ListNode(5); +ListNode n4 = new ListNode(4); +// 노드 사이의 참조 설정 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```csharp title="linked_list.cs" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +ListNode n0 = new(1); +ListNode n1 = new(3); +ListNode n2 = new(2); +ListNode n3 = new(5); +ListNode n4 = new(4); +// 노드 사이의 참조 설정 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```go title="linked_list.go" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +n0 := NewListNode(1) +n1 := NewListNode(3) +n2 := NewListNode(2) +n3 := NewListNode(5) +n4 := NewListNode(4) +// 노드 사이의 참조 설정 +n0.Next = n1 +n1.Next = n2 +n2.Next = n3 +n3.Next = n4 +``` + +```swift title="linked_list.swift" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +let n0 = ListNode(x: 1) +let n1 = ListNode(x: 3) +let n2 = ListNode(x: 2) +let n3 = ListNode(x: 5) +let n4 = ListNode(x: 4) +// 노드 사이의 참조 설정 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```javascript title="linked_list.js" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// 노드 사이의 참조 설정 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```typescript title="linked_list.ts" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// 노드 사이의 참조 설정 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```dart title="linked_list.dart" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */\ +// 각 노드 초기화 +ListNode n0 = ListNode(1); +ListNode n1 = ListNode(3); +ListNode n2 = ListNode(2); +ListNode n3 = ListNode(5); +ListNode n4 = ListNode(4); +// 노드 사이의 참조 설정 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```rust title="linked_list.rs" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); +let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); +let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); +let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); +let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); + +// 노드 사이의 참조 설정 +n0.borrow_mut().next = Some(n1.clone()); +n1.borrow_mut().next = Some(n2.clone()); +n2.borrow_mut().next = Some(n3.clone()); +n3.borrow_mut().next = Some(n4.clone()); +``` + +```c title="linked_list.c" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +ListNode* n0 = newListNode(1); +ListNode* n1 = newListNode(3); +ListNode* n2 = newListNode(2); +ListNode* n3 = newListNode(5); +ListNode* n4 = newListNode(4); +// 노드 사이의 참조 설정 +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```kotlin title="linked_list.kt" +/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ +// 각 노드 초기화 +val n0 = ListNode(1) +val n1 = ListNode(3) +val n2 = ListNode(2) +val n3 = ListNode(5) +val n4 = ListNode(4) +// 노드 사이의 참조 설정 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```ruby title="linked_list.rb" +# 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 +# 각 노드 초기화 +n0 = ListNode.new(1) +n1 = ListNode.new(3) +n2 = ListNode.new(2) +n3 = ListNode.new(5) +n4 = ListNode.new(4) +# 노드 사이의 참조 설정 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%ED%9B%84%EC%86%8D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EA%B0%81%20%EB%85%B8%EB%93%9C%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%AC%EC%9D%B4%EC%9D%98%20%EC%B0%B8%EC%A1%B0%20%EC%84%A4%EC%A0%95%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="" +class ListNode: + """이중 연결 리스트 노드 클래스""" + def __init__(self, val: int): + self.val: int = val # 노드 값 + self.next: ListNode | None = None # 후속 노드를 가리키는 참조 + self.prev: ListNode | None = None # 선행 노드를 가리키는 참조 +``` + +```cpp title="" +/* 이중 연결 리스트 노드 구조체 */ +struct ListNode { + int val; // 노드 값 + ListNode *next; // 후속 노드를 가리키는 포인터 + ListNode *prev; // 선행 노드를 가리키는 포인터 + ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 생성자 +}; +``` + +```java title="" +/* 이중 연결 리스트 노드 클래스 */ +class ListNode { + int val; // 노드 값 + ListNode next; // 후속 노드를 가리키는 참조 + ListNode prev; // 선행 노드를 가리키는 참조 + ListNode(int x) { val = x; } // 생성자 +} +``` + +```csharp title="" +/* 이중 연결 리스트 노드 클래스 */ +class ListNode(int x) { // 생성자 + int val = x; // 노드 값 + ListNode next; // 후속 노드를 가리키는 참조 + ListNode prev; // 선행 노드를 가리키는 참조 +} +``` + +```go title="" +/* 이중 연결 리스트 노드 구조체 */ +type DoublyListNode struct { + Val int // 노드 값 + Next *DoublyListNode // 후속 노드를 가리키는 포인터 + Prev *DoublyListNode // 선행 노드를 가리키는 포인터 +} + +// NewDoublyListNode 초기화 +func NewDoublyListNode(val int) *DoublyListNode { + return &DoublyListNode{ + Val: val, + Next: nil, + Prev: nil, + } +} +``` + +```swift title="" +/* 이중 연결 리스트 노드 클래스 */ +class ListNode { + var val: Int // 노드 값 + var next: ListNode? // 후속 노드를 가리키는 참조 + var prev: ListNode? // 선행 노드를 가리키는 참조 + + init(x: Int) { // 생성자 + val = x + } +} +``` + +```javascript title="" +/* 이중 연결 리스트 노드 클래스 */ +class ListNode { + constructor(val, next, prev) { + this.val = val === undefined ? 0 : val; // 노드 값 + this.next = next === undefined ? null : next; // 후속 노드를 가리키는 참조 + this.prev = prev === undefined ? null : prev; // 선행 노드를 가리키는 참조 + } +} +``` + +```typescript title="" +/* 이중 연결 리스트 노드 클래스 */ +class ListNode { + val: number; + next: ListNode | null; + prev: ListNode | null; + constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { + this.val = val === undefined ? 0 : val; // 노드 값 + this.next = next === undefined ? null : next; // 후속 노드를 가리키는 참조 + this.prev = prev === undefined ? null : prev; // 선행 노드를 가리키는 참조 + } +} +``` + +```dart title="" +/* 이중 연결 리스트 노드 클래스 */ +class ListNode { + int val; // 노드 값 + ListNode? next; // 후속 노드를 가리키는 참조 + ListNode? prev; // 선행 노드를 가리키는 참조 + ListNode(this.val, [this.next, this.prev]); // 생성자 +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 이중 연결 리스트 노드 자료형 */ +#[derive(Debug)] +struct ListNode { + val: i32, // 노드 값 + next: Option>>, // 후속 노드를 가리키는 포인터 + prev: Option>>, // 선행 노드를 가리키는 포인터 +} + +/* 생성자 */ +impl ListNode { + fn new(val: i32) -> Self { + ListNode { + val, + next: None, + prev: None, + } + } +} +``` + +```c title="" +/* 이중 연결 리스트 노드 구조체 */ +typedef struct ListNode { + int val; // 노드 값 + struct ListNode *next; // 후속 노드를 가리키는 포인터 + struct ListNode *prev; // 선행 노드를 가리키는 포인터 +} ListNode; + +/* 생성자 */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + node->prev = NULL; + return node; +} +``` + +```kotlin title="" +/* 이중 연결 리스트 노드 클래스 */ +// 생성자 +class ListNode(x: Int) { + val _val: Int = x // 노드 값 + var next: ListNode? = null // 후속 노드를 가리키는 참조 + var prev: ListNode? = null // 선행 노드를 가리키는 참조 +} +``` + +```ruby title="" +# 이중 연결 리스트 노드 클래스 +class ListNode + attr_accessor :val # 노드 값 + attr_accessor :next # 후속 노드를 가리키는 참조 + attr_accessor :prev # 선행 노드를 가리키는 참조 + + def initialize(val=0, next_node=nil, prev_node=nil) + @val = val + @next = next_node + @prev = prev_node + end +end +``` diff --git a/ko/codes/snippets/chapter_array_and_linkedlist/list.md b/ko/codes/snippets/chapter_array_and_linkedlist/list.md new file mode 100644 index 000000000..1462ad78e --- /dev/null +++ b/ko/codes/snippets/chapter_array_and_linkedlist/list.md @@ -0,0 +1,752 @@ + +```python title="list.py" +# 리스트 초기화 +# 초깃값 없음 +nums1: list[int] = [] +# 초깃값 지정 +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="list.cpp" +/* 리스트 초기화 */ +// C++의 vector가 이 글에서 설명하는 nums에 해당한다 +// 초깃값 없음 +vector nums1; +// 초깃값 지정 +vector nums = { 1, 3, 2, 5, 4 }; +``` + +```java title="list.java" +/* 리스트 초기화 */ +// 초깃값 없음 +List nums1 = new ArrayList<>(); +// 초깃값 지정(배열은 int[]의 래퍼형인 Integer[]여야 함) +Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; +List nums = new ArrayList<>(Arrays.asList(numbers)); +``` + +```csharp title="list.cs" +/* 리스트 초기화 */ +// 초깃값 없음 +List nums1 = []; +// 초깃값 지정 +int[] numbers = [1, 3, 2, 5, 4]; +List nums = [.. numbers]; +``` + +```go title="list_test.go" +/* 리스트 초기화 */ +// 초깃값 없음 +nums1 := []int{} +// 초깃값 지정 +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="list.swift" +/* 리스트 초기화 */ +// 초깃값 없음 +let nums1: [Int] = [] +// 초깃값 지정 +var nums = [1, 3, 2, 5, 4] +``` + +```javascript title="list.js" +/* 리스트 초기화 */ +// 초깃값 없음 +const nums1 = []; +// 초깃값 지정 +const nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="list.ts" +/* 리스트 초기화 */ +// 초깃값 없음 +const nums1: number[] = []; +// 초깃값 지정 +const nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="list.dart" +/* 리스트 초기화 */ +// 초깃값 없음 +List nums1 = []; +// 초깃값 지정 +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="list.rs" +/* 리스트 초기화 */ +// 초깃값 없음 +let nums1: Vec = Vec::new(); +// 초깃값 지정 +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="list.c" +// C는 내장 동적 배열을 제공하지 않는다 +``` + +```kotlin title="list.kt" +/* 리스트 초기화 */ +// 초깃값 없음 +var nums1 = listOf() +// 초깃값 지정 +var numbers = arrayOf(1, 3, 2, 5, 4) +var nums = numbers.toMutableList() +``` + +```ruby title="list.rb" +# 리스트 초기화 +# 초깃값 없음 +nums1 = [] +# 초깃값 지정 +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%97%86%EC%9D%8C%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%A7%80%EC%A0%95%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 원소 접근 +num: int = nums[1] # 인덱스 1의 원소에 접근 + +# 원소 갱신 +nums[1] = 0 # 인덱스 1의 원소를 0으로 갱신 +``` + +```cpp title="list.cpp" +/* 원소 접근 */ +int num = nums[1]; // 인덱스 1의 원소에 접근 + +/* 원소 갱신 */ +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +``` + +```java title="list.java" +/* 원소 접근 */ +int num = nums.get(1); // 인덱스 1의 원소에 접근 + +/* 원소 갱신 */ +nums.set(1, 0); // 인덱스 1의 원소를 0으로 갱신 +``` + +```csharp title="list.cs" +/* 원소 접근 */ +int num = nums[1]; // 인덱스 1의 원소에 접근 + +/* 원소 갱신 */ +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +``` + +```go title="list_test.go" +/* 원소 접근 */ +num := nums[1] // 인덱스 1의 원소에 접근 + +/* 원소 갱신 */ +nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신 +``` + +```swift title="list.swift" +/* 원소 접근 */ +let num = nums[1] // 인덱스 1의 원소에 접근 + +/* 원소 갱신 */ +nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신 +``` + +```javascript title="list.js" +/* 원소 접근 */ +const num = nums[1]; // 인덱스 1의 원소에 접근 + +/* 원소 갱신 */ +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +``` + +```typescript title="list.ts" +/* 원소 접근 */ +const num: number = nums[1]; // 인덱스 1의 원소에 접근 + +/* 원소 갱신 */ +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +``` + +```dart title="list.dart" +/* 원소 접근 */ +int num = nums[1]; // 인덱스 1의 원소에 접근 + +/* 원소 갱신 */ +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +``` + +```rust title="list.rs" +/* 원소 접근 */ +let num: i32 = nums[1]; // 인덱스 1의 원소에 접근 +/* 원소 갱신 */ +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +``` + +```c title="list.c" +// C는 내장 동적 배열을 제공하지 않는다 +``` + +```kotlin title="list.kt" +/* 원소 접근 */ +val num = nums[1] // 인덱스 1의 원소에 접근 +/* 원소 갱신 */ +nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신 +``` + +```ruby title="list.rb" +# 원소 접근 +num = nums[1] # 인덱스 1의 원소에 접근 +# 원소 갱신 +nums[1] = 0 # 인덱스 1의 원소를 0으로 갱신 +``` + + +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%201%EC%9D%98%20%EC%9B%90%EC%86%8C%EC%97%90%20%EC%A0%91%EA%B7%BC%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EA%B0%B1%EC%8B%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%201%EC%9D%98%20%EC%9B%90%EC%86%8C%EB%A5%BC%200%EC%9C%BC%EB%A1%9C%20%EA%B0%B1%EC%8B%A0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 리스트 비우기 +nums.clear() + +# 끝에 원소 추가 +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +# 중간에 원소 삽입 +nums.insert(3, 6) # 인덱스 3에 숫자 6 삽입 + +# 원소 삭제 +nums.pop(3) # 인덱스 3의 원소 삭제 +``` + +```cpp title="list.cpp" +/* 리스트 비우기 */ +nums.clear(); + +/* 끝에 원소 추가 */ +nums.push_back(1); +nums.push_back(3); +nums.push_back(2); +nums.push_back(5); +nums.push_back(4); + +/* 중간에 원소 삽입 */ +nums.insert(nums.begin() + 3, 6); // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums.erase(nums.begin() + 3); // 인덱스 3의 원소 삭제 +``` + +```java title="list.java" +/* 리스트 비우기 */ +nums.clear(); + +/* 끝에 원소 추가 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 중간에 원소 삽입 */ +nums.add(3, 6); // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums.remove(3); // 인덱스 3의 원소 삭제 +``` + +```csharp title="list.cs" +/* 리스트 비우기 */ +nums.Clear(); + +/* 끝에 원소 추가 */ +nums.Add(1); +nums.Add(3); +nums.Add(2); +nums.Add(5); +nums.Add(4); + +/* 중간에 원소 삽입 */ +nums.Insert(3, 6); // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums.RemoveAt(3); // 인덱스 3의 원소 삭제 +``` + +```go title="list_test.go" +/* 리스트 비우기 */ +nums = nil + +/* 끝에 원소 추가 */ +nums = append(nums, 1) +nums = append(nums, 3) +nums = append(nums, 2) +nums = append(nums, 5) +nums = append(nums, 4) + +/* 중간에 원소 삽입 */ +nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums = append(nums[:3], nums[4:]...) // 인덱스 3의 원소 삭제 +``` + +```swift title="list.swift" +/* 리스트 비우기 */ +nums.removeAll() + +/* 끝에 원소 추가 */ +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +/* 중간에 원소 삽입 */ +nums.insert(6, at: 3) // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums.remove(at: 3) // 인덱스 3의 원소 삭제 +``` + +```javascript title="list.js" +/* 리스트 비우기 */ +nums.length = 0; + +/* 끝에 원소 추가 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 중간에 원소 삽입 */ +nums.splice(3, 0, 6); // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums.splice(3, 1); // 인덱스 3의 원소 삭제 +``` + +```typescript title="list.ts" +/* 리스트 비우기 */ +nums.length = 0; + +/* 끝에 원소 추가 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 중간에 원소 삽입 */ +nums.splice(3, 0, 6); // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums.splice(3, 1); // 인덱스 3의 원소 삭제 +``` + +```dart title="list.dart" +/* 리스트 비우기 */ +nums.clear(); + +/* 끝에 원소 추가 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 중간에 원소 삽입 */ +nums.insert(3, 6); // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums.removeAt(3); // 인덱스 3의 원소 삭제 +``` + +```rust title="list.rs" +/* 리스트 비우기 */ +nums.clear(); + +/* 끝에 원소 추가 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 중간에 원소 삽입 */ +nums.insert(3, 6); // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums.remove(3); // 인덱스 3의 원소 삭제 +``` + +```c title="list.c" +// C는 내장 동적 배열을 제공하지 않는다 +``` + +```kotlin title="list.kt" +/* 리스트 비우기 */ +nums.clear(); + +/* 끝에 원소 추가 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 중간에 원소 삽입 */ +nums.add(3, 6); // 인덱스 3에 숫자 6 삽입 + +/* 원소 삭제 */ +nums.remove(3); // 인덱스 3의 원소 삭제 +``` + +```ruby title="list.rb" +# 리스트 비우기 +nums.clear + +# 끝에 원소 추가 +nums << 1 +nums << 3 +nums << 2 +nums << 5 +nums << 4 + +# 중간에 원소 삽입 +nums.insert(3, 6) # 인덱스 3에 숫자 6 삽입 + +# 원소 삭제 +nums.delete_at(3) # 인덱스 3의 원소 삭제 +``` + + +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%A7%80%EC%A0%95%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%B9%84%EC%9A%B0%EA%B8%B0%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%81%9D%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%B6%94%EA%B0%80%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%A4%91%EA%B0%84%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20nums.insert%283%2C%206%29%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%203%EC%97%90%20%EC%88%AB%EC%9E%90%206%20%EC%82%BD%EC%9E%85%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%203%EC%9D%98%20%EC%9B%90%EC%86%8C%20%EC%82%AD%EC%A0%9C&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 인덱스로 리스트 순회 +count = 0 +for i in range(len(nums)): + count += nums[i] + +# 리스트 원소를 직접 순회 +for num in nums: + count += num +``` + +```cpp title="list.cpp" +/* 인덱스로 리스트 순회 */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums[i]; +} + +/* 리스트 원소를 직접 순회 */ +count = 0; +for (int num : nums) { + count += num; +} +``` + +```java title="list.java" +/* 인덱스로 리스트 순회 */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums.get(i); +} + +/* 리스트 원소를 직접 순회 */ +for (int num : nums) { + count += num; +} +``` + +```csharp title="list.cs" +/* 인덱스로 리스트 순회 */ +int count = 0; +for (int i = 0; i < nums.Count; i++) { + count += nums[i]; +} + +/* 리스트 원소를 직접 순회 */ +count = 0; +foreach (int num in nums) { + count += num; +} +``` + +```go title="list_test.go" +/* 인덱스로 리스트 순회 */ +count := 0 +for i := 0; i < len(nums); i++ { + count += nums[i] +} + +/* 리스트 원소를 직접 순회 */ +count = 0 +for _, num := range nums { + count += num +} +``` + +```swift title="list.swift" +/* 인덱스로 리스트 순회 */ +var count = 0 +for i in nums.indices { + count += nums[i] +} + +/* 리스트 원소를 직접 순회 */ +count = 0 +for num in nums { + count += num +} +``` + +```javascript title="list.js" +/* 인덱스로 리스트 순회 */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* 리스트 원소를 직접 순회 */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```typescript title="list.ts" +/* 인덱스로 리스트 순회 */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* 리스트 원소를 직접 순회 */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```dart title="list.dart" +/* 인덱스로 리스트 순회 */ +int count = 0; +for (var i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* 리스트 원소를 직접 순회 */ +count = 0; +for (var num in nums) { + count += num; +} +``` + +```rust title="list.rs" +// 인덱스로 리스트 순회 +let mut _count = 0; +for i in 0..nums.len() { + _count += nums[i]; +} + +// 리스트 원소를 직접 순회 +_count = 0; +for num in &nums { + _count += num; +} +``` + +```c title="list.c" +// C는 내장 동적 배열을 제공하지 않는다 +``` + +```kotlin title="list.kt" +/* 인덱스로 리스트 순회 */ +var count = 0 +for (i in nums.indices) { + count += nums[i] +} + +/* 리스트 원소를 직접 순회 */ +for (num in nums) { + count += num +} +``` + +```ruby title="list.rb" +# 인덱스로 리스트 순회 +count = 0 +for i in 0...nums.length + count += nums[i] +end + +# 리스트 원소를 직접 순회 +count = 0 +for num in nums + count += num +end +``` + + +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%EB%A1%9C%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%9B%90%EC%86%8C%EB%A5%BC%20%EC%A7%81%EC%A0%91%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 두 리스트 연결 +nums1: list[int] = [6, 8, 7, 10, 9] +nums += nums1 # 리스트 nums1을 nums 뒤에 연결 +``` + +```cpp title="list.cpp" +/* 두 리스트 연결 */ +vector nums1 = { 6, 8, 7, 10, 9 }; +// 리스트 nums1을 nums 뒤에 연결 +nums.insert(nums.end(), nums1.begin(), nums1.end()); +``` + +```java title="list.java" +/* 두 리스트 연결 */ +List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); +nums.addAll(nums1); // 리스트 nums1을 nums 뒤에 연결 +``` + +```csharp title="list.cs" +/* 두 리스트 연결 */ +List nums1 = [6, 8, 7, 10, 9]; +nums.AddRange(nums1); // 리스트 nums1을 nums 뒤에 연결 +``` + +```go title="list_test.go" +/* 두 리스트 연결 */ +nums1 := []int{6, 8, 7, 10, 9} +nums = append(nums, nums1...) // 리스트 nums1을 nums 뒤에 연결 +``` + +```swift title="list.swift" +/* 두 리스트 연결 */ +let nums1 = [6, 8, 7, 10, 9] +nums.append(contentsOf: nums1) // 리스트 nums1을 nums 뒤에 연결 +``` + +```javascript title="list.js" +/* 두 리스트 연결 */ +const nums1 = [6, 8, 7, 10, 9]; +nums.push(...nums1); // 리스트 nums1을 nums 뒤에 연결 +``` + +```typescript title="list.ts" +/* 두 리스트 연결 */ +const nums1: number[] = [6, 8, 7, 10, 9]; +nums.push(...nums1); // 리스트 nums1을 nums 뒤에 연결 +``` + +```dart title="list.dart" +/* 두 리스트 연결 */ +List nums1 = [6, 8, 7, 10, 9]; +nums.addAll(nums1); // 리스트 nums1을 nums 뒤에 연결 +``` + +```rust title="list.rs" +/* 두 리스트 연결 */ +let nums1: Vec = vec![6, 8, 7, 10, 9]; +nums.extend(nums1); +``` + +```c title="list.c" +// C는 내장 동적 배열을 제공하지 않는다 +``` + +```kotlin title="list.kt" +/* 두 리스트 연결 */ +val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() +nums.addAll(nums1) // 리스트 nums1을 nums 뒤에 연결 +``` + +```ruby title="list.rb" +# 두 리스트 연결 +nums1 = [6, 8, 7, 10, 9] +nums += nums1 +``` + + +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%91%90%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%97%B0%EA%B2%B0%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20nums1%EC%9D%84%20nums%20%EB%92%A4%EC%97%90%20%EC%97%B0%EA%B2%B0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 리스트 정렬 +nums.sort() # 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```cpp title="list.cpp" +/* 리스트 정렬 */ +sort(nums.begin(), nums.end()); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```java title="list.java" +/* 리스트 정렬 */ +Collections.sort(nums); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```csharp title="list.cs" +/* 리스트 정렬 */ +nums.Sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```go title="list_test.go" +/* 리스트 정렬 */ +sort.Ints(nums) // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```swift title="list.swift" +/* 리스트 정렬 */ +nums.sort() // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```javascript title="list.js" +/* 리스트 정렬 */ +nums.sort((a, b) => a - b); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```typescript title="list.ts" +/* 리스트 정렬 */ +nums.sort((a, b) => a - b); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```dart title="list.dart" +/* 리스트 정렬 */ +nums.sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```rust title="list.rs" +/* 리스트 정렬 */ +nums.sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```c title="list.c" +// C는 내장 동적 배열을 제공하지 않는다 +``` + +```kotlin title="list.kt" +/* 리스트 정렬 */ +nums.sort() // 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + +```ruby title="list.rb" +# 리스트 정렬 +nums = nums.sort { |a, b| a <=> b } # 정렬 후 리스트 원소가 오름차순으로 배치됨 +``` + + +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%A0%95%EB%A0%AC%0A%20%20%20%20nums.sort%28%29%20%20%23%20%EC%A0%95%EB%A0%AC%20%ED%9B%84%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%9B%90%EC%86%8C%EA%B0%80%20%EC%98%A4%EB%A6%84%EC%B0%A8%EC%88%9C%EC%9C%BC%EB%A1%9C%20%EB%B0%B0%EC%B9%98%EB%90%A8&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_backtracking/backtracking_algorithm.md b/ko/codes/snippets/chapter_backtracking/backtracking_algorithm.md new file mode 100644 index 000000000..946ccaca4 --- /dev/null +++ b/ko/codes/snippets/chapter_backtracking/backtracking_algorithm.md @@ -0,0 +1,308 @@ + +```python title="" +def backtrack(state: State, choices: list[choice], res: list[state]): + """백트래킹 알고리즘의 기본 틀""" + # 해인지 확인 + if is_solution(state): + # 해 기록 + record_solution(state, res) + # 더 이상 탐색하지 않는다 + return + # 모든 선택지 순회 + for choice in choices: + # 가지치기: 선택이 유효한지 확인 + if is_valid(state, choice): + # 시도: 선택하고 상태 갱신 + make_choice(state, choice) + backtrack(state, choices, res) + # 되돌리기: 선택을 취소하고 이전 상태 복원 + undo_choice(state, choice) +``` + +```cpp title="" +/* 백트래킹 알고리즘의 기본 틀 */ +void backtrack(State *state, vector &choices, vector &res) { + // 해인지 확인 + if (isSolution(state)) { + // 해 기록 + recordSolution(state, res); + // 더 이상 탐색하지 않는다 + return; + } + // 모든 선택지 순회 + for (Choice choice : choices) { + // 가지치기: 선택이 유효한지 확인 + if (isValid(state, choice)) { + // 시도: 선택하고 상태 갱신 + makeChoice(state, choice); + backtrack(state, choices, res); + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undoChoice(state, choice); + } + } +} +``` + +```java title="" +/* 백트래킹 알고리즘의 기본 틀 */ +void backtrack(State state, List choices, List res) { + // 해인지 확인 + if (isSolution(state)) { + // 해 기록 + recordSolution(state, res); + // 더 이상 탐색하지 않는다 + return; + } + // 모든 선택지 순회 + for (Choice choice : choices) { + // 가지치기: 선택이 유효한지 확인 + if (isValid(state, choice)) { + // 시도: 선택하고 상태 갱신 + makeChoice(state, choice); + backtrack(state, choices, res); + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undoChoice(state, choice); + } + } +} +``` + +```csharp title="" +/* 백트래킹 알고리즘의 기본 틀 */ +void Backtrack(State state, List choices, List res) { + // 해인지 확인 + if (IsSolution(state)) { + // 해 기록 + RecordSolution(state, res); + // 더 이상 탐색하지 않는다 + return; + } + // 모든 선택지 순회 + foreach (Choice choice in choices) { + // 가지치기: 선택이 유효한지 확인 + if (IsValid(state, choice)) { + // 시도: 선택하고 상태 갱신 + MakeChoice(state, choice); + Backtrack(state, choices, res); + // 되돌리기: 선택을 취소하고 이전 상태 복원 + UndoChoice(state, choice); + } + } +} +``` + +```go title="" +/* 백트래킹 알고리즘의 기본 틀 */ +func backtrack(state *State, choices []Choice, res *[]State) { + // 해인지 확인 + if isSolution(state) { + // 해 기록 + recordSolution(state, res) + // 더 이상 탐색하지 않는다 + return + } + // 모든 선택지 순회 + for _, choice := range choices { + // 가지치기: 선택이 유효한지 확인 + if isValid(state, choice) { + // 시도: 선택하고 상태 갱신 + makeChoice(state, choice) + backtrack(state, choices, res) + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undoChoice(state, choice) + } + } +} +``` + +```swift title="" +/* 백트래킹 알고리즘의 기본 틀 */ +func backtrack(state: inout State, choices: [Choice], res: inout [State]) { + // 해인지 확인 + if isSolution(state: state) { + // 해 기록 + recordSolution(state: state, res: &res) + // 더 이상 탐색하지 않는다 + return + } + // 모든 선택지 순회 + for choice in choices { + // 가지치기: 선택이 유효한지 확인 + if isValid(state: state, choice: choice) { + // 시도: 선택하고 상태 갱신 + makeChoice(state: &state, choice: choice) + backtrack(state: &state, choices: choices, res: &res) + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undoChoice(state: &state, choice: choice) + } + } +} +``` + +```javascript title="" +/* 백트래킹 알고리즘의 기본 틀 */ +function backtrack(state, choices, res) { + // 해인지 확인 + if (isSolution(state)) { + // 해 기록 + recordSolution(state, res); + // 더 이상 탐색하지 않는다 + return; + } + // 모든 선택지 순회 + for (let choice of choices) { + // 가지치기: 선택이 유효한지 확인 + if (isValid(state, choice)) { + // 시도: 선택하고 상태 갱신 + makeChoice(state, choice); + backtrack(state, choices, res); + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undoChoice(state, choice); + } + } +} +``` + +```typescript title="" +/* 백트래킹 알고리즘의 기본 틀 */ +function backtrack(state: State, choices: Choice[], res: State[]): void { + // 해인지 확인 + if (isSolution(state)) { + // 해 기록 + recordSolution(state, res); + // 더 이상 탐색하지 않는다 + return; + } + // 모든 선택지 순회 + for (let choice of choices) { + // 가지치기: 선택이 유효한지 확인 + if (isValid(state, choice)) { + // 시도: 선택하고 상태 갱신 + makeChoice(state, choice); + backtrack(state, choices, res); + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undoChoice(state, choice); + } + } +} +``` + +```dart title="" +/* 백트래킹 알고리즘의 기본 틀 */ +void backtrack(State state, List, List res) { + // 해인지 확인 + if (isSolution(state)) { + // 해 기록 + recordSolution(state, res); + // 더 이상 탐색하지 않는다 + return; + } + // 모든 선택지 순회 + for (Choice choice in choices) { + // 가지치기: 선택이 유효한지 확인 + if (isValid(state, choice)) { + // 시도: 선택하고 상태 갱신 + makeChoice(state, choice); + backtrack(state, choices, res); + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undoChoice(state, choice); + } + } +} +``` + +```rust title="" +/* 백트래킹 알고리즘의 기본 틀 */ +fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { + // 해인지 확인 + if is_solution(state) { + // 해 기록 + record_solution(state, res); + // 더 이상 탐색하지 않는다 + return; + } + // 모든 선택지 순회 + for choice in choices { + // 가지치기: 선택이 유효한지 확인 + if is_valid(state, choice) { + // 시도: 선택하고 상태 갱신 + make_choice(state, choice); + backtrack(state, choices, res); + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undo_choice(state, choice); + } + } +} +``` + +```c title="" +/* 백트래킹 알고리즘의 기본 틀 */ +void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { + // 해인지 확인 + if (isSolution(state)) { + // 해 기록 + recordSolution(state, res, numRes); + // 더 이상 탐색하지 않는다 + return; + } + // 모든 선택지 순회 + for (int i = 0; i < numChoices; i++) { + // 가지치기: 선택이 유효한지 확인 + if (isValid(state, &choices[i])) { + // 시도: 선택하고 상태 갱신 + makeChoice(state, &choices[i]); + backtrack(state, choices, numChoices, res, numRes); + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undoChoice(state, &choices[i]); + } + } +} +``` + +```kotlin title="" +/* 백트래킹 알고리즘의 기본 틀 */ +fun backtrack(state: State?, choices: List, res: List?) { + // 해인지 확인 + if (isSolution(state)) { + // 해 기록 + recordSolution(state, res) + // 더 이상 탐색하지 않는다 + return + } + // 모든 선택지 순회 + for (choice in choices) { + // 가지치기: 선택이 유효한지 확인 + if (isValid(state, choice)) { + // 시도: 선택하고 상태 갱신 + makeChoice(state, choice) + backtrack(state, choices, res) + // 되돌리기: 선택을 취소하고 이전 상태 복원 + undoChoice(state, choice) + } + } +} +``` + +```ruby title="" +### 백트래킹 알고리즘의 기본 틀 ### +def backtrack(state, choices, res) + # 해인지 확인 + if is_solution?(state) + # 해 기록 + record_solution(state, res) + return + end + + # 모든 선택지 순회 + for choice in choices + # 가지치기: 선택이 유효한지 확인 + if is_valid?(state, choice) + # 시도: 선택하고 상태 갱신 + make_choice(state, choice) + backtrack(state, choices, res) + # 되돌리기: 선택을 취소하고 이전 상태 복원 + undo_choice(state, choice) + end + end +end +``` diff --git a/ko/codes/snippets/chapter_computational_complexity/space_complexity.md b/ko/codes/snippets/chapter_computational_complexity/space_complexity.md new file mode 100644 index 000000000..a6cbe347a --- /dev/null +++ b/ko/codes/snippets/chapter_computational_complexity/space_complexity.md @@ -0,0 +1,682 @@ + +```python title="" +class Node: + """클래스""" + def __init__(self, x: int): + self.val: int = x # 노드 값 + self.next: Node | None = None # 다음 노드를 가리키는 참조 + +def function() -> int: + """함수""" + # 몇 가지 연산 수행... + return 0 + +def algorithm(n) -> int: # 입력 데이터 + A = 0 # 임시 데이터(상수, 보통 대문자로 표기) + b = 0 # 임시 데이터(변수) + node = Node(0) # 임시 데이터(객체) + c = function() # 스택 프레임 공간(함수 호출) + return A + b + c # 출력 데이터 +``` + +```cpp title="" +/* 구조체 */ +struct Node { + int val; + Node *next; + Node(int x) : val(x), next(nullptr) {} +}; + +/* 함수 */ +int func() { + // 몇 가지 연산 수행... + return 0; +} + +int algorithm(int n) { // 입력 데이터 + const int a = 0; // 임시 데이터(상수) + int b = 0; // 임시 데이터(변수) + Node* node = new Node(0); // 임시 데이터(객체) + int c = func(); // 스택 프레임 공간(함수 호출) + return a + b + c; // 출력 데이터 +} +``` + +```java title="" +/* 클래스 */ +class Node { + int val; + Node next; + Node(int x) { val = x; } +} + +/* 함수 */ +int function() { + // 몇 가지 연산 수행... + return 0; +} + +int algorithm(int n) { // 입력 데이터 + final int a = 0; // 임시 데이터(상수) + int b = 0; // 임시 데이터(변수) + Node node = new Node(0); // 임시 데이터(객체) + int c = function(); // 스택 프레임 공간(함수 호출) + return a + b + c; // 출력 데이터 +} +``` + +```csharp title="" +/* 클래스 */ +class Node(int x) { + int val = x; + Node next; +} + +/* 함수 */ +int Function() { + // 몇 가지 연산 수행... + return 0; +} + +int Algorithm(int n) { // 입력 데이터 + const int a = 0; // 임시 데이터(상수) + int b = 0; // 임시 데이터(변수) + Node node = new(0); // 임시 데이터(객체) + int c = Function(); // 스택 프레임 공간(함수 호출) + return a + b + c; // 출력 데이터 +} +``` + +```go title="" +/* 구조체 */ +type node struct { + val int + next *node +} + +/* node 구조체 생성 */ +func newNode(val int) *node { + return &node{val: val} +} + +/* 함수 */ +func function() int { + // 몇 가지 연산 수행... + return 0 +} + +func algorithm(n int) int { // 입력 데이터 + const a = 0 // 임시 데이터(상수) + b := 0 // 임시 데이터(변수) + newNode(0) // 임시 데이터(객체) + c := function() // 스택 프레임 공간(함수 호출) + return a + b + c // 출력 데이터 +} +``` + +```swift title="" +/* 클래스 */ +class Node { + var val: Int + var next: Node? + + init(x: Int) { + val = x + } +} + +/* 함수 */ +func function() -> Int { + // 몇 가지 연산 수행... + return 0 +} + +func algorithm(n: Int) -> Int { // 입력 데이터 + let a = 0 // 임시 데이터(상수) + var b = 0 // 임시 데이터(변수) + let node = Node(x: 0) // 임시 데이터(객체) + let c = function() // 스택 프레임 공간(함수 호출) + return a + b + c // 출력 데이터 +} +``` + +```javascript title="" +/* 클래스 */ +class Node { + val; + next; + constructor(val) { + this.val = val === undefined ? 0 : val; // 노드 값 + this.next = null; // 다음 노드를 가리키는 참조 + } +} + +/* 함수 */ +function constFunc() { + // 몇 가지 연산 수행 + return 0; +} + +function algorithm(n) { // 입력 데이터 + const a = 0; // 임시 데이터(상수) + let b = 0; // 임시 데이터(변수) + const node = new Node(0); // 임시 데이터(객체) + const c = constFunc(); // 스택 프레임 공간(함수 호출) + return a + b + c; // 출력 데이터 +} +``` + +```typescript title="" +/* 클래스 */ +class Node { + val: number; + next: Node | null; + constructor(val?: number) { + this.val = val === undefined ? 0 : val; // 노드 값 + this.next = null; // 다음 노드를 가리키는 참조 + } +} + +/* 함수 */ +function constFunc(): number { + // 몇 가지 연산 수행 + return 0; +} + +function algorithm(n: number): number { // 입력 데이터 + const a = 0; // 임시 데이터(상수) + let b = 0; // 임시 데이터(변수) + const node = new Node(0); // 임시 데이터(객체) + const c = constFunc(); // 스택 프레임 공간(함수 호출) + return a + b + c; // 출력 데이터 +} +``` + +```dart title="" +/* 클래스 */ +class Node { + int val; + Node next; + Node(this.val, [this.next]); +} + +/* 함수 */ +int function() { + // 몇 가지 연산 수행... + return 0; +} + +int algorithm(int n) { // 입력 데이터 + const int a = 0; // 임시 데이터(상수) + int b = 0; // 임시 데이터(변수) + Node node = Node(0); // 임시 데이터(객체) + int c = function(); // 스택 프레임 공간(함수 호출) + return a + b + c; // 출력 데이터 +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 구조체 */ +struct Node { + val: i32, + next: Option>>, +} + +/* Node 구조체 생성 */ +impl Node { + fn new(val: i32) -> Self { + Self { val: val, next: None } + } +} + +/* 함수 */ +fn function() -> i32 { + // 몇 가지 연산 수행... + return 0; +} + +fn algorithm(n: i32) -> i32 { // 입력 데이터 + const a: i32 = 0; // 임시 데이터(상수) + let mut b = 0; // 임시 데이터(변수) + let node = Node::new(0); // 임시 데이터(객체) + let c = function(); // 스택 프레임 공간(함수 호출) + return a + b + c; // 출력 데이터 +} +``` + +```c title="" +/* 함수 */ +int func() { + // 몇 가지 연산 수행... + return 0; +} + +int algorithm(int n) { // 입력 데이터 + const int a = 0; // 임시 데이터(상수) + int b = 0; // 임시 데이터(변수) + int c = func(); // 스택 프레임 공간(함수 호출) + return a + b + c; // 출력 데이터 +} +``` + +```kotlin title="" +/* 클래스 */ +class Node(var _val: Int) { + var next: Node? = null +} + +/* 함수 */ +fun function(): Int { + // 몇 가지 연산 수행... + return 0 +} + +fun algorithm(n: Int): Int { // 입력 데이터 + val a = 0 // 임시 데이터(상수) + var b = 0 // 임시 데이터(변수) + val node = Node(0) // 임시 데이터(객체) + val c = function() // 스택 프레임 공간(함수 호출) + return a + b + c // 출력 데이터 +} +``` + +```ruby title="" +### 클래스 ### +class Node + attr_accessor :val # 노드 값 + attr_accessor :next # 다음 노드를 가리키는 참조 + + def initialize(x) + @val = x + end +end + +### 함수 ### +def function + # 몇 가지 연산 수행... + 0 +end + +### 알고리즘 ### +def algorithm(n) # 입력 데이터 + a = 0 # 임시 데이터(상수) + b = 0 # 임시 데이터(변수) + node = Node.new(0) # 임시 데이터(객체) + c = function # 스택 프레임 공간(함수 호출) + a + b + c # 출력 데이터 +end +``` + + +```python title="" +def algorithm(n: int): + a = 0 # O(1) + b = [0] * 10000 # O(1) + if n > 10: + nums = [0] * n # O(n) +``` + +```cpp title="" +void algorithm(int n) { + int a = 0; // O(1) + vector b(10000); // O(1) + if (n > 10) + vector nums(n); // O(n) +} +``` + +```java title="" +void algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) + int[] nums = new int[n]; // O(n) +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) { + int[] nums = new int[n]; // O(n) + } +} +``` + +```go title="" +func algorithm(n int) { + a := 0 // O(1) + b := make([]int, 10000) // O(1) + var nums []int + if n > 10 { + nums := make([]int, n) // O(n) + } + fmt.Println(a, b, nums) +} +``` + +```swift title="" +func algorithm(n: Int) { + let a = 0 // O(1) + let b = Array(repeating: 0, count: 10000) // O(1) + if n > 10 { + let nums = Array(repeating: 0, count: n) // O(n) + } +} +``` + +```javascript title="" +function algorithm(n) { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 0; // O(1) + List b = List.filled(10000, 0); // O(1) + if (n > 10) { + List nums = List.filled(n, 0); // O(n) + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let a = 0; // O(1) + let b = [0; 10000]; // O(1) + if n > 10 { + let nums = vec![0; n as usize]; // O(n) + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 0; // O(1) + int b[10000]; // O(1) + if (n > 10) + int nums[n] = {0}; // O(n) +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + val a = 0 // O(1) + val b = IntArray(10000) // O(1) + if (n > 10) { + val nums = IntArray(n) // O(n) + } +} +``` + +```ruby title="" +def algorithm(n) + a = 0 # O(1) + b = Array.new(10000) # O(1) + nums = Array.new(n) if n > 10 # O(n) +end +``` + + +```python title="" +def function() -> int: + # 몇 가지 연산 수행 + return 0 + +def loop(n: int): + """반복문의 공간 복잡도는 O(1)""" + for _ in range(n): + function() + +def recur(n: int): + """재귀의 공간 복잡도는 O(n)""" + if n == 1: + return + return recur(n - 1) +``` + +```cpp title="" +int func() { + // 몇 가지 연산 수행 + return 0; +} +/* 반복문의 공간 복잡도는 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* 재귀의 공간 복잡도는 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```java title="" +int function() { + // 몇 가지 연산 수행 + return 0; +} +/* 반복문의 공간 복잡도는 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* 재귀의 공간 복잡도는 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```csharp title="" +int Function() { + // 몇 가지 연산 수행 + return 0; +} +/* 반복문의 공간 복잡도는 O(1) */ +void Loop(int n) { + for (int i = 0; i < n; i++) { + Function(); + } +} +/* 재귀의 공간 복잡도는 O(n) */ +int Recur(int n) { + if (n == 1) return 1; + return Recur(n - 1); +} +``` + +```go title="" +func function() int { + // 몇 가지 연산 수행 + return 0 +} + +/* 반복문의 공간 복잡도는 O(1) */ +func loop(n int) { + for i := 0; i < n; i++ { + function() + } +} + +/* 재귀의 공간 복잡도는 O(n) */ +func recur(n int) { + if n == 1 { + return + } + recur(n - 1) +} +``` + +```swift title="" +@discardableResult +func function() -> Int { + // 몇 가지 연산 수행 + return 0 +} + +/* 반복문의 공간 복잡도는 O(1) */ +func loop(n: Int) { + for _ in 0 ..< n { + function() + } +} + +/* 재귀의 공간 복잡도는 O(n) */ +func recur(n: Int) { + if n == 1 { + return + } + recur(n: n - 1) +} +``` + +```javascript title="" +function constFunc() { + // 몇 가지 연산 수행 + return 0; +} +/* 반복문의 공간 복잡도는 O(1) */ +function loop(n) { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* 재귀의 공간 복잡도는 O(n) */ +function recur(n) { + if (n === 1) return; + return recur(n - 1); +} +``` + +```typescript title="" +function constFunc(): number { + // 몇 가지 연산 수행 + return 0; +} +/* 반복문의 공간 복잡도는 O(1) */ +function loop(n: number): void { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* 재귀의 공간 복잡도는 O(n) */ +function recur(n: number): void { + if (n === 1) return; + return recur(n - 1); +} +``` + +```dart title="" +int function() { + // 몇 가지 연산 수행 + return 0; +} +/* 반복문의 공간 복잡도는 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* 재귀의 공간 복잡도는 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```rust title="" +fn function() -> i32 { + // 몇 가지 연산 수행 + return 0; +} +/* 반복문의 공간 복잡도는 O(1) */ +fn loop(n: i32) { + for i in 0..n { + function(); + } +} +/* 재귀의 공간 복잡도는 O(n) */ +fn recur(n: i32) { + if n == 1 { + return; + } + recur(n - 1); +} +``` + +```c title="" +int func() { + // 몇 가지 연산 수행 + return 0; +} +/* 반복문의 공간 복잡도는 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* 재귀의 공간 복잡도는 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```kotlin title="" +fun function(): Int { + // 몇 가지 연산 수행 + return 0 +} +/* 반복문의 공간 복잡도는 O(1) */ +fun loop(n: Int) { + for (i in 0.. +```python title="" +# 어떤 실행 플랫폼에서 +def algorithm(n: int): + a = 2 # 1 ns + a = a + 1 # 1 ns + a = a * 2 # 10 ns + # n번 반복 + for _ in range(n): # 1 ns + print(0) # 5 ns +``` + +```cpp title="" +// 어떤 실행 플랫폼에서 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n번 반복 + for (int i = 0; i < n; i++) { // 1 ns + cout << 0 << endl; // 5 ns + } +} +``` + +```java title="" +// 어떤 실행 플랫폼에서 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n번 반복 + for (int i = 0; i < n; i++) { // 1 ns + System.out.println(0); // 5 ns + } +} +``` + +```csharp title="" +// 어떤 실행 플랫폼에서 +void Algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n번 반복 + for (int i = 0; i < n; i++) { // 1 ns + Console.WriteLine(0); // 5 ns + } +} +``` + +```go title="" +// 어떤 실행 플랫폼에서 +func algorithm(n int) { + a := 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // n번 반복 + for i := 0; i < n; i++ { // 1 ns + fmt.Println(a) // 5 ns + } +} +``` + +```swift title="" +// 어떤 실행 플랫폼에서 +func algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // n번 반복 + for _ in 0 ..< n { // 1 ns + print(0) // 5 ns + } +} +``` + +```javascript title="" +// 어떤 실행 플랫폼에서 +function algorithm(n) { + var a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n번 반복 + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```typescript title="" +// 어떤 실행 플랫폼에서 +function algorithm(n: number): void { + var a: number = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n번 반복 + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```dart title="" +// 어떤 실행 플랫폼에서 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n번 반복 + for (int i = 0; i < n; i++) { // 1 ns + print(0); // 5 ns + } +} +``` + +```rust title="" +// 어떤 실행 플랫폼에서 +fn algorithm(n: i32) { + let mut a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n번 반복 + for _ in 0..n { // 1 ns + println!("{}", 0); // 5 ns + } +} +``` + +```c title="" +// 어떤 실행 플랫폼에서 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // n번 반복 + for (int i = 0; i < n; i++) { // 1 ns + printf("%d", 0); // 5 ns + } +} +``` + +```kotlin title="" +// 어떤 실행 플랫폼에서 +fun algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // n번 반복 + for (i in 0.. +```python title="" +# 알고리즘 A의 시간 복잡도: 상수 시간 +def algorithm_A(n: int): + print(0) +# 알고리즘 B의 시간 복잡도: 선형 시간 +def algorithm_B(n: int): + for _ in range(n): + print(0) +# 알고리즘 C의 시간 복잡도: 상수 시간 +def algorithm_C(n: int): + for _ in range(1000000): + print(0) +``` + +```cpp title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +void algorithm_A(int n) { + cout << 0 << endl; +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + cout << 0 << endl; + } +} +// 알고리즘 C의 시간 복잡도: 상수 시간 +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + cout << 0 << endl; + } +} +``` + +```java title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +void algorithm_A(int n) { + System.out.println(0); +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + System.out.println(0); + } +} +// 알고리즘 C의 시간 복잡도: 상수 시간 +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + System.out.println(0); + } +} +``` + +```csharp title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +void AlgorithmA(int n) { + Console.WriteLine(0); +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +void AlgorithmB(int n) { + for (int i = 0; i < n; i++) { + Console.WriteLine(0); + } +} +// 알고리즘 C의 시간 복잡도: 상수 시간 +void AlgorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + Console.WriteLine(0); + } +} +``` + +```go title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +func algorithm_A(n int) { + fmt.Println(0) +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +func algorithm_B(n int) { + for i := 0; i < n; i++ { + fmt.Println(0) + } +} +// 알고리즘 C의 시간 복잡도: 상수 시간 +func algorithm_C(n int) { + for i := 0; i < 1000000; i++ { + fmt.Println(0) + } +} +``` + +```swift title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +func algorithmA(n: Int) { + print(0) +} + +// 알고리즘 B의 시간 복잡도: 선형 시간 +func algorithmB(n: Int) { + for _ in 0 ..< n { + print(0) + } +} + +// 알고리즘 C의 시간 복잡도: 상수 시간 +func algorithmC(n: Int) { + for _ in 0 ..< 1_000_000 { + print(0) + } +} +``` + +```javascript title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +function algorithm_A(n) { + console.log(0); +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +function algorithm_B(n) { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// 알고리즘 C의 시간 복잡도: 상수 시간 +function algorithm_C(n) { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} + +``` + +```typescript title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +function algorithm_A(n: number): void { + console.log(0); +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +function algorithm_B(n: number): void { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// 알고리즘 C의 시간 복잡도: 상수 시간 +function algorithm_C(n: number): void { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} +``` + +```dart title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +void algorithmA(int n) { + print(0); +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +void algorithmB(int n) { + for (int i = 0; i < n; i++) { + print(0); + } +} +// 알고리즘 C의 시간 복잡도: 상수 시간 +void algorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + print(0); + } +} +``` + +```rust title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +fn algorithm_A(n: i32) { + println!("{}", 0); +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +fn algorithm_B(n: i32) { + for _ in 0..n { + println!("{}", 0); + } +} +// 알고리즘 C의 시간 복잡도: 상수 시간 +fn algorithm_C(n: i32) { + for _ in 0..1000000 { + println!("{}", 0); + } +} +``` + +```c title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +void algorithm_A(int n) { + printf("%d", 0); +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + printf("%d", 0); + } +} +// 알고리즘 C의 시간 복잡도: 상수 시간 +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + printf("%d", 0); + } +} +``` + +```kotlin title="" +// 알고리즘 A의 시간 복잡도: 상수 시간 +fun algoritm_A(n: Int) { + println(0) +} +// 알고리즘 B의 시간 복잡도: 선형 시간 +fun algorithm_B(n: Int) { + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +1 + a = a + 1 # +1 + a = a * 2 # +1 + # n번 반복 + for i in range(n): # +1 + print(0) # +1 +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n번 반복 + for (int i = 0; i < n; i++) { // +1(매번 i ++ 실행) + cout << 0 << endl; // +1 + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n번 반복 + for (int i = 0; i < n; i++) { // +1(매번 i ++ 실행) + System.out.println(0); // +1 + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n번 반복 + for (int i = 0; i < n; i++) { // +1(매번 i ++ 실행) + Console.WriteLine(0); // +1 + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // n번 반복 + for i := 0; i < n; i++ { // +1 + fmt.Println(a) // +1 + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // n번 반복 + for _ in 0 ..< n { // +1 + print(0) // +1 + } +} +``` + +```javascript title="" +function algorithm(n) { + var a = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // n번 반복 + for(let i = 0; i < n; i++){ // +1(매번 i ++ 실행) + console.log(0); // +1 + } +} +``` + +```typescript title="" +function algorithm(n: number): void{ + var a: number = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // n번 반복 + for(let i = 0; i < n; i++){ // +1(매번 i ++ 실행) + console.log(0); // +1 + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n번 반복 + for (int i = 0; i < n; i++) { // +1(매번 i ++ 실행) + print(0); // +1 + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + + // n번 반복 + for _ in 0..n { // +1(매번 i ++ 실행) + println!("{}", 0); // +1 + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // n번 반복 + for (int i = 0; i < n; i++) { // +1(매번 i ++ 실행) + printf("%d", 0); // +1 + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // n번 반복 + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +0(요령 1) + a = a + n # +0(요령 1) + # +n(요령 2) + for i in range(5 * n + 1): + print(0) + # +n*n(요령 3) + for i in range(2 * n): + for j in range(n + 1): + print(0) +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +0(요령 1) + a = a + n; // +0(요령 1) + // +n(요령 2) + for (int i = 0; i < 5 * n + 1; i++) { + cout << 0 << endl; + } + // +n*n(요령 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + cout << 0 << endl; + } + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +0(요령 1) + a = a + n; // +0(요령 1) + // +n(요령 2) + for (int i = 0; i < 5 * n + 1; i++) { + System.out.println(0); + } + // +n*n(요령 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + System.out.println(0); + } + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +0(요령 1) + a = a + n; // +0(요령 1) + // +n(요령 2) + for (int i = 0; i < 5 * n + 1; i++) { + Console.WriteLine(0); + } + // +n*n(요령 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + Console.WriteLine(0); + } + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +0(요령 1) + a = a + n // +0(요령 1) + // +n(요령 2) + for i := 0; i < 5 * n + 1; i++ { + fmt.Println(0) + } + // +n*n(요령 3) + for i := 0; i < 2 * n; i++ { + for j := 0; j < n + 1; j++ { + fmt.Println(0) + } + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +0(요령 1) + a = a + n // +0(요령 1) + // +n(요령 2) + for _ in 0 ..< (5 * n + 1) { + print(0) + } + // +n*n(요령 3) + for _ in 0 ..< (2 * n) { + for _ in 0 ..< (n + 1) { + print(0) + } + } +} +``` + +```javascript title="" +function algorithm(n) { + let a = 1; // +0(요령 1) + a = a + n; // +0(요령 1) + // +n(요령 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n(요령 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + let a = 1; // +0(요령 1) + a = a + n; // +0(요령 1) + // +n(요령 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n(요령 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +0(요령 1) + a = a + n; // +0(요령 1) + // +n(요령 2) + for (int i = 0; i < 5 * n + 1; i++) { + print(0); + } + // +n*n(요령 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + print(0); + } + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +0(요령 1) + a = a + n; // +0(요령 1) + + // +n(요령 2) + for i in 0..(5 * n + 1) { + println!("{}", 0); + } + + // +n*n(요령 3) + for i in 0..(2 * n) { + for j in 0..(n + 1) { + println!("{}", 0); + } + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +0(요령 1) + a = a + n; // +0(요령 1) + // +n(요령 2) + for (int i = 0; i < 5 * n + 1; i++) { + printf("%d", 0); + } + // +n*n(요령 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + printf("%d", 0); + } + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +0(요령 1) + a = a + n // +0(요령 1) + // +n(요령 2) + for (i in 0..<5 * n + 1) { + println(0) + } + // +n*n(요령 3) + for (i in 0..<2 * n) { + for (j in 0.. +```python title="" +# 여러 기본 자료형으로 배열 초기화 +numbers: list[int] = [0] * 5 +decimals: list[float] = [0.0] * 5 +# Python의 문자는 실제로 길이가 1인 문자열이다 +characters: list[str] = ['0'] * 5 +bools: list[bool] = [False] * 5 +# Python의 리스트는 여러 기본 자료형과 객체 참조를 자유롭게 저장할 수 있다 +data = [0, 0.0, 'a', False, ListNode(0)] +``` + +```cpp title="" +// 여러 기본 자료형으로 배열 초기화 +int numbers[5]; +float decimals[5]; +char characters[5]; +bool bools[5]; +``` + +```java title="" +// 여러 기본 자료형으로 배열 초기화 +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +boolean[] bools = new boolean[5]; +``` + +```csharp title="" +// 여러 기본 자료형으로 배열 초기화 +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +bool[] bools = new bool[5]; +``` + +```go title="" +// 여러 기본 자료형으로 배열 초기화 +var numbers = [5]int{} +var decimals = [5]float64{} +var characters = [5]byte{} +var bools = [5]bool{} +``` + +```swift title="" +// 여러 기본 자료형으로 배열 초기화 +let numbers = Array(repeating: 0, count: 5) +let decimals = Array(repeating: 0.0, count: 5) +let characters: [Character] = Array(repeating: "a", count: 5) +let bools = Array(repeating: false, count: 5) +``` + +```javascript title="" +// JavaScript의 배열은 여러 기본 자료형과 객체를 자유롭게 저장할 수 있다 +const array = [0, 0.0, 'a', false]; +``` + +```typescript title="" +// 여러 기본 자료형으로 배열 초기화 +const numbers: number[] = []; +const characters: string[] = []; +const bools: boolean[] = []; +``` + +```dart title="" +// 여러 기본 자료형으로 배열 초기화 +List numbers = List.filled(5, 0); +List decimals = List.filled(5, 0.0); +List characters = List.filled(5, 'a'); +List bools = List.filled(5, false); +``` + +```rust title="" +// 여러 기본 자료형으로 배열 초기화 +let numbers: Vec = vec![0; 5]; +let decimals: Vec = vec![0.0; 5]; +let characters: Vec = vec!['0'; 5]; +let bools: Vec = vec![false; 5]; +``` + +```c title="" +// 여러 기본 자료형으로 배열 초기화 +int numbers[10]; +float decimals[10]; +char characters[10]; +bool bools[10]; +``` + +```kotlin title="" +// 여러 기본 자료형으로 배열 초기화 +val numbers = IntArray(5) +val decinals = FloatArray(5) +val characters = CharArray(5) +val bools = BooleanArray(5) +``` + +```ruby title="" +# Ruby의 리스트는 여러 기본 자료형과 객체 참조를 자유롭게 저장할 수 있다 +data = [0, 0.0, 'a', false, ListNode(0)] +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%EB%8B%A4%EC%9D%8C%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%97%AC%EB%9F%AC%20%EA%B8%B0%EB%B3%B8%20%EC%9E%90%EB%A3%8C%ED%98%95%EC%9C%BC%EB%A1%9C%20%EB%B0%B0%EC%97%B4%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20%2A%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20%2A%205%0A%20%20%20%20%23%20Python%EC%9D%98%20%EB%AC%B8%EC%9E%90%EB%8A%94%20%EC%8B%A4%EC%A0%9C%EB%A1%9C%20%EA%B8%B8%EC%9D%B4%EA%B0%80%201%EC%9D%B8%20%EB%AC%B8%EC%9E%90%EC%97%B4%EC%9D%B4%EB%8B%A4%0A%20%20%20%20characters%20%3D%20%5B%270%27%5D%20%2A%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20%2A%205%0A%20%20%20%20%23%20Python%EC%9D%98%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%8A%94%20%EC%97%AC%EB%9F%AC%20%EA%B8%B0%EB%B3%B8%20%EC%9E%90%EB%A3%8C%ED%98%95%EA%B3%BC%20%EA%B0%9D%EC%B2%B4%20%EC%B0%B8%EC%A1%B0%EB%A5%BC%20%EC%9E%90%EC%9C%A0%EB%A1%AD%EA%B2%8C%20%EC%A0%80%EC%9E%A5%ED%95%A0%20%EC%88%98%20%EC%9E%88%EB%8B%A4%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20%27a%27%2C%20False%2C%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_hashing/hash_algorithm.md b/ko/codes/snippets/chapter_hashing/hash_algorithm.md new file mode 100644 index 000000000..928219822 --- /dev/null +++ b/ko/codes/snippets/chapter_hashing/hash_algorithm.md @@ -0,0 +1,263 @@ + +```python title="built_in_hash.py" +num = 3 +hash_num = hash(num) +# 정수 3의 해시값은 3 + +bol = True +hash_bol = hash(bol) +# 불리언 True의 해시값은 1 + +dec = 3.14159 +hash_dec = hash(dec) +# 소수 3.14159의 해시값은 326484311674566659 + +str = "Hello 算法" +hash_str = hash(str) +# 문자열 “Hello 算法”의 해시값은 4617003410720528961 + +tup = (12836, "小哈") +hash_tup = hash(tup) +# 튜플 (12836, '小哈')의 해시값은 1029005403108185979 + +obj = ListNode(0) +hash_obj = hash(obj) +# 노드 객체 의 해시값은 274267521 +``` + +```cpp title="built_in_hash.cpp" +int num = 3; +size_t hashNum = hash()(num); +// 정수 3의 해시값은 3 + +bool bol = true; +size_t hashBol = hash()(bol); +// 불리언 1의 해시값은 1 + +double dec = 3.14159; +size_t hashDec = hash()(dec); +// 소수 3.14159의 해시값은 4614256650576692846 + +string str = "Hello 算法"; +size_t hashStr = hash()(str); +// 문자열 “Hello 算法”의 해시값은 15466937326284535026 + +// C++의 내장 std::hash()는 기본 자료형의 해시값 계산만 제공한다 +// 배열과 객체의 해시값 계산은 직접 구현해야 한다 +``` + +```java title="built_in_hash.java" +int num = 3; +int hashNum = Integer.hashCode(num); +// 정수 3의 해시값은 3 + +boolean bol = true; +int hashBol = Boolean.hashCode(bol); +// 불리언 true의 해시값은 1231 + +double dec = 3.14159; +int hashDec = Double.hashCode(dec); +// 소수 3.14159의 해시값은 -1340954729 + +String str = "Hello 算法"; +int hashStr = str.hashCode(); +// 문자열 “Hello 算法”의 해시값은 -727081396 + +Object[] arr = { 12836, "小哈" }; +int hashTup = Arrays.hashCode(arr); +// 배열 [12836, 小哈]의 해시값은 1151158 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode(); +// 노드 객체 utils.ListNode@7dc5e7b4의 해시값은 2110121908 +``` + +```csharp title="built_in_hash.cs" +int num = 3; +int hashNum = num.GetHashCode(); +// 정수 3의 해시값은 3; + +bool bol = true; +int hashBol = bol.GetHashCode(); +// 불리언 true의 해시값은 1; + +double dec = 3.14159; +int hashDec = dec.GetHashCode(); +// 소수 3.14159의 해시값은 -1340954729; + +string str = "Hello 算法"; +int hashStr = str.GetHashCode(); +// 문자열 “Hello 算法”의 해시값은 -586107568; + +object[] arr = [12836, "小哈"]; +int hashTup = arr.GetHashCode(); +// 배열 [12836, 小哈]의 해시값은 42931033; + +ListNode obj = new(0); +int hashObj = obj.GetHashCode(); +// 노드 객체 0의 해시값은 39053774; +``` + +```go title="built_in_hash.go" +// Go는 내장 hash code 함수를 제공하지 않는다 +``` + +```swift title="built_in_hash.swift" +let num = 3 +let hashNum = num.hashValue +// 정수 3의 해시값은 9047044699613009734 + +let bol = true +let hashBol = bol.hashValue +// 불리언 true의 해시값은 -4431640247352757451 + +let dec = 3.14159 +let hashDec = dec.hashValue +// 소수 3.14159의 해시값은 -2465384235396674631 + +let str = "Hello 算法" +let hashStr = str.hashValue +// 문자열 “Hello 算法”의 해시값은 -7850626797806988787 + +let arr = [AnyHashable(12836), AnyHashable("小哈")] +let hashTup = arr.hashValue +// 배열 [AnyHashable(12836), AnyHashable("小哈")]의 해시값은 -2308633508154532996 + +let obj = ListNode(x: 0) +let hashObj = obj.hashValue +// 노드 객체 utils.ListNode의 해시값은 -2434780518035996159 +``` + +```javascript title="built_in_hash.js" +// JavaScript는 내장 hash code 함수를 제공하지 않는다 +``` + +```typescript title="built_in_hash.ts" +// TypeScript는 내장 hash code 함수를 제공하지 않는다 +``` + +```dart title="built_in_hash.dart" +int num = 3; +int hashNum = num.hashCode; +// 정수 3의 해시값은 34803 + +bool bol = true; +int hashBol = bol.hashCode; +// 불리언 true의 해시값은 1231 + +double dec = 3.14159; +int hashDec = dec.hashCode; +// 소수 3.14159의 해시값은 2570631074981783 + +String str = "Hello 算法"; +int hashStr = str.hashCode; +// 문자열 “Hello 算法”의 해시값은 468167534 + +List arr = [12836, "小哈"]; +int hashArr = arr.hashCode; +// 배열 [12836, 小哈]의 해시값은 976512528 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode; +// 노드 객체 Instance of 'ListNode'의 해시값은 1033450432 +``` + +```rust title="built_in_hash.rs" +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +let num = 3; +let mut num_hasher = DefaultHasher::new(); +num.hash(&mut num_hasher); +let hash_num = num_hasher.finish(); +// 정수 3의 해시값은 568126464209439262 + +let bol = true; +let mut bol_hasher = DefaultHasher::new(); +bol.hash(&mut bol_hasher); +let hash_bol = bol_hasher.finish(); +// 불리언 true의 해시값은 4952851536318644461 + +let dec: f32 = 3.14159; +let mut dec_hasher = DefaultHasher::new(); +dec.to_bits().hash(&mut dec_hasher); +let hash_dec = dec_hasher.finish(); +// 소수 3.14159의 해시값은 2566941990314602357 + +let str = "Hello 算法"; +let mut str_hasher = DefaultHasher::new(); +str.hash(&mut str_hasher); +let hash_str = str_hasher.finish(); +// 문자열 “Hello 算法”의 해시값은 16092673739211250988 + +let arr = (&12836, &"小哈"); +let mut tup_hasher = DefaultHasher::new(); +arr.hash(&mut tup_hasher); +let hash_tup = tup_hasher.finish(); +// 튜플 (12836, "小哈")의 해시값은 1885128010422702749 + +let node = ListNode::new(42); +let mut hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut hasher); +let hash = hasher.finish(); +// 노드 객체 RefCell { value: ListNode { val: 42, next: None } }의 해시값은 15387811073369036852 +``` + +```c title="built_in_hash.c" +// C는 내장 hash code 함수를 제공하지 않는다 +``` + +```kotlin title="built_in_hash.kt" +val num = 3 +val hashNum = num.hashCode() +// 정수 3의 해시값은 3 + +val bol = true +val hashBol = bol.hashCode() +// 불리언 true의 해시값은 1231 + +val dec = 3.14159 +val hashDec = dec.hashCode() +// 소수 3.14159의 해시값은 -1340954729 + +val str = "Hello 算法" +val hashStr = str.hashCode() +// 문자열 “Hello 算法”의 해시값은 -727081396 + +val arr = arrayOf(12836, "小哈") +val hashTup = arr.hashCode() +// 배열 [12836, 小哈]의 해시값은 189568618 + +val obj = ListNode(0) +val hashObj = obj.hashCode() +// 노드 객체 utils.ListNode@1d81eb93의 해시값은 495053715 +``` + +```ruby title="built_in_hash.rb" +num = 3 +hash_num = num.hash +# 정수 3의 해시값은 -4385856518450339636 + +bol = true +hash_bol = bol.hash +# 불리언 true의 해시값은 -1617938112149317027 + +dec = 3.14159 +hash_dec = dec.hash +# 소수 3.14159의 해시값은 -1479186995943067893 + +str = "Hello 算法" +hash_str = str.hash +# 문자열 “Hello 算法”의 해시값은 -4075943250025831763 + +tup = [12836, '小哈'] +hash_tup = tup.hash +# 튜플 (12836, '小哈')의 해시값은 1999544809202288822 + +obj = ListNode.new(0) +hash_obj = obj.hash +# 노드 객체 #의 해시값은 4302940560806366381 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%ED%9B%84%EC%86%8D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%EC%A0%95%EC%88%98%203%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%EB%B6%88%EB%A6%AC%EC%96%B8%20True%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%EC%86%8C%EC%88%98%203.14159%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%EB%AC%B8%EC%9E%90%EC%97%B4%20%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%ED%8A%9C%ED%94%8C%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%9D%EC%B2%B4%20%3CListNode%20object%20at%200x1058fd810%3E%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_hashing/hash_map.md b/ko/codes/snippets/chapter_hashing/hash_map.md new file mode 100644 index 000000000..e646914c5 --- /dev/null +++ b/ko/codes/snippets/chapter_hashing/hash_map.md @@ -0,0 +1,457 @@ + +```python title="hash_map.py" +# 해시 테이블 초기화 +hmap: dict = {} + +# 추가 연산 +# 해시 테이블에 키-값 쌍 (key, value) 추가 +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +# 조회 연산 +# 해시 테이블에 키 key를 입력하여 값 value를 얻음 +name: str = hmap[15937] + +# 삭제 연산 +# 해시 테이블에서 키-값 쌍 (key, value) 삭제 +hmap.pop(10583) +``` + +```cpp title="hash_map.cpp" +/* 해시 테이블 초기화 */ +unordered_map map; + +/* 추가 연산 */ +// 해시 테이블에 키-값 쌍 (key, value) 추가 +map[12836] = "小哈"; +map[15937] = "小啰"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鸭"; + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +string name = map[15937]; + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +map.erase(10583); +``` + +```java title="hash_map.java" +/* 해시 테이블 초기화 */ +Map map = new HashMap<>(); + +/* 추가 연산 */ +// 해시 테이블에 키-값 쌍 (key, value) 추가 +map.put(12836, "小哈"); +map.put(15937, "小啰"); +map.put(16750, "小算"); +map.put(13276, "小法"); +map.put(10583, "小鸭"); + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +String name = map.get(15937); + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +map.remove(10583); +``` + +```csharp title="hash_map.cs" +/* 해시 테이블 초기화 */ +Dictionary map = new() { + /* 추가 연산 */ + // 해시 테이블에 키-값 쌍 (key, value) 추가 + { 12836, "小哈" }, + { 15937, "小啰" }, + { 16750, "小算" }, + { 13276, "小法" }, + { 10583, "小鸭" } +}; + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +string name = map[15937]; + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +map.Remove(10583); +``` + +```go title="hash_map_test.go" +/* 해시 테이블 초기화 */ +hmap := make(map[int]string) + +/* 추가 연산 */ +// 해시 테이블에 키-값 쌍 (key, value) 추가 +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +name := hmap[15937] + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +delete(hmap, 10583) +``` + +```swift title="hash_map.swift" +/* 해시 테이블 초기화 */ +var map: [Int: String] = [:] + +/* 추가 연산 */ +// 해시 테이블에 키-값 쌍 (key, value) 추가 +map[12836] = "小哈" +map[15937] = "小啰" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鸭" + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +let name = map[15937]! + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +map.removeValue(forKey: 10583) +``` + +```javascript title="hash_map.js" +/* 해시 테이블 초기화 */ +const map = new Map(); +/* 추가 연산 */ +// 해시 테이블에 키-값 쌍 (key, value) 추가 +map.set(12836, '小哈'); +map.set(15937, '小啰'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鸭'); + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +let name = map.get(15937); + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +map.delete(10583); +``` + +```typescript title="hash_map.ts" +/* 해시 테이블 초기화 */ +const map = new Map(); +/* 추가 연산 */ +// 해시 테이블에 키-값 쌍 (key, value) 추가 +map.set(12836, '小哈'); +map.set(15937, '小啰'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鸭'); +console.info('\n추가한 뒤의 해시 테이블\nKey -> Value'); +console.info(map); + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +let name = map.get(15937); +console.info('\n학번 15937을 입력하여 찾은 이름 ' + name); + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +map.delete(10583); +console.info('\n10583을 삭제한 뒤의 해시 테이블\nKey -> Value'); +console.info(map); +``` + +```dart title="hash_map.dart" +/* 해시 테이블 초기화 */ +Map map = {}; + +/* 추가 연산 */ +// 해시 테이블에 키-값 쌍 (key, value) 추가 +map[12836] = "小哈"; +map[15937] = "小啰"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鸭"; + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +String name = map[15937]; + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +map.remove(10583); +``` + +```rust title="hash_map.rs" +use std::collections::HashMap; + +/* 해시 테이블 초기화 */ +let mut map: HashMap = HashMap::new(); + +/* 추가 연산 */ +// 해시 테이블에 키-값 쌍 (key, value) 추가 +map.insert(12836, "小哈".to_string()); +map.insert(15937, "小啰".to_string()); +map.insert(16750, "小算".to_string()); +map.insert(13279, "小法".to_string()); +map.insert(10583, "小鸭".to_string()); + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +let _name: Option<&String> = map.get(&15937); + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +let _removed_value: Option = map.remove(&10583); +``` + +```c title="hash_map.c" +// C는 내장 해시 테이블을 제공하지 않는다 +``` + +```kotlin title="hash_map.kt" +/* 해시 테이블 초기화 */ +val map = HashMap() + +/* 추가 연산 */ +// 해시 테이블에 키-값 쌍 (key, value) 추가 +map[12836] = "小哈" +map[15937] = "小啰" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鸭" + +/* 조회 연산 */ +// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +val name = map[15937] + +/* 삭제 연산 */ +// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +map.remove(10583) +``` + +```ruby title="hash_map.rb" +# 해시 테이블 초기화 +hmap = {} + +# 추가 연산 +# 해시 테이블에 키-값 쌍 (key, value) 추가 +hmap[12836] = "小哈" +hmap[15937] = "小啰" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鸭" + +# 조회 연산 +# 해시 테이블에 키 key를 입력하여 값 value를 얻음 +name = hmap[15937] + +# 삭제 연산 +# 해시 테이블에서 키-값 쌍 (key, value) 삭제 +hmap.delete(10583) +``` + + +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%B6%94%EA%B0%80%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20%28key%2C%20value%29%20%EC%B6%94%EA%B0%80%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%A1%B0%ED%9A%8C%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%20%ED%82%A4%20key%EB%A5%BC%20%EC%9E%85%EB%A0%A5%ED%95%98%EC%97%AC%20%EA%B0%92%20value%EB%A5%BC%20%EC%96%BB%EC%9D%8C%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%82%AD%EC%A0%9C%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%EC%84%9C%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20%28key%2C%20value%29%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="hash_map.py" +# 해시 테이블 순회 +# 키-값 쌍 key->value 순회 +for key, value in hmap.items(): + print(key, "->", value) +# 키 key만 순회 +for key in hmap.keys(): + print(key) +# 값 value만 순회 +for value in hmap.values(): + print(value) +``` + +```cpp title="hash_map.cpp" +/* 해시 테이블 순회 */ +// 키-값 쌍 key->value 순회 +for (auto kv: map) { + cout << kv.first << " -> " << kv.second << endl; +} +// 이터레이터로 key->value 순회 +for (auto iter = map.begin(); iter != map.end(); iter++) { + cout << iter->first << "->" << iter->second << endl; +} +``` + +```java title="hash_map.java" +/* 해시 테이블 순회 */ +// 키-값 쌍 key->value 순회 +for (Map.Entry kv: map.entrySet()) { + System.out.println(kv.getKey() + " -> " + kv.getValue()); +} +// 키 key만 순회 +for (int key: map.keySet()) { + System.out.println(key); +} +// 값 value만 순회 +for (String val: map.values()) { + System.out.println(val); +} +``` + +```csharp title="hash_map.cs" +/* 해시 테이블 순회 */ +// 키-값 쌍 Key->Value 순회 +foreach (var kv in map) { + Console.WriteLine(kv.Key + " -> " + kv.Value); +} +// 키 key만 순회 +foreach (int key in map.Keys) { + Console.WriteLine(key); +} +// 값 value만 순회 +foreach (string val in map.Values) { + Console.WriteLine(val); +} +``` + +```go title="hash_map_test.go" +/* 해시 테이블 순회 */ +// 키-값 쌍 key->value 순회 +for key, value := range hmap { + fmt.Println(key, "->", value) +} +// 키 key만 순회 +for key := range hmap { + fmt.Println(key) +} +// 값 value만 순회 +for _, value := range hmap { + fmt.Println(value) +} +``` + +```swift title="hash_map.swift" +/* 해시 테이블 순회 */ +// 키-값 쌍 Key->Value 순회 +for (key, value) in map { + print("\(key) -> \(value)") +} +// 키 Key만 순회 +for key in map.keys { + print(key) +} +// 값 Value만 순회 +for value in map.values { + print(value) +} +``` + +```javascript title="hash_map.js" +/* 해시 테이블 순회 */ +console.info('\n키-값 쌍 Key->Value 순회'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\n키 Key만 순회'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\n값 Value만 순회'); +for (const v of map.values()) { + console.info(v); +} +``` + +```typescript title="hash_map.ts" +/* 해시 테이블 순회 */ +console.info('\n키-값 쌍 Key->Value 순회'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\n키 Key만 순회'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\n값 Value만 순회'); +for (const v of map.values()) { + console.info(v); +} +``` + +```dart title="hash_map.dart" +/* 해시 테이블 순회 */ +// 키-값 쌍 Key->Value 순회 +map.forEach((key, value) { + print('$key -> $value'); +}); + +// 키 Key만 순회 +map.keys.forEach((key) { + print(key); +}); + +// 값 Value만 순회 +map.values.forEach((value) { + print(value); +}); +``` + +```rust title="hash_map.rs" +/* 해시 테이블 순회 */ +// 키-값 쌍 Key->Value 순회 +for (key, value) in &map { + println!("{key} -> {value}"); +} + +// 키 Key만 순회 +for key in map.keys() { + println!("{key}"); +} + +// 값 Value만 순회 +for value in map.values() { + println!("{value}"); +} +``` + +```c title="hash_map.c" +// C는 내장 해시 테이블을 제공하지 않는다 +``` + +```kotlin title="hash_map.kt" +/* 해시 테이블 순회 */ +// 키-값 쌍 key->value 순회 +for ((key, value) in map) { + println("$key -> $value") +} +// 키 key만 순회 +for (key in map.keys) { + println(key) +} +// 값 value만 순회 +for (_val in map.values) { + println(_val) +} +``` + +```ruby title="hash_map.rb" +# 해시 테이블 순회 +# 키-값 쌍 key->value 순회 +hmap.entries.each { |key, value| puts "#{key} -> #{value}" } + +# 키 key만 순회 +hmap.keys.each { |key| puts key } + +# 값 value만 순회 +hmap.values.each { |val| puts val } +``` + + +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%B6%94%EA%B0%80%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20%28key%2C%20value%29%20%EC%B6%94%EA%B0%80%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20%23%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20key-%3Evalue%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%ED%82%A4%20key%EB%A7%8C%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%EA%B0%92%20value%EB%A7%8C%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_heap/heap.md b/ko/codes/snippets/chapter_heap/heap.md new file mode 100644 index 000000000..e5086769f --- /dev/null +++ b/ko/codes/snippets/chapter_heap/heap.md @@ -0,0 +1,350 @@ + +```python title="heap.py" +# 최소 힙 초기화 +min_heap, flag = [], 1 +# 최대 힙 초기화 +max_heap, flag = [], -1 + +# Python의 heapq 모듈은 기본적으로 최소 힙을 구현한다 +# 원소의 부호를 바꾼 뒤 삽입하면 대소 관계가 뒤집히므로 최대 힙을 구현할 수 있다 +# 이 예제에서 flag = 1이면 최소 힙, flag = -1이면 최대 힙에 해당한다 + +# 힙에 원소 삽입 +heapq.heappush(max_heap, flag * 1) +heapq.heappush(max_heap, flag * 3) +heapq.heappush(max_heap, flag * 2) +heapq.heappush(max_heap, flag * 5) +heapq.heappush(max_heap, flag * 4) + +# 힙의 루트 원소 구하기 +peek: int = flag * max_heap[0] # 5 + +# 힙의 루트 원소 꺼내기 +# 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 + +# 힙의 크기 구하기 +size: int = len(max_heap) + +# 힙이 비어 있는지 확인 +is_empty: bool = not max_heap + +# 리스트를 입력받아 힙 구성 +min_heap: list[int] = [1, 3, 2, 5, 4] +heapq.heapify(min_heap) +``` + +```cpp title="heap.cpp" +/* 힙 초기화 */ +// 최소 힙 초기화 +priority_queue, greater> minHeap; +// 최대 힙 초기화 +priority_queue, less> maxHeap; + +/* 힙에 원소 삽입 */ +maxHeap.push(1); +maxHeap.push(3); +maxHeap.push(2); +maxHeap.push(5); +maxHeap.push(4); + +/* 힙의 루트 원소 구하기 */ +int peek = maxHeap.top(); // 5 + +/* 힙의 루트 원소 꺼내기 */ +// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 +maxHeap.pop(); // 5 +maxHeap.pop(); // 4 +maxHeap.pop(); // 3 +maxHeap.pop(); // 2 +maxHeap.pop(); // 1 + +/* 힙의 크기 구하기 */ +int size = maxHeap.size(); + +/* 힙이 비어 있는지 확인 */ +bool isEmpty = maxHeap.empty(); + +/* 리스트를 입력받아 힙 구성 */ +vector input{1, 3, 2, 5, 4}; +priority_queue, greater> minHeap(input.begin(), input.end()); +``` + +```java title="heap.java" +/* 힙 초기화 */ +// 최소 힙 초기화 +Queue minHeap = new PriorityQueue<>(); +// 최대 힙 초기화(lambda 식으로 Comparator를 수정하면 된다) +Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + +/* 힙에 원소 삽입 */ +maxHeap.offer(1); +maxHeap.offer(3); +maxHeap.offer(2); +maxHeap.offer(5); +maxHeap.offer(4); + +/* 힙의 루트 원소 구하기 */ +int peek = maxHeap.peek(); // 5 + +/* 힙의 루트 원소 꺼내기 */ +// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 +peek = maxHeap.poll(); // 5 +peek = maxHeap.poll(); // 4 +peek = maxHeap.poll(); // 3 +peek = maxHeap.poll(); // 2 +peek = maxHeap.poll(); // 1 + +/* 힙의 크기 구하기 */ +int size = maxHeap.size(); + +/* 힙이 비어 있는지 확인 */ +boolean isEmpty = maxHeap.isEmpty(); + +/* 리스트를 입력받아 힙 구성 */ +minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +``` + +```csharp title="heap.cs" +/* 힙 초기화 */ +// 최소 힙 초기화 +PriorityQueue minHeap = new(); +// 최대 힙 초기화(lambda 식으로 Comparer를 수정하면 된다) +PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + +/* 힙에 원소 삽입 */ +maxHeap.Enqueue(1, 1); +maxHeap.Enqueue(3, 3); +maxHeap.Enqueue(2, 2); +maxHeap.Enqueue(5, 5); +maxHeap.Enqueue(4, 4); + +/* 힙의 루트 원소 구하기 */ +int peek = maxHeap.Peek();//5 + +/* 힙의 루트 원소 꺼내기 */ +// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 + +/* 힙의 크기 구하기 */ +int size = maxHeap.Count; + +/* 힙이 비어 있는지 확인 */ +bool isEmpty = maxHeap.Count == 0; + +/* 리스트를 입력받아 힙 구성 */ +minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +``` + +```go title="heap.go" +// Go에서는 heap.Interface를 구현하여 정수 최대 힙을 만들 수 있다 +// heap.Interface를 구현하려면 sort.Interface도 구현해야 한다 +type intHeap []any + +// Push는 heap.Interface의 메서드로, 힙에 원소를 삽입한다 +func (h *intHeap) Push(x any) { + // Push와 Pop은 포인터 리시버(pointer receiver)를 매개변수로 사용한다 + // 슬라이스의 내용뿐 아니라 길이도 수정하기 때문이다. + *h = append(*h, x.(int)) +} + +// Pop은 heap.Interface의 메서드로, 힙의 루트 원소를 꺼낸다 +func (h *intHeap) Pop() any { + // 꺼낼 원소는 맨 끝에 저장되어 있다 + last := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return last +} + +// Len은 sort.Interface의 메서드다 +func (h *intHeap) Len() int { + return len(*h) +} + +// Less는 sort.Interface의 메서드다 +func (h *intHeap) Less(i, j int) bool { + // 최소 힙을 구현하려면 부등호를 <로 바꿔야 한다 + return (*h)[i].(int) > (*h)[j].(int) +} + +// Swap은 sort.Interface의 메서드다 +func (h *intHeap) Swap(i, j int) { + (*h)[i], (*h)[j] = (*h)[j], (*h)[i] +} + +// Top은 힙의 루트 원소를 구한다 +func (h *intHeap) Top() any { + return (*h)[0] +} + +/* 실행 코드 */ +func TestHeap(t *testing.T) { + /* 힙 초기화 */ + // 최대 힙 초기화 + maxHeap := &intHeap{} + heap.Init(maxHeap) + /* 힙에 원소 삽입 */ + // heap.Interface의 메서드를 호출하여 원소를 추가한다 + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 4) + heap.Push(maxHeap, 5) + + /* 힙의 루트 원소 구하기 */ + top := maxHeap.Top() + fmt.Printf("힙의 루트 원소: %d\n", top) + + /* 힙의 루트 원소 꺼내기 */ + // heap.Interface의 메서드를 호출하여 원소를 제거한다 + heap.Pop(maxHeap) // 5 + heap.Pop(maxHeap) // 4 + heap.Pop(maxHeap) // 3 + heap.Pop(maxHeap) // 2 + heap.Pop(maxHeap) // 1 + + /* 힙의 크기 구하기 */ + size := len(*maxHeap) + fmt.Printf("힙의 원소 수: %d\n", size) + + /* 힙이 비어 있는지 확인 */ + isEmpty := len(*maxHeap) == 0 + fmt.Printf("힙이 비어 있는가: %t\n", isEmpty) +} +``` + +```swift title="heap.swift" +/* 힙 초기화 */ +// Swift의 Heap 타입은 최대 힙과 최소 힙을 모두 지원하며, swift-collections를 가져와야 한다 +var heap = Heap() + +/* 힙에 원소 삽입 */ +heap.insert(1) +heap.insert(3) +heap.insert(2) +heap.insert(5) +heap.insert(4) + +/* 힙의 루트 원소 구하기 */ +var peek = heap.max()! + +/* 힙의 루트 원소 꺼내기 */ +peek = heap.removeMax() // 5 +peek = heap.removeMax() // 4 +peek = heap.removeMax() // 3 +peek = heap.removeMax() // 2 +peek = heap.removeMax() // 1 + +/* 힙의 크기 구하기 */ +let size = heap.count + +/* 힙이 비어 있는지 확인 */ +let isEmpty = heap.isEmpty + +/* 리스트를 입력받아 힙 구성 */ +let heap2 = Heap([1, 3, 2, 5, 4]) +``` + +```javascript title="heap.js" +// JavaScript는 내장 Heap 클래스를 제공하지 않는다 +``` + +```typescript title="heap.ts" +// TypeScript는 내장 Heap 클래스를 제공하지 않는다 +``` + +```dart title="heap.dart" +// Dart는 내장 Heap 클래스를 제공하지 않는다 +``` + +```rust title="heap.rs" +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +/* 힙 초기화 */ +// 최소 힙 초기화 +let mut min_heap = BinaryHeap::>::new(); +// 최대 힙 초기화 +let mut max_heap = BinaryHeap::new(); + +/* 힙에 원소 삽입 */ +max_heap.push(1); +max_heap.push(3); +max_heap.push(2); +max_heap.push(5); +max_heap.push(4); + +/* 힙의 루트 원소 구하기 */ +let peek = max_heap.peek().unwrap(); // 5 + +/* 힙의 루트 원소 꺼내기 */ +// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 + +/* 힙의 크기 구하기 */ +let size = max_heap.len(); + +/* 힙이 비어 있는지 확인 */ +let is_empty = max_heap.is_empty(); + +/* 리스트를 입력받아 힙 구성 */ +let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +``` + +```c title="heap.c" +// C는 내장 Heap 클래스를 제공하지 않는다 +``` + +```kotlin title="heap.kt" +/* 힙 초기화 */ +// 최소 힙 초기화 +var minHeap = PriorityQueue() +// 최대 힙 초기화(lambda 식으로 Comparator를 수정하면 된다) +val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + +/* 힙에 원소 삽입 */ +maxHeap.offer(1) +maxHeap.offer(3) +maxHeap.offer(2) +maxHeap.offer(5) +maxHeap.offer(4) + +/* 힙의 루트 원소 구하기 */ +var peek = maxHeap.peek() // 5 + +/* 힙의 루트 원소 꺼내기 */ +// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 +peek = maxHeap.poll() // 5 +peek = maxHeap.poll() // 4 +peek = maxHeap.poll() // 3 +peek = maxHeap.poll() // 2 +peek = maxHeap.poll() // 1 + +/* 힙의 크기 구하기 */ +val size = maxHeap.size + +/* 힙이 비어 있는지 확인 */ +val isEmpty = maxHeap.isEmpty() + +/* 리스트를 입력받아 힙 구성 */ +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +``` + +```ruby title="heap.rb" +# Ruby는 내장 Heap 클래스를 제공하지 않는다 +``` + + +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%EC%9D%98%20heapq%20%EB%AA%A8%EB%93%88%EC%9D%80%20%EA%B8%B0%EB%B3%B8%EC%A0%81%EC%9C%BC%EB%A1%9C%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%EC%9D%84%20%EA%B5%AC%ED%98%84%ED%95%9C%EB%8B%A4%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%EC%9D%98%20%EB%B6%80%ED%98%B8%EB%A5%BC%20%EB%B0%94%EA%BE%BC%20%EB%92%A4%20%EC%82%BD%EC%9E%85%ED%95%98%EB%A9%B4%20%EB%8C%80%EC%86%8C%20%EA%B4%80%EA%B3%84%EA%B0%80%20%EB%92%A4%EC%A7%91%ED%9E%88%EB%AF%80%EB%A1%9C%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%EC%9D%84%20%EA%B5%AC%ED%98%84%ED%95%A0%20%EC%88%98%20%EC%9E%88%EB%8B%A4%0A%20%20%20%20%23%20%EC%9D%B4%20%EC%98%88%EC%A0%9C%EC%97%90%EC%84%9C%20flag%20%3D%201%EC%9D%B4%EB%A9%B4%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%2C%20flag%20%3D%20-1%EC%9D%B4%EB%A9%B4%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%EC%97%90%20%ED%95%B4%EB%8B%B9%ED%95%9C%EB%8B%A4%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%EB%A3%A8%ED%8A%B8%20%EC%9B%90%EC%86%8C%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%EB%A3%A8%ED%8A%B8%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20%23%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%EB%93%A4%EC%9D%80%20%ED%81%B0%20%EA%B0%92%EB%B6%80%ED%84%B0%20%EC%9E%91%EC%9D%80%20%EA%B0%92%20%EC%88%9C%EC%84%9C%EB%A1%9C%20%EB%82%98%EC%97%B4%EB%90%9C%EB%8B%A4%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%ED%81%AC%EA%B8%B0%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A5%BC%20%EC%9E%85%EB%A0%A5%EB%B0%9B%EC%95%84%20%ED%9E%99%20%EA%B5%AC%EC%84%B1%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_preface/suggestions.md b/ko/codes/snippets/chapter_preface/suggestions.md new file mode 100644 index 000000000..9b97ae9dc --- /dev/null +++ b/ko/codes/snippets/chapter_preface/suggestions.md @@ -0,0 +1,139 @@ + +```python title="" +"""함수, 클래스, 테스트 사례 등을 표시하는 제목 주석""" + +# 코드를 자세히 설명하는 설명 주석 + +""" +여러 줄 +주석 +""" +``` + +```cpp title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```java title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```csharp title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```go title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```swift title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```javascript title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```typescript title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```dart title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```rust title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +// 여러 줄 +// 주석 +``` + +```c title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```kotlin title="" +/* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ + +// 코드를 자세히 설명하는 설명 주석 + +/** + * 여러 줄 + * 주석 + */ +``` + +```ruby title="" +### 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 ### + +# 코드를 자세히 설명하는 설명 주석 + +# 여러 줄 +# 주석 +``` diff --git a/ko/codes/snippets/chapter_stack_and_queue/deque.md b/ko/codes/snippets/chapter_stack_and_queue/deque.md new file mode 100644 index 000000000..465f2364c --- /dev/null +++ b/ko/codes/snippets/chapter_stack_and_queue/deque.md @@ -0,0 +1,339 @@ + +```python title="deque.py" +from collections import deque + +# 덱 초기화 +deq: deque[int] = deque() + +# 덱에 원소 삽입 +deq.append(2) # 맨 뒤에 추가 +deq.append(5) +deq.append(4) +deq.appendleft(3) # 맨 앞에 추가 +deq.appendleft(1) + +# 원소 접근 +front: int = deq[0] # 맨 앞 원소 +rear: int = deq[-1] # 맨 뒤 원소 + +# 덱에서 원소 꺼내기 +pop_front: int = deq.popleft() # 맨 앞 원소 꺼내기 +pop_rear: int = deq.pop() # 맨 뒤 원소 꺼내기 + +# 덱 길이 구하기 +size: int = len(deq) + +# 덱이 비어 있는지 확인 +is_empty: bool = len(deq) == 0 +``` + +```cpp title="deque.cpp" +/* 덱 초기화 */ +deque deque; + +/* 덱에 원소 삽입 */ +deque.push_back(2); // 맨 뒤에 추가 +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // 맨 앞에 추가 +deque.push_front(1); + +/* 원소 접근 */ +int front = deque.front(); // 맨 앞 원소 +int back = deque.back(); // 맨 뒤 원소 + +/* 덱에서 원소 꺼내기 */ +deque.pop_front(); // 맨 앞 원소 꺼내기 +deque.pop_back(); // 맨 뒤 원소 꺼내기 + +/* 덱 길이 구하기 */ +int size = deque.size(); + +/* 덱이 비어 있는지 확인 */ +bool empty = deque.empty(); +``` + +```java title="deque.java" +/* 덱 초기화 */ +Deque deque = new LinkedList<>(); + +/* 덱에 원소 삽입 */ +deque.offerLast(2); // 맨 뒤에 추가 +deque.offerLast(5); +deque.offerLast(4); +deque.offerFirst(3); // 맨 앞에 추가 +deque.offerFirst(1); + +/* 원소 접근 */ +int peekFirst = deque.peekFirst(); // 맨 앞 원소 +int peekLast = deque.peekLast(); // 맨 뒤 원소 + +/* 덱에서 원소 꺼내기 */ +int popFirst = deque.pollFirst(); // 맨 앞 원소 꺼내기 +int popLast = deque.pollLast(); // 맨 뒤 원소 꺼내기 + +/* 덱 길이 구하기 */ +int size = deque.size(); + +/* 덱이 비어 있는지 확인 */ +boolean isEmpty = deque.isEmpty(); +``` + +```csharp title="deque.cs" +/* 덱 초기화 */ +// C#에서는 연결 리스트 LinkedList를 덱으로 사용한다 +LinkedList deque = new(); + +/* 덱에 원소 삽입 */ +deque.AddLast(2); // 맨 뒤에 추가 +deque.AddLast(5); +deque.AddLast(4); +deque.AddFirst(3); // 맨 앞에 추가 +deque.AddFirst(1); + +/* 원소 접근 */ +int peekFirst = deque.First.Value; // 맨 앞 원소 +int peekLast = deque.Last.Value; // 맨 뒤 원소 + +/* 덱에서 원소 꺼내기 */ +deque.RemoveFirst(); // 맨 앞 원소 꺼내기 +deque.RemoveLast(); // 맨 뒤 원소 꺼내기 + +/* 덱 길이 구하기 */ +int size = deque.Count; + +/* 덱이 비어 있는지 확인 */ +bool isEmpty = deque.Count == 0; +``` + +```go title="deque_test.go" +/* 덱 초기화 */ +// Go에서는 list를 덱으로 사용한다 +deque := list.New() + +/* 덱에 원소 삽입 */ +deque.PushBack(2) // 맨 뒤에 추가 +deque.PushBack(5) +deque.PushBack(4) +deque.PushFront(3) // 맨 앞에 추가 +deque.PushFront(1) + +/* 원소 접근 */ +front := deque.Front() // 맨 앞 원소 +rear := deque.Back() // 맨 뒤 원소 + +/* 덱에서 원소 꺼내기 */ +deque.Remove(front) // 맨 앞 원소 꺼내기 +deque.Remove(rear) // 맨 뒤 원소 꺼내기 + +/* 덱 길이 구하기 */ +size := deque.Len() + +/* 덱이 비어 있는지 확인 */ +isEmpty := deque.Len() == 0 +``` + +```swift title="deque.swift" +/* 덱 초기화 */ +// Swift에는 내장 덱 클래스가 없으므로 Array를 덱으로 사용할 수 있다 +var deque: [Int] = [] + +/* 덱에 원소 삽입 */ +deque.append(2) // 맨 뒤에 추가 +deque.append(5) +deque.append(4) +deque.insert(3, at: 0) // 맨 앞에 추가 +deque.insert(1, at: 0) + +/* 원소 접근 */ +let peekFirst = deque.first! // 맨 앞 원소 +let peekLast = deque.last! // 맨 뒤 원소 + +/* 덱에서 원소 꺼내기 */ +// Array로 구현하면 popFirst의 복잡도는 O(n)이다 +let popFirst = deque.removeFirst() // 맨 앞 원소 꺼내기 +let popLast = deque.removeLast() // 맨 뒤 원소 꺼내기 + +/* 덱 길이 구하기 */ +let size = deque.count + +/* 덱이 비어 있는지 확인 */ +let isEmpty = deque.isEmpty +``` + +```javascript title="deque.js" +/* 덱 초기화 */ +// JavaScript에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 +const deque = []; + +/* 덱에 원소 삽입 */ +deque.push(2); +deque.push(5); +deque.push(4); +// 배열이므로 unshift() 메서드의 시간 복잡도는 O(n)임에 주의 +deque.unshift(3); +deque.unshift(1); + +/* 원소 접근 */ +const peekFirst = deque[0]; +const peekLast = deque[deque.length - 1]; + +/* 덱에서 원소 꺼내기 */ +// 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 주의 +const popFront = deque.shift(); +const popBack = deque.pop(); + +/* 덱 길이 구하기 */ +const size = deque.length; + +/* 덱이 비어 있는지 확인 */ +const isEmpty = size === 0; +``` + +```typescript title="deque.ts" +/* 덱 초기화 */ +// TypeScript에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 +const deque: number[] = []; + +/* 덱에 원소 삽입 */ +deque.push(2); +deque.push(5); +deque.push(4); +// 배열이므로 unshift() 메서드의 시간 복잡도는 O(n)임에 주의 +deque.unshift(3); +deque.unshift(1); + +/* 원소 접근 */ +const peekFirst: number = deque[0]; +const peekLast: number = deque[deque.length - 1]; + +/* 덱에서 원소 꺼내기 */ +// 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 주의 +const popFront: number = deque.shift() as number; +const popBack: number = deque.pop() as number; + +/* 덱 길이 구하기 */ +const size: number = deque.length; + +/* 덱이 비어 있는지 확인 */ +const isEmpty: boolean = size === 0; +``` + +```dart title="deque.dart" +/* 덱 초기화 */ +// Dart의 Queue는 덱으로 정의되어 있다 +Queue deque = Queue(); + +/* 덱에 원소 삽입 */ +deque.addLast(2); // 맨 뒤에 추가 +deque.addLast(5); +deque.addLast(4); +deque.addFirst(3); // 맨 앞에 추가 +deque.addFirst(1); + +/* 원소 접근 */ +int peekFirst = deque.first; // 맨 앞 원소 +int peekLast = deque.last; // 맨 뒤 원소 + +/* 덱에서 원소 꺼내기 */ +int popFirst = deque.removeFirst(); // 맨 앞 원소 꺼내기 +int popLast = deque.removeLast(); // 맨 뒤 원소 꺼내기 + +/* 덱 길이 구하기 */ +int size = deque.length; + +/* 덱이 비어 있는지 확인 */ +bool isEmpty = deque.isEmpty; +``` + +```rust title="deque.rs" +/* 덱 초기화 */ +let mut deque: VecDeque = VecDeque::new(); + +/* 덱에 원소 삽입 */ +deque.push_back(2); // 맨 뒤에 추가 +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // 맨 앞에 추가 +deque.push_front(1); + +/* 원소 접근 */ +if let Some(front) = deque.front() { // 맨 앞 원소 +} +if let Some(rear) = deque.back() { // 맨 뒤 원소 +} + +/* 덱에서 원소 꺼내기 */ +if let Some(pop_front) = deque.pop_front() { // 맨 앞 원소 꺼내기 +} +if let Some(pop_rear) = deque.pop_back() { // 맨 뒤 원소 꺼내기 +} + +/* 덱 길이 구하기 */ +let size = deque.len(); + +/* 덱이 비어 있는지 확인 */ +let is_empty = deque.is_empty(); +``` + +```c title="deque.c" +// C는 내장 덱을 제공하지 않는다 +``` + +```kotlin title="deque.kt" +/* 덱 초기화 */ +val deque = LinkedList() + +/* 덱에 원소 삽입 */ +deque.offerLast(2) // 맨 뒤에 추가 +deque.offerLast(5) +deque.offerLast(4) +deque.offerFirst(3) // 맨 앞에 추가 +deque.offerFirst(1) + +/* 원소 접근 */ +val peekFirst = deque.peekFirst() // 맨 앞 원소 +val peekLast = deque.peekLast() // 맨 뒤 원소 + +/* 덱에서 원소 꺼내기 */ +val popFirst = deque.pollFirst() // 맨 앞 원소 꺼내기 +val popLast = deque.pollLast() // 맨 뒤 원소 꺼내기 + +/* 덱 길이 구하기 */ +val size = deque.size + +/* 덱이 비어 있는지 확인 */ +val isEmpty = deque.isEmpty() +``` + +```ruby title="deque.rb" +# 덱 초기화 +# Ruby에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 +deque = [] + +# 덱에 원소 삽입 +deque << 2 +deque << 5 +deque << 4 +# 배열이므로 Array#unshift 메서드의 시간 복잡도는 O(n)임에 주의 +deque.unshift(3) +deque.unshift(1) + +# 원소 접근 +peek_first = deque.first +peek_last = deque.last + +# 덱에서 원소 꺼내기 +# 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 주의 +pop_front = deque.shift +pop_back = deque.pop + +# 덱 길이 구하기 +size = deque.length + +# 덱이 비어 있는지 확인 +is_empty = size.zero? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%8D%B1%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%EB%8D%B1%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20deq.append%282%29%20%20%23%20%EB%A7%A8%20%EB%92%A4%EC%97%90%20%EC%B6%94%EA%B0%80%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20%EB%A7%A8%20%EC%95%9E%EC%97%90%20%EC%B6%94%EA%B0%80%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22%EB%8D%B1%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%0A%20%20%20%20print%28%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20front%20%3D%22%2C%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%EB%A7%A8%20%EB%92%A4%20%EC%9B%90%EC%86%8C%0A%20%20%20%20print%28%22%EB%A7%A8%20%EB%92%A4%20%EC%9B%90%EC%86%8C%20rear%20%3D%22%2C%20rear%29%0A%0A%20%20%20%20%23%20%EB%8D%B1%EC%97%90%EC%84%9C%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20print%28%22%EB%A7%A8%20%EC%95%9E%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20%20pop_front%20%3D%22%2C%20pop_front%29%0A%20%20%20%20print%28%22%EB%A7%A8%20%EC%95%9E%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EB%92%A4%20deque%20%3D%22%2C%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20%EB%A7%A8%20%EB%92%A4%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20print%28%22%EB%A7%A8%20%EB%92%A4%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20%20pop_rear%20%3D%22%2C%20pop_rear%29%0A%20%20%20%20print%28%22%EB%A7%A8%20%EB%92%A4%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EB%92%A4%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%EB%8D%B1%20%EA%B8%B8%EC%9D%B4%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22%EB%8D%B1%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%EB%8D%B1%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22%EB%8D%B1%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_stack_and_queue/queue.md b/ko/codes/snippets/chapter_stack_and_queue/queue.md new file mode 100644 index 000000000..1c7c87436 --- /dev/null +++ b/ko/codes/snippets/chapter_stack_and_queue/queue.md @@ -0,0 +1,313 @@ + +```python title="queue.py" +from collections import deque + +# 큐 초기화 +# Python에서는 보통 덱 클래스 deque를 큐로 사용한다 +# queue.Queue()는 전용 큐 클래스이지만 사용이 불편하므로 권하지 않는다 +que: deque[int] = deque() + +# 큐에 원소 삽입 +que.append(1) +que.append(3) +que.append(2) +que.append(5) +que.append(4) + +# 큐의 맨 앞 원소에 접근 +front: int = que[0] + +# 큐에서 원소 꺼내기 +pop: int = que.popleft() + +# 큐 길이 구하기 +size: int = len(que) + +# 큐가 비어 있는지 확인 +is_empty: bool = len(que) == 0 +``` + +```cpp title="queue.cpp" +/* 큐 초기화 */ +queue queue; + +/* 큐에 원소 삽입 */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 큐의 맨 앞 원소에 접근 */ +int front = queue.front(); + +/* 큐에서 원소 꺼내기 */ +queue.pop(); + +/* 큐 길이 구하기 */ +int size = queue.size(); + +/* 큐가 비어 있는지 확인 */ +bool empty = queue.empty(); +``` + +```java title="queue.java" +/* 큐 초기화 */ +Queue queue = new LinkedList<>(); + +/* 큐에 원소 삽입 */ +queue.offer(1); +queue.offer(3); +queue.offer(2); +queue.offer(5); +queue.offer(4); + +/* 큐의 맨 앞 원소에 접근 */ +int peek = queue.peek(); + +/* 큐에서 원소 꺼내기 */ +int pop = queue.poll(); + +/* 큐 길이 구하기 */ +int size = queue.size(); + +/* 큐가 비어 있는지 확인 */ +boolean isEmpty = queue.isEmpty(); +``` + +```csharp title="queue.cs" +/* 큐 초기화 */ +Queue queue = new(); + +/* 큐에 원소 삽입 */ +queue.Enqueue(1); +queue.Enqueue(3); +queue.Enqueue(2); +queue.Enqueue(5); +queue.Enqueue(4); + +/* 큐의 맨 앞 원소에 접근 */ +int peek = queue.Peek(); + +/* 큐에서 원소 꺼내기 */ +int pop = queue.Dequeue(); + +/* 큐 길이 구하기 */ +int size = queue.Count; + +/* 큐가 비어 있는지 확인 */ +bool isEmpty = queue.Count == 0; +``` + +```go title="queue_test.go" +/* 큐 초기화 */ +// Go에서는 list를 큐로 사용한다 +queue := list.New() + +/* 큐에 원소 삽입 */ +queue.PushBack(1) +queue.PushBack(3) +queue.PushBack(2) +queue.PushBack(5) +queue.PushBack(4) + +/* 큐의 맨 앞 원소에 접근 */ +peek := queue.Front() + +/* 큐에서 원소 꺼내기 */ +pop := queue.Front() +queue.Remove(pop) + +/* 큐 길이 구하기 */ +size := queue.Len() + +/* 큐가 비어 있는지 확인 */ +isEmpty := queue.Len() == 0 +``` + +```swift title="queue.swift" +/* 큐 초기화 */ +// Swift에는 내장 큐 클래스가 없으므로 Array를 큐로 사용할 수 있다 +var queue: [Int] = [] + +/* 큐에 원소 삽입 */ +queue.append(1) +queue.append(3) +queue.append(2) +queue.append(5) +queue.append(4) + +/* 큐의 맨 앞 원소에 접근 */ +let peek = queue.first! + +/* 큐에서 원소 꺼내기 */ +// 배열이므로 removeFirst의 복잡도는 O(n)이다 +let pop = queue.removeFirst() + +/* 큐 길이 구하기 */ +let size = queue.count + +/* 큐가 비어 있는지 확인 */ +let isEmpty = queue.isEmpty +``` + +```javascript title="queue.js" +/* 큐 초기화 */ +// JavaScript에는 내장 큐가 없으므로 Array를 큐로 사용할 수 있다 +const queue = []; + +/* 큐에 원소 삽입 */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 큐의 맨 앞 원소에 접근 */ +const peek = queue[0]; + +/* 큐에서 원소 꺼내기 */ +// 기반이 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 +const pop = queue.shift(); + +/* 큐 길이 구하기 */ +const size = queue.length; + +/* 큐가 비어 있는지 확인 */ +const empty = queue.length === 0; +``` + +```typescript title="queue.ts" +/* 큐 초기화 */ +// TypeScript에는 내장 큐가 없으므로 Array를 큐로 사용할 수 있다 +const queue: number[] = []; + +/* 큐에 원소 삽입 */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 큐의 맨 앞 원소에 접근 */ +const peek = queue[0]; + +/* 큐에서 원소 꺼내기 */ +// 기반이 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 +const pop = queue.shift(); + +/* 큐 길이 구하기 */ +const size = queue.length; + +/* 큐가 비어 있는지 확인 */ +const empty = queue.length === 0; +``` + +```dart title="queue.dart" +/* 큐 초기화 */ +// Dart의 Queue 클래스는 덱이며 일반 큐로도 사용할 수 있다 +Queue queue = Queue(); + +/* 큐에 원소 삽입 */ +queue.add(1); +queue.add(3); +queue.add(2); +queue.add(5); +queue.add(4); + +/* 큐의 맨 앞 원소에 접근 */ +int peek = queue.first; + +/* 큐에서 원소 꺼내기 */ +int pop = queue.removeFirst(); + +/* 큐 길이 구하기 */ +int size = queue.length; + +/* 큐가 비어 있는지 확인 */ +bool isEmpty = queue.isEmpty; +``` + +```rust title="queue.rs" +/* 덱 초기화 */ +// Rust에서는 덱을 일반 큐로 사용한다 +let mut deque: VecDeque = VecDeque::new(); + +/* 큐에 원소 삽입 */ +deque.push_back(1); +deque.push_back(3); +deque.push_back(2); +deque.push_back(5); +deque.push_back(4); + +/* 큐의 맨 앞 원소에 접근 */ +if let Some(front) = deque.front() { +} + +/* 큐에서 원소 꺼내기 */ +if let Some(pop) = deque.pop_front() { +} + +/* 큐 길이 구하기 */ +let size = deque.len(); + +/* 큐가 비어 있는지 확인 */ +let is_empty = deque.is_empty(); +``` + +```c title="queue.c" +// C는 내장 큐를 제공하지 않는다 +``` + +```kotlin title="queue.kt" +/* 큐 초기화 */ +val queue = LinkedList() + +/* 큐에 원소 삽입 */ +queue.offer(1) +queue.offer(3) +queue.offer(2) +queue.offer(5) +queue.offer(4) + +/* 큐의 맨 앞 원소에 접근 */ +val peek = queue.peek() + +/* 큐에서 원소 꺼내기 */ +val pop = queue.poll() + +/* 큐 길이 구하기 */ +val size = queue.size + +/* 큐가 비어 있는지 확인 */ +val isEmpty = queue.isEmpty() +``` + +```ruby title="queue.rb" +# 큐 초기화 +# Ruby의 내장 큐(Thread::Queue)에는 peek와 순회 메서드가 없으므로 Array를 큐로 사용할 수 있다 +queue = [] + +# 큐에 원소 삽입 +queue.push(1) +queue.push(3) +queue.push(2) +queue.push(5) +queue.push(4) + +# 큐 원소에 접근 +peek = queue.first + +# 큐에서 원소 꺼내기 +# 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 주의 +pop = queue.shift + +# 큐 길이 구하기 +size = queue.length + +# 큐가 비어 있는지 확인 +is_empty = queue.empty? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%ED%81%90%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20Python%EC%97%90%EC%84%9C%EB%8A%94%20%EB%B3%B4%ED%86%B5%20%EB%8D%B1%20%ED%81%B4%EB%9E%98%EC%8A%A4%20deque%EB%A5%BC%20%ED%81%90%EB%A1%9C%20%EC%82%AC%EC%9A%A9%ED%95%9C%EB%8B%A4%0A%20%20%20%20%23%20queue.Queue%28%29%EB%8A%94%20%EC%A0%84%EC%9A%A9%20%ED%81%90%20%ED%81%B4%EB%9E%98%EC%8A%A4%EC%9D%B4%EC%A7%80%EB%A7%8C%20%EC%82%AC%EC%9A%A9%EC%9D%B4%20%EB%B6%88%ED%8E%B8%ED%95%98%EB%8B%A4%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%ED%81%90%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22%ED%81%90%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%ED%81%90%EC%9D%98%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%EC%97%90%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22%ED%81%90%EC%9D%98%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20front%20%3D%22%2C%20front%29%0A%0A%20%20%20%20%23%20%ED%81%90%EC%97%90%EC%84%9C%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%EC%9B%90%EC%86%8C%EB%A5%BC%20%EA%BA%BC%EB%82%B8%20%EB%92%A4%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%ED%81%90%20%EA%B8%B8%EC%9D%B4%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22%ED%81%90%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_stack_and_queue/stack.md b/ko/codes/snippets/chapter_stack_and_queue/stack.md new file mode 100644 index 000000000..a8f6ce82d --- /dev/null +++ b/ko/codes/snippets/chapter_stack_and_queue/stack.md @@ -0,0 +1,304 @@ + +```python title="stack.py" +# 스택 초기화 +# Python에는 내장 스택 클래스가 없으므로 list를 스택으로 사용할 수 있다 +stack: list[int] = [] + +# 스택에 원소 삽입 +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +# 스택 맨 위 원소에 접근 +peek: int = stack[-1] + +# 스택에서 원소 꺼내기 +pop: int = stack.pop() + +# 스택 길이 구하기 +size: int = len(stack) + +# 비어 있는지 확인 +is_empty: bool = len(stack) == 0 +``` + +```cpp title="stack.cpp" +/* 스택 초기화 */ +stack stack; + +/* 스택에 원소 삽입 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 스택 맨 위 원소에 접근 */ +int top = stack.top(); + +/* 스택에서 원소 꺼내기 */ +stack.pop(); // 반환값 없음 + +/* 스택 길이 구하기 */ +int size = stack.size(); + +/* 비어 있는지 확인 */ +bool empty = stack.empty(); +``` + +```java title="stack.java" +/* 스택 초기화 */ +Stack stack = new Stack<>(); + +/* 스택에 원소 삽입 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 스택 맨 위 원소에 접근 */ +int peek = stack.peek(); + +/* 스택에서 원소 꺼내기 */ +int pop = stack.pop(); + +/* 스택 길이 구하기 */ +int size = stack.size(); + +/* 비어 있는지 확인 */ +boolean isEmpty = stack.isEmpty(); +``` + +```csharp title="stack.cs" +/* 스택 초기화 */ +Stack stack = new(); + +/* 스택에 원소 삽입 */ +stack.Push(1); +stack.Push(3); +stack.Push(2); +stack.Push(5); +stack.Push(4); + +/* 스택 맨 위 원소에 접근 */ +int peek = stack.Peek(); + +/* 스택에서 원소 꺼내기 */ +int pop = stack.Pop(); + +/* 스택 길이 구하기 */ +int size = stack.Count; + +/* 비어 있는지 확인 */ +bool isEmpty = stack.Count == 0; +``` + +```go title="stack_test.go" +/* 스택 초기화 */ +// Go에서는 Slice를 스택으로 사용하는 것을 권한다 +var stack []int + +/* 스택에 원소 삽입 */ +stack = append(stack, 1) +stack = append(stack, 3) +stack = append(stack, 2) +stack = append(stack, 5) +stack = append(stack, 4) + +/* 스택 맨 위 원소에 접근 */ +peek := stack[len(stack)-1] + +/* 스택에서 원소 꺼내기 */ +pop := stack[len(stack)-1] +stack = stack[:len(stack)-1] + +/* 스택 길이 구하기 */ +size := len(stack) + +/* 비어 있는지 확인 */ +isEmpty := len(stack) == 0 +``` + +```swift title="stack.swift" +/* 스택 초기화 */ +// Swift에는 내장 스택 클래스가 없으므로 Array를 스택으로 사용할 수 있다 +var stack: [Int] = [] + +/* 스택에 원소 삽입 */ +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +/* 스택 맨 위 원소에 접근 */ +let peek = stack.last! + +/* 스택에서 원소 꺼내기 */ +let pop = stack.removeLast() + +/* 스택 길이 구하기 */ +let size = stack.count + +/* 비어 있는지 확인 */ +let isEmpty = stack.isEmpty +``` + +```javascript title="stack.js" +/* 스택 초기화 */ +// JavaScript에는 내장 스택 클래스가 없으므로 Array를 스택으로 사용할 수 있다 +const stack = []; + +/* 스택에 원소 삽입 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 스택 맨 위 원소에 접근 */ +const peek = stack[stack.length-1]; + +/* 스택에서 원소 꺼내기 */ +const pop = stack.pop(); + +/* 스택 길이 구하기 */ +const size = stack.length; + +/* 비어 있는지 확인 */ +const is_empty = stack.length === 0; +``` + +```typescript title="stack.ts" +/* 스택 초기화 */ +// TypeScript에는 내장 스택 클래스가 없으므로 Array를 스택으로 사용할 수 있다 +const stack: number[] = []; + +/* 스택에 원소 삽입 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 스택 맨 위 원소에 접근 */ +const peek = stack[stack.length - 1]; + +/* 스택에서 원소 꺼내기 */ +const pop = stack.pop(); + +/* 스택 길이 구하기 */ +const size = stack.length; + +/* 비어 있는지 확인 */ +const is_empty = stack.length === 0; +``` + +```dart title="stack.dart" +/* 스택 초기화 */ +// Dart에는 내장 스택 클래스가 없으므로 List를 스택으로 사용할 수 있다 +List stack = []; + +/* 스택에 원소 삽입 */ +stack.add(1); +stack.add(3); +stack.add(2); +stack.add(5); +stack.add(4); + +/* 스택 맨 위 원소에 접근 */ +int peek = stack.last; + +/* 스택에서 원소 꺼내기 */ +int pop = stack.removeLast(); + +/* 스택 길이 구하기 */ +int size = stack.length; + +/* 비어 있는지 확인 */ +bool isEmpty = stack.isEmpty; +``` + +```rust title="stack.rs" +/* 스택 초기화 */ +// Vec를 스택으로 사용 +let mut stack: Vec = Vec::new(); + +/* 스택에 원소 삽입 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 스택 맨 위 원소에 접근 */ +let top = stack.last().unwrap(); + +/* 스택에서 원소 꺼내기 */ +let pop = stack.pop().unwrap(); + +/* 스택 길이 구하기 */ +let size = stack.len(); + +/* 비어 있는지 확인 */ +let is_empty = stack.is_empty(); +``` + +```c title="stack.c" +// C는 내장 스택을 제공하지 않는다 +``` + +```kotlin title="stack.kt" +/* 스택 초기화 */ +val stack = Stack() + +/* 스택에 원소 삽입 */ +stack.push(1) +stack.push(3) +stack.push(2) +stack.push(5) +stack.push(4) + +/* 스택 맨 위 원소에 접근 */ +val peek = stack.peek() + +/* 스택에서 원소 꺼내기 */ +val pop = stack.pop() + +/* 스택 길이 구하기 */ +val size = stack.size + +/* 비어 있는지 확인 */ +val isEmpty = stack.isEmpty() +``` + +```ruby title="stack.rb" +# 스택 초기화 +# Ruby에는 내장 스택 클래스가 없으므로 Array를 스택으로 사용할 수 있다 +stack = [] + +# 스택에 원소 삽입 +stack << 1 +stack << 3 +stack << 2 +stack << 5 +stack << 4 + +# 스택 맨 위 원소에 접근 +peek = stack.last + +# 스택에서 원소 꺼내기 +pop = stack.pop + +# 스택 길이 구하기 +size = stack.length + +# 비어 있는지 확인 +is_empty = stack.empty? +``` + + +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20Python%EC%97%90%EB%8A%94%20%EB%82%B4%EC%9E%A5%20%EC%8A%A4%ED%83%9D%20%ED%81%B4%EB%9E%98%EC%8A%A4%EA%B0%80%20%EC%97%86%EC%9C%BC%EB%AF%80%EB%A1%9C%20list%EB%A5%BC%20%EC%8A%A4%ED%83%9D%EC%9C%BC%EB%A1%9C%20%EC%82%AC%EC%9A%A9%ED%95%A0%20%EC%88%98%20%EC%9E%88%EB%8B%A4%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22%EC%8A%A4%ED%83%9D%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%20%EB%A7%A8%20%EC%9C%84%20%EC%9B%90%EC%86%8C%EC%97%90%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22%EC%8A%A4%ED%83%9D%20%EB%A7%A8%20%EC%9C%84%20%EC%9B%90%EC%86%8C%20peek%20%3D%22%2C%20peek%29%0A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%EC%97%90%EC%84%9C%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%EC%9B%90%EC%86%8C%EB%A5%BC%20%EA%BA%BC%EB%82%B8%20%EB%92%A4%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%20%EA%B8%B8%EC%9D%B4%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22%EC%8A%A4%ED%83%9D%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22%EC%8A%A4%ED%83%9D%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_tree/array_representation_of_tree.md b/ko/codes/snippets/chapter_tree/array_representation_of_tree.md new file mode 100644 index 000000000..5c56c1bc2 --- /dev/null +++ b/ko/codes/snippets/chapter_tree/array_representation_of_tree.md @@ -0,0 +1,78 @@ + +```python title="" +# 이진 트리의 배열 표현 +# None으로 빈자리 표시 +tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] +``` + +```cpp title="" +/* 이진 트리의 배열 표현 */ +// int의 최댓값 INT_MAX로 빈자리 표시 +vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```java title="" +/* 이진 트리의 배열 표현 */ +// int의 래퍼 클래스 Integer를 사용하면 null로 빈자리를 표시할 수 있다 +Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; +``` + +```csharp title="" +/* 이진 트리의 배열 표현 */ +// 널 허용 타입 int?를 사용하면 null로 빈자리를 표시할 수 있다 +int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```go title="" +/* 이진 트리의 배열 표현 */ +// any 타입의 슬라이스를 사용하면 nil로 빈자리를 표시할 수 있다 +tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} +``` + +```swift title="" +/* 이진 트리의 배열 표현 */ +// 널 허용 타입 Int?를 사용하면 nil로 빈자리를 표시할 수 있다 +let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` + +```javascript title="" +/* 이진 트리의 배열 표현 */ +// null로 빈자리 표시 +let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```typescript title="" +/* 이진 트리의 배열 표현 */ +// null로 빈자리 표시 +let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```dart title="" +/* 이진 트리의 배열 표현 */ +// 널 허용 타입 int?를 사용하면 null로 빈자리를 표시할 수 있다 +List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```rust title="" +/* 이진 트리의 배열 표현 */ +// None으로 빈자리 표시 +let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; +``` + +```c title="" +/* 이진 트리의 배열 표현 */ +// int의 최댓값으로 빈자리를 표시하므로 노드 값은 INT_MAX이면 안 된다 +int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```kotlin title="" +/* 이진 트리의 배열 표현 */ +// null로 빈자리 표시 +val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) +``` + +```ruby title="" +### 이진 트리의 배열 표현 ### +# nil로 빈자리 표시 +tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` diff --git a/ko/codes/snippets/chapter_tree/avl_tree.md b/ko/codes/snippets/chapter_tree/avl_tree.md new file mode 100644 index 000000000..77e8009f4 --- /dev/null +++ b/ko/codes/snippets/chapter_tree/avl_tree.md @@ -0,0 +1,182 @@ + +```python title="" +class TreeNode: + """AVL 트리 노드 클래스""" + def __init__(self, val: int): + self.val: int = val # 노드 값 + self.height: int = 0 # 노드 높이 + self.left: TreeNode | None = None # 왼쪽 자식 노드 참조 + self.right: TreeNode | None = None # 오른쪽 자식 노드 참조 +``` + +```cpp title="" +/* AVL 트리 노드 클래스 */ +struct TreeNode { + int val{}; // 노드 값 + int height = 0; // 노드 높이 + TreeNode *left{}; // 왼쪽 자식 노드 + TreeNode *right{}; // 오른쪽 자식 노드 + TreeNode() = default; + explicit TreeNode(int x) : val(x){} +}; +``` + +```java title="" +/* AVL 트리 노드 클래스 */ +class TreeNode { + public int val; // 노드 값 + public int height; // 노드 높이 + public TreeNode left; // 왼쪽 자식 노드 + public TreeNode right; // 오른쪽 자식 노드 + public TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* AVL 트리 노드 클래스 */ +class TreeNode(int? x) { + public int? val = x; // 노드 값 + public int height; // 노드 높이 + public TreeNode? left; // 왼쪽 자식 노드 참조 + public TreeNode? right; // 오른쪽 자식 노드 참조 +} +``` + +```go title="" +/* AVL 트리 노드 구조체 */ +type TreeNode struct { + Val int // 노드 값 + Height int // 노드 높이 + Left *TreeNode // 왼쪽 자식 노드 참조 + Right *TreeNode // 오른쪽 자식 노드 참조 +} +``` + +```swift title="" +/* AVL 트리 노드 클래스 */ +class TreeNode { + var val: Int // 노드 값 + var height: Int // 노드 높이 + var left: TreeNode? // 왼쪽 자식 노드 + var right: TreeNode? // 오른쪽 자식 노드 + + init(x: Int) { + val = x + height = 0 + } +} +``` + +```javascript title="" +/* AVL 트리 노드 클래스 */ +class TreeNode { + val; // 노드 값 + height; //노드 높이 + left; // 왼쪽 자식 노드 포인터 + right; // 오른쪽 자식 노드 포인터 + constructor(val, left, right, height) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* AVL 트리 노드 클래스 */ +class TreeNode { + val: number; // 노드 값 + height: number; // 노드 높이 + left: TreeNode | null; // 왼쪽 자식 노드 포인터 + right: TreeNode | null; // 오른쪽 자식 노드 포인터 + constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```dart title="" +/* AVL 트리 노드 클래스 */ +class TreeNode { + int val; // 노드 값 + int height; // 노드 높이 + TreeNode? left; // 왼쪽 자식 노드 + TreeNode? right; // 오른쪽 자식 노드 + TreeNode(this.val, [this.height = 0, this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* AVL 트리 노드 구조체 */ +struct TreeNode { + val: i32, // 노드 값 + height: i32, // 노드 높이 + left: Option>>, // 왼쪽 자식 노드 + right: Option>>, // 오른쪽 자식 노드 +} + +impl TreeNode { + /* 생성자 */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + height: 0, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* AVL 트리 노드 구조체 */ +typedef struct TreeNode { + int val; + int height; + struct TreeNode *left; + struct TreeNode *right; +} TreeNode; + +/* 생성자 */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* AVL 트리 노드 클래스 */ +class TreeNode(val _val: Int) { // 노드 값 + var height: Int = 0 // 노드 높이 + var left: TreeNode? = null // 왼쪽 자식 노드 + var right: TreeNode? = null // 오른쪽 자식 노드 +} +``` + +```ruby title="" +### AVL 트리 노드 클래스 ### +class TreeNode + attr_accessor :val # 노드 값 + attr_accessor :height # 노드 높이 + attr_accessor :left # 왼쪽 자식 노드 참조 + attr_accessor :right # 오른쪽 자식 노드 참조 + + def initialize(val) + @val = val + @height = 0 + end +end +``` diff --git a/ko/codes/snippets/chapter_tree/binary_tree.md b/ko/codes/snippets/chapter_tree/binary_tree.md new file mode 100644 index 000000000..b43edb2f5 --- /dev/null +++ b/ko/codes/snippets/chapter_tree/binary_tree.md @@ -0,0 +1,502 @@ + +```python title="" +class TreeNode: + """이진 트리 노드 클래스""" + def __init__(self, val: int): + self.val: int = val # 노드 값 + self.left: TreeNode | None = None # 왼쪽 자식 노드 참조 + self.right: TreeNode | None = None # 오른쪽 자식 노드 참조 +``` + +```cpp title="" +/* 이진 트리 노드 구조체 */ +struct TreeNode { + int val; // 노드 값 + TreeNode *left; // 왼쪽 자식 노드 포인터 + TreeNode *right; // 오른쪽 자식 노드 포인터 + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; +``` + +```java title="" +/* 이진 트리 노드 클래스 */ +class TreeNode { + int val; // 노드 값 + TreeNode left; // 왼쪽 자식 노드 참조 + TreeNode right; // 오른쪽 자식 노드 참조 + TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* 이진 트리 노드 클래스 */ +class TreeNode(int? x) { + public int? val = x; // 노드 값 + public TreeNode? left; // 왼쪽 자식 노드 참조 + public TreeNode? right; // 오른쪽 자식 노드 참조 +} +``` + +```go title="" +/* 이진 트리 노드 구조체 */ +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} +/* 생성자 */ +func NewTreeNode(v int) *TreeNode { + return &TreeNode{ + Left: nil, // 왼쪽 자식 노드 포인터 + Right: nil, // 오른쪽 자식 노드 포인터 + Val: v, // 노드 값 + } +} +``` + +```swift title="" +/* 이진 트리 노드 클래스 */ +class TreeNode { + var val: Int // 노드 값 + var left: TreeNode? // 왼쪽 자식 노드 참조 + var right: TreeNode? // 오른쪽 자식 노드 참조 + + init(x: Int) { + val = x + } +} +``` + +```javascript title="" +/* 이진 트리 노드 클래스 */ +class TreeNode { + val; // 노드 값 + left; // 왼쪽 자식 노드 포인터 + right; // 오른쪽 자식 노드 포인터 + constructor(val, left, right) { + this.val = val === undefined ? 0 : val; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* 이진 트리 노드 클래스 */ +class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; // 노드 값 + this.left = left === undefined ? null : left; // 왼쪽 자식 노드 참조 + this.right = right === undefined ? null : right; // 오른쪽 자식 노드 참조 + } +} +``` + +```dart title="" +/* 이진 트리 노드 클래스 */ +class TreeNode { + int val; // 노드 값 + TreeNode? left; // 왼쪽 자식 노드 참조 + TreeNode? right; // 오른쪽 자식 노드 참조 + TreeNode(this.val, [this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 이진 트리 노드 구조체 */ +struct TreeNode { + val: i32, // 노드 값 + left: Option>>, // 왼쪽 자식 노드 참조 + right: Option>>, // 오른쪽 자식 노드 참조 +} + +impl TreeNode { + /* 생성자 */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* 이진 트리 노드 구조체 */ +typedef struct TreeNode { + int val; // 노드 값 + int height; // 노드 높이 + struct TreeNode *left; // 왼쪽 자식 노드 포인터 + struct TreeNode *right; // 오른쪽 자식 노드 포인터 +} TreeNode; + +/* 생성자 */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* 이진 트리 노드 클래스 */ +class TreeNode(val _val: Int) { // 노드 값 + var left: TreeNode? = null // 왼쪽 자식 노드 참조 + var right: TreeNode? = null // 오른쪽 자식 노드 참조 +} +``` + +```ruby title="" +### 이진 트리 노드 클래스 ### +class TreeNode + attr_accessor :val # 노드 값 + attr_accessor :left # 왼쪽 자식 노드 참조 + attr_accessor :right # 오른쪽 자식 노드 참조 + + def initialize(val) + @val = val + end +end +``` + + +```python title="binary_tree.py" +# 이진 트리 초기화 +# 노드 초기화 +n1 = TreeNode(val=1) +n2 = TreeNode(val=2) +n3 = TreeNode(val=3) +n4 = TreeNode(val=4) +n5 = TreeNode(val=5) +# 노드 사이의 참조(포인터) 연결 +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```cpp title="binary_tree.cpp" +/* 이진 트리 초기화 */ +// 노드 초기화 +TreeNode* n1 = new TreeNode(1); +TreeNode* n2 = new TreeNode(2); +TreeNode* n3 = new TreeNode(3); +TreeNode* n4 = new TreeNode(4); +TreeNode* n5 = new TreeNode(5); +// 노드 사이의 참조(포인터) 연결 +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```java title="binary_tree.java" +// 노드 초기화 +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// 노드 사이의 참조(포인터) 연결 +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```csharp title="binary_tree.cs" +/* 이진 트리 초기화 */ +// 노드 초기화 +TreeNode n1 = new(1); +TreeNode n2 = new(2); +TreeNode n3 = new(3); +TreeNode n4 = new(4); +TreeNode n5 = new(5); +// 노드 사이의 참조(포인터) 연결 +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```go title="binary_tree.go" +/* 이진 트리 초기화 */ +// 노드 초기화 +n1 := NewTreeNode(1) +n2 := NewTreeNode(2) +n3 := NewTreeNode(3) +n4 := NewTreeNode(4) +n5 := NewTreeNode(5) +// 노드 사이의 참조(포인터) 연결 +n1.Left = n2 +n1.Right = n3 +n2.Left = n4 +n2.Right = n5 +``` + +```swift title="binary_tree.swift" +// 노드 초기화 +let n1 = TreeNode(x: 1) +let n2 = TreeNode(x: 2) +let n3 = TreeNode(x: 3) +let n4 = TreeNode(x: 4) +let n5 = TreeNode(x: 5) +// 노드 사이의 참조(포인터) 연결 +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```javascript title="binary_tree.js" +/* 이진 트리 초기화 */ +// 노드 초기화 +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// 노드 사이의 참조(포인터) 연결 +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```typescript title="binary_tree.ts" +/* 이진 트리 초기화 */ +// 노드 초기화 +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// 노드 사이의 참조(포인터) 연결 +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```dart title="binary_tree.dart" +/* 이진 트리 초기화 */ +// 노드 초기화 +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// 노드 사이의 참조(포인터) 연결 +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```rust title="binary_tree.rs" +// 노드 초기화 +let n1 = TreeNode::new(1); +let n2 = TreeNode::new(2); +let n3 = TreeNode::new(3); +let n4 = TreeNode::new(4); +let n5 = TreeNode::new(5); +// 노드 사이의 참조(포인터) 연결 +n1.borrow_mut().left = Some(n2.clone()); +n1.borrow_mut().right = Some(n3); +n2.borrow_mut().left = Some(n4); +n2.borrow_mut().right = Some(n5); +``` + +```c title="binary_tree.c" +/* 이진 트리 초기화 */ +// 노드 초기화 +TreeNode *n1 = newTreeNode(1); +TreeNode *n2 = newTreeNode(2); +TreeNode *n3 = newTreeNode(3); +TreeNode *n4 = newTreeNode(4); +TreeNode *n5 = newTreeNode(5); +// 노드 사이의 참조(포인터) 연결 +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```kotlin title="binary_tree.kt" +// 노드 초기화 +val n1 = TreeNode(1) +val n2 = TreeNode(2) +val n3 = TreeNode(3) +val n4 = TreeNode(4) +val n5 = TreeNode(5) +// 노드 사이의 참조(포인터) 연결 +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```ruby title="binary_tree.rb" +# 이진 트리 초기화 +# 노드 초기화 +n1 = TreeNode.new(1) +n2 = TreeNode.new(2) +n3 = TreeNode.new(3) +n4 = TreeNode.new(4) +n5 = TreeNode.new(5) +# 노드 사이의 참조(포인터) 연결 +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%EC%99%BC%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%EC%98%A4%EB%A5%B8%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%AC%EC%9D%B4%EC%9D%98%20%EC%B0%B8%EC%A1%B0%28%ED%8F%AC%EC%9D%B8%ED%84%B0%29%20%EC%97%B0%EA%B2%B0%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="binary_tree.py" +# 노드 삽입과 삭제 +p = TreeNode(0) +# n1 -> n2 사이에 노드 P 삽입 +n1.left = p +p.left = n2 +# 노드 P 삭제 +n1.left = n2 +``` + +```cpp title="binary_tree.cpp" +/* 노드 삽입과 삭제 */ +TreeNode* P = new TreeNode(0); +// n1 -> n2 사이에 노드 P 삽입 +n1->left = P; +P->left = n2; +// 노드 P 삭제 +n1->left = n2; +// 메모리 해제 +delete P; +``` + +```java title="binary_tree.java" +TreeNode P = new TreeNode(0); +// n1 -> n2 사이에 노드 P 삽입 +n1.left = P; +P.left = n2; +// 노드 P 삭제 +n1.left = n2; +``` + +```csharp title="binary_tree.cs" +/* 노드 삽입과 삭제 */ +TreeNode P = new(0); +// n1 -> n2 사이에 노드 P 삽입 +n1.left = P; +P.left = n2; +// 노드 P 삭제 +n1.left = n2; +``` + +```go title="binary_tree.go" +/* 노드 삽입과 삭제 */ +// n1 -> n2 사이에 노드 P 삽입 +p := NewTreeNode(0) +n1.Left = p +p.Left = n2 +// 노드 P 삭제 +n1.Left = n2 +``` + +```swift title="binary_tree.swift" +let P = TreeNode(x: 0) +// n1 -> n2 사이에 노드 P 삽입 +n1.left = P +P.left = n2 +// 노드 P 삭제 +n1.left = n2 +``` + +```javascript title="binary_tree.js" +/* 노드 삽입과 삭제 */ +let P = new TreeNode(0); +// n1 -> n2 사이에 노드 P 삽입 +n1.left = P; +P.left = n2; +// 노드 P 삭제 +n1.left = n2; +``` + +```typescript title="binary_tree.ts" +/* 노드 삽입과 삭제 */ +const P = new TreeNode(0); +// n1 -> n2 사이에 노드 P 삽입 +n1.left = P; +P.left = n2; +// 노드 P 삭제 +n1.left = n2; +``` + +```dart title="binary_tree.dart" +/* 노드 삽입과 삭제 */ +TreeNode P = new TreeNode(0); +// n1 -> n2 사이에 노드 P 삽입 +n1.left = P; +P.left = n2; +// 노드 P 삭제 +n1.left = n2; +``` + +```rust title="binary_tree.rs" +let p = TreeNode::new(0); +// n1 -> n2 사이에 노드 P 삽입 +n1.borrow_mut().left = Some(p.clone()); +p.borrow_mut().left = Some(n2.clone()); +// 노드 p 삭제 +n1.borrow_mut().left = Some(n2); +``` + +```c title="binary_tree.c" +/* 노드 삽입과 삭제 */ +TreeNode *P = newTreeNode(0); +// n1 -> n2 사이에 노드 P 삽입 +n1->left = P; +P->left = n2; +// 노드 P 삭제 +n1->left = n2; +// 메모리 해제 +free(P); +``` + +```kotlin title="binary_tree.kt" +val P = TreeNode(0) +// n1 -> n2 사이에 노드 P 삽입 +n1.left = P +P.left = n2 +// 노드 P 삭제 +n1.left = n2 +``` + +```ruby title="binary_tree.rb" +# 노드 삽입과 삭제 +_p = TreeNode.new(0) +# n1 -> n2 사이에 노드 _p 삽입 +n1.left = _p +_p.left = n2 +# 노드 삭제 +n1.left = n2 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%EC%99%BC%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%EC%98%A4%EB%A5%B8%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%AC%EC%9D%B4%EC%9D%98%20%EC%B0%B8%EC%A1%B0%28%ED%8F%AC%EC%9D%B8%ED%84%B0%29%20%EC%97%B0%EA%B2%B0%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%BD%EC%9E%85%EA%B3%BC%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20n1%20-%3E%20n2%20%EC%82%AC%EC%9D%B4%EC%97%90%20%EB%85%B8%EB%93%9C%20P%20%EC%82%BD%EC%9E%85%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20P%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/docs/chapter_array_and_linkedlist/array.md b/ko/docs/chapter_array_and_linkedlist/array.md index 6ac51ac96..14819393e 100644 --- a/ko/docs/chapter_array_and_linkedlist/array.md +++ b/ko/docs/chapter_array_and_linkedlist/array.md @@ -10,125 +10,13 @@ 필요에 따라 초깃값을 지정하지 않거나 지정하는 두 가지 초기화 방식을 사용할 수 있다. 초깃값을 지정하지 않으면 대부분의 프로그래밍 언어는 배열 원소를 $0$으로 초기화한다. -=== "Python" - - ```python title="array.py" - # 배열 초기화 - arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="array.cpp" - /* 배열 초기화 */ - // 스택에 저장 - int arr[5] = {}; - int nums[5] = { 1, 3, 2, 5, 4 }; - // 힙에 저장(공간을 직접 해제해야 함) - int* arr1 = new int[5] {}; - int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="array.java" - /* 배열 초기화 */ - int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } - int[] nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "C#" - - ```csharp title="array.cs" - /* 배열 초기화 */ - int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] - int[] nums = [1, 3, 2, 5, 4]; - ``` - -=== "Go" - - ```go title="array.go" - /* 배열 초기화 */ - var arr [5]int - // Go에서 길이를 지정하면([5]int) 배열이고, 지정하지 않으면([]int) 슬라이스다 - // Go 배열의 길이는 컴파일 시 결정되도록 설계되었으므로 상수로만 길이를 지정할 수 있다 - // 용량 확장 메서드 extend()를 쉽게 구현하기 위해 아래에서는 슬라이스(Slice)를 배열(Array)로 간주한다 - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="array.swift" - /* 배열 초기화 */ - let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] - let nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="array.js" - /* 배열 초기화 */ - var arr = new Array(5).fill(0); - var nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="array.ts" - /* 배열 초기화 */ - let arr: number[] = new Array(5).fill(0); - let nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="array.dart" - /* 배열 초기화 */ - List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="array.rs" - /* 배열 초기화 */ - let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] - let slice: &[i32] = &[0; 5]; - // Rust에서 길이를 지정하면([i32; 5]) 배열이고, 지정하지 않으면(&[i32]) 슬라이스다 - // Rust 배열의 길이는 컴파일 시 결정되도록 설계되었으므로 상수로만 길이를 지정할 수 있다 - // Vector는 Rust에서 일반적으로 동적 배열로 사용하는 자료형이다 - // 용량 확장 메서드 extend()를 쉽게 구현하기 위해 아래에서는 vector를 배열(array)로 간주한다 - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="array.c" - /* 배열 초기화 */ - int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } - int nums[5] = { 1, 3, 2, 5, 4 }; - ``` - -=== "Kotlin" - - ```kotlin title="array.kt" - /* 배열 초기화 */ - var arr = IntArray(5) // { 0, 0, 0, 0, 0 } - var nums = intArrayOf(1, 3, 2, 5, 4) - ``` - -=== "Ruby" - - ```ruby title="array.rb" - # 배열 초기화 - arr = Array.new(5, 0) - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_array +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%23%20%EB%B0%B0%EC%97%B4%20%EC%B4%88%EA%B8%B0%ED%99%94%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_array_tutor ### 원소 접근 diff --git a/ko/docs/chapter_array_and_linkedlist/linked_list.md b/ko/docs/chapter_array_and_linkedlist/linked_list.md index ce1f9c5c9..bd6f5dbca 100644 --- a/ko/docs/chapter_array_and_linkedlist/linked_list.md +++ b/ko/docs/chapter_array_and_linkedlist/linked_list.md @@ -16,174 +16,9 @@ 다음 코드와 같이 연결 리스트 노드 `ListNode`는 값 외에도 참조(포인터)를 하나 더 저장해야 한다. 따라서 같은 양의 데이터를 저장할 때 **연결 리스트는 배열보다 메모리 공간을 더 많이 차지한다**. -=== "Python" - - ```python title="" - class ListNode: - """연결 리스트 노드 클래스""" - def __init__(self, val: int): - self.val: int = val # 노드 값 - self.next: ListNode | None = None # 다음 노드를 가리키는 참조 - ``` - -=== "C++" - - ```cpp title="" - /* 연결 리스트 노드 구조체 */ - struct ListNode { - int val; // 노드 값 - ListNode *next; // 다음 노드를 가리키는 포인터 - ListNode(int x) : val(x), next(nullptr) {} // 생성자 - }; - ``` - -=== "Java" - - ```java title="" - /* 연결 리스트 노드 클래스 */ - class ListNode { - int val; // 노드 값 - ListNode next; // 다음 노드를 가리키는 참조 - ListNode(int x) { val = x; } // 생성자 - } - ``` - -=== "C#" - - ```csharp title="" - /* 연결 리스트 노드 클래스 */ - class ListNode(int x) { //생성자 - int val = x; // 노드 값 - ListNode? next; // 다음 노드를 가리키는 참조 - } - ``` - -=== "Go" - - ```go title="" - /* 연결 리스트 노드 구조체 */ - type ListNode struct { - Val int // 노드 값 - Next *ListNode // 다음 노드를 가리키는 포인터 - } - - // NewListNode 생성자: 새 연결 리스트 생성 - func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 연결 리스트 노드 클래스 */ - class ListNode { - var val: Int // 노드 값 - var next: ListNode? // 다음 노드를 가리키는 참조 - - init(x: Int) { // 생성자 - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 연결 리스트 노드 클래스 */ - class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // 노드 값 - this.next = (next === undefined ? null : next); // 다음 노드를 가리키는 참조 - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 연결 리스트 노드 클래스 */ - class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.next = next === undefined ? null : next; // 다음 노드를 가리키는 참조 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 연결 리스트 노드 클래스 */ - class ListNode { - int val; // 노드 값 - ListNode? next; // 다음 노드를 가리키는 참조 - ListNode(this.val, [this.next]); // 생성자 - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - /* 연결 리스트 노드 클래스 */ - #[derive(Debug)] - struct ListNode { - val: i32, // 노드 값 - next: Option>>, // 다음 노드를 가리키는 포인터 - } - ``` - -=== "C" - - ```c title="" - /* 연결 리스트 노드 구조체 */ - typedef struct ListNode { - int val; // 노드 값 - struct ListNode *next; // 다음 노드를 가리키는 포인터 - } ListNode; - - /* 생성자 */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 연결 리스트 노드 클래스 */ - // 생성자 - class ListNode(x: Int) { - val _val: Int = x // 노드 값 - var next: ListNode? = null // 다음 노드를 가리키는 참조 - } - ``` - -=== "Ruby" - - ```ruby title="" - # 연결 리스트 노드 클래스 - class ListNode - attr_accessor :val # 노드 값 - attr_accessor :next # 다음 노드를 가리키는 참조 - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end - end - ``` +```snippet +list_node_class +``` ## 연결 리스트의 기본 연산 @@ -191,231 +26,13 @@ 연결 리스트를 만드는 과정은 두 단계다. 먼저 각 노드 객체를 초기화한 다음, 노드 사이의 참조 관계를 설정한다. 초기화가 끝나면 머리 노드부터 시작하여 `next` 참조를 따라 모든 노드에 차례로 접근할 수 있다. -=== "Python" - - ```python title="linked_list.py" - # 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 - # 각 노드 초기화 - n0 = ListNode(1) - n1 = ListNode(3) - n2 = ListNode(2) - n3 = ListNode(5) - n4 = ListNode(4) - # 노드 사이의 참조 설정 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "C++" - - ```cpp title="linked_list.cpp" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - ListNode* n0 = new ListNode(1); - ListNode* n1 = new ListNode(3); - ListNode* n2 = new ListNode(2); - ListNode* n3 = new ListNode(5); - ListNode* n4 = new ListNode(4); - // 노드 사이의 참조 설정 - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Java" - - ```java title="linked_list.java" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - ListNode n0 = new ListNode(1); - ListNode n1 = new ListNode(3); - ListNode n2 = new ListNode(2); - ListNode n3 = new ListNode(5); - ListNode n4 = new ListNode(4); - // 노드 사이의 참조 설정 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "C#" - - ```csharp title="linked_list.cs" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - ListNode n0 = new(1); - ListNode n1 = new(3); - ListNode n2 = new(2); - ListNode n3 = new(5); - ListNode n4 = new(4); - // 노드 사이의 참조 설정 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Go" - - ```go title="linked_list.go" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - n0 := NewListNode(1) - n1 := NewListNode(3) - n2 := NewListNode(2) - n3 := NewListNode(5) - n4 := NewListNode(4) - // 노드 사이의 참조 설정 - n0.Next = n1 - n1.Next = n2 - n2.Next = n3 - n3.Next = n4 - ``` - -=== "Swift" - - ```swift title="linked_list.swift" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - let n0 = ListNode(x: 1) - let n1 = ListNode(x: 3) - let n2 = ListNode(x: 2) - let n3 = ListNode(x: 5) - let n4 = ListNode(x: 4) - // 노드 사이의 참조 설정 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "JS" - - ```javascript title="linked_list.js" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // 노드 사이의 참조 설정 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "TS" - - ```typescript title="linked_list.ts" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // 노드 사이의 참조 설정 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Dart" - - ```dart title="linked_list.dart" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */\ - // 각 노드 초기화 - ListNode n0 = ListNode(1); - ListNode n1 = ListNode(3); - ListNode n2 = ListNode(2); - ListNode n3 = ListNode(5); - ListNode n4 = ListNode(4); - // 노드 사이의 참조 설정 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Rust" - - ```rust title="linked_list.rs" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); - let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); - let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); - let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); - let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); - - // 노드 사이의 참조 설정 - n0.borrow_mut().next = Some(n1.clone()); - n1.borrow_mut().next = Some(n2.clone()); - n2.borrow_mut().next = Some(n3.clone()); - n3.borrow_mut().next = Some(n4.clone()); - ``` - -=== "C" - - ```c title="linked_list.c" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - ListNode* n0 = newListNode(1); - ListNode* n1 = newListNode(3); - ListNode* n2 = newListNode(2); - ListNode* n3 = newListNode(5); - ListNode* n4 = newListNode(4); - // 노드 사이의 참조 설정 - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Kotlin" - - ```kotlin title="linked_list.kt" - /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ - // 각 노드 초기화 - val n0 = ListNode(1) - val n1 = ListNode(3) - val n2 = ListNode(2) - val n3 = ListNode(5) - val n4 = ListNode(4) - // 노드 사이의 참조 설정 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Ruby" - - ```ruby title="linked_list.rb" - # 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 - # 각 노드 초기화 - n0 = ListNode.new(1) - n1 = ListNode.new(3) - n2 = ListNode.new(2) - n3 = ListNode.new(5) - n4 = ListNode.new(4) - # 노드 사이의 참조 설정 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` +```snippet +init_linked_list +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%ED%9B%84%EC%86%8D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EA%B0%81%20%EB%85%B8%EB%93%9C%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%AC%EC%9D%B4%EC%9D%98%20%EC%B0%B8%EC%A1%B0%20%EC%84%A4%EC%A0%95%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_linked_list_tutor 배열은 전체가 하나의 변수다. 예를 들어 배열 `nums`에는 `nums[0]`, `nums[1]` 등의 원소가 들어 있다. 반면 연결 리스트는 독립된 여러 노드 객체로 이루어진다. **보통 머리 노드로 연결 리스트 전체를 지칭한다**. 예를 들어 위 코드의 연결 리스트는 연결 리스트 `n0`라고 부를 수 있다. @@ -482,203 +99,9 @@ - **원형 연결 리스트**: 단일 연결 리스트의 꼬리 노드가 머리 노드를 가리키도록 앞뒤를 이으면 원형 연결 리스트가 된다. 원형 연결 리스트에서는 어느 노드든 머리 노드로 볼 수 있다. - **이중 연결 리스트**: 단일 연결 리스트와 달리 양방향 참조를 기록한다. 각 노드는 후속 노드(다음 노드)와 선행 노드(이전 노드)를 가리키는 참조(포인터)를 모두 포함한다. 양방향으로 순회할 수 있어 단일 연결 리스트보다 유연하지만, 그만큼 메모리 공간도 더 많이 차지한다. -=== "Python" - - ```python title="" - class ListNode: - """이중 연결 리스트 노드 클래스""" - def __init__(self, val: int): - self.val: int = val # 노드 값 - self.next: ListNode | None = None # 후속 노드를 가리키는 참조 - self.prev: ListNode | None = None # 선행 노드를 가리키는 참조 - ``` - -=== "C++" - - ```cpp title="" - /* 이중 연결 리스트 노드 구조체 */ - struct ListNode { - int val; // 노드 값 - ListNode *next; // 후속 노드를 가리키는 포인터 - ListNode *prev; // 선행 노드를 가리키는 포인터 - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 생성자 - }; - ``` - -=== "Java" - - ```java title="" - /* 이중 연결 리스트 노드 클래스 */ - class ListNode { - int val; // 노드 값 - ListNode next; // 후속 노드를 가리키는 참조 - ListNode prev; // 선행 노드를 가리키는 참조 - ListNode(int x) { val = x; } // 생성자 - } - ``` - -=== "C#" - - ```csharp title="" - /* 이중 연결 리스트 노드 클래스 */ - class ListNode(int x) { // 생성자 - int val = x; // 노드 값 - ListNode next; // 후속 노드를 가리키는 참조 - ListNode prev; // 선행 노드를 가리키는 참조 - } - ``` - -=== "Go" - - ```go title="" - /* 이중 연결 리스트 노드 구조체 */ - type DoublyListNode struct { - Val int // 노드 값 - Next *DoublyListNode // 후속 노드를 가리키는 포인터 - Prev *DoublyListNode // 선행 노드를 가리키는 포인터 - } - - // NewDoublyListNode 초기화 - func NewDoublyListNode(val int) *DoublyListNode { - return &DoublyListNode{ - Val: val, - Next: nil, - Prev: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 이중 연결 리스트 노드 클래스 */ - class ListNode { - var val: Int // 노드 값 - var next: ListNode? // 후속 노드를 가리키는 참조 - var prev: ListNode? // 선행 노드를 가리키는 참조 - - init(x: Int) { // 생성자 - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 이중 연결 리스트 노드 클래스 */ - class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.next = next === undefined ? null : next; // 후속 노드를 가리키는 참조 - this.prev = prev === undefined ? null : prev; // 선행 노드를 가리키는 참조 - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 이중 연결 리스트 노드 클래스 */ - class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.next = next === undefined ? null : next; // 후속 노드를 가리키는 참조 - this.prev = prev === undefined ? null : prev; // 선행 노드를 가리키는 참조 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 이중 연결 리스트 노드 클래스 */ - class ListNode { - int val; // 노드 값 - ListNode? next; // 후속 노드를 가리키는 참조 - ListNode? prev; // 선행 노드를 가리키는 참조 - ListNode(this.val, [this.next, this.prev]); // 생성자 - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 이중 연결 리스트 노드 자료형 */ - #[derive(Debug)] - struct ListNode { - val: i32, // 노드 값 - next: Option>>, // 후속 노드를 가리키는 포인터 - prev: Option>>, // 선행 노드를 가리키는 포인터 - } - - /* 생성자 */ - impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } - } - ``` - -=== "C" - - ```c title="" - /* 이중 연결 리스트 노드 구조체 */ - typedef struct ListNode { - int val; // 노드 값 - struct ListNode *next; // 후속 노드를 가리키는 포인터 - struct ListNode *prev; // 선행 노드를 가리키는 포인터 - } ListNode; - - /* 생성자 */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 이중 연결 리스트 노드 클래스 */ - // 생성자 - class ListNode(x: Int) { - val _val: Int = x // 노드 값 - var next: ListNode? = null // 후속 노드를 가리키는 참조 - var prev: ListNode? = null // 선행 노드를 가리키는 참조 - } - ``` - -=== "Ruby" - - ```ruby title="" - # 이중 연결 리스트 노드 클래스 - class ListNode - attr_accessor :val # 노드 값 - attr_accessor :next # 후속 노드를 가리키는 참조 - attr_accessor :prev # 선행 노드를 가리키는 참조 - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end - end - ``` +```snippet +doubly_list_node_class +``` ![대표적인 연결 리스트 종류](linked_list.assets/linkedlist_common_types.svg) diff --git a/ko/docs/chapter_array_and_linkedlist/list.md b/ko/docs/chapter_array_and_linkedlist/list.md index 81109e7f6..dca4dc317 100644 --- a/ko/docs/chapter_array_and_linkedlist/list.md +++ b/ko/docs/chapter_array_and_linkedlist/list.md @@ -17,934 +17,73 @@ 보통 ‘초깃값 없음’과 ‘초깃값 지정’의 두 가지 초기화 방식을 사용한다. -=== "Python" - - ```python title="list.py" - # 리스트 초기화 - # 초깃값 없음 - nums1: list[int] = [] - # 초깃값 지정 - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 리스트 초기화 */ - // C++의 vector가 이 글에서 설명하는 nums에 해당한다 - // 초깃값 없음 - vector nums1; - // 초깃값 지정 - vector nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="list.java" - /* 리스트 초기화 */ - // 초깃값 없음 - List nums1 = new ArrayList<>(); - // 초깃값 지정(배열은 int[]의 래퍼형인 Integer[]여야 함) - Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; - List nums = new ArrayList<>(Arrays.asList(numbers)); - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 리스트 초기화 */ - // 초깃값 없음 - List nums1 = []; - // 초깃값 지정 - int[] numbers = [1, 3, 2, 5, 4]; - List nums = [.. numbers]; - ``` - -=== "Go" - - ```go title="list_test.go" - /* 리스트 초기화 */ - // 초깃값 없음 - nums1 := []int{} - // 초깃값 지정 - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 리스트 초기화 */ - // 초깃값 없음 - let nums1: [Int] = [] - // 초깃값 지정 - var nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="list.js" - /* 리스트 초기화 */ - // 초깃값 없음 - const nums1 = []; - // 초깃값 지정 - const nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 리스트 초기화 */ - // 초깃값 없음 - const nums1: number[] = []; - // 초깃값 지정 - const nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 리스트 초기화 */ - // 초깃값 없음 - List nums1 = []; - // 초깃값 지정 - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 리스트 초기화 */ - // 초깃값 없음 - let nums1: Vec = Vec::new(); - // 초깃값 지정 - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="list.c" - // C는 내장 동적 배열을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 리스트 초기화 */ - // 초깃값 없음 - var nums1 = listOf() - // 초깃값 지정 - var numbers = arrayOf(1, 3, 2, 5, 4) - var nums = numbers.toMutableList() - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 리스트 초기화 - # 초깃값 없음 - nums1 = [] - # 초깃값 지정 - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_list +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%97%86%EC%9D%8C%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%A7%80%EC%A0%95%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_list_tutor ### 원소 접근 리스트는 본질적으로 배열이므로 원소에 접근하고 갱신하는 데 $O(1)$ 시간이 걸려 매우 효율적이다. -=== "Python" - - ```python title="list.py" - # 원소 접근 - num: int = nums[1] # 인덱스 1의 원소에 접근 - - # 원소 갱신 - nums[1] = 0 # 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 원소 접근 */ - int num = nums[1]; // 인덱스 1의 원소에 접근 - - /* 원소 갱신 */ - nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "Java" - - ```java title="list.java" - /* 원소 접근 */ - int num = nums.get(1); // 인덱스 1의 원소에 접근 - - /* 원소 갱신 */ - nums.set(1, 0); // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 원소 접근 */ - int num = nums[1]; // 인덱스 1의 원소에 접근 - - /* 원소 갱신 */ - nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 원소 접근 */ - num := nums[1] // 인덱스 1의 원소에 접근 - - /* 원소 갱신 */ - nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 원소 접근 */ - let num = nums[1] // 인덱스 1의 원소에 접근 - - /* 원소 갱신 */ - nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 원소 접근 */ - const num = nums[1]; // 인덱스 1의 원소에 접근 - - /* 원소 갱신 */ - nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 원소 접근 */ - const num: number = nums[1]; // 인덱스 1의 원소에 접근 - - /* 원소 갱신 */ - nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 원소 접근 */ - int num = nums[1]; // 인덱스 1의 원소에 접근 - - /* 원소 갱신 */ - nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 원소 접근 */ - let num: i32 = nums[1]; // 인덱스 1의 원소에 접근 - /* 원소 갱신 */ - nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "C" - - ```c title="list.c" - // C는 내장 동적 배열을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 원소 접근 */ - val num = nums[1] // 인덱스 1의 원소에 접근 - /* 원소 갱신 */ - nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 원소 접근 - num = nums[1] # 인덱스 1의 원소에 접근 - # 원소 갱신 - nums[1] = 0 # 인덱스 1의 원소를 0으로 갱신 - ``` +```snippet +access_element +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%201%EC%9D%98%20%EC%9B%90%EC%86%8C%EC%97%90%20%EC%A0%91%EA%B7%BC%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EA%B0%B1%EC%8B%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%201%EC%9D%98%20%EC%9B%90%EC%86%8C%EB%A5%BC%200%EC%9C%BC%EB%A1%9C%20%EA%B0%B1%EC%8B%A0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor access_element_tutor ### 원소 삽입과 삭제 배열과 달리 리스트는 원소를 자유롭게 추가하고 삭제할 수 있다. 끝에 원소를 추가하는 시간 복잡도는 $O(1)$이지만, 삽입과 삭제의 효율은 배열과 같아 시간 복잡도가 $O(n)$이다. -=== "Python" - - ```python title="list.py" - # 리스트 비우기 - nums.clear() - - # 끝에 원소 추가 - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - # 중간에 원소 삽입 - nums.insert(3, 6) # 인덱스 3에 숫자 6 삽입 - - # 원소 삭제 - nums.pop(3) # 인덱스 3의 원소 삭제 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 리스트 비우기 */ - nums.clear(); - - /* 끝에 원소 추가 */ - nums.push_back(1); - nums.push_back(3); - nums.push_back(2); - nums.push_back(5); - nums.push_back(4); - - /* 중간에 원소 삽입 */ - nums.insert(nums.begin() + 3, 6); // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums.erase(nums.begin() + 3); // 인덱스 3의 원소 삭제 - ``` - -=== "Java" - - ```java title="list.java" - /* 리스트 비우기 */ - nums.clear(); - - /* 끝에 원소 추가 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 중간에 원소 삽입 */ - nums.add(3, 6); // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums.remove(3); // 인덱스 3의 원소 삭제 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 리스트 비우기 */ - nums.Clear(); - - /* 끝에 원소 추가 */ - nums.Add(1); - nums.Add(3); - nums.Add(2); - nums.Add(5); - nums.Add(4); - - /* 중간에 원소 삽입 */ - nums.Insert(3, 6); // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums.RemoveAt(3); // 인덱스 3의 원소 삭제 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 리스트 비우기 */ - nums = nil - - /* 끝에 원소 추가 */ - nums = append(nums, 1) - nums = append(nums, 3) - nums = append(nums, 2) - nums = append(nums, 5) - nums = append(nums, 4) - - /* 중간에 원소 삽입 */ - nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums = append(nums[:3], nums[4:]...) // 인덱스 3의 원소 삭제 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 리스트 비우기 */ - nums.removeAll() - - /* 끝에 원소 추가 */ - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - /* 중간에 원소 삽입 */ - nums.insert(6, at: 3) // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums.remove(at: 3) // 인덱스 3의 원소 삭제 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 리스트 비우기 */ - nums.length = 0; - - /* 끝에 원소 추가 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 중간에 원소 삽입 */ - nums.splice(3, 0, 6); // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums.splice(3, 1); // 인덱스 3의 원소 삭제 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 리스트 비우기 */ - nums.length = 0; - - /* 끝에 원소 추가 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 중간에 원소 삽입 */ - nums.splice(3, 0, 6); // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums.splice(3, 1); // 인덱스 3의 원소 삭제 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 리스트 비우기 */ - nums.clear(); - - /* 끝에 원소 추가 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 중간에 원소 삽입 */ - nums.insert(3, 6); // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums.removeAt(3); // 인덱스 3의 원소 삭제 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 리스트 비우기 */ - nums.clear(); - - /* 끝에 원소 추가 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 중간에 원소 삽입 */ - nums.insert(3, 6); // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums.remove(3); // 인덱스 3의 원소 삭제 - ``` - -=== "C" - - ```c title="list.c" - // C는 내장 동적 배열을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 리스트 비우기 */ - nums.clear(); - - /* 끝에 원소 추가 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 중간에 원소 삽입 */ - nums.add(3, 6); // 인덱스 3에 숫자 6 삽입 - - /* 원소 삭제 */ - nums.remove(3); // 인덱스 3의 원소 삭제 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 리스트 비우기 - nums.clear - - # 끝에 원소 추가 - nums << 1 - nums << 3 - nums << 2 - nums << 5 - nums << 4 - - # 중간에 원소 삽입 - nums.insert(3, 6) # 인덱스 3에 숫자 6 삽입 - - # 원소 삭제 - nums.delete_at(3) # 인덱스 3의 원소 삭제 - ``` +```snippet +insert_remove_element +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%A7%80%EC%A0%95%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%B9%84%EC%9A%B0%EA%B8%B0%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%81%9D%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%B6%94%EA%B0%80%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%A4%91%EA%B0%84%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20nums.insert%283%2C%206%29%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%203%EC%97%90%20%EC%88%AB%EC%9E%90%206%20%EC%82%BD%EC%9E%85%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%203%EC%9D%98%20%EC%9B%90%EC%86%8C%20%EC%82%AD%EC%A0%9C&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_element_tutor ### 리스트 순회 배열처럼 리스트도 인덱스로 순회하거나 각 원소를 직접 순회할 수 있다. -=== "Python" - - ```python title="list.py" - # 인덱스로 리스트 순회 - count = 0 - for i in range(len(nums)): - count += nums[i] - - # 리스트 원소를 직접 순회 - for num in nums: - count += num - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 인덱스로 리스트 순회 */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums[i]; - } - - /* 리스트 원소를 직접 순회 */ - count = 0; - for (int num : nums) { - count += num; - } - ``` - -=== "Java" - - ```java title="list.java" - /* 인덱스로 리스트 순회 */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums.get(i); - } - - /* 리스트 원소를 직접 순회 */ - for (int num : nums) { - count += num; - } - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 인덱스로 리스트 순회 */ - int count = 0; - for (int i = 0; i < nums.Count; i++) { - count += nums[i]; - } - - /* 리스트 원소를 직접 순회 */ - count = 0; - foreach (int num in nums) { - count += num; - } - ``` - -=== "Go" - - ```go title="list_test.go" - /* 인덱스로 리스트 순회 */ - count := 0 - for i := 0; i < len(nums); i++ { - count += nums[i] - } - - /* 리스트 원소를 직접 순회 */ - count = 0 - for _, num := range nums { - count += num - } - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 인덱스로 리스트 순회 */ - var count = 0 - for i in nums.indices { - count += nums[i] - } - - /* 리스트 원소를 직접 순회 */ - count = 0 - for num in nums { - count += num - } - ``` - -=== "JS" - - ```javascript title="list.js" - /* 인덱스로 리스트 순회 */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* 리스트 원소를 직접 순회 */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 인덱스로 리스트 순회 */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* 리스트 원소를 직접 순회 */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 인덱스로 리스트 순회 */ - int count = 0; - for (var i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* 리스트 원소를 직접 순회 */ - count = 0; - for (var num in nums) { - count += num; - } - ``` - -=== "Rust" - - ```rust title="list.rs" - // 인덱스로 리스트 순회 - let mut _count = 0; - for i in 0..nums.len() { - _count += nums[i]; - } - - // 리스트 원소를 직접 순회 - _count = 0; - for num in &nums { - _count += num; - } - ``` - -=== "C" - - ```c title="list.c" - // C는 내장 동적 배열을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 인덱스로 리스트 순회 */ - var count = 0 - for (i in nums.indices) { - count += nums[i] - } - - /* 리스트 원소를 직접 순회 */ - for (num in nums) { - count += num - } - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 인덱스로 리스트 순회 - count = 0 - for i in 0...nums.length - count += nums[i] - end - - # 리스트 원소를 직접 순회 - count = 0 - for num in nums - count += num - end - ``` +```snippet +iterate_list +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%EB%A1%9C%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%9B%90%EC%86%8C%EB%A5%BC%20%EC%A7%81%EC%A0%91%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor iterate_list_tutor ### 리스트 연결 새 리스트 `nums1`이 주어지면 기존 리스트의 끝에 이어 붙일 수 있다. -=== "Python" - - ```python title="list.py" - # 두 리스트 연결 - nums1: list[int] = [6, 8, 7, 10, 9] - nums += nums1 # 리스트 nums1을 nums 뒤에 연결 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 두 리스트 연결 */ - vector nums1 = { 6, 8, 7, 10, 9 }; - // 리스트 nums1을 nums 뒤에 연결 - nums.insert(nums.end(), nums1.begin(), nums1.end()); - ``` - -=== "Java" - - ```java title="list.java" - /* 두 리스트 연결 */ - List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); - nums.addAll(nums1); // 리스트 nums1을 nums 뒤에 연결 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 두 리스트 연결 */ - List nums1 = [6, 8, 7, 10, 9]; - nums.AddRange(nums1); // 리스트 nums1을 nums 뒤에 연결 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 두 리스트 연결 */ - nums1 := []int{6, 8, 7, 10, 9} - nums = append(nums, nums1...) // 리스트 nums1을 nums 뒤에 연결 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 두 리스트 연결 */ - let nums1 = [6, 8, 7, 10, 9] - nums.append(contentsOf: nums1) // 리스트 nums1을 nums 뒤에 연결 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 두 리스트 연결 */ - const nums1 = [6, 8, 7, 10, 9]; - nums.push(...nums1); // 리스트 nums1을 nums 뒤에 연결 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 두 리스트 연결 */ - const nums1: number[] = [6, 8, 7, 10, 9]; - nums.push(...nums1); // 리스트 nums1을 nums 뒤에 연결 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 두 리스트 연결 */ - List nums1 = [6, 8, 7, 10, 9]; - nums.addAll(nums1); // 리스트 nums1을 nums 뒤에 연결 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 두 리스트 연결 */ - let nums1: Vec = vec![6, 8, 7, 10, 9]; - nums.extend(nums1); - ``` - -=== "C" - - ```c title="list.c" - // C는 내장 동적 배열을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 두 리스트 연결 */ - val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() - nums.addAll(nums1) // 리스트 nums1을 nums 뒤에 연결 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 두 리스트 연결 - nums1 = [6, 8, 7, 10, 9] - nums += nums1 - ``` +```snippet +concat_list +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%91%90%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%97%B0%EA%B2%B0%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20nums1%EC%9D%84%20nums%20%EB%92%A4%EC%97%90%20%EC%97%B0%EA%B2%B0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor concat_list_tutor ### 리스트 정렬 리스트를 정렬하면 배열 관련 알고리즘 문제에 자주 등장하는 ‘이진 탐색’과 ‘투 포인터’ 알고리즘을 사용할 수 있다. -=== "Python" - - ```python title="list.py" - # 리스트 정렬 - nums.sort() # 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 리스트 정렬 */ - sort(nums.begin(), nums.end()); // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "Java" - - ```java title="list.java" - /* 리스트 정렬 */ - Collections.sort(nums); // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 리스트 정렬 */ - nums.Sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 리스트 정렬 */ - sort.Ints(nums) // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 리스트 정렬 */ - nums.sort() // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 리스트 정렬 */ - nums.sort((a, b) => a - b); // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 리스트 정렬 */ - nums.sort((a, b) => a - b); // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 리스트 정렬 */ - nums.sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 리스트 정렬 */ - nums.sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "C" - - ```c title="list.c" - // C는 내장 동적 배열을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 리스트 정렬 */ - nums.sort() // 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 리스트 정렬 - nums = nums.sort { |a, b| a <=> b } # 정렬 후 리스트 원소가 오름차순으로 배치됨 - ``` +```snippet +sort_list +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%A0%95%EB%A0%AC%0A%20%20%20%20nums.sort%28%29%20%20%23%20%EC%A0%95%EB%A0%AC%20%ED%9B%84%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%9B%90%EC%86%8C%EA%B0%80%20%EC%98%A4%EB%A6%84%EC%B0%A8%EC%88%9C%EC%9C%BC%EB%A1%9C%20%EB%B0%B0%EC%B9%98%EB%90%A8&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor sort_list_tutor ## 리스트 구현 diff --git a/ko/docs/chapter_backtracking/backtracking_algorithm.md b/ko/docs/chapter_backtracking/backtracking_algorithm.md index ba1c96cec..364714296 100644 --- a/ko/docs/chapter_backtracking/backtracking_algorithm.md +++ b/ko/docs/chapter_backtracking/backtracking_algorithm.md @@ -95,339 +95,9 @@ 아래 기본 틀 코드에서 `state`는 문제의 현재 상태를, `choices`는 그 상태에서 가능한 선택들을 나타낸다. -=== "Python" - - ```python title="" - def backtrack(state: State, choices: list[choice], res: list[state]): - """백트래킹 알고리즘의 기본 틀""" - # 해인지 확인 - if is_solution(state): - # 해 기록 - record_solution(state, res) - # 더 이상 탐색하지 않는다 - return - # 모든 선택지 순회 - for choice in choices: - # 가지치기: 선택이 유효한지 확인 - if is_valid(state, choice): - # 시도: 선택하고 상태 갱신 - make_choice(state, choice) - backtrack(state, choices, res) - # 되돌리기: 선택을 취소하고 이전 상태 복원 - undo_choice(state, choice) - ``` - -=== "C++" - - ```cpp title="" - /* 백트래킹 알고리즘의 기본 틀 */ - void backtrack(State *state, vector &choices, vector &res) { - // 해인지 확인 - if (isSolution(state)) { - // 해 기록 - recordSolution(state, res); - // 더 이상 탐색하지 않는다 - return; - } - // 모든 선택지 순회 - for (Choice choice : choices) { - // 가지치기: 선택이 유효한지 확인 - if (isValid(state, choice)) { - // 시도: 선택하고 상태 갱신 - makeChoice(state, choice); - backtrack(state, choices, res); - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undoChoice(state, choice); - } - } - } - ``` - -=== "Java" - - ```java title="" - /* 백트래킹 알고리즘의 기본 틀 */ - void backtrack(State state, List choices, List res) { - // 해인지 확인 - if (isSolution(state)) { - // 해 기록 - recordSolution(state, res); - // 더 이상 탐색하지 않는다 - return; - } - // 모든 선택지 순회 - for (Choice choice : choices) { - // 가지치기: 선택이 유효한지 확인 - if (isValid(state, choice)) { - // 시도: 선택하고 상태 갱신 - makeChoice(state, choice); - backtrack(state, choices, res); - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undoChoice(state, choice); - } - } - } - ``` - -=== "C#" - - ```csharp title="" - /* 백트래킹 알고리즘의 기본 틀 */ - void Backtrack(State state, List choices, List res) { - // 해인지 확인 - if (IsSolution(state)) { - // 해 기록 - RecordSolution(state, res); - // 더 이상 탐색하지 않는다 - return; - } - // 모든 선택지 순회 - foreach (Choice choice in choices) { - // 가지치기: 선택이 유효한지 확인 - if (IsValid(state, choice)) { - // 시도: 선택하고 상태 갱신 - MakeChoice(state, choice); - Backtrack(state, choices, res); - // 되돌리기: 선택을 취소하고 이전 상태 복원 - UndoChoice(state, choice); - } - } - } - ``` - -=== "Go" - - ```go title="" - /* 백트래킹 알고리즘의 기본 틀 */ - func backtrack(state *State, choices []Choice, res *[]State) { - // 해인지 확인 - if isSolution(state) { - // 해 기록 - recordSolution(state, res) - // 더 이상 탐색하지 않는다 - return - } - // 모든 선택지 순회 - for _, choice := range choices { - // 가지치기: 선택이 유효한지 확인 - if isValid(state, choice) { - // 시도: 선택하고 상태 갱신 - makeChoice(state, choice) - backtrack(state, choices, res) - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undoChoice(state, choice) - } - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 백트래킹 알고리즘의 기본 틀 */ - func backtrack(state: inout State, choices: [Choice], res: inout [State]) { - // 해인지 확인 - if isSolution(state: state) { - // 해 기록 - recordSolution(state: state, res: &res) - // 더 이상 탐색하지 않는다 - return - } - // 모든 선택지 순회 - for choice in choices { - // 가지치기: 선택이 유효한지 확인 - if isValid(state: state, choice: choice) { - // 시도: 선택하고 상태 갱신 - makeChoice(state: &state, choice: choice) - backtrack(state: &state, choices: choices, res: &res) - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undoChoice(state: &state, choice: choice) - } - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 백트래킹 알고리즘의 기본 틀 */ - function backtrack(state, choices, res) { - // 해인지 확인 - if (isSolution(state)) { - // 해 기록 - recordSolution(state, res); - // 더 이상 탐색하지 않는다 - return; - } - // 모든 선택지 순회 - for (let choice of choices) { - // 가지치기: 선택이 유효한지 확인 - if (isValid(state, choice)) { - // 시도: 선택하고 상태 갱신 - makeChoice(state, choice); - backtrack(state, choices, res); - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undoChoice(state, choice); - } - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 백트래킹 알고리즘의 기본 틀 */ - function backtrack(state: State, choices: Choice[], res: State[]): void { - // 해인지 확인 - if (isSolution(state)) { - // 해 기록 - recordSolution(state, res); - // 더 이상 탐색하지 않는다 - return; - } - // 모든 선택지 순회 - for (let choice of choices) { - // 가지치기: 선택이 유효한지 확인 - if (isValid(state, choice)) { - // 시도: 선택하고 상태 갱신 - makeChoice(state, choice); - backtrack(state, choices, res); - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undoChoice(state, choice); - } - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 백트래킹 알고리즘의 기본 틀 */ - void backtrack(State state, List, List res) { - // 해인지 확인 - if (isSolution(state)) { - // 해 기록 - recordSolution(state, res); - // 더 이상 탐색하지 않는다 - return; - } - // 모든 선택지 순회 - for (Choice choice in choices) { - // 가지치기: 선택이 유효한지 확인 - if (isValid(state, choice)) { - // 시도: 선택하고 상태 갱신 - makeChoice(state, choice); - backtrack(state, choices, res); - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undoChoice(state, choice); - } - } - } - ``` - -=== "Rust" - - ```rust title="" - /* 백트래킹 알고리즘의 기본 틀 */ - fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { - // 해인지 확인 - if is_solution(state) { - // 해 기록 - record_solution(state, res); - // 더 이상 탐색하지 않는다 - return; - } - // 모든 선택지 순회 - for choice in choices { - // 가지치기: 선택이 유효한지 확인 - if is_valid(state, choice) { - // 시도: 선택하고 상태 갱신 - make_choice(state, choice); - backtrack(state, choices, res); - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undo_choice(state, choice); - } - } - } - ``` - -=== "C" - - ```c title="" - /* 백트래킹 알고리즘의 기본 틀 */ - void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { - // 해인지 확인 - if (isSolution(state)) { - // 해 기록 - recordSolution(state, res, numRes); - // 더 이상 탐색하지 않는다 - return; - } - // 모든 선택지 순회 - for (int i = 0; i < numChoices; i++) { - // 가지치기: 선택이 유효한지 확인 - if (isValid(state, &choices[i])) { - // 시도: 선택하고 상태 갱신 - makeChoice(state, &choices[i]); - backtrack(state, choices, numChoices, res, numRes); - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undoChoice(state, &choices[i]); - } - } - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 백트래킹 알고리즘의 기본 틀 */ - fun backtrack(state: State?, choices: List, res: List?) { - // 해인지 확인 - if (isSolution(state)) { - // 해 기록 - recordSolution(state, res) - // 더 이상 탐색하지 않는다 - return - } - // 모든 선택지 순회 - for (choice in choices) { - // 가지치기: 선택이 유효한지 확인 - if (isValid(state, choice)) { - // 시도: 선택하고 상태 갱신 - makeChoice(state, choice) - backtrack(state, choices, res) - // 되돌리기: 선택을 취소하고 이전 상태 복원 - undoChoice(state, choice) - } - } - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 백트래킹 알고리즘의 기본 틀 ### - def backtrack(state, choices, res) - # 해인지 확인 - if is_solution?(state) - # 해 기록 - record_solution(state, res) - return - end - - # 모든 선택지 순회 - for choice in choices - # 가지치기: 선택이 유효한지 확인 - if is_valid?(state, choice) - # 시도: 선택하고 상태 갱신 - make_choice(state, choice) - backtrack(state, choices, res) - # 되돌리기: 선택을 취소하고 이전 상태 복원 - undo_choice(state, choice) - end - end - end - ``` +```snippet +backtrack_framework +``` 이제 기본 틀 코드로 예제 3을 해결해 보자. 상태 `state`는 노드 순회 경로, 선택지 `choices`는 현재 노드의 왼쪽과 오른쪽 자식 노드, 결과 `res`는 경로들의 리스트다. diff --git a/ko/docs/chapter_computational_complexity/space_complexity.md b/ko/docs/chapter_computational_complexity/space_complexity.md index 975c3d96c..eb5c9902d 100644 --- a/ko/docs/chapter_computational_complexity/space_complexity.md +++ b/ko/docs/chapter_computational_complexity/space_complexity.md @@ -24,342 +24,9 @@ 관련 코드는 다음과 같다. -=== "Python" - - ```python title="" - class Node: - """클래스""" - def __init__(self, x: int): - self.val: int = x # 노드 값 - self.next: Node | None = None # 다음 노드를 가리키는 참조 - - def function() -> int: - """함수""" - # 몇 가지 연산 수행... - return 0 - - def algorithm(n) -> int: # 입력 데이터 - A = 0 # 임시 데이터(상수, 보통 대문자로 표기) - b = 0 # 임시 데이터(변수) - node = Node(0) # 임시 데이터(객체) - c = function() # 스택 프레임 공간(함수 호출) - return A + b + c # 출력 데이터 - ``` - -=== "C++" - - ```cpp title="" - /* 구조체 */ - struct Node { - int val; - Node *next; - Node(int x) : val(x), next(nullptr) {} - }; - - /* 함수 */ - int func() { - // 몇 가지 연산 수행... - return 0; - } - - int algorithm(int n) { // 입력 데이터 - const int a = 0; // 임시 데이터(상수) - int b = 0; // 임시 데이터(변수) - Node* node = new Node(0); // 임시 데이터(객체) - int c = func(); // 스택 프레임 공간(함수 호출) - return a + b + c; // 출력 데이터 - } - ``` - -=== "Java" - - ```java title="" - /* 클래스 */ - class Node { - int val; - Node next; - Node(int x) { val = x; } - } - - /* 함수 */ - int function() { - // 몇 가지 연산 수행... - return 0; - } - - int algorithm(int n) { // 입력 데이터 - final int a = 0; // 임시 데이터(상수) - int b = 0; // 임시 데이터(변수) - Node node = new Node(0); // 임시 데이터(객체) - int c = function(); // 스택 프레임 공간(함수 호출) - return a + b + c; // 출력 데이터 - } - ``` - -=== "C#" - - ```csharp title="" - /* 클래스 */ - class Node(int x) { - int val = x; - Node next; - } - - /* 함수 */ - int Function() { - // 몇 가지 연산 수행... - return 0; - } - - int Algorithm(int n) { // 입력 데이터 - const int a = 0; // 임시 데이터(상수) - int b = 0; // 임시 데이터(변수) - Node node = new(0); // 임시 데이터(객체) - int c = Function(); // 스택 프레임 공간(함수 호출) - return a + b + c; // 출력 데이터 - } - ``` - -=== "Go" - - ```go title="" - /* 구조체 */ - type node struct { - val int - next *node - } - - /* node 구조체 생성 */ - func newNode(val int) *node { - return &node{val: val} - } - - /* 함수 */ - func function() int { - // 몇 가지 연산 수행... - return 0 - } - - func algorithm(n int) int { // 입력 데이터 - const a = 0 // 임시 데이터(상수) - b := 0 // 임시 데이터(변수) - newNode(0) // 임시 데이터(객체) - c := function() // 스택 프레임 공간(함수 호출) - return a + b + c // 출력 데이터 - } - ``` - -=== "Swift" - - ```swift title="" - /* 클래스 */ - class Node { - var val: Int - var next: Node? - - init(x: Int) { - val = x - } - } - - /* 함수 */ - func function() -> Int { - // 몇 가지 연산 수행... - return 0 - } - - func algorithm(n: Int) -> Int { // 입력 데이터 - let a = 0 // 임시 데이터(상수) - var b = 0 // 임시 데이터(변수) - let node = Node(x: 0) // 임시 데이터(객체) - let c = function() // 스택 프레임 공간(함수 호출) - return a + b + c // 출력 데이터 - } - ``` - -=== "JS" - - ```javascript title="" - /* 클래스 */ - class Node { - val; - next; - constructor(val) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.next = null; // 다음 노드를 가리키는 참조 - } - } - - /* 함수 */ - function constFunc() { - // 몇 가지 연산 수행 - return 0; - } - - function algorithm(n) { // 입력 데이터 - const a = 0; // 임시 데이터(상수) - let b = 0; // 임시 데이터(변수) - const node = new Node(0); // 임시 데이터(객체) - const c = constFunc(); // 스택 프레임 공간(함수 호출) - return a + b + c; // 출력 데이터 - } - ``` - -=== "TS" - - ```typescript title="" - /* 클래스 */ - class Node { - val: number; - next: Node | null; - constructor(val?: number) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.next = null; // 다음 노드를 가리키는 참조 - } - } - - /* 함수 */ - function constFunc(): number { - // 몇 가지 연산 수행 - return 0; - } - - function algorithm(n: number): number { // 입력 데이터 - const a = 0; // 임시 데이터(상수) - let b = 0; // 임시 데이터(변수) - const node = new Node(0); // 임시 데이터(객체) - const c = constFunc(); // 스택 프레임 공간(함수 호출) - return a + b + c; // 출력 데이터 - } - ``` - -=== "Dart" - - ```dart title="" - /* 클래스 */ - class Node { - int val; - Node next; - Node(this.val, [this.next]); - } - - /* 함수 */ - int function() { - // 몇 가지 연산 수행... - return 0; - } - - int algorithm(int n) { // 입력 데이터 - const int a = 0; // 임시 데이터(상수) - int b = 0; // 임시 데이터(변수) - Node node = Node(0); // 임시 데이터(객체) - int c = function(); // 스택 프레임 공간(함수 호출) - return a + b + c; // 출력 데이터 - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 구조체 */ - struct Node { - val: i32, - next: Option>>, - } - - /* Node 구조체 생성 */ - impl Node { - fn new(val: i32) -> Self { - Self { val: val, next: None } - } - } - - /* 함수 */ - fn function() -> i32 { - // 몇 가지 연산 수행... - return 0; - } - - fn algorithm(n: i32) -> i32 { // 입력 데이터 - const a: i32 = 0; // 임시 데이터(상수) - let mut b = 0; // 임시 데이터(변수) - let node = Node::new(0); // 임시 데이터(객체) - let c = function(); // 스택 프레임 공간(함수 호출) - return a + b + c; // 출력 데이터 - } - ``` - -=== "C" - - ```c title="" - /* 함수 */ - int func() { - // 몇 가지 연산 수행... - return 0; - } - - int algorithm(int n) { // 입력 데이터 - const int a = 0; // 임시 데이터(상수) - int b = 0; // 임시 데이터(변수) - int c = func(); // 스택 프레임 공간(함수 호출) - return a + b + c; // 출력 데이터 - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 클래스 */ - class Node(var _val: Int) { - var next: Node? = null - } - - /* 함수 */ - fun function(): Int { - // 몇 가지 연산 수행... - return 0 - } - - fun algorithm(n: Int): Int { // 입력 데이터 - val a = 0 // 임시 데이터(상수) - var b = 0 // 임시 데이터(변수) - val node = Node(0) // 임시 데이터(객체) - val c = function() // 스택 프레임 공간(함수 호출) - return a + b + c // 출력 데이터 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 클래스 ### - class Node - attr_accessor :val # 노드 값 - attr_accessor :next # 다음 노드를 가리키는 참조 - - def initialize(x) - @val = x - end - end - - ### 함수 ### - def function - # 몇 가지 연산 수행... - 0 - end - - ### 알고리즘 ### - def algorithm(n) # 입력 데이터 - a = 0 # 임시 데이터(상수) - b = 0 # 임시 데이터(변수) - node = Node.new(0) # 임시 데이터(객체) - c = function # 스택 프레임 공간(함수 호출) - a + b + c # 출력 데이터 - end - ``` +```snippet +space_categories +``` ## 계산 방법 @@ -372,428 +39,15 @@ 1. **가장 불리한 입력 데이터를 기준으로 한다**: $n < 10$이면 공간 복잡도는 $O(1)$이다. 그러나 $n > 10$이면 초기화한 배열 `nums`가 $O(n)$ 공간을 차지하므로 최악 공간 복잡도는 $O(n)$이다. 2. **알고리즘 실행 중 최대 메모리 사용량을 기준으로 한다**: 예를 들어 프로그램이 마지막 줄을 실행하기 전에는 $O(1)$ 공간을 차지하지만, 배열 `nums`를 초기화하면 $O(n)$ 공간을 차지한다. 따라서 최악 공간 복잡도는 $O(n)$이다. -=== "Python" - - ```python title="" - def algorithm(n: int): - a = 0 # O(1) - b = [0] * 10000 # O(1) - if n > 10: - nums = [0] * n # O(n) - ``` - -=== "C++" - - ```cpp title="" - void algorithm(int n) { - int a = 0; // O(1) - vector b(10000); // O(1) - if (n > 10) - vector nums(n); // O(n) - } - ``` - -=== "Java" - - ```java title="" - void algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) - int[] nums = new int[n]; // O(n) - } - ``` - -=== "C#" - - ```csharp title="" - void Algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) { - int[] nums = new int[n]; // O(n) - } - } - ``` - -=== "Go" - - ```go title="" - func algorithm(n int) { - a := 0 // O(1) - b := make([]int, 10000) // O(1) - var nums []int - if n > 10 { - nums := make([]int, n) // O(n) - } - fmt.Println(a, b, nums) - } - ``` - -=== "Swift" - - ```swift title="" - func algorithm(n: Int) { - let a = 0 // O(1) - let b = Array(repeating: 0, count: 10000) // O(1) - if n > 10 { - let nums = Array(repeating: 0, count: n) // O(n) - } - } - ``` - -=== "JS" - - ```javascript title="" - function algorithm(n) { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "TS" - - ```typescript title="" - function algorithm(n: number): void { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "Dart" - - ```dart title="" - void algorithm(int n) { - int a = 0; // O(1) - List b = List.filled(10000, 0); // O(1) - if (n > 10) { - List nums = List.filled(n, 0); // O(n) - } - } - ``` - -=== "Rust" - - ```rust title="" - fn algorithm(n: i32) { - let a = 0; // O(1) - let b = [0; 10000]; // O(1) - if n > 10 { - let nums = vec![0; n as usize]; // O(n) - } - } - ``` - -=== "C" - - ```c title="" - void algorithm(int n) { - int a = 0; // O(1) - int b[10000]; // O(1) - if (n > 10) - int nums[n] = {0}; // O(n) - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun algorithm(n: Int) { - val a = 0 // O(1) - val b = IntArray(10000) // O(1) - if (n > 10) { - val nums = IntArray(n) // O(n) - } - } - ``` - -=== "Ruby" - - ```ruby title="" - def algorithm(n) - a = 0 # O(1) - b = Array.new(10000) # O(1) - nums = Array.new(n) if n > 10 # O(n) - end - ``` +```snippet +worst_case_space +``` **재귀 함수에서는 스택 프레임 공간을 계산하는 데 주의해야 한다**. 다음 코드를 살펴보자. -=== "Python" - - ```python title="" - def function() -> int: - # 몇 가지 연산 수행 - return 0 - - def loop(n: int): - """반복문의 공간 복잡도는 O(1)""" - for _ in range(n): - function() - - def recur(n: int): - """재귀의 공간 복잡도는 O(n)""" - if n == 1: - return - return recur(n - 1) - ``` - -=== "C++" - - ```cpp title="" - int func() { - // 몇 가지 연산 수행 - return 0; - } - /* 반복문의 공간 복잡도는 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* 재귀의 공간 복잡도는 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Java" - - ```java title="" - int function() { - // 몇 가지 연산 수행 - return 0; - } - /* 반복문의 공간 복잡도는 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* 재귀의 공간 복잡도는 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "C#" - - ```csharp title="" - int Function() { - // 몇 가지 연산 수행 - return 0; - } - /* 반복문의 공간 복잡도는 O(1) */ - void Loop(int n) { - for (int i = 0; i < n; i++) { - Function(); - } - } - /* 재귀의 공간 복잡도는 O(n) */ - int Recur(int n) { - if (n == 1) return 1; - return Recur(n - 1); - } - ``` - -=== "Go" - - ```go title="" - func function() int { - // 몇 가지 연산 수행 - return 0 - } - - /* 반복문의 공간 복잡도는 O(1) */ - func loop(n int) { - for i := 0; i < n; i++ { - function() - } - } - - /* 재귀의 공간 복잡도는 O(n) */ - func recur(n int) { - if n == 1 { - return - } - recur(n - 1) - } - ``` - -=== "Swift" - - ```swift title="" - @discardableResult - func function() -> Int { - // 몇 가지 연산 수행 - return 0 - } - - /* 반복문의 공간 복잡도는 O(1) */ - func loop(n: Int) { - for _ in 0 ..< n { - function() - } - } - - /* 재귀의 공간 복잡도는 O(n) */ - func recur(n: Int) { - if n == 1 { - return - } - recur(n: n - 1) - } - ``` - -=== "JS" - - ```javascript title="" - function constFunc() { - // 몇 가지 연산 수행 - return 0; - } - /* 반복문의 공간 복잡도는 O(1) */ - function loop(n) { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* 재귀의 공간 복잡도는 O(n) */ - function recur(n) { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "TS" - - ```typescript title="" - function constFunc(): number { - // 몇 가지 연산 수행 - return 0; - } - /* 반복문의 공간 복잡도는 O(1) */ - function loop(n: number): void { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* 재귀의 공간 복잡도는 O(n) */ - function recur(n: number): void { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "Dart" - - ```dart title="" - int function() { - // 몇 가지 연산 수행 - return 0; - } - /* 반복문의 공간 복잡도는 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* 재귀의 공간 복잡도는 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Rust" - - ```rust title="" - fn function() -> i32 { - // 몇 가지 연산 수행 - return 0; - } - /* 반복문의 공간 복잡도는 O(1) */ - fn loop(n: i32) { - for i in 0..n { - function(); - } - } - /* 재귀의 공간 복잡도는 O(n) */ - fn recur(n: i32) { - if n == 1 { - return; - } - recur(n - 1); - } - ``` - -=== "C" - - ```c title="" - int func() { - // 몇 가지 연산 수행 - return 0; - } - /* 반복문의 공간 복잡도는 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* 재귀의 공간 복잡도는 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun function(): Int { - // 몇 가지 연산 수행 - return 0 - } - /* 반복문의 공간 복잡도는 O(1) */ - fun loop(n: Int) { - for (i in 0.. numbers = List.filled(5, 0); - List decimals = List.filled(5, 0.0); - List characters = List.filled(5, 'a'); - List bools = List.filled(5, false); - ``` - -=== "Rust" - - ```rust title="" - // 여러 기본 자료형으로 배열 초기화 - let numbers: Vec = vec![0; 5]; - let decimals: Vec = vec![0.0; 5]; - let characters: Vec = vec!['0'; 5]; - let bools: Vec = vec![false; 5]; - ``` - -=== "C" - - ```c title="" - // 여러 기본 자료형으로 배열 초기화 - int numbers[10]; - float decimals[10]; - char characters[10]; - bool bools[10]; - ``` - -=== "Kotlin" - - ```kotlin title="" - // 여러 기본 자료형으로 배열 초기화 - val numbers = IntArray(5) - val decinals = FloatArray(5) - val characters = CharArray(5) - val bools = BooleanArray(5) - ``` - -=== "Ruby" - - ```ruby title="" - # Ruby의 리스트는 여러 기본 자료형과 객체 참조를 자유롭게 저장할 수 있다 - data = [0, 0.0, 'a', false, ListNode(0)] - ``` +```snippet +basic_type_arrays +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%EB%8B%A4%EC%9D%8C%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%97%AC%EB%9F%AC%20%EA%B8%B0%EB%B3%B8%20%EC%9E%90%EB%A3%8C%ED%98%95%EC%9C%BC%EB%A1%9C%20%EB%B0%B0%EC%97%B4%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20%2A%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20%2A%205%0A%20%20%20%20%23%20Python%EC%9D%98%20%EB%AC%B8%EC%9E%90%EB%8A%94%20%EC%8B%A4%EC%A0%9C%EB%A1%9C%20%EA%B8%B8%EC%9D%B4%EA%B0%80%201%EC%9D%B8%20%EB%AC%B8%EC%9E%90%EC%97%B4%EC%9D%B4%EB%8B%A4%0A%20%20%20%20characters%20%3D%20%5B%270%27%5D%20%2A%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20%2A%205%0A%20%20%20%20%23%20Python%EC%9D%98%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%8A%94%20%EC%97%AC%EB%9F%AC%20%EA%B8%B0%EB%B3%B8%20%EC%9E%90%EB%A3%8C%ED%98%95%EA%B3%BC%20%EA%B0%9D%EC%B2%B4%20%EC%B0%B8%EC%A1%B0%EB%A5%BC%20%EC%9E%90%EC%9C%A0%EB%A1%AD%EA%B2%8C%20%EC%A0%80%EC%9E%A5%ED%95%A0%20%EC%88%98%20%EC%9E%88%EB%8B%A4%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20%27a%27%2C%20False%2C%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor basic_type_arrays_tutor diff --git a/ko/docs/chapter_hashing/hash_algorithm.md b/ko/docs/chapter_hashing/hash_algorithm.md index e7fdadcec..af52f26b9 100644 --- a/ko/docs/chapter_hashing/hash_algorithm.md +++ b/ko/docs/chapter_hashing/hash_algorithm.md @@ -113,295 +113,13 @@ $$ 프로그래밍 언어마다 내장 해시값 계산 함수의 정의와 방식이 다르다는 점에 주의하자. -=== "Python" - - ```python title="built_in_hash.py" - num = 3 - hash_num = hash(num) - # 정수 3의 해시값은 3 - - bol = True - hash_bol = hash(bol) - # 불리언 True의 해시값은 1 - - dec = 3.14159 - hash_dec = hash(dec) - # 소수 3.14159의 해시값은 326484311674566659 - - str = "Hello 算法" - hash_str = hash(str) - # 문자열 “Hello 算法”의 해시값은 4617003410720528961 - - tup = (12836, "小哈") - hash_tup = hash(tup) - # 튜플 (12836, '小哈')의 해시값은 1029005403108185979 - - obj = ListNode(0) - hash_obj = hash(obj) - # 노드 객체 의 해시값은 274267521 - ``` - -=== "C++" - - ```cpp title="built_in_hash.cpp" - int num = 3; - size_t hashNum = hash()(num); - // 정수 3의 해시값은 3 - - bool bol = true; - size_t hashBol = hash()(bol); - // 불리언 1의 해시값은 1 - - double dec = 3.14159; - size_t hashDec = hash()(dec); - // 소수 3.14159의 해시값은 4614256650576692846 - - string str = "Hello 算法"; - size_t hashStr = hash()(str); - // 문자열 “Hello 算法”의 해시값은 15466937326284535026 - - // C++의 내장 std::hash()는 기본 자료형의 해시값 계산만 제공한다 - // 배열과 객체의 해시값 계산은 직접 구현해야 한다 - ``` - -=== "Java" - - ```java title="built_in_hash.java" - int num = 3; - int hashNum = Integer.hashCode(num); - // 정수 3의 해시값은 3 - - boolean bol = true; - int hashBol = Boolean.hashCode(bol); - // 불리언 true의 해시값은 1231 - - double dec = 3.14159; - int hashDec = Double.hashCode(dec); - // 소수 3.14159의 해시값은 -1340954729 - - String str = "Hello 算法"; - int hashStr = str.hashCode(); - // 문자열 “Hello 算法”의 해시값은 -727081396 - - Object[] arr = { 12836, "小哈" }; - int hashTup = Arrays.hashCode(arr); - // 배열 [12836, 小哈]의 해시값은 1151158 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode(); - // 노드 객체 utils.ListNode@7dc5e7b4의 해시값은 2110121908 - ``` - -=== "C#" - - ```csharp title="built_in_hash.cs" - int num = 3; - int hashNum = num.GetHashCode(); - // 정수 3의 해시값은 3; - - bool bol = true; - int hashBol = bol.GetHashCode(); - // 불리언 true의 해시값은 1; - - double dec = 3.14159; - int hashDec = dec.GetHashCode(); - // 소수 3.14159의 해시값은 -1340954729; - - string str = "Hello 算法"; - int hashStr = str.GetHashCode(); - // 문자열 “Hello 算法”의 해시값은 -586107568; - - object[] arr = [12836, "小哈"]; - int hashTup = arr.GetHashCode(); - // 배열 [12836, 小哈]의 해시값은 42931033; - - ListNode obj = new(0); - int hashObj = obj.GetHashCode(); - // 노드 객체 0의 해시값은 39053774; - ``` - -=== "Go" - - ```go title="built_in_hash.go" - // Go는 내장 hash code 함수를 제공하지 않는다 - ``` - -=== "Swift" - - ```swift title="built_in_hash.swift" - let num = 3 - let hashNum = num.hashValue - // 정수 3의 해시값은 9047044699613009734 - - let bol = true - let hashBol = bol.hashValue - // 불리언 true의 해시값은 -4431640247352757451 - - let dec = 3.14159 - let hashDec = dec.hashValue - // 소수 3.14159의 해시값은 -2465384235396674631 - - let str = "Hello 算法" - let hashStr = str.hashValue - // 문자열 “Hello 算法”의 해시값은 -7850626797806988787 - - let arr = [AnyHashable(12836), AnyHashable("小哈")] - let hashTup = arr.hashValue - // 배열 [AnyHashable(12836), AnyHashable("小哈")]의 해시값은 -2308633508154532996 - - let obj = ListNode(x: 0) - let hashObj = obj.hashValue - // 노드 객체 utils.ListNode의 해시값은 -2434780518035996159 - ``` - -=== "JS" - - ```javascript title="built_in_hash.js" - // JavaScript는 내장 hash code 함수를 제공하지 않는다 - ``` - -=== "TS" - - ```typescript title="built_in_hash.ts" - // TypeScript는 내장 hash code 함수를 제공하지 않는다 - ``` - -=== "Dart" - - ```dart title="built_in_hash.dart" - int num = 3; - int hashNum = num.hashCode; - // 정수 3의 해시값은 34803 - - bool bol = true; - int hashBol = bol.hashCode; - // 불리언 true의 해시값은 1231 - - double dec = 3.14159; - int hashDec = dec.hashCode; - // 소수 3.14159의 해시값은 2570631074981783 - - String str = "Hello 算法"; - int hashStr = str.hashCode; - // 문자열 “Hello 算法”의 해시값은 468167534 - - List arr = [12836, "小哈"]; - int hashArr = arr.hashCode; - // 배열 [12836, 小哈]의 해시값은 976512528 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode; - // 노드 객체 Instance of 'ListNode'의 해시값은 1033450432 - ``` - -=== "Rust" - - ```rust title="built_in_hash.rs" - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - - let num = 3; - let mut num_hasher = DefaultHasher::new(); - num.hash(&mut num_hasher); - let hash_num = num_hasher.finish(); - // 정수 3의 해시값은 568126464209439262 - - let bol = true; - let mut bol_hasher = DefaultHasher::new(); - bol.hash(&mut bol_hasher); - let hash_bol = bol_hasher.finish(); - // 불리언 true의 해시값은 4952851536318644461 - - let dec: f32 = 3.14159; - let mut dec_hasher = DefaultHasher::new(); - dec.to_bits().hash(&mut dec_hasher); - let hash_dec = dec_hasher.finish(); - // 소수 3.14159의 해시값은 2566941990314602357 - - let str = "Hello 算法"; - let mut str_hasher = DefaultHasher::new(); - str.hash(&mut str_hasher); - let hash_str = str_hasher.finish(); - // 문자열 “Hello 算法”의 해시값은 16092673739211250988 - - let arr = (&12836, &"小哈"); - let mut tup_hasher = DefaultHasher::new(); - arr.hash(&mut tup_hasher); - let hash_tup = tup_hasher.finish(); - // 튜플 (12836, "小哈")의 해시값은 1885128010422702749 - - let node = ListNode::new(42); - let mut hasher = DefaultHasher::new(); - node.borrow().val.hash(&mut hasher); - let hash = hasher.finish(); - // 노드 객체 RefCell { value: ListNode { val: 42, next: None } }의 해시값은 15387811073369036852 - ``` - -=== "C" - - ```c title="built_in_hash.c" - // C는 내장 hash code 함수를 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="built_in_hash.kt" - val num = 3 - val hashNum = num.hashCode() - // 정수 3의 해시값은 3 - - val bol = true - val hashBol = bol.hashCode() - // 불리언 true의 해시값은 1231 - - val dec = 3.14159 - val hashDec = dec.hashCode() - // 소수 3.14159의 해시값은 -1340954729 - - val str = "Hello 算法" - val hashStr = str.hashCode() - // 문자열 “Hello 算法”의 해시값은 -727081396 - - val arr = arrayOf(12836, "小哈") - val hashTup = arr.hashCode() - // 배열 [12836, 小哈]의 해시값은 189568618 - - val obj = ListNode(0) - val hashObj = obj.hashCode() - // 노드 객체 utils.ListNode@1d81eb93의 해시값은 495053715 - ``` - -=== "Ruby" - - ```ruby title="built_in_hash.rb" - num = 3 - hash_num = num.hash - # 정수 3의 해시값은 -4385856518450339636 - - bol = true - hash_bol = bol.hash - # 불리언 true의 해시값은 -1617938112149317027 - - dec = 3.14159 - hash_dec = dec.hash - # 소수 3.14159의 해시값은 -1479186995943067893 - - str = "Hello 算法" - hash_str = str.hash - # 문자열 “Hello 算法”의 해시값은 -4075943250025831763 - - tup = [12836, '小哈'] - hash_tup = tup.hash - # 튜플 (12836, '小哈')의 해시값은 1999544809202288822 - - obj = ListNode.new(0) - hash_obj = obj.hash - # 노드 객체 #의 해시값은 4302940560806366381 - ``` +```snippet +builtin_hash +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%ED%9B%84%EC%86%8D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%EC%A0%95%EC%88%98%203%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%EB%B6%88%EB%A6%AC%EC%96%B8%20True%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%EC%86%8C%EC%88%98%203.14159%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%EB%AC%B8%EC%9E%90%EC%97%B4%20%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%ED%8A%9C%ED%94%8C%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%9D%EC%B2%B4%20%3CListNode%20object%20at%200x1058fd810%3E%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor builtin_hash_tutor 많은 프로그래밍 언어에서는 **불변 객체만 해시 테이블의 `key`로 사용할 수 있다**. 리스트(동적 배열)를 `key`로 사용하면 내용이 바뀔 때 해시값도 달라져, 기존의 `value`를 조회할 수 없게 된다. diff --git a/ko/docs/chapter_hashing/hash_map.md b/ko/docs/chapter_hashing/hash_map.md index 0c73c3039..8ffa21e24 100644 --- a/ko/docs/chapter_hashing/hash_map.md +++ b/ko/docs/chapter_hashing/hash_map.md @@ -26,517 +26,23 @@ 대표적인 연산에는 초기화, 조회, 키-값 쌍 추가와 삭제 등이 있다. 예제 코드는 다음과 같다. -=== "Python" - - ```python title="hash_map.py" - # 해시 테이블 초기화 - hmap: dict = {} - - # 추가 연산 - # 해시 테이블에 키-값 쌍 (key, value) 추가 - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - # 조회 연산 - # 해시 테이블에 키 key를 입력하여 값 value를 얻음 - name: str = hmap[15937] - - # 삭제 연산 - # 해시 테이블에서 키-값 쌍 (key, value) 삭제 - hmap.pop(10583) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* 해시 테이블 초기화 */ - unordered_map map; - - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - map[12836] = "小哈"; - map[15937] = "小啰"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鸭"; - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - string name = map[15937]; - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - map.erase(10583); - ``` - -=== "Java" - - ```java title="hash_map.java" - /* 해시 테이블 초기화 */ - Map map = new HashMap<>(); - - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - map.put(12836, "小哈"); - map.put(15937, "小啰"); - map.put(16750, "小算"); - map.put(13276, "小法"); - map.put(10583, "小鸭"); - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - String name = map.get(15937); - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - map.remove(10583); - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* 해시 테이블 초기화 */ - Dictionary map = new() { - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - { 12836, "小哈" }, - { 15937, "小啰" }, - { 16750, "小算" }, - { 13276, "小法" }, - { 10583, "小鸭" } - }; - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - string name = map[15937]; - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - map.Remove(10583); - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* 해시 테이블 초기화 */ - hmap := make(map[int]string) - - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - name := hmap[15937] - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - delete(hmap, 10583) - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* 해시 테이블 초기화 */ - var map: [Int: String] = [:] - - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - map[12836] = "小哈" - map[15937] = "小啰" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鸭" - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - let name = map[15937]! - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - map.removeValue(forKey: 10583) - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* 해시 테이블 초기화 */ - const map = new Map(); - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - map.set(12836, '小哈'); - map.set(15937, '小啰'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鸭'); - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - let name = map.get(15937); - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - map.delete(10583); - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* 해시 테이블 초기화 */ - const map = new Map(); - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - map.set(12836, '小哈'); - map.set(15937, '小啰'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鸭'); - console.info('\n추가한 뒤의 해시 테이블\nKey -> Value'); - console.info(map); - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - let name = map.get(15937); - console.info('\n학번 15937을 입력하여 찾은 이름 ' + name); - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - map.delete(10583); - console.info('\n10583을 삭제한 뒤의 해시 테이블\nKey -> Value'); - console.info(map); - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* 해시 테이블 초기화 */ - Map map = {}; - - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - map[12836] = "小哈"; - map[15937] = "小啰"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鸭"; - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - String name = map[15937]; - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - map.remove(10583); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - use std::collections::HashMap; - - /* 해시 테이블 초기화 */ - let mut map: HashMap = HashMap::new(); - - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - map.insert(12836, "小哈".to_string()); - map.insert(15937, "小啰".to_string()); - map.insert(16750, "小算".to_string()); - map.insert(13279, "小法".to_string()); - map.insert(10583, "小鸭".to_string()); - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - let _name: Option<&String> = map.get(&15937); - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - let _removed_value: Option = map.remove(&10583); - ``` - -=== "C" - - ```c title="hash_map.c" - // C는 내장 해시 테이블을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* 해시 테이블 초기화 */ - val map = HashMap() - - /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 - map[12836] = "小哈" - map[15937] = "小啰" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鸭" - - /* 조회 연산 */ - // 해시 테이블에 키 key를 입력하여 값 value를 얻음 - val name = map[15937] - - /* 삭제 연산 */ - // 해시 테이블에서 키-값 쌍 (key, value) 삭제 - map.remove(10583) - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # 해시 테이블 초기화 - hmap = {} - - # 추가 연산 - # 해시 테이블에 키-값 쌍 (key, value) 추가 - hmap[12836] = "小哈" - hmap[15937] = "小啰" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鸭" - - # 조회 연산 - # 해시 테이블에 키 key를 입력하여 값 value를 얻음 - name = hmap[15937] - - # 삭제 연산 - # 해시 테이블에서 키-값 쌍 (key, value) 삭제 - hmap.delete(10583) - ``` +```snippet +hash_map_operations +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%B6%94%EA%B0%80%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20%28key%2C%20value%29%20%EC%B6%94%EA%B0%80%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%A1%B0%ED%9A%8C%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%20%ED%82%A4%20key%EB%A5%BC%20%EC%9E%85%EB%A0%A5%ED%95%98%EC%97%AC%20%EA%B0%92%20value%EB%A5%BC%20%EC%96%BB%EC%9D%8C%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%82%AD%EC%A0%9C%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%EC%84%9C%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20%28key%2C%20value%29%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_operations_tutor 해시 테이블을 순회하는 대표적인 방식은 키-값 쌍 순회, 키 순회, 값 순회의 세 가지다. 예제 코드는 다음과 같다. -=== "Python" - - ```python title="hash_map.py" - # 해시 테이블 순회 - # 키-값 쌍 key->value 순회 - for key, value in hmap.items(): - print(key, "->", value) - # 키 key만 순회 - for key in hmap.keys(): - print(key) - # 값 value만 순회 - for value in hmap.values(): - print(value) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* 해시 테이블 순회 */ - // 키-값 쌍 key->value 순회 - for (auto kv: map) { - cout << kv.first << " -> " << kv.second << endl; - } - // 이터레이터로 key->value 순회 - for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; - } - ``` - -=== "Java" - - ```java title="hash_map.java" - /* 해시 테이블 순회 */ - // 키-값 쌍 key->value 순회 - for (Map.Entry kv: map.entrySet()) { - System.out.println(kv.getKey() + " -> " + kv.getValue()); - } - // 키 key만 순회 - for (int key: map.keySet()) { - System.out.println(key); - } - // 값 value만 순회 - for (String val: map.values()) { - System.out.println(val); - } - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* 해시 테이블 순회 */ - // 키-값 쌍 Key->Value 순회 - foreach (var kv in map) { - Console.WriteLine(kv.Key + " -> " + kv.Value); - } - // 키 key만 순회 - foreach (int key in map.Keys) { - Console.WriteLine(key); - } - // 값 value만 순회 - foreach (string val in map.Values) { - Console.WriteLine(val); - } - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* 해시 테이블 순회 */ - // 키-값 쌍 key->value 순회 - for key, value := range hmap { - fmt.Println(key, "->", value) - } - // 키 key만 순회 - for key := range hmap { - fmt.Println(key) - } - // 값 value만 순회 - for _, value := range hmap { - fmt.Println(value) - } - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* 해시 테이블 순회 */ - // 키-값 쌍 Key->Value 순회 - for (key, value) in map { - print("\(key) -> \(value)") - } - // 키 Key만 순회 - for key in map.keys { - print(key) - } - // 값 Value만 순회 - for value in map.values { - print(value) - } - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* 해시 테이블 순회 */ - console.info('\n키-값 쌍 Key->Value 순회'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\n키 Key만 순회'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\n값 Value만 순회'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* 해시 테이블 순회 */ - console.info('\n키-값 쌍 Key->Value 순회'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\n키 Key만 순회'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\n값 Value만 순회'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* 해시 테이블 순회 */ - // 키-값 쌍 Key->Value 순회 - map.forEach((key, value) { - print('$key -> $value'); - }); - - // 키 Key만 순회 - map.keys.forEach((key) { - print(key); - }); - - // 값 Value만 순회 - map.values.forEach((value) { - print(value); - }); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - /* 해시 테이블 순회 */ - // 키-값 쌍 Key->Value 순회 - for (key, value) in &map { - println!("{key} -> {value}"); - } - - // 키 Key만 순회 - for key in map.keys() { - println!("{key}"); - } - - // 값 Value만 순회 - for value in map.values() { - println!("{value}"); - } - ``` - -=== "C" - - ```c title="hash_map.c" - // C는 내장 해시 테이블을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* 해시 테이블 순회 */ - // 키-값 쌍 key->value 순회 - for ((key, value) in map) { - println("$key -> $value") - } - // 키 key만 순회 - for (key in map.keys) { - println(key) - } - // 값 value만 순회 - for (_val in map.values) { - println(_val) - } - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # 해시 테이블 순회 - # 키-값 쌍 key->value 순회 - hmap.entries.each { |key, value| puts "#{key} -> #{value}" } - - # 키 key만 순회 - hmap.keys.each { |key| puts key } - - # 값 value만 순회 - hmap.values.each { |val| puts val } - ``` +```snippet +hash_map_traversal +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%B6%94%EA%B0%80%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20%28key%2C%20value%29%20%EC%B6%94%EA%B0%80%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20%23%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20key-%3Evalue%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%ED%82%A4%20key%EB%A7%8C%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%EA%B0%92%20value%EB%A7%8C%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_traversal_tutor ## 간단한 해시 테이블 구현 diff --git a/ko/docs/chapter_heap/heap.md b/ko/docs/chapter_heap/heap.md index a396f8fef..61581304e 100644 --- a/ko/docs/chapter_heap/heap.md +++ b/ko/docs/chapter_heap/heap.md @@ -35,382 +35,13 @@ 정렬 알고리즘에서 '오름차순 정렬'과 '내림차순 정렬'을 선택하듯이, `flag`를 설정하거나 `Comparator`를 수정하여 '최소 힙'과 '최대 힙'을 전환할 수 있다. 코드는 다음과 같다. -=== "Python" - - ```python title="heap.py" - # 최소 힙 초기화 - min_heap, flag = [], 1 - # 최대 힙 초기화 - max_heap, flag = [], -1 - - # Python의 heapq 모듈은 기본적으로 최소 힙을 구현한다 - # 원소의 부호를 바꾼 뒤 삽입하면 대소 관계가 뒤집히므로 최대 힙을 구현할 수 있다 - # 이 예제에서 flag = 1이면 최소 힙, flag = -1이면 최대 힙에 해당한다 - - # 힙에 원소 삽입 - heapq.heappush(max_heap, flag * 1) - heapq.heappush(max_heap, flag * 3) - heapq.heappush(max_heap, flag * 2) - heapq.heappush(max_heap, flag * 5) - heapq.heappush(max_heap, flag * 4) - - # 힙의 루트 원소 구하기 - peek: int = flag * max_heap[0] # 5 - - # 힙의 루트 원소 꺼내기 - # 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 - val = flag * heapq.heappop(max_heap) # 5 - val = flag * heapq.heappop(max_heap) # 4 - val = flag * heapq.heappop(max_heap) # 3 - val = flag * heapq.heappop(max_heap) # 2 - val = flag * heapq.heappop(max_heap) # 1 - - # 힙의 크기 구하기 - size: int = len(max_heap) - - # 힙이 비어 있는지 확인 - is_empty: bool = not max_heap - - # 리스트를 입력받아 힙 구성 - min_heap: list[int] = [1, 3, 2, 5, 4] - heapq.heapify(min_heap) - ``` - -=== "C++" - - ```cpp title="heap.cpp" - /* 힙 초기화 */ - // 최소 힙 초기화 - priority_queue, greater> minHeap; - // 최대 힙 초기화 - priority_queue, less> maxHeap; - - /* 힙에 원소 삽입 */ - maxHeap.push(1); - maxHeap.push(3); - maxHeap.push(2); - maxHeap.push(5); - maxHeap.push(4); - - /* 힙의 루트 원소 구하기 */ - int peek = maxHeap.top(); // 5 - - /* 힙의 루트 원소 꺼내기 */ - // 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 - maxHeap.pop(); // 5 - maxHeap.pop(); // 4 - maxHeap.pop(); // 3 - maxHeap.pop(); // 2 - maxHeap.pop(); // 1 - - /* 힙의 크기 구하기 */ - int size = maxHeap.size(); - - /* 힙이 비어 있는지 확인 */ - bool isEmpty = maxHeap.empty(); - - /* 리스트를 입력받아 힙 구성 */ - vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); - ``` - -=== "Java" - - ```java title="heap.java" - /* 힙 초기화 */ - // 최소 힙 초기화 - Queue minHeap = new PriorityQueue<>(); - // 최대 힙 초기화(lambda 식으로 Comparator를 수정하면 된다) - Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); - - /* 힙에 원소 삽입 */ - maxHeap.offer(1); - maxHeap.offer(3); - maxHeap.offer(2); - maxHeap.offer(5); - maxHeap.offer(4); - - /* 힙의 루트 원소 구하기 */ - int peek = maxHeap.peek(); // 5 - - /* 힙의 루트 원소 꺼내기 */ - // 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 - peek = maxHeap.poll(); // 5 - peek = maxHeap.poll(); // 4 - peek = maxHeap.poll(); // 3 - peek = maxHeap.poll(); // 2 - peek = maxHeap.poll(); // 1 - - /* 힙의 크기 구하기 */ - int size = maxHeap.size(); - - /* 힙이 비어 있는지 확인 */ - boolean isEmpty = maxHeap.isEmpty(); - - /* 리스트를 입력받아 힙 구성 */ - minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); - ``` - -=== "C#" - - ```csharp title="heap.cs" - /* 힙 초기화 */ - // 최소 힙 초기화 - PriorityQueue minHeap = new(); - // 최대 힙 초기화(lambda 식으로 Comparer를 수정하면 된다) - PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); - - /* 힙에 원소 삽입 */ - maxHeap.Enqueue(1, 1); - maxHeap.Enqueue(3, 3); - maxHeap.Enqueue(2, 2); - maxHeap.Enqueue(5, 5); - maxHeap.Enqueue(4, 4); - - /* 힙의 루트 원소 구하기 */ - int peek = maxHeap.Peek();//5 - - /* 힙의 루트 원소 꺼내기 */ - // 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 - peek = maxHeap.Dequeue(); // 5 - peek = maxHeap.Dequeue(); // 4 - peek = maxHeap.Dequeue(); // 3 - peek = maxHeap.Dequeue(); // 2 - peek = maxHeap.Dequeue(); // 1 - - /* 힙의 크기 구하기 */ - int size = maxHeap.Count; - - /* 힙이 비어 있는지 확인 */ - bool isEmpty = maxHeap.Count == 0; - - /* 리스트를 입력받아 힙 구성 */ - minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); - ``` - -=== "Go" - - ```go title="heap.go" - // Go에서는 heap.Interface를 구현하여 정수 최대 힙을 만들 수 있다 - // heap.Interface를 구현하려면 sort.Interface도 구현해야 한다 - type intHeap []any - - // Push는 heap.Interface의 메서드로, 힙에 원소를 삽입한다 - func (h *intHeap) Push(x any) { - // Push와 Pop은 포인터 리시버(pointer receiver)를 매개변수로 사용한다 - // 슬라이스의 내용뿐 아니라 길이도 수정하기 때문이다. - *h = append(*h, x.(int)) - } - - // Pop은 heap.Interface의 메서드로, 힙의 루트 원소를 꺼낸다 - func (h *intHeap) Pop() any { - // 꺼낼 원소는 맨 끝에 저장되어 있다 - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last - } - - // Len은 sort.Interface의 메서드다 - func (h *intHeap) Len() int { - return len(*h) - } - - // Less는 sort.Interface의 메서드다 - func (h *intHeap) Less(i, j int) bool { - // 최소 힙을 구현하려면 부등호를 <로 바꿔야 한다 - return (*h)[i].(int) > (*h)[j].(int) - } - - // Swap은 sort.Interface의 메서드다 - func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] - } - - // Top은 힙의 루트 원소를 구한다 - func (h *intHeap) Top() any { - return (*h)[0] - } - - /* 실행 코드 */ - func TestHeap(t *testing.T) { - /* 힙 초기화 */ - // 최대 힙 초기화 - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* 힙에 원소 삽입 */ - // heap.Interface의 메서드를 호출하여 원소를 추가한다 - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* 힙의 루트 원소 구하기 */ - top := maxHeap.Top() - fmt.Printf("힙의 루트 원소: %d\n", top) - - /* 힙의 루트 원소 꺼내기 */ - // heap.Interface의 메서드를 호출하여 원소를 제거한다 - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 - - /* 힙의 크기 구하기 */ - size := len(*maxHeap) - fmt.Printf("힙의 원소 수: %d\n", size) - - /* 힙이 비어 있는지 확인 */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("힙이 비어 있는가: %t\n", isEmpty) - } - ``` - -=== "Swift" - - ```swift title="heap.swift" - /* 힙 초기화 */ - // Swift의 Heap 타입은 최대 힙과 최소 힙을 모두 지원하며, swift-collections를 가져와야 한다 - var heap = Heap() - - /* 힙에 원소 삽입 */ - heap.insert(1) - heap.insert(3) - heap.insert(2) - heap.insert(5) - heap.insert(4) - - /* 힙의 루트 원소 구하기 */ - var peek = heap.max()! - - /* 힙의 루트 원소 꺼내기 */ - peek = heap.removeMax() // 5 - peek = heap.removeMax() // 4 - peek = heap.removeMax() // 3 - peek = heap.removeMax() // 2 - peek = heap.removeMax() // 1 - - /* 힙의 크기 구하기 */ - let size = heap.count - - /* 힙이 비어 있는지 확인 */ - let isEmpty = heap.isEmpty - - /* 리스트를 입력받아 힙 구성 */ - let heap2 = Heap([1, 3, 2, 5, 4]) - ``` - -=== "JS" - - ```javascript title="heap.js" - // JavaScript는 내장 Heap 클래스를 제공하지 않는다 - ``` - -=== "TS" - - ```typescript title="heap.ts" - // TypeScript는 내장 Heap 클래스를 제공하지 않는다 - ``` - -=== "Dart" - - ```dart title="heap.dart" - // Dart는 내장 Heap 클래스를 제공하지 않는다 - ``` - -=== "Rust" - - ```rust title="heap.rs" - use std::collections::BinaryHeap; - use std::cmp::Reverse; - - /* 힙 초기화 */ - // 최소 힙 초기화 - let mut min_heap = BinaryHeap::>::new(); - // 최대 힙 초기화 - let mut max_heap = BinaryHeap::new(); - - /* 힙에 원소 삽입 */ - max_heap.push(1); - max_heap.push(3); - max_heap.push(2); - max_heap.push(5); - max_heap.push(4); - - /* 힙의 루트 원소 구하기 */ - let peek = max_heap.peek().unwrap(); // 5 - - /* 힙의 루트 원소 꺼내기 */ - // 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 - let peek = max_heap.pop().unwrap(); // 5 - let peek = max_heap.pop().unwrap(); // 4 - let peek = max_heap.pop().unwrap(); // 3 - let peek = max_heap.pop().unwrap(); // 2 - let peek = max_heap.pop().unwrap(); // 1 - - /* 힙의 크기 구하기 */ - let size = max_heap.len(); - - /* 힙이 비어 있는지 확인 */ - let is_empty = max_heap.is_empty(); - - /* 리스트를 입력받아 힙 구성 */ - let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); - ``` - -=== "C" - - ```c title="heap.c" - // C는 내장 Heap 클래스를 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="heap.kt" - /* 힙 초기화 */ - // 최소 힙 초기화 - var minHeap = PriorityQueue() - // 최대 힙 초기화(lambda 식으로 Comparator를 수정하면 된다) - val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } - - /* 힙에 원소 삽입 */ - maxHeap.offer(1) - maxHeap.offer(3) - maxHeap.offer(2) - maxHeap.offer(5) - maxHeap.offer(4) - - /* 힙의 루트 원소 구하기 */ - var peek = maxHeap.peek() // 5 - - /* 힙의 루트 원소 꺼내기 */ - // 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 - peek = maxHeap.poll() // 5 - peek = maxHeap.poll() // 4 - peek = maxHeap.poll() // 3 - peek = maxHeap.poll() // 2 - peek = maxHeap.poll() // 1 - - /* 힙의 크기 구하기 */ - val size = maxHeap.size - - /* 힙이 비어 있는지 확인 */ - val isEmpty = maxHeap.isEmpty() - - /* 리스트를 입력받아 힙 구성 */ - minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) - ``` - -=== "Ruby" - - ```ruby title="heap.rb" - # Ruby는 내장 Heap 클래스를 제공하지 않는다 - ``` +```snippet +heap_operations +``` ??? pythontutor "실행 시각화" - https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%EC%9D%98%20heapq%20%EB%AA%A8%EB%93%88%EC%9D%80%20%EA%B8%B0%EB%B3%B8%EC%A0%81%EC%9C%BC%EB%A1%9C%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%EC%9D%84%20%EA%B5%AC%ED%98%84%ED%95%9C%EB%8B%A4%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%EC%9D%98%20%EB%B6%80%ED%98%B8%EB%A5%BC%20%EB%B0%94%EA%BE%BC%20%EB%92%A4%20%EC%82%BD%EC%9E%85%ED%95%98%EB%A9%B4%20%EB%8C%80%EC%86%8C%20%EA%B4%80%EA%B3%84%EA%B0%80%20%EB%92%A4%EC%A7%91%ED%9E%88%EB%AF%80%EB%A1%9C%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%EC%9D%84%20%EA%B5%AC%ED%98%84%ED%95%A0%20%EC%88%98%20%EC%9E%88%EB%8B%A4%0A%20%20%20%20%23%20%EC%9D%B4%20%EC%98%88%EC%A0%9C%EC%97%90%EC%84%9C%20flag%20%3D%201%EC%9D%B4%EB%A9%B4%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%2C%20flag%20%3D%20-1%EC%9D%B4%EB%A9%B4%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%EC%97%90%20%ED%95%B4%EB%8B%B9%ED%95%9C%EB%8B%A4%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%EB%A3%A8%ED%8A%B8%20%EC%9B%90%EC%86%8C%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%EB%A3%A8%ED%8A%B8%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20%23%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%EB%93%A4%EC%9D%80%20%ED%81%B0%20%EA%B0%92%EB%B6%80%ED%84%B0%20%EC%9E%91%EC%9D%80%20%EA%B0%92%20%EC%88%9C%EC%84%9C%EB%A1%9C%20%EB%82%98%EC%97%B4%EB%90%9C%EB%8B%A4%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%ED%81%AC%EA%B8%B0%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A5%BC%20%EC%9E%85%EB%A0%A5%EB%B0%9B%EC%95%84%20%ED%9E%99%20%EA%B5%AC%EC%84%B1%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor heap_operations_tutor ## 힙의 구현 diff --git a/ko/docs/chapter_preface/suggestions.md b/ko/docs/chapter_preface/suggestions.md index 99730f643..585dbe004 100644 --- a/ko/docs/chapter_preface/suggestions.md +++ b/ko/docs/chapter_preface/suggestions.md @@ -13,170 +13,9 @@ - 프로그래밍 언어마다 명칭이 다를 때는 Python을 기준으로 삼는다. 예를 들어 ‘비어 있음’을 나타낼 때 `None`을 사용한다. - 이 책은 내용을 더 간결하게 배치하기 위해 프로그래밍 언어의 주석 작성 규칙을 일부 따르지 않는다. 주석은 주로 제목 주석, 설명 주석, 여러 줄 주석의 세 유형으로 나뉜다. -=== "Python" - - ```python title="" - """함수, 클래스, 테스트 사례 등을 표시하는 제목 주석""" - - # 코드를 자세히 설명하는 설명 주석 - - """ - 여러 줄 - 주석 - """ - ``` - -=== "C++" - - ```cpp title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "Java" - - ```java title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "C#" - - ```csharp title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "Go" - - ```go title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "Swift" - - ```swift title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "JS" - - ```javascript title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "TS" - - ```typescript title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "Dart" - - ```dart title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "Rust" - - ```rust title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - // 여러 줄 - // 주석 - ``` - -=== "C" - - ```c title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 */ - - // 코드를 자세히 설명하는 설명 주석 - - /** - * 여러 줄 - * 주석 - */ - ``` - -=== "Ruby" - - ```ruby title="" - ### 함수, 클래스, 테스트 사례 등을 표시하는 제목 주석 ### - - # 코드를 자세히 설명하는 설명 주석 - - # 여러 줄 - # 주석 - ``` +```snippet +comment_style +``` ## 애니메이션 그림으로 효율적으로 배우기 diff --git a/ko/docs/chapter_stack_and_queue/deque.md b/ko/docs/chapter_stack_and_queue/deque.md index 448d46e2a..ce7d4b33a 100644 --- a/ko/docs/chapter_stack_and_queue/deque.md +++ b/ko/docs/chapter_stack_and_queue/deque.md @@ -21,371 +21,13 @@ 마찬가지로 프로그래밍 언어가 제공하는 덱 클래스를 바로 사용할 수 있다. -=== "Python" - - ```python title="deque.py" - from collections import deque - - # 덱 초기화 - deq: deque[int] = deque() - - # 덱에 원소 삽입 - deq.append(2) # 맨 뒤에 추가 - deq.append(5) - deq.append(4) - deq.appendleft(3) # 맨 앞에 추가 - deq.appendleft(1) - - # 원소 접근 - front: int = deq[0] # 맨 앞 원소 - rear: int = deq[-1] # 맨 뒤 원소 - - # 덱에서 원소 꺼내기 - pop_front: int = deq.popleft() # 맨 앞 원소 꺼내기 - pop_rear: int = deq.pop() # 맨 뒤 원소 꺼내기 - - # 덱 길이 구하기 - size: int = len(deq) - - # 덱이 비어 있는지 확인 - is_empty: bool = len(deq) == 0 - ``` - -=== "C++" - - ```cpp title="deque.cpp" - /* 덱 초기화 */ - deque deque; - - /* 덱에 원소 삽입 */ - deque.push_back(2); // 맨 뒤에 추가 - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // 맨 앞에 추가 - deque.push_front(1); - - /* 원소 접근 */ - int front = deque.front(); // 맨 앞 원소 - int back = deque.back(); // 맨 뒤 원소 - - /* 덱에서 원소 꺼내기 */ - deque.pop_front(); // 맨 앞 원소 꺼내기 - deque.pop_back(); // 맨 뒤 원소 꺼내기 - - /* 덱 길이 구하기 */ - int size = deque.size(); - - /* 덱이 비어 있는지 확인 */ - bool empty = deque.empty(); - ``` - -=== "Java" - - ```java title="deque.java" - /* 덱 초기화 */ - Deque deque = new LinkedList<>(); - - /* 덱에 원소 삽입 */ - deque.offerLast(2); // 맨 뒤에 추가 - deque.offerLast(5); - deque.offerLast(4); - deque.offerFirst(3); // 맨 앞에 추가 - deque.offerFirst(1); - - /* 원소 접근 */ - int peekFirst = deque.peekFirst(); // 맨 앞 원소 - int peekLast = deque.peekLast(); // 맨 뒤 원소 - - /* 덱에서 원소 꺼내기 */ - int popFirst = deque.pollFirst(); // 맨 앞 원소 꺼내기 - int popLast = deque.pollLast(); // 맨 뒤 원소 꺼내기 - - /* 덱 길이 구하기 */ - int size = deque.size(); - - /* 덱이 비어 있는지 확인 */ - boolean isEmpty = deque.isEmpty(); - ``` - -=== "C#" - - ```csharp title="deque.cs" - /* 덱 초기화 */ - // C#에서는 연결 리스트 LinkedList를 덱으로 사용한다 - LinkedList deque = new(); - - /* 덱에 원소 삽입 */ - deque.AddLast(2); // 맨 뒤에 추가 - deque.AddLast(5); - deque.AddLast(4); - deque.AddFirst(3); // 맨 앞에 추가 - deque.AddFirst(1); - - /* 원소 접근 */ - int peekFirst = deque.First.Value; // 맨 앞 원소 - int peekLast = deque.Last.Value; // 맨 뒤 원소 - - /* 덱에서 원소 꺼내기 */ - deque.RemoveFirst(); // 맨 앞 원소 꺼내기 - deque.RemoveLast(); // 맨 뒤 원소 꺼내기 - - /* 덱 길이 구하기 */ - int size = deque.Count; - - /* 덱이 비어 있는지 확인 */ - bool isEmpty = deque.Count == 0; - ``` - -=== "Go" - - ```go title="deque_test.go" - /* 덱 초기화 */ - // Go에서는 list를 덱으로 사용한다 - deque := list.New() - - /* 덱에 원소 삽입 */ - deque.PushBack(2) // 맨 뒤에 추가 - deque.PushBack(5) - deque.PushBack(4) - deque.PushFront(3) // 맨 앞에 추가 - deque.PushFront(1) - - /* 원소 접근 */ - front := deque.Front() // 맨 앞 원소 - rear := deque.Back() // 맨 뒤 원소 - - /* 덱에서 원소 꺼내기 */ - deque.Remove(front) // 맨 앞 원소 꺼내기 - deque.Remove(rear) // 맨 뒤 원소 꺼내기 - - /* 덱 길이 구하기 */ - size := deque.Len() - - /* 덱이 비어 있는지 확인 */ - isEmpty := deque.Len() == 0 - ``` - -=== "Swift" - - ```swift title="deque.swift" - /* 덱 초기화 */ - // Swift에는 내장 덱 클래스가 없으므로 Array를 덱으로 사용할 수 있다 - var deque: [Int] = [] - - /* 덱에 원소 삽입 */ - deque.append(2) // 맨 뒤에 추가 - deque.append(5) - deque.append(4) - deque.insert(3, at: 0) // 맨 앞에 추가 - deque.insert(1, at: 0) - - /* 원소 접근 */ - let peekFirst = deque.first! // 맨 앞 원소 - let peekLast = deque.last! // 맨 뒤 원소 - - /* 덱에서 원소 꺼내기 */ - // Array로 구현하면 popFirst의 복잡도는 O(n)이다 - let popFirst = deque.removeFirst() // 맨 앞 원소 꺼내기 - let popLast = deque.removeLast() // 맨 뒤 원소 꺼내기 - - /* 덱 길이 구하기 */ - let size = deque.count - - /* 덱이 비어 있는지 확인 */ - let isEmpty = deque.isEmpty - ``` - -=== "JS" - - ```javascript title="deque.js" - /* 덱 초기화 */ - // JavaScript에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 - const deque = []; - - /* 덱에 원소 삽입 */ - deque.push(2); - deque.push(5); - deque.push(4); - // 배열이므로 unshift() 메서드의 시간 복잡도는 O(n)임에 주의 - deque.unshift(3); - deque.unshift(1); - - /* 원소 접근 */ - const peekFirst = deque[0]; - const peekLast = deque[deque.length - 1]; - - /* 덱에서 원소 꺼내기 */ - // 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 주의 - const popFront = deque.shift(); - const popBack = deque.pop(); - - /* 덱 길이 구하기 */ - const size = deque.length; - - /* 덱이 비어 있는지 확인 */ - const isEmpty = size === 0; - ``` - -=== "TS" - - ```typescript title="deque.ts" - /* 덱 초기화 */ - // TypeScript에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 - const deque: number[] = []; - - /* 덱에 원소 삽입 */ - deque.push(2); - deque.push(5); - deque.push(4); - // 배열이므로 unshift() 메서드의 시간 복잡도는 O(n)임에 주의 - deque.unshift(3); - deque.unshift(1); - - /* 원소 접근 */ - const peekFirst: number = deque[0]; - const peekLast: number = deque[deque.length - 1]; - - /* 덱에서 원소 꺼내기 */ - // 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 주의 - const popFront: number = deque.shift() as number; - const popBack: number = deque.pop() as number; - - /* 덱 길이 구하기 */ - const size: number = deque.length; - - /* 덱이 비어 있는지 확인 */ - const isEmpty: boolean = size === 0; - ``` - -=== "Dart" - - ```dart title="deque.dart" - /* 덱 초기화 */ - // Dart의 Queue는 덱으로 정의되어 있다 - Queue deque = Queue(); - - /* 덱에 원소 삽입 */ - deque.addLast(2); // 맨 뒤에 추가 - deque.addLast(5); - deque.addLast(4); - deque.addFirst(3); // 맨 앞에 추가 - deque.addFirst(1); - - /* 원소 접근 */ - int peekFirst = deque.first; // 맨 앞 원소 - int peekLast = deque.last; // 맨 뒤 원소 - - /* 덱에서 원소 꺼내기 */ - int popFirst = deque.removeFirst(); // 맨 앞 원소 꺼내기 - int popLast = deque.removeLast(); // 맨 뒤 원소 꺼내기 - - /* 덱 길이 구하기 */ - int size = deque.length; - - /* 덱이 비어 있는지 확인 */ - bool isEmpty = deque.isEmpty; - ``` - -=== "Rust" - - ```rust title="deque.rs" - /* 덱 초기화 */ - let mut deque: VecDeque = VecDeque::new(); - - /* 덱에 원소 삽입 */ - deque.push_back(2); // 맨 뒤에 추가 - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // 맨 앞에 추가 - deque.push_front(1); - - /* 원소 접근 */ - if let Some(front) = deque.front() { // 맨 앞 원소 - } - if let Some(rear) = deque.back() { // 맨 뒤 원소 - } - - /* 덱에서 원소 꺼내기 */ - if let Some(pop_front) = deque.pop_front() { // 맨 앞 원소 꺼내기 - } - if let Some(pop_rear) = deque.pop_back() { // 맨 뒤 원소 꺼내기 - } - - /* 덱 길이 구하기 */ - let size = deque.len(); - - /* 덱이 비어 있는지 확인 */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="deque.c" - // C는 내장 덱을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="deque.kt" - /* 덱 초기화 */ - val deque = LinkedList() - - /* 덱에 원소 삽입 */ - deque.offerLast(2) // 맨 뒤에 추가 - deque.offerLast(5) - deque.offerLast(4) - deque.offerFirst(3) // 맨 앞에 추가 - deque.offerFirst(1) - - /* 원소 접근 */ - val peekFirst = deque.peekFirst() // 맨 앞 원소 - val peekLast = deque.peekLast() // 맨 뒤 원소 - - /* 덱에서 원소 꺼내기 */ - val popFirst = deque.pollFirst() // 맨 앞 원소 꺼내기 - val popLast = deque.pollLast() // 맨 뒤 원소 꺼내기 - - /* 덱 길이 구하기 */ - val size = deque.size - - /* 덱이 비어 있는지 확인 */ - val isEmpty = deque.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="deque.rb" - # 덱 초기화 - # Ruby에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 - deque = [] - - # 덱에 원소 삽입 - deque << 2 - deque << 5 - deque << 4 - # 배열이므로 Array#unshift 메서드의 시간 복잡도는 O(n)임에 주의 - deque.unshift(3) - deque.unshift(1) - - # 원소 접근 - peek_first = deque.first - peek_last = deque.last - - # 덱에서 원소 꺼내기 - # 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 주의 - pop_front = deque.shift - pop_back = deque.pop - - # 덱 길이 구하기 - size = deque.length - - # 덱이 비어 있는지 확인 - is_empty = size.zero? - ``` +```snippet +deque_operations +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%8D%B1%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%EB%8D%B1%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20deq.append%282%29%20%20%23%20%EB%A7%A8%20%EB%92%A4%EC%97%90%20%EC%B6%94%EA%B0%80%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20%EB%A7%A8%20%EC%95%9E%EC%97%90%20%EC%B6%94%EA%B0%80%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22%EB%8D%B1%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%0A%20%20%20%20print%28%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20front%20%3D%22%2C%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%EB%A7%A8%20%EB%92%A4%20%EC%9B%90%EC%86%8C%0A%20%20%20%20print%28%22%EB%A7%A8%20%EB%92%A4%20%EC%9B%90%EC%86%8C%20rear%20%3D%22%2C%20rear%29%0A%0A%20%20%20%20%23%20%EB%8D%B1%EC%97%90%EC%84%9C%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20print%28%22%EB%A7%A8%20%EC%95%9E%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20%20pop_front%20%3D%22%2C%20pop_front%29%0A%20%20%20%20print%28%22%EB%A7%A8%20%EC%95%9E%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EB%92%A4%20deque%20%3D%22%2C%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20%EB%A7%A8%20%EB%92%A4%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20print%28%22%EB%A7%A8%20%EB%92%A4%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20%20pop_rear%20%3D%22%2C%20pop_rear%29%0A%20%20%20%20print%28%22%EB%A7%A8%20%EB%92%A4%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EB%92%A4%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%EB%8D%B1%20%EA%B8%B8%EC%9D%B4%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22%EB%8D%B1%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%EB%8D%B1%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22%EB%8D%B1%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor deque_operations_tutor ## 덱 구현 * diff --git a/ko/docs/chapter_stack_and_queue/queue.md b/ko/docs/chapter_stack_and_queue/queue.md index ed666bf39..3d807e882 100644 --- a/ko/docs/chapter_stack_and_queue/queue.md +++ b/ko/docs/chapter_stack_and_queue/queue.md @@ -20,345 +20,13 @@ 프로그래밍 언어가 제공하는 큐 클래스를 바로 사용할 수 있다. -=== "Python" - - ```python title="queue.py" - from collections import deque - - # 큐 초기화 - # Python에서는 보통 덱 클래스 deque를 큐로 사용한다 - # queue.Queue()는 전용 큐 클래스이지만 사용이 불편하므로 권하지 않는다 - que: deque[int] = deque() - - # 큐에 원소 삽입 - que.append(1) - que.append(3) - que.append(2) - que.append(5) - que.append(4) - - # 큐의 맨 앞 원소에 접근 - front: int = que[0] - - # 큐에서 원소 꺼내기 - pop: int = que.popleft() - - # 큐 길이 구하기 - size: int = len(que) - - # 큐가 비어 있는지 확인 - is_empty: bool = len(que) == 0 - ``` - -=== "C++" - - ```cpp title="queue.cpp" - /* 큐 초기화 */ - queue queue; - - /* 큐에 원소 삽입 */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 큐의 맨 앞 원소에 접근 */ - int front = queue.front(); - - /* 큐에서 원소 꺼내기 */ - queue.pop(); - - /* 큐 길이 구하기 */ - int size = queue.size(); - - /* 큐가 비어 있는지 확인 */ - bool empty = queue.empty(); - ``` - -=== "Java" - - ```java title="queue.java" - /* 큐 초기화 */ - Queue queue = new LinkedList<>(); - - /* 큐에 원소 삽입 */ - queue.offer(1); - queue.offer(3); - queue.offer(2); - queue.offer(5); - queue.offer(4); - - /* 큐의 맨 앞 원소에 접근 */ - int peek = queue.peek(); - - /* 큐에서 원소 꺼내기 */ - int pop = queue.poll(); - - /* 큐 길이 구하기 */ - int size = queue.size(); - - /* 큐가 비어 있는지 확인 */ - boolean isEmpty = queue.isEmpty(); - ``` - -=== "C#" - - ```csharp title="queue.cs" - /* 큐 초기화 */ - Queue queue = new(); - - /* 큐에 원소 삽입 */ - queue.Enqueue(1); - queue.Enqueue(3); - queue.Enqueue(2); - queue.Enqueue(5); - queue.Enqueue(4); - - /* 큐의 맨 앞 원소에 접근 */ - int peek = queue.Peek(); - - /* 큐에서 원소 꺼내기 */ - int pop = queue.Dequeue(); - - /* 큐 길이 구하기 */ - int size = queue.Count; - - /* 큐가 비어 있는지 확인 */ - bool isEmpty = queue.Count == 0; - ``` - -=== "Go" - - ```go title="queue_test.go" - /* 큐 초기화 */ - // Go에서는 list를 큐로 사용한다 - queue := list.New() - - /* 큐에 원소 삽입 */ - queue.PushBack(1) - queue.PushBack(3) - queue.PushBack(2) - queue.PushBack(5) - queue.PushBack(4) - - /* 큐의 맨 앞 원소에 접근 */ - peek := queue.Front() - - /* 큐에서 원소 꺼내기 */ - pop := queue.Front() - queue.Remove(pop) - - /* 큐 길이 구하기 */ - size := queue.Len() - - /* 큐가 비어 있는지 확인 */ - isEmpty := queue.Len() == 0 - ``` - -=== "Swift" - - ```swift title="queue.swift" - /* 큐 초기화 */ - // Swift에는 내장 큐 클래스가 없으므로 Array를 큐로 사용할 수 있다 - var queue: [Int] = [] - - /* 큐에 원소 삽입 */ - queue.append(1) - queue.append(3) - queue.append(2) - queue.append(5) - queue.append(4) - - /* 큐의 맨 앞 원소에 접근 */ - let peek = queue.first! - - /* 큐에서 원소 꺼내기 */ - // 배열이므로 removeFirst의 복잡도는 O(n)이다 - let pop = queue.removeFirst() - - /* 큐 길이 구하기 */ - let size = queue.count - - /* 큐가 비어 있는지 확인 */ - let isEmpty = queue.isEmpty - ``` - -=== "JS" - - ```javascript title="queue.js" - /* 큐 초기화 */ - // JavaScript에는 내장 큐가 없으므로 Array를 큐로 사용할 수 있다 - const queue = []; - - /* 큐에 원소 삽입 */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 큐의 맨 앞 원소에 접근 */ - const peek = queue[0]; - - /* 큐에서 원소 꺼내기 */ - // 기반이 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 - const pop = queue.shift(); - - /* 큐 길이 구하기 */ - const size = queue.length; - - /* 큐가 비어 있는지 확인 */ - const empty = queue.length === 0; - ``` - -=== "TS" - - ```typescript title="queue.ts" - /* 큐 초기화 */ - // TypeScript에는 내장 큐가 없으므로 Array를 큐로 사용할 수 있다 - const queue: number[] = []; - - /* 큐에 원소 삽입 */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 큐의 맨 앞 원소에 접근 */ - const peek = queue[0]; - - /* 큐에서 원소 꺼내기 */ - // 기반이 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 - const pop = queue.shift(); - - /* 큐 길이 구하기 */ - const size = queue.length; - - /* 큐가 비어 있는지 확인 */ - const empty = queue.length === 0; - ``` - -=== "Dart" - - ```dart title="queue.dart" - /* 큐 초기화 */ - // Dart의 Queue 클래스는 덱이며 일반 큐로도 사용할 수 있다 - Queue queue = Queue(); - - /* 큐에 원소 삽입 */ - queue.add(1); - queue.add(3); - queue.add(2); - queue.add(5); - queue.add(4); - - /* 큐의 맨 앞 원소에 접근 */ - int peek = queue.first; - - /* 큐에서 원소 꺼내기 */ - int pop = queue.removeFirst(); - - /* 큐 길이 구하기 */ - int size = queue.length; - - /* 큐가 비어 있는지 확인 */ - bool isEmpty = queue.isEmpty; - ``` - -=== "Rust" - - ```rust title="queue.rs" - /* 덱 초기화 */ - // Rust에서는 덱을 일반 큐로 사용한다 - let mut deque: VecDeque = VecDeque::new(); - - /* 큐에 원소 삽입 */ - deque.push_back(1); - deque.push_back(3); - deque.push_back(2); - deque.push_back(5); - deque.push_back(4); - - /* 큐의 맨 앞 원소에 접근 */ - if let Some(front) = deque.front() { - } - - /* 큐에서 원소 꺼내기 */ - if let Some(pop) = deque.pop_front() { - } - - /* 큐 길이 구하기 */ - let size = deque.len(); - - /* 큐가 비어 있는지 확인 */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="queue.c" - // C는 내장 큐를 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="queue.kt" - /* 큐 초기화 */ - val queue = LinkedList() - - /* 큐에 원소 삽입 */ - queue.offer(1) - queue.offer(3) - queue.offer(2) - queue.offer(5) - queue.offer(4) - - /* 큐의 맨 앞 원소에 접근 */ - val peek = queue.peek() - - /* 큐에서 원소 꺼내기 */ - val pop = queue.poll() - - /* 큐 길이 구하기 */ - val size = queue.size - - /* 큐가 비어 있는지 확인 */ - val isEmpty = queue.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="queue.rb" - # 큐 초기화 - # Ruby의 내장 큐(Thread::Queue)에는 peek와 순회 메서드가 없으므로 Array를 큐로 사용할 수 있다 - queue = [] - - # 큐에 원소 삽입 - queue.push(1) - queue.push(3) - queue.push(2) - queue.push(5) - queue.push(4) - - # 큐 원소에 접근 - peek = queue.first - - # 큐에서 원소 꺼내기 - # 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 주의 - pop = queue.shift - - # 큐 길이 구하기 - size = queue.length - - # 큐가 비어 있는지 확인 - is_empty = queue.empty? - ``` +```snippet +queue_operations +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%ED%81%90%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20Python%EC%97%90%EC%84%9C%EB%8A%94%20%EB%B3%B4%ED%86%B5%20%EB%8D%B1%20%ED%81%B4%EB%9E%98%EC%8A%A4%20deque%EB%A5%BC%20%ED%81%90%EB%A1%9C%20%EC%82%AC%EC%9A%A9%ED%95%9C%EB%8B%A4%0A%20%20%20%20%23%20queue.Queue%28%29%EB%8A%94%20%EC%A0%84%EC%9A%A9%20%ED%81%90%20%ED%81%B4%EB%9E%98%EC%8A%A4%EC%9D%B4%EC%A7%80%EB%A7%8C%20%EC%82%AC%EC%9A%A9%EC%9D%B4%20%EB%B6%88%ED%8E%B8%ED%95%98%EB%8B%A4%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%ED%81%90%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22%ED%81%90%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%ED%81%90%EC%9D%98%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%EC%97%90%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22%ED%81%90%EC%9D%98%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20front%20%3D%22%2C%20front%29%0A%0A%20%20%20%20%23%20%ED%81%90%EC%97%90%EC%84%9C%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%EC%9B%90%EC%86%8C%EB%A5%BC%20%EA%BA%BC%EB%82%B8%20%EB%92%A4%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%ED%81%90%20%EA%B8%B8%EC%9D%B4%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22%ED%81%90%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor queue_operations_tutor ## 큐 구현 diff --git a/ko/docs/chapter_stack_and_queue/stack.md b/ko/docs/chapter_stack_and_queue/stack.md index 364d27ca9..765d13e99 100644 --- a/ko/docs/chapter_stack_and_queue/stack.md +++ b/ko/docs/chapter_stack_and_queue/stack.md @@ -22,336 +22,13 @@ 보통 프로그래밍 언어에 내장된 스택 클래스를 바로 사용할 수 있다. 전용 스택 클래스가 없는 언어에서는 ‘배열’이나 ‘연결 리스트’를 스택으로 사용하면서, 프로그램 논리상 스택과 무관한 연산은 사용하지 않으면 된다. -=== "Python" - - ```python title="stack.py" - # 스택 초기화 - # Python에는 내장 스택 클래스가 없으므로 list를 스택으로 사용할 수 있다 - stack: list[int] = [] - - # 스택에 원소 삽입 - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - # 스택 맨 위 원소에 접근 - peek: int = stack[-1] - - # 스택에서 원소 꺼내기 - pop: int = stack.pop() - - # 스택 길이 구하기 - size: int = len(stack) - - # 비어 있는지 확인 - is_empty: bool = len(stack) == 0 - ``` - -=== "C++" - - ```cpp title="stack.cpp" - /* 스택 초기화 */ - stack stack; - - /* 스택에 원소 삽입 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 스택 맨 위 원소에 접근 */ - int top = stack.top(); - - /* 스택에서 원소 꺼내기 */ - stack.pop(); // 반환값 없음 - - /* 스택 길이 구하기 */ - int size = stack.size(); - - /* 비어 있는지 확인 */ - bool empty = stack.empty(); - ``` - -=== "Java" - - ```java title="stack.java" - /* 스택 초기화 */ - Stack stack = new Stack<>(); - - /* 스택에 원소 삽입 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 스택 맨 위 원소에 접근 */ - int peek = stack.peek(); - - /* 스택에서 원소 꺼내기 */ - int pop = stack.pop(); - - /* 스택 길이 구하기 */ - int size = stack.size(); - - /* 비어 있는지 확인 */ - boolean isEmpty = stack.isEmpty(); - ``` - -=== "C#" - - ```csharp title="stack.cs" - /* 스택 초기화 */ - Stack stack = new(); - - /* 스택에 원소 삽입 */ - stack.Push(1); - stack.Push(3); - stack.Push(2); - stack.Push(5); - stack.Push(4); - - /* 스택 맨 위 원소에 접근 */ - int peek = stack.Peek(); - - /* 스택에서 원소 꺼내기 */ - int pop = stack.Pop(); - - /* 스택 길이 구하기 */ - int size = stack.Count; - - /* 비어 있는지 확인 */ - bool isEmpty = stack.Count == 0; - ``` - -=== "Go" - - ```go title="stack_test.go" - /* 스택 초기화 */ - // Go에서는 Slice를 스택으로 사용하는 것을 권한다 - var stack []int - - /* 스택에 원소 삽입 */ - stack = append(stack, 1) - stack = append(stack, 3) - stack = append(stack, 2) - stack = append(stack, 5) - stack = append(stack, 4) - - /* 스택 맨 위 원소에 접근 */ - peek := stack[len(stack)-1] - - /* 스택에서 원소 꺼내기 */ - pop := stack[len(stack)-1] - stack = stack[:len(stack)-1] - - /* 스택 길이 구하기 */ - size := len(stack) - - /* 비어 있는지 확인 */ - isEmpty := len(stack) == 0 - ``` - -=== "Swift" - - ```swift title="stack.swift" - /* 스택 초기화 */ - // Swift에는 내장 스택 클래스가 없으므로 Array를 스택으로 사용할 수 있다 - var stack: [Int] = [] - - /* 스택에 원소 삽입 */ - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - /* 스택 맨 위 원소에 접근 */ - let peek = stack.last! - - /* 스택에서 원소 꺼내기 */ - let pop = stack.removeLast() - - /* 스택 길이 구하기 */ - let size = stack.count - - /* 비어 있는지 확인 */ - let isEmpty = stack.isEmpty - ``` - -=== "JS" - - ```javascript title="stack.js" - /* 스택 초기화 */ - // JavaScript에는 내장 스택 클래스가 없으므로 Array를 스택으로 사용할 수 있다 - const stack = []; - - /* 스택에 원소 삽입 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 스택 맨 위 원소에 접근 */ - const peek = stack[stack.length-1]; - - /* 스택에서 원소 꺼내기 */ - const pop = stack.pop(); - - /* 스택 길이 구하기 */ - const size = stack.length; - - /* 비어 있는지 확인 */ - const is_empty = stack.length === 0; - ``` - -=== "TS" - - ```typescript title="stack.ts" - /* 스택 초기화 */ - // TypeScript에는 내장 스택 클래스가 없으므로 Array를 스택으로 사용할 수 있다 - const stack: number[] = []; - - /* 스택에 원소 삽입 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 스택 맨 위 원소에 접근 */ - const peek = stack[stack.length - 1]; - - /* 스택에서 원소 꺼내기 */ - const pop = stack.pop(); - - /* 스택 길이 구하기 */ - const size = stack.length; - - /* 비어 있는지 확인 */ - const is_empty = stack.length === 0; - ``` - -=== "Dart" - - ```dart title="stack.dart" - /* 스택 초기화 */ - // Dart에는 내장 스택 클래스가 없으므로 List를 스택으로 사용할 수 있다 - List stack = []; - - /* 스택에 원소 삽입 */ - stack.add(1); - stack.add(3); - stack.add(2); - stack.add(5); - stack.add(4); - - /* 스택 맨 위 원소에 접근 */ - int peek = stack.last; - - /* 스택에서 원소 꺼내기 */ - int pop = stack.removeLast(); - - /* 스택 길이 구하기 */ - int size = stack.length; - - /* 비어 있는지 확인 */ - bool isEmpty = stack.isEmpty; - ``` - -=== "Rust" - - ```rust title="stack.rs" - /* 스택 초기화 */ - // Vec를 스택으로 사용 - let mut stack: Vec = Vec::new(); - - /* 스택에 원소 삽입 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 스택 맨 위 원소에 접근 */ - let top = stack.last().unwrap(); - - /* 스택에서 원소 꺼내기 */ - let pop = stack.pop().unwrap(); - - /* 스택 길이 구하기 */ - let size = stack.len(); - - /* 비어 있는지 확인 */ - let is_empty = stack.is_empty(); - ``` - -=== "C" - - ```c title="stack.c" - // C는 내장 스택을 제공하지 않는다 - ``` - -=== "Kotlin" - - ```kotlin title="stack.kt" - /* 스택 초기화 */ - val stack = Stack() - - /* 스택에 원소 삽입 */ - stack.push(1) - stack.push(3) - stack.push(2) - stack.push(5) - stack.push(4) - - /* 스택 맨 위 원소에 접근 */ - val peek = stack.peek() - - /* 스택에서 원소 꺼내기 */ - val pop = stack.pop() - - /* 스택 길이 구하기 */ - val size = stack.size - - /* 비어 있는지 확인 */ - val isEmpty = stack.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="stack.rb" - # 스택 초기화 - # Ruby에는 내장 스택 클래스가 없으므로 Array를 스택으로 사용할 수 있다 - stack = [] - - # 스택에 원소 삽입 - stack << 1 - stack << 3 - stack << 2 - stack << 5 - stack << 4 - - # 스택 맨 위 원소에 접근 - peek = stack.last - - # 스택에서 원소 꺼내기 - pop = stack.pop - - # 스택 길이 구하기 - size = stack.length - - # 비어 있는지 확인 - is_empty = stack.empty? - ``` +```snippet +stack_operations +``` ??? pythontutor "코드 시각화" - https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20Python%EC%97%90%EB%8A%94%20%EB%82%B4%EC%9E%A5%20%EC%8A%A4%ED%83%9D%20%ED%81%B4%EB%9E%98%EC%8A%A4%EA%B0%80%20%EC%97%86%EC%9C%BC%EB%AF%80%EB%A1%9C%20list%EB%A5%BC%20%EC%8A%A4%ED%83%9D%EC%9C%BC%EB%A1%9C%20%EC%82%AC%EC%9A%A9%ED%95%A0%20%EC%88%98%20%EC%9E%88%EB%8B%A4%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22%EC%8A%A4%ED%83%9D%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%20%EB%A7%A8%20%EC%9C%84%20%EC%9B%90%EC%86%8C%EC%97%90%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22%EC%8A%A4%ED%83%9D%20%EB%A7%A8%20%EC%9C%84%20%EC%9B%90%EC%86%8C%20peek%20%3D%22%2C%20peek%29%0A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%EC%97%90%EC%84%9C%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%EC%9B%90%EC%86%8C%EB%A5%BC%20%EA%BA%BC%EB%82%B8%20%EB%92%A4%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%EC%8A%A4%ED%83%9D%20%EA%B8%B8%EC%9D%B4%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22%EC%8A%A4%ED%83%9D%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22%EC%8A%A4%ED%83%9D%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor stack_operations_tutor ## 스택 구현 diff --git a/ko/docs/chapter_tree/array_representation_of_tree.md b/ko/docs/chapter_tree/array_representation_of_tree.md index d6f7e25c5..4c9535d5f 100644 --- a/ko/docs/chapter_tree/array_representation_of_tree.md +++ b/ko/docs/chapter_tree/array_representation_of_tree.md @@ -24,109 +24,9 @@ 이를 해결하려면 **레벨 순서 순회 결과에 모든 `None`을 명시적으로 넣을 수 있다**. 아래 그림처럼 처리하면 순회 결과가 이진 트리를 유일하게 나타낸다. 예시 코드는 다음과 같다. -=== "Python" - - ```python title="" - # 이진 트리의 배열 표현 - # None으로 빈자리 표시 - tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] - ``` - -=== "C++" - - ```cpp title="" - /* 이진 트리의 배열 표현 */ - // int의 최댓값 INT_MAX로 빈자리 표시 - vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Java" - - ```java title="" - /* 이진 트리의 배열 표현 */ - // int의 래퍼 클래스 Integer를 사용하면 null로 빈자리를 표시할 수 있다 - Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; - ``` - -=== "C#" - - ```csharp title="" - /* 이진 트리의 배열 표현 */ - // 널 허용 타입 int?를 사용하면 null로 빈자리를 표시할 수 있다 - int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Go" - - ```go title="" - /* 이진 트리의 배열 표현 */ - // any 타입의 슬라이스를 사용하면 nil로 빈자리를 표시할 수 있다 - tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} - ``` - -=== "Swift" - - ```swift title="" - /* 이진 트리의 배열 표현 */ - // 널 허용 타입 Int?를 사용하면 nil로 빈자리를 표시할 수 있다 - let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` - -=== "JS" - - ```javascript title="" - /* 이진 트리의 배열 표현 */ - // null로 빈자리 표시 - let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "TS" - - ```typescript title="" - /* 이진 트리의 배열 표현 */ - // null로 빈자리 표시 - let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Dart" - - ```dart title="" - /* 이진 트리의 배열 표현 */ - // 널 허용 타입 int?를 사용하면 null로 빈자리를 표시할 수 있다 - List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Rust" - - ```rust title="" - /* 이진 트리의 배열 표현 */ - // None으로 빈자리 표시 - let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; - ``` - -=== "C" - - ```c title="" - /* 이진 트리의 배열 표현 */ - // int의 최댓값으로 빈자리를 표시하므로 노드 값은 INT_MAX이면 안 된다 - int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 이진 트리의 배열 표현 */ - // null로 빈자리 표시 - val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) - ``` - -=== "Ruby" - - ```ruby title="" - ### 이진 트리의 배열 표현 ### - # nil로 빈자리 표시 - tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` +```snippet +tree_array_representation +``` ![임의의 이진 트리의 배열 표현](array_representation_of_tree.assets/array_representation_with_empty.svg) diff --git a/ko/docs/chapter_tree/avl_tree.md b/ko/docs/chapter_tree/avl_tree.md index a22e1a32c..39a538fea 100644 --- a/ko/docs/chapter_tree/avl_tree.md +++ b/ko/docs/chapter_tree/avl_tree.md @@ -20,213 +20,9 @@ AVL 트리는 이진 탐색 트리이면서 균형 이진 트리다. 두 종류 AVL 트리 연산에는 노드 높이가 필요하므로 노드 클래스에 `height` 변수를 추가해야 한다. -=== "Python" - - ```python title="" - class TreeNode: - """AVL 트리 노드 클래스""" - def __init__(self, val: int): - self.val: int = val # 노드 값 - self.height: int = 0 # 노드 높이 - self.left: TreeNode | None = None # 왼쪽 자식 노드 참조 - self.right: TreeNode | None = None # 오른쪽 자식 노드 참조 - ``` - -=== "C++" - - ```cpp title="" - /* AVL 트리 노드 클래스 */ - struct TreeNode { - int val{}; // 노드 값 - int height = 0; // 노드 높이 - TreeNode *left{}; // 왼쪽 자식 노드 - TreeNode *right{}; // 오른쪽 자식 노드 - TreeNode() = default; - explicit TreeNode(int x) : val(x){} - }; - ``` - -=== "Java" - - ```java title="" - /* AVL 트리 노드 클래스 */ - class TreeNode { - public int val; // 노드 값 - public int height; // 노드 높이 - public TreeNode left; // 왼쪽 자식 노드 - public TreeNode right; // 오른쪽 자식 노드 - public TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* AVL 트리 노드 클래스 */ - class TreeNode(int? x) { - public int? val = x; // 노드 값 - public int height; // 노드 높이 - public TreeNode? left; // 왼쪽 자식 노드 참조 - public TreeNode? right; // 오른쪽 자식 노드 참조 - } - ``` - -=== "Go" - - ```go title="" - /* AVL 트리 노드 구조체 */ - type TreeNode struct { - Val int // 노드 값 - Height int // 노드 높이 - Left *TreeNode // 왼쪽 자식 노드 참조 - Right *TreeNode // 오른쪽 자식 노드 참조 - } - ``` - -=== "Swift" - - ```swift title="" - /* AVL 트리 노드 클래스 */ - class TreeNode { - var val: Int // 노드 값 - var height: Int // 노드 높이 - var left: TreeNode? // 왼쪽 자식 노드 - var right: TreeNode? // 오른쪽 자식 노드 - - init(x: Int) { - val = x - height = 0 - } - } - ``` - -=== "JS" - - ```javascript title="" - /* AVL 트리 노드 클래스 */ - class TreeNode { - val; // 노드 값 - height; //노드 높이 - left; // 왼쪽 자식 노드 포인터 - right; // 오른쪽 자식 노드 포인터 - constructor(val, left, right, height) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* AVL 트리 노드 클래스 */ - class TreeNode { - val: number; // 노드 값 - height: number; // 노드 높이 - left: TreeNode | null; // 왼쪽 자식 노드 포인터 - right: TreeNode | null; // 오른쪽 자식 노드 포인터 - constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "Dart" - - ```dart title="" - /* AVL 트리 노드 클래스 */ - class TreeNode { - int val; // 노드 값 - int height; // 노드 높이 - TreeNode? left; // 왼쪽 자식 노드 - TreeNode? right; // 오른쪽 자식 노드 - TreeNode(this.val, [this.height = 0, this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* AVL 트리 노드 구조체 */ - struct TreeNode { - val: i32, // 노드 값 - height: i32, // 노드 높이 - left: Option>>, // 왼쪽 자식 노드 - right: Option>>, // 오른쪽 자식 노드 - } - - impl TreeNode { - /* 생성자 */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - height: 0, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* AVL 트리 노드 구조체 */ - typedef struct TreeNode { - int val; - int height; - struct TreeNode *left; - struct TreeNode *right; - } TreeNode; - - /* 생성자 */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* AVL 트리 노드 클래스 */ - class TreeNode(val _val: Int) { // 노드 값 - var height: Int = 0 // 노드 높이 - var left: TreeNode? = null // 왼쪽 자식 노드 - var right: TreeNode? = null // 오른쪽 자식 노드 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### AVL 트리 노드 클래스 ### - class TreeNode - attr_accessor :val # 노드 값 - attr_accessor :height # 노드 높이 - attr_accessor :left # 왼쪽 자식 노드 참조 - attr_accessor :right # 오른쪽 자식 노드 참조 - - def initialize(val) - @val = val - @height = 0 - end - end - ``` +```snippet +avl_tree_node +``` '노드 높이'는 해당 노드에서 가장 먼 리프까지의 거리, 즉 거치는 '간선' 수다. 특히 리프의 높이는 $0$, 빈 노드의 높이는 $-1$임에 주의하자. 높이를 조회하고 갱신하는 두 보조 함수를 만든다. diff --git a/ko/docs/chapter_tree/binary_tree.md b/ko/docs/chapter_tree/binary_tree.md index 791b45984..1beb19e90 100644 --- a/ko/docs/chapter_tree/binary_tree.md +++ b/ko/docs/chapter_tree/binary_tree.md @@ -2,204 +2,9 @@ 이진 트리(binary tree)는 '조상'과 '후손' 사이의 파생 관계를 나타내는 비선형 자료 구조로, '하나를 둘로 나누는' 분할 정복의 논리를 보여 준다. 연결 리스트처럼 기본 단위는 노드이며, 각 노드는 값과 왼쪽 자식 참조, 오른쪽 자식 참조를 포함한다. -=== "Python" - - ```python title="" - class TreeNode: - """이진 트리 노드 클래스""" - def __init__(self, val: int): - self.val: int = val # 노드 값 - self.left: TreeNode | None = None # 왼쪽 자식 노드 참조 - self.right: TreeNode | None = None # 오른쪽 자식 노드 참조 - ``` - -=== "C++" - - ```cpp title="" - /* 이진 트리 노드 구조체 */ - struct TreeNode { - int val; // 노드 값 - TreeNode *left; // 왼쪽 자식 노드 포인터 - TreeNode *right; // 오른쪽 자식 노드 포인터 - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - }; - ``` - -=== "Java" - - ```java title="" - /* 이진 트리 노드 클래스 */ - class TreeNode { - int val; // 노드 값 - TreeNode left; // 왼쪽 자식 노드 참조 - TreeNode right; // 오른쪽 자식 노드 참조 - TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* 이진 트리 노드 클래스 */ - class TreeNode(int? x) { - public int? val = x; // 노드 값 - public TreeNode? left; // 왼쪽 자식 노드 참조 - public TreeNode? right; // 오른쪽 자식 노드 참조 - } - ``` - -=== "Go" - - ```go title="" - /* 이진 트리 노드 구조체 */ - type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode - } - /* 생성자 */ - func NewTreeNode(v int) *TreeNode { - return &TreeNode{ - Left: nil, // 왼쪽 자식 노드 포인터 - Right: nil, // 오른쪽 자식 노드 포인터 - Val: v, // 노드 값 - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 이진 트리 노드 클래스 */ - class TreeNode { - var val: Int // 노드 값 - var left: TreeNode? // 왼쪽 자식 노드 참조 - var right: TreeNode? // 오른쪽 자식 노드 참조 - - init(x: Int) { - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 이진 트리 노드 클래스 */ - class TreeNode { - val; // 노드 값 - left; // 왼쪽 자식 노드 포인터 - right; // 오른쪽 자식 노드 포인터 - constructor(val, left, right) { - this.val = val === undefined ? 0 : val; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 이진 트리 노드 클래스 */ - class TreeNode { - val: number; - left: TreeNode | null; - right: TreeNode | null; - - constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.left = left === undefined ? null : left; // 왼쪽 자식 노드 참조 - this.right = right === undefined ? null : right; // 오른쪽 자식 노드 참조 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 이진 트리 노드 클래스 */ - class TreeNode { - int val; // 노드 값 - TreeNode? left; // 왼쪽 자식 노드 참조 - TreeNode? right; // 오른쪽 자식 노드 참조 - TreeNode(this.val, [this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 이진 트리 노드 구조체 */ - struct TreeNode { - val: i32, // 노드 값 - left: Option>>, // 왼쪽 자식 노드 참조 - right: Option>>, // 오른쪽 자식 노드 참조 - } - - impl TreeNode { - /* 생성자 */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* 이진 트리 노드 구조체 */ - typedef struct TreeNode { - int val; // 노드 값 - int height; // 노드 높이 - struct TreeNode *left; // 왼쪽 자식 노드 포인터 - struct TreeNode *right; // 오른쪽 자식 노드 포인터 - } TreeNode; - - /* 생성자 */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 이진 트리 노드 클래스 */ - class TreeNode(val _val: Int) { // 노드 값 - var left: TreeNode? = null // 왼쪽 자식 노드 참조 - var right: TreeNode? = null // 오른쪽 자식 노드 참조 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 이진 트리 노드 클래스 ### - class TreeNode - attr_accessor :val # 노드 값 - attr_accessor :left # 왼쪽 자식 노드 참조 - attr_accessor :right # 오른쪽 자식 노드 참조 - - def initialize(val) - @val = val - end - end - ``` +```snippet +tree_node_class +``` 각 노드는 두 참조(포인터)를 가지며, 각각 왼쪽 자식 노드(left-child node)와 오른쪽 자식 노드(right-child node)를 가리킨다. 해당 노드는 두 자식의 부모 노드(parent node)라고 한다. 어떤 노드의 왼쪽 자식과 그 아래 노드들이 이루는 트리를 그 노드의 왼쪽 서브트리(left subtree)라고 하며, 같은 방식으로 오른쪽 서브트리(right subtree)를 정의한다. @@ -232,226 +37,13 @@ 연결 리스트처럼 먼저 노드를 초기화하고 참조(포인터)를 연결한다. -=== "Python" - - ```python title="binary_tree.py" - # 이진 트리 초기화 - # 노드 초기화 - n1 = TreeNode(val=1) - n2 = TreeNode(val=2) - n3 = TreeNode(val=3) - n4 = TreeNode(val=4) - n5 = TreeNode(val=5) - # 노드 사이의 참조(포인터) 연결 - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* 이진 트리 초기화 */ - // 노드 초기화 - TreeNode* n1 = new TreeNode(1); - TreeNode* n2 = new TreeNode(2); - TreeNode* n3 = new TreeNode(3); - TreeNode* n4 = new TreeNode(4); - TreeNode* n5 = new TreeNode(5); - // 노드 사이의 참조(포인터) 연결 - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Java" - - ```java title="binary_tree.java" - // 노드 초기화 - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // 노드 사이의 참조(포인터) 연결 - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* 이진 트리 초기화 */ - // 노드 초기화 - TreeNode n1 = new(1); - TreeNode n2 = new(2); - TreeNode n3 = new(3); - TreeNode n4 = new(4); - TreeNode n5 = new(5); - // 노드 사이의 참조(포인터) 연결 - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* 이진 트리 초기화 */ - // 노드 초기화 - n1 := NewTreeNode(1) - n2 := NewTreeNode(2) - n3 := NewTreeNode(3) - n4 := NewTreeNode(4) - n5 := NewTreeNode(5) - // 노드 사이의 참조(포인터) 연결 - n1.Left = n2 - n1.Right = n3 - n2.Left = n4 - n2.Right = n5 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - // 노드 초기화 - let n1 = TreeNode(x: 1) - let n2 = TreeNode(x: 2) - let n3 = TreeNode(x: 3) - let n4 = TreeNode(x: 4) - let n5 = TreeNode(x: 5) - // 노드 사이의 참조(포인터) 연결 - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* 이진 트리 초기화 */ - // 노드 초기화 - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // 노드 사이의 참조(포인터) 연결 - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* 이진 트리 초기화 */ - // 노드 초기화 - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // 노드 사이의 참조(포인터) 연결 - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* 이진 트리 초기화 */ - // 노드 초기화 - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // 노드 사이의 참조(포인터) 연결 - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - // 노드 초기화 - let n1 = TreeNode::new(1); - let n2 = TreeNode::new(2); - let n3 = TreeNode::new(3); - let n4 = TreeNode::new(4); - let n5 = TreeNode::new(5); - // 노드 사이의 참조(포인터) 연결 - n1.borrow_mut().left = Some(n2.clone()); - n1.borrow_mut().right = Some(n3); - n2.borrow_mut().left = Some(n4); - n2.borrow_mut().right = Some(n5); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* 이진 트리 초기화 */ - // 노드 초기화 - TreeNode *n1 = newTreeNode(1); - TreeNode *n2 = newTreeNode(2); - TreeNode *n3 = newTreeNode(3); - TreeNode *n4 = newTreeNode(4); - TreeNode *n5 = newTreeNode(5); - // 노드 사이의 참조(포인터) 연결 - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - // 노드 초기화 - val n1 = TreeNode(1) - val n2 = TreeNode(2) - val n3 = TreeNode(3) - val n4 = TreeNode(4) - val n5 = TreeNode(5) - // 노드 사이의 참조(포인터) 연결 - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # 이진 트리 초기화 - # 노드 초기화 - n1 = TreeNode.new(1) - n2 = TreeNode.new(2) - n3 = TreeNode.new(3) - n4 = TreeNode.new(4) - n5 = TreeNode.new(5) - # 노드 사이의 참조(포인터) 연결 - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` +```snippet +init_binary_tree +``` ??? pythontutor "실행 시각화" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%EC%99%BC%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%EC%98%A4%EB%A5%B8%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%AC%EC%9D%B4%EC%9D%98%20%EC%B0%B8%EC%A1%B0%28%ED%8F%AC%EC%9D%B8%ED%84%B0%29%20%EC%97%B0%EA%B2%B0%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_binary_tree_tutor ### 노드 삽입과 삭제 @@ -459,165 +51,13 @@ ![이진 트리의 노드 삽입과 삭제](binary_tree.assets/binary_tree_add_remove.svg) -=== "Python" - - ```python title="binary_tree.py" - # 노드 삽입과 삭제 - p = TreeNode(0) - # n1 -> n2 사이에 노드 P 삽입 - n1.left = p - p.left = n2 - # 노드 P 삭제 - n1.left = n2 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* 노드 삽입과 삭제 */ - TreeNode* P = new TreeNode(0); - // n1 -> n2 사이에 노드 P 삽입 - n1->left = P; - P->left = n2; - // 노드 P 삭제 - n1->left = n2; - // 메모리 해제 - delete P; - ``` - -=== "Java" - - ```java title="binary_tree.java" - TreeNode P = new TreeNode(0); - // n1 -> n2 사이에 노드 P 삽입 - n1.left = P; - P.left = n2; - // 노드 P 삭제 - n1.left = n2; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* 노드 삽입과 삭제 */ - TreeNode P = new(0); - // n1 -> n2 사이에 노드 P 삽입 - n1.left = P; - P.left = n2; - // 노드 P 삭제 - n1.left = n2; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* 노드 삽입과 삭제 */ - // n1 -> n2 사이에 노드 P 삽입 - p := NewTreeNode(0) - n1.Left = p - p.Left = n2 - // 노드 P 삭제 - n1.Left = n2 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - let P = TreeNode(x: 0) - // n1 -> n2 사이에 노드 P 삽입 - n1.left = P - P.left = n2 - // 노드 P 삭제 - n1.left = n2 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* 노드 삽입과 삭제 */ - let P = new TreeNode(0); - // n1 -> n2 사이에 노드 P 삽입 - n1.left = P; - P.left = n2; - // 노드 P 삭제 - n1.left = n2; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* 노드 삽입과 삭제 */ - const P = new TreeNode(0); - // n1 -> n2 사이에 노드 P 삽입 - n1.left = P; - P.left = n2; - // 노드 P 삭제 - n1.left = n2; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* 노드 삽입과 삭제 */ - TreeNode P = new TreeNode(0); - // n1 -> n2 사이에 노드 P 삽입 - n1.left = P; - P.left = n2; - // 노드 P 삭제 - n1.left = n2; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - let p = TreeNode::new(0); - // n1 -> n2 사이에 노드 P 삽입 - n1.borrow_mut().left = Some(p.clone()); - p.borrow_mut().left = Some(n2.clone()); - // 노드 p 삭제 - n1.borrow_mut().left = Some(n2); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* 노드 삽입과 삭제 */ - TreeNode *P = newTreeNode(0); - // n1 -> n2 사이에 노드 P 삽입 - n1->left = P; - P->left = n2; - // 노드 P 삭제 - n1->left = n2; - // 메모리 해제 - free(P); - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - val P = TreeNode(0) - // n1 -> n2 사이에 노드 P 삽입 - n1.left = P - P.left = n2 - // 노드 P 삭제 - n1.left = n2 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # 노드 삽입과 삭제 - _p = TreeNode.new(0) - # n1 -> n2 사이에 노드 _p 삽입 - n1.left = _p - _p.left = n2 - # 노드 삭제 - n1.left = n2 - ``` +```snippet +insert_remove_node +``` ??? pythontutor "실행 시각화" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%EC%99%BC%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%EC%98%A4%EB%A5%B8%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%AC%EC%9D%B4%EC%9D%98%20%EC%B0%B8%EC%A1%B0%28%ED%8F%AC%EC%9D%B8%ED%84%B0%29%20%EC%97%B0%EA%B2%B0%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%BD%EC%9E%85%EA%B3%BC%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20n1%20-%3E%20n2%20%EC%82%AC%EC%9D%B4%EC%97%90%20%EB%85%B8%EB%93%9C%20P%20%EC%82%BD%EC%9E%85%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20P%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_node_tutor !!! tip "참고" diff --git a/ru/codes/snippets/chapter_array_and_linkedlist/array.md b/ru/codes/snippets/chapter_array_and_linkedlist/array.md new file mode 100644 index 000000000..53595cac5 --- /dev/null +++ b/ru/codes/snippets/chapter_array_and_linkedlist/array.md @@ -0,0 +1,93 @@ + +```python title="array.py" +# Инициализация массива +arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="array.cpp" +/* Инициализация массива */ +// Хранится в стеке +int arr[5] = {}; +int nums[5] = { 1, 3, 2, 5, 4 }; +// Хранится в куче (требуется ручное освобождение памяти) +int* arr1 = new int[5] {}; +int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +``` + +```java title="array.java" +/* Инициализация массива */ +int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } +int[] nums = { 1, 3, 2, 5, 4 }; +``` + +```csharp title="array.cs" +/* Инициализация массива */ +int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] +int[] nums = [1, 3, 2, 5, 4]; +``` + +```go title="array.go" +/* Инициализация массива */ +var arr [5]int +// В Go указание длины ([5]int) создает массив, а отсутствие длины ([]int) - срез +// Поскольку длина массива в Go определяется на этапе компиляции, для задания длины можно использовать только константы +// Чтобы упростить реализацию метода extend(), ниже будем рассматривать срезы (Slice) как массивы (Array) +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="array.swift" +/* Инициализация массива */ +let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] +let nums = [1, 3, 2, 5, 4] +``` + +```javascript title="array.js" +/* Инициализация массива */ +var arr = new Array(5).fill(0); +var nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="array.ts" +/* Инициализация массива */ +let arr: number[] = new Array(5).fill(0); +let nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="array.dart" +/* Инициализация массива */ +List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="array.rs" +/* Инициализация массива */ +let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] +let slice: &[i32] = &[0; 5]; +// В Rust указание длины ([i32; 5]) создает массив, а отсутствие длины (&[i32]) - срез +// Поскольку длина массива в Rust определяется на этапе компиляции, для задания длины можно использовать только константы +// Vector в Rust обычно используется как динамический массив +// Чтобы упростить реализацию метода extend(), ниже будем рассматривать vector как массив (array) +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="array.c" +/* Инициализация массива */ +int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } +int nums[5] = { 1, 3, 2, 5, 4 }; +``` + +```kotlin title="array.kt" +/* Инициализация массива */ +var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +var nums = intArrayOf(1, 3, 2, 5, 4) +``` + +```ruby title="array.rb" +# Инициализация массива +arr = Array.new(5, 0) +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/ru/codes/snippets/chapter_array_and_linkedlist/linked_list.md new file mode 100644 index 000000000..5d83ddbd9 --- /dev/null +++ b/ru/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -0,0 +1,516 @@ + +```python title="" +class ListNode: + """Класс узла связного списка""" + def __init__(self, val: int): + self.val: int = val # Значение узла + self.next: ListNode | None = None # Ссылка на следующий узел +``` + +```cpp title="" +/* Структура узла связного списка */ +struct ListNode { + int val; // Значение узла + ListNode *next; // Указатель на следующий узел + ListNode(int x) : val(x), next(nullptr) {} // Конструктор +}; +``` + +```java title="" +/* Класс узла связного списка */ +class ListNode { + int val; // Значение узла + ListNode next; // Ссылка на следующий узел + ListNode(int x) { val = x; } // Конструктор +} +``` + +```csharp title="" +/* Класс узла связного списка */ +class ListNode(int x) { // Конструктор + int val = x; // Значение узла + ListNode? next; // Ссылка на следующий узел +} +``` + +```go title="" +/* Структура узла связного списка */ +type ListNode struct { + Val int // Значение узла + Next *ListNode // Указатель на следующий узел +} + +// NewListNode — функция-конструктор, создающая новый связный список. +func NewListNode(val int) *ListNode { + return &ListNode{ + Val: val, + Next: nil, + } +} +``` + +```swift title="" +/* Класс узла связного списка */ +class ListNode { + var val: Int // Значение узла + var next: ListNode? // Ссылка на следующий узел + + init(x: Int) { // Конструктор + val = x + } +} +``` + +```javascript title="" +/* Класс узла связного списка */ +class ListNode { + constructor(val, next) { + this.val = (val === undefined ? 0 : val); // Значение узла + this.next = (next === undefined ? null : next); // Ссылка на следующий узел + } +} +``` + +```typescript title="" +/* Класс узла связного списка */ +class ListNode { + val: number; + next: ListNode | null; + constructor(val?: number, next?: ListNode | null) { + this.val = val === undefined ? 0 : val; // Значение узла + this.next = next === undefined ? null : next; // Ссылка на следующий узел + } +} +``` + +```dart title="" +/* Класс узла связного списка */ +class ListNode { + int val; // Значение узла + ListNode? next; // Ссылка на следующий узел + ListNode(this.val, [this.next]); // Конструктор +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; +/* Класс узла связного списка */ +#[derive(Debug)] +struct ListNode { + val: i32, // Значение узла + next: Option>>, // Указатель на следующий узел +} +``` + +```c title="" +/* Структура узла связного списка */ +typedef struct ListNode { + int val; // Значение узла + struct ListNode *next; // Указатель на следующий узел +} ListNode; + +/* Конструктор */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + return node; +} +``` + +```kotlin title="" +/* Класс узла связного списка */ +// Конструктор +class ListNode(x: Int) { + val _val: Int = x // Значение узла + var next: ListNode? = null // Ссылка на следующий узел +} +``` + +```ruby title="" +# Класс узла связного списка +class ListNode + attr_accessor :val # Значение узла + attr_accessor :next # Ссылка на следующий узел + + def initialize(val=0, next_node=nil) + @val = val + @next = next_node + end +end +``` + + +```python title="linked_list.py" +# Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 +# Инициализация каждого узла +n0 = ListNode(1) +n1 = ListNode(3) +n2 = ListNode(2) +n3 = ListNode(5) +n4 = ListNode(4) +# Построение ссылок между узлами +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```cpp title="linked_list.cpp" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +ListNode* n0 = new ListNode(1); +ListNode* n1 = new ListNode(3); +ListNode* n2 = new ListNode(2); +ListNode* n3 = new ListNode(5); +ListNode* n4 = new ListNode(4); +// Построение ссылок между узлами +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```java title="linked_list.java" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +ListNode n0 = new ListNode(1); +ListNode n1 = new ListNode(3); +ListNode n2 = new ListNode(2); +ListNode n3 = new ListNode(5); +ListNode n4 = new ListNode(4); +// Построение ссылок между узлами +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```csharp title="linked_list.cs" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +ListNode n0 = new(1); +ListNode n1 = new(3); +ListNode n2 = new(2); +ListNode n3 = new(5); +ListNode n4 = new(4); +// Построение ссылок между узлами +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```go title="linked_list.go" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +n0 := NewListNode(1) +n1 := NewListNode(3) +n2 := NewListNode(2) +n3 := NewListNode(5) +n4 := NewListNode(4) +// Построение ссылок между узлами +n0.Next = n1 +n1.Next = n2 +n2.Next = n3 +n3.Next = n4 +``` + +```swift title="linked_list.swift" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +let n0 = ListNode(x: 1) +let n1 = ListNode(x: 3) +let n2 = ListNode(x: 2) +let n3 = ListNode(x: 5) +let n4 = ListNode(x: 4) +// Построение ссылок между узлами +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```javascript title="linked_list.js" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// Построение ссылок между узлами +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```typescript title="linked_list.ts" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// Построение ссылок между узлами +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```dart title="linked_list.dart" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */\ +// Инициализация каждого узла +ListNode n0 = ListNode(1); +ListNode n1 = ListNode(3); +ListNode n2 = ListNode(2); +ListNode n3 = ListNode(5); +ListNode n4 = ListNode(4); +// Построение ссылок между узлами +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```rust title="linked_list.rs" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); +let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); +let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); +let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); +let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); + +// Построение ссылок между узлами +n0.borrow_mut().next = Some(n1.clone()); +n1.borrow_mut().next = Some(n2.clone()); +n2.borrow_mut().next = Some(n3.clone()); +n3.borrow_mut().next = Some(n4.clone()); +``` + +```c title="linked_list.c" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +ListNode* n0 = newListNode(1); +ListNode* n1 = newListNode(3); +ListNode* n2 = newListNode(2); +ListNode* n3 = newListNode(5); +ListNode* n4 = newListNode(4); +// Построение ссылок между узлами +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```kotlin title="linked_list.kt" +/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация каждого узла +val n0 = ListNode(1) +val n1 = ListNode(3) +val n2 = ListNode(2) +val n3 = ListNode(5) +val n4 = ListNode(4) +// Построение ссылок между узлами +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```ruby title="linked_list.rb" +# Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 +# Инициализация каждого узла +n0 = ListNode.new(1) +n1 = ListNode.new(3) +n2 = ListNode.new(2) +n3 = ListNode.new(5) +n4 = ListNode.new(4) +# Построение ссылок между узлами +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D1%83%D0%B7%D0%B5%D0%BB%D0%BA%D0%BB%D0%B0%D1%81%D1%81%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D1%81%D0%BB%D0%B5%D0%B4%D1%83%D1%8E%D1%89%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BA%D0%B0%D0%B6%D0%B4%D1%8B%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20%D0%9F%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B8%D1%82%D1%8C%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20%D1%83%D0%B7%D0%BB%D0%B0%D0%BC%D0%B8%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="" +class ListNode: + """Класс узла двусвязного списка""" + def __init__(self, val: int): + self.val: int = val # Значение узла + self.next: ListNode | None = None # Ссылка на следующий узел + self.prev: ListNode | None = None # Ссылка на предыдущий узел +``` + +```cpp title="" +/* Структура узла двусвязного списка */ +struct ListNode { + int val; // Значение узла + ListNode *next; // Указатель на следующий узел + ListNode *prev; // Указатель на предыдущий узел + ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // Конструктор +}; +``` + +```java title="" +/* Класс узла двусвязного списка */ +class ListNode { + int val; // Значение узла + ListNode next; // Ссылка на следующий узел + ListNode prev; // Ссылка на предыдущий узел + ListNode(int x) { val = x; } // Конструктор +} +``` + +```csharp title="" +/* Класс узла двусвязного списка */ +class ListNode(int x) { // Конструктор + int val = x; // Значение узла + ListNode next; // Ссылка на следующий узел + ListNode prev; // Ссылка на предыдущий узел +} +``` + +```go title="" +/* Структура узла двусвязного списка */ +type DoublyListNode struct { + Val int // Значение узла + Next *DoublyListNode // Указатель на следующий узел + Prev *DoublyListNode // Указатель на предыдущий узел +} + +// NewDoublyListNode инициализирует узел двусвязного списка. +func NewDoublyListNode(val int) *DoublyListNode { + return &DoublyListNode{ + Val: val, + Next: nil, + Prev: nil, + } +} +``` + +```swift title="" +/* Класс узла двусвязного списка */ +class ListNode { + var val: Int // Значение узла + var next: ListNode? // Ссылка на следующий узел + var prev: ListNode? // Ссылка на предыдущий узел + + init(x: Int) { // Конструктор + val = x + } +} +``` + +```javascript title="" +/* Класс узла двусвязного списка */ +class ListNode { + constructor(val, next, prev) { + this.val = val === undefined ? 0 : val; // Значение узла + this.next = next === undefined ? null : next; // Ссылка на следующий узел + this.prev = prev === undefined ? null : prev; // Ссылка на предыдущий узел + } +} +``` + +```typescript title="" +/* Класс узла двусвязного списка */ +class ListNode { + val: number; + next: ListNode | null; + prev: ListNode | null; + constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { + this.val = val === undefined ? 0 : val; // Значение узла + this.next = next === undefined ? null : next; // Ссылка на следующий узел + this.prev = prev === undefined ? null : prev; // Ссылка на предыдущий узел + } +} +``` + +```dart title="" +/* Класс узла двусвязного списка */ +class ListNode { + int val; // Значение узла + ListNode? next; // Ссылка на следующий узел + ListNode? prev; // Ссылка на предыдущий узел + ListNode(this.val, [this.next, this.prev]); // Конструктор +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* Тип узла двусвязного списка */ +#[derive(Debug)] +struct ListNode { + val: i32, // Значение узла + next: Option>>, // Указатель на следующий узел + prev: Option>>, // Указатель на предыдущий узел +} + +/* Конструктор */ +impl ListNode { + fn new(val: i32) -> Self { + ListNode { + val, + next: None, + prev: None, + } + } +} +``` + +```c title="" +/* Структура узла двусвязного списка */ +typedef struct ListNode { + int val; // Значение узла + struct ListNode *next; // Указатель на следующий узел + struct ListNode *prev; // Указатель на предыдущий узел +} ListNode; + +/* Конструктор */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + node->prev = NULL; + return node; +} +``` + +```kotlin title="" +/* Класс узла двусвязного списка */ +// Конструктор +class ListNode(x: Int) { + val _val: Int = x // Значение узла + var next: ListNode? = null // Ссылка на следующий узел + var prev: ListNode? = null // Ссылка на предыдущий узел +} +``` + +```ruby title="" +# Класс узла двусвязного списка +class ListNode + attr_accessor :val # Значение узла + attr_accessor :next # Ссылка на следующий узел + attr_accessor :prev # Ссылка на предыдущий узел + + def initialize(val=0, next_node=nil, prev_node=nil) + @val = val + @next = next_node + @prev = prev_node + end +end +``` diff --git a/ru/codes/snippets/chapter_array_and_linkedlist/list.md b/ru/codes/snippets/chapter_array_and_linkedlist/list.md new file mode 100644 index 000000000..d29dd39a5 --- /dev/null +++ b/ru/codes/snippets/chapter_array_and_linkedlist/list.md @@ -0,0 +1,752 @@ + +```python title="list.py" +# Инициализация списка +# Без начальных значений +nums1: list[int] = [] +# С начальными значениями +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="list.cpp" +/* Инициализация списка */ +// Обратите внимание: в C++ vector соответствует описываемому здесь nums +// Без начальных значений +vector nums1; +// С начальными значениями +vector nums = { 1, 3, 2, 5, 4 }; +``` + +```java title="list.java" +/* Инициализация списка */ +// Без начальных значений +List nums1 = new ArrayList<>(); +// С начальными значениями (обратите внимание: элементы массива должны использовать обертку Integer[] вместо int[]) +Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; +List nums = new ArrayList<>(Arrays.asList(numbers)); +``` + +```csharp title="list.cs" +/* Инициализация списка */ +// Без начальных значений +List nums1 = []; +// С начальными значениями +int[] numbers = [1, 3, 2, 5, 4]; +List nums = [.. numbers]; +``` + +```go title="list_test.go" +/* Инициализация списка */ +// Без начальных значений +nums1 := []int{} +// С начальными значениями +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="list.swift" +/* Инициализация списка */ +// Без начальных значений +let nums1: [Int] = [] +// С начальными значениями +var nums = [1, 3, 2, 5, 4] +``` + +```javascript title="list.js" +/* Инициализация списка */ +// Без начальных значений +const nums1 = []; +// С начальными значениями +const nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="list.ts" +/* Инициализация списка */ +// Без начальных значений +const nums1: number[] = []; +// С начальными значениями +const nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="list.dart" +/* Инициализация списка */ +// Без начальных значений +List nums1 = []; +// С начальными значениями +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="list.rs" +/* Инициализация списка */ +// Без начальных значений +let nums1: Vec = Vec::new(); +// С начальными значениями +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="list.c" +// В C нет встроенного динамического массива +``` + +```kotlin title="list.kt" +/* Инициализация списка */ +// Без начальных значений +var nums1 = listOf() +// С начальными значениями +var numbers = arrayOf(1, 3, 2, 5, 4) +var nums = numbers.toMutableList() +``` + +```ruby title="list.rb" +# Инициализация списка +# Без начальных значений +nums1 = [] +# С начальными значениями +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20%23%20%D0%91%D0%B5%D0%B7%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D1%85%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B9%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%D0%A1%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%BC%D0%B8%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%D0%BC%D0%B8%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Доступ к элементу +num: int = nums[1] # Доступ к элементу по индексу 1 + +# Изменение элемента +nums[1] = 0 # Изменить значение элемента с индексом 1 на 0 +``` + +```cpp title="list.cpp" +/* Доступ к элементу */ +int num = nums[1]; // Доступ к элементу по индексу 1 + +/* Изменение элемента */ +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +``` + +```java title="list.java" +/* Доступ к элементу */ +int num = nums.get(1); // Доступ к элементу по индексу 1 + +/* Изменение элемента */ +nums.set(1, 0); // Изменить значение элемента с индексом 1 на 0 +``` + +```csharp title="list.cs" +/* Доступ к элементу */ +int num = nums[1]; // Доступ к элементу по индексу 1 + +/* Изменение элемента */ +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +``` + +```go title="list_test.go" +/* Доступ к элементу */ +num := nums[1] // Доступ к элементу по индексу 1 + +/* Изменение элемента */ +nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 +``` + +```swift title="list.swift" +/* Доступ к элементу */ +let num = nums[1] // Доступ к элементу по индексу 1 + +/* Изменение элемента */ +nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 +``` + +```javascript title="list.js" +/* Доступ к элементу */ +const num = nums[1]; // Доступ к элементу по индексу 1 + +/* Изменение элемента */ +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +``` + +```typescript title="list.ts" +/* Доступ к элементу */ +const num: number = nums[1]; // Доступ к элементу по индексу 1 + +/* Изменение элемента */ +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +``` + +```dart title="list.dart" +/* Доступ к элементу */ +int num = nums[1]; // Доступ к элементу по индексу 1 + +/* Изменение элемента */ +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +``` + +```rust title="list.rs" +/* Доступ к элементу */ +let num: i32 = nums[1]; // Доступ к элементу по индексу 1 +/* Изменение элемента */ +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +``` + +```c title="list.c" +// В C нет встроенного динамического массива +``` + +```kotlin title="list.kt" +/* Доступ к элементу */ +val num = nums[1] // Доступ к элементу по индексу 1 +/* Изменение элемента */ +nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 +``` + +```ruby title="list.rb" +# Доступ к элементу +num = nums[1] # Доступ к элементу по индексу 1 +# Изменение элемента +nums[1] = 0 # Изменить значение элемента с индексом 1 на 0 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%D0%94%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D1%83%201%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%BC%D0%B5%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%D0%98%D0%B7%D0%BC%D0%B5%D0%BD%D0%B8%D1%82%D1%8C%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%20%D1%81%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D0%BE%D0%BC%201%20%D0%BD%D0%B0%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Очистить список +nums.clear() + +# Добавить элементы в конец +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +# Вставить элемент в середину +nums.insert(3, 6) # Вставить число 6 по индексу 3 + +# Удалить элемент +nums.pop(3) # Удалить элемент по индексу 3 +``` + +```cpp title="list.cpp" +/* Очистить список */ +nums.clear(); + +/* Добавить элементы в конец */ +nums.push_back(1); +nums.push_back(3); +nums.push_back(2); +nums.push_back(5); +nums.push_back(4); + +/* Вставить элемент в середину */ +nums.insert(nums.begin() + 3, 6); // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums.erase(nums.begin() + 3); // Удалить элемент по индексу 3 +``` + +```java title="list.java" +/* Очистить список */ +nums.clear(); + +/* Добавить элементы в конец */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* Вставить элемент в середину */ +nums.add(3, 6); // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums.remove(3); // Удалить элемент по индексу 3 +``` + +```csharp title="list.cs" +/* Очистить список */ +nums.Clear(); + +/* Добавить элементы в конец */ +nums.Add(1); +nums.Add(3); +nums.Add(2); +nums.Add(5); +nums.Add(4); + +/* Вставить элемент в середину */ +nums.Insert(3, 6); // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums.RemoveAt(3); // Удалить элемент по индексу 3 +``` + +```go title="list_test.go" +/* Очистить список */ +nums = nil + +/* Добавить элементы в конец */ +nums = append(nums, 1) +nums = append(nums, 3) +nums = append(nums, 2) +nums = append(nums, 5) +nums = append(nums, 4) + +/* Вставить элемент в середину */ +nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums = append(nums[:3], nums[4:]...) // Удалить элемент по индексу 3 +``` + +```swift title="list.swift" +/* Очистить список */ +nums.removeAll() + +/* Добавить элементы в конец */ +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +/* Вставить элемент в середину */ +nums.insert(6, at: 3) // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums.remove(at: 3) // Удалить элемент по индексу 3 +``` + +```javascript title="list.js" +/* Очистить список */ +nums.length = 0; + +/* Добавить элементы в конец */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* Вставить элемент в середину */ +nums.splice(3, 0, 6); // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums.splice(3, 1); // Удалить элемент по индексу 3 +``` + +```typescript title="list.ts" +/* Очистить список */ +nums.length = 0; + +/* Добавить элементы в конец */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* Вставить элемент в середину */ +nums.splice(3, 0, 6); // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums.splice(3, 1); // Удалить элемент по индексу 3 +``` + +```dart title="list.dart" +/* Очистить список */ +nums.clear(); + +/* Добавить элементы в конец */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* Вставить элемент в середину */ +nums.insert(3, 6); // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums.removeAt(3); // Удалить элемент по индексу 3 +``` + +```rust title="list.rs" +/* Очистить список */ +nums.clear(); + +/* Добавить элементы в конец */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* Вставить элемент в середину */ +nums.insert(3, 6); // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums.remove(3); // Удалить элемент по индексу 3 +``` + +```c title="list.c" +// В C нет встроенного динамического массива +``` + +```kotlin title="list.kt" +/* Очистить список */ +nums.clear(); + +/* Добавить элементы в конец */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* Вставить элемент в середину */ +nums.add(3, 6); // Вставить число 6 по индексу 3 + +/* Удалить элемент */ +nums.remove(3); // Удалить элемент по индексу 3 +``` + +```ruby title="list.rb" +# Очистить список +nums.clear + +# Добавить элементы в конец +nums << 1 +nums << 3 +nums << 2 +nums << 5 +nums << 4 + +# Вставить элемент в середину +nums.insert(3, 6) # Вставить число 6 по индексу 3 + +# Удалить элемент +nums.delete_at(3) # Удалить элемент по индексу 3 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%A1%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%BC%D0%B8%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%D0%BC%D0%B8%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D1%87%D0%B8%D1%81%D1%82%D0%B8%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BA%D0%BE%D0%BD%D0%B5%D1%86%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D1%81%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%D0%BD%D1%83%0A%20%20%20%20nums.insert%283%2C%206%29%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%87%D0%B8%D1%81%D0%BB%D0%BE%206%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D1%83%203%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D1%83%203&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Обход списка по индексам +count = 0 +for i in range(len(nums)): + count += nums[i] + +# Прямой обход элементов списка +for num in nums: + count += num +``` + +```cpp title="list.cpp" +/* Обход списка по индексам */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums[i]; +} + +/* Прямой обход элементов списка */ +count = 0; +for (int num : nums) { + count += num; +} +``` + +```java title="list.java" +/* Обход списка по индексам */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums.get(i); +} + +/* Прямой обход элементов списка */ +for (int num : nums) { + count += num; +} +``` + +```csharp title="list.cs" +/* Обход списка по индексам */ +int count = 0; +for (int i = 0; i < nums.Count; i++) { + count += nums[i]; +} + +/* Прямой обход элементов списка */ +count = 0; +foreach (int num in nums) { + count += num; +} +``` + +```go title="list_test.go" +/* Обход списка по индексам */ +count := 0 +for i := 0; i < len(nums); i++ { + count += nums[i] +} + +/* Прямой обход элементов списка */ +count = 0 +for _, num := range nums { + count += num +} +``` + +```swift title="list.swift" +/* Обход списка по индексам */ +var count = 0 +for i in nums.indices { + count += nums[i] +} + +/* Прямой обход элементов списка */ +count = 0 +for num in nums { + count += num +} +``` + +```javascript title="list.js" +/* Обход списка по индексам */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* Прямой обход элементов списка */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```typescript title="list.ts" +/* Обход списка по индексам */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* Прямой обход элементов списка */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```dart title="list.dart" +/* Обход списка по индексам */ +int count = 0; +for (var i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* Прямой обход элементов списка */ +count = 0; +for (var num in nums) { + count += num; +} +``` + +```rust title="list.rs" +// Обход списка по индексам +let mut _count = 0; +for i in 0..nums.len() { + _count += nums[i]; +} + +// Прямой обход элементов списка +_count = 0; +for num in &nums { + _count += num; +} +``` + +```c title="list.c" +// В C нет встроенного динамического массива +``` + +```kotlin title="list.kt" +/* Обход списка по индексам */ +var count = 0 +for (i in nums.indices) { + count += nums[i] +} + +/* Прямой обход элементов списка */ +for (num in nums) { + count += num +} +``` + +```ruby title="list.rb" +# Обход списка по индексам +count = 0 +for i in 0...nums.length + count += nums[i] +end + +# Прямой обход элементов списка +count = 0 +for num in nums + count += num +end +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%B1%D1%85%D0%BE%D0%B4%D0%B8%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D0%B0%D0%BC%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%D0%9D%D0%B5%D0%BF%D0%BE%D1%81%D1%80%D0%B5%D0%B4%D1%81%D1%82%D0%B2%D0%B5%D0%BD%D0%BD%D0%BE%20%D0%BE%D0%B1%D1%85%D0%BE%D0%B4%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%8B%20%D1%81%D0%BF%D0%B8%D1%81%D0%BA%D0%B0%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Конкатенация двух списков +nums1: list[int] = [6, 8, 7, 10, 9] +nums += nums1 # Присоединить список nums1 к концу nums +``` + +```cpp title="list.cpp" +/* Конкатенация двух списков */ +vector nums1 = { 6, 8, 7, 10, 9 }; +// Присоединить список nums1 к концу nums +nums.insert(nums.end(), nums1.begin(), nums1.end()); +``` + +```java title="list.java" +/* Конкатенация двух списков */ +List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); +nums.addAll(nums1); // Присоединить список nums1 к концу nums +``` + +```csharp title="list.cs" +/* Конкатенация двух списков */ +List nums1 = [6, 8, 7, 10, 9]; +nums.AddRange(nums1); // Присоединить список nums1 к концу nums +``` + +```go title="list_test.go" +/* Конкатенация двух списков */ +nums1 := []int{6, 8, 7, 10, 9} +nums = append(nums, nums1...) // Присоединить список nums1 к концу nums +``` + +```swift title="list.swift" +/* Конкатенация двух списков */ +let nums1 = [6, 8, 7, 10, 9] +nums.append(contentsOf: nums1) // Присоединить список nums1 к концу nums +``` + +```javascript title="list.js" +/* Конкатенация двух списков */ +const nums1 = [6, 8, 7, 10, 9]; +nums.push(...nums1); // Присоединить список nums1 к концу nums +``` + +```typescript title="list.ts" +/* Конкатенация двух списков */ +const nums1: number[] = [6, 8, 7, 10, 9]; +nums.push(...nums1); // Присоединить список nums1 к концу nums +``` + +```dart title="list.dart" +/* Конкатенация двух списков */ +List nums1 = [6, 8, 7, 10, 9]; +nums.addAll(nums1); // Присоединить список nums1 к концу nums +``` + +```rust title="list.rs" +/* Конкатенация двух списков */ +let nums1: Vec = vec![6, 8, 7, 10, 9]; +nums.extend(nums1); +``` + +```c title="list.c" +// В C нет встроенного динамического массива +``` + +```kotlin title="list.kt" +/* Конкатенация двух списков */ +val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() +nums.addAll(nums1) // Присоединить список nums1 к концу nums +``` + +```ruby title="list.rb" +# Конкатенация двух списков +nums1 = [6, 8, 7, 10, 9] +nums += nums1 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%B1%D1%8A%D0%B5%D0%B4%D0%B8%D0%BD%D0%B8%D1%82%D1%8C%20%D0%B4%D0%B2%D0%B0%20%D1%81%D0%BF%D0%B8%D1%81%D0%BA%D0%B0%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%D0%9F%D1%80%D0%B8%D1%81%D0%BE%D0%B5%D0%B4%D0%B8%D0%BD%D0%B8%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%20nums1%20%D0%BA%20nums&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# Отсортировать список +nums.sort() # После сортировки элементы списка идут по возрастанию +``` + +```cpp title="list.cpp" +/* Отсортировать список */ +sort(nums.begin(), nums.end()); // После сортировки элементы списка идут по возрастанию +``` + +```java title="list.java" +/* Отсортировать список */ +Collections.sort(nums); // После сортировки элементы списка идут по возрастанию +``` + +```csharp title="list.cs" +/* Отсортировать список */ +nums.Sort(); // После сортировки элементы списка идут по возрастанию +``` + +```go title="list_test.go" +/* Отсортировать список */ +sort.Ints(nums) // После сортировки элементы списка идут по возрастанию +``` + +```swift title="list.swift" +/* Отсортировать список */ +nums.sort() // После сортировки элементы списка идут по возрастанию +``` + +```javascript title="list.js" +/* Отсортировать список */ +nums.sort((a, b) => a - b); // После сортировки элементы списка идут по возрастанию +``` + +```typescript title="list.ts" +/* Отсортировать список */ +nums.sort((a, b) => a - b); // После сортировки элементы списка идут по возрастанию +``` + +```dart title="list.dart" +/* Отсортировать список */ +nums.sort(); // После сортировки элементы списка идут по возрастанию +``` + +```rust title="list.rs" +/* Отсортировать список */ +nums.sort(); // После сортировки элементы списка идут по возрастанию +``` + +```c title="list.c" +// В C нет встроенного динамического массива +``` + +```kotlin title="list.kt" +/* Отсортировать список */ +nums.sort() // После сортировки элементы списка идут по возрастанию +``` + +```ruby title="list.rb" +# Отсортировать список +nums = nums.sort { |a, b| a <=> b } # После сортировки элементы списка идут по возрастанию +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D1%82%D1%81%D0%BE%D1%80%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums.sort%28%29%20%20%23%20%D0%9F%D0%BE%D1%81%D0%BB%D0%B5%20%D1%81%D0%BE%D1%80%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B8%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%8B%20%D1%81%D0%BF%D0%B8%D1%81%D0%BA%D0%B0%20%D1%80%D0%B0%D1%81%D0%BF%D0%BE%D0%BB%D0%B0%D0%B3%D0%B0%D1%8E%D1%82%D1%81%D1%8F%20%D0%BF%D0%BE%20%D0%B2%D0%BE%D0%B7%D1%80%D0%B0%D1%81%D1%82%D0%B0%D0%BD%D0%B8%D1%8E&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_backtracking/backtracking_algorithm.md b/ru/codes/snippets/chapter_backtracking/backtracking_algorithm.md new file mode 100644 index 000000000..54727e6b5 --- /dev/null +++ b/ru/codes/snippets/chapter_backtracking/backtracking_algorithm.md @@ -0,0 +1,308 @@ + +```python title="" +def backtrack(state: State, choices: list[choice], res: list[state]): + """Каркас алгоритма поиска с возвратом""" + # Проверка, является ли текущее состояние решением + if is_solution(state): + # Запись решения + record_solution(state, res) + # Дальше не продолжаем поиск + return + # Перебор всех возможных выборов + for choice in choices: + # Обрезка: проверка допустимости выбора + if is_valid(state, choice): + # Попытка: сделать выбор и обновить состояние + make_choice(state, choice) + backtrack(state, choices, res) + # Откат: отменить выбор и восстановить предыдущее состояние + undo_choice(state, choice) +``` + +```cpp title="" +/* Каркас алгоритма поиска с возвратом */ +void backtrack(State *state, vector &choices, vector &res) { + // Проверка, является ли текущее состояние решением + if (isSolution(state)) { + // Запись решения + recordSolution(state, res); + // Дальше не продолжаем поиск + return; + } + // Перебор всех возможных выборов + for (Choice choice : choices) { + // Обрезка: проверка допустимости выбора + if (isValid(state, choice)) { + // Попытка: сделать выбор и обновить состояние + makeChoice(state, choice); + backtrack(state, choices, res); + // Откат: отменить выбор и восстановить предыдущее состояние + undoChoice(state, choice); + } + } +} +``` + +```java title="" +/* Каркас алгоритма поиска с возвратом */ +void backtrack(State state, List choices, List res) { + // Проверка, является ли текущее состояние решением + if (isSolution(state)) { + // Запись решения + recordSolution(state, res); + // Дальше не продолжаем поиск + return; + } + // Перебор всех возможных выборов + for (Choice choice : choices) { + // Обрезка: проверка допустимости выбора + if (isValid(state, choice)) { + // Попытка: сделать выбор и обновить состояние + makeChoice(state, choice); + backtrack(state, choices, res); + // Откат: отменить выбор и восстановить предыдущее состояние + undoChoice(state, choice); + } + } +} +``` + +```csharp title="" +/* Каркас алгоритма поиска с возвратом */ +void Backtrack(State state, List choices, List res) { + // Проверка, является ли текущее состояние решением + if (IsSolution(state)) { + // Запись решения + RecordSolution(state, res); + // Дальше не продолжаем поиск + return; + } + // Перебор всех возможных выборов + foreach (Choice choice in choices) { + // Обрезка: проверка допустимости выбора + if (IsValid(state, choice)) { + // Попытка: сделать выбор и обновить состояние + MakeChoice(state, choice); + Backtrack(state, choices, res); + // Откат: отменить выбор и восстановить предыдущее состояние + UndoChoice(state, choice); + } + } +} +``` + +```go title="" +/* Каркас алгоритма поиска с возвратом */ +func backtrack(state *State, choices []Choice, res *[]State) { + // Проверка, является ли текущее состояние решением + if isSolution(state) { + // Запись решения + recordSolution(state, res) + // Дальше не продолжаем поиск + return + } + // Перебор всех возможных выборов + for _, choice := range choices { + // Обрезка: проверка допустимости выбора + if isValid(state, choice) { + // Попытка: сделать выбор и обновить состояние + makeChoice(state, choice) + backtrack(state, choices, res) + // Откат: отменить выбор и восстановить предыдущее состояние + undoChoice(state, choice) + } + } +} +``` + +```swift title="" +/* Каркас алгоритма поиска с возвратом */ +func backtrack(state: inout State, choices: [Choice], res: inout [State]) { + // Проверка, является ли текущее состояние решением + if isSolution(state: state) { + // Запись решения + recordSolution(state: state, res: &res) + // Дальше не продолжаем поиск + return + } + // Перебор всех возможных выборов + for choice in choices { + // Обрезка: проверка допустимости выбора + if isValid(state: state, choice: choice) { + // Попытка: сделать выбор и обновить состояние + makeChoice(state: &state, choice: choice) + backtrack(state: &state, choices: choices, res: &res) + // Откат: отменить выбор и восстановить предыдущее состояние + undoChoice(state: &state, choice: choice) + } + } +} +``` + +```javascript title="" +/* Каркас алгоритма поиска с возвратом */ +function backtrack(state, choices, res) { + // Проверка, является ли текущее состояние решением + if (isSolution(state)) { + // Запись решения + recordSolution(state, res); + // Дальше не продолжаем поиск + return; + } + // Перебор всех возможных выборов + for (let choice of choices) { + // Обрезка: проверка допустимости выбора + if (isValid(state, choice)) { + // Попытка: сделать выбор и обновить состояние + makeChoice(state, choice); + backtrack(state, choices, res); + // Откат: отменить выбор и восстановить предыдущее состояние + undoChoice(state, choice); + } + } +} +``` + +```typescript title="" +/* Каркас алгоритма поиска с возвратом */ +function backtrack(state: State, choices: Choice[], res: State[]): void { + // Проверка, является ли текущее состояние решением + if (isSolution(state)) { + // Запись решения + recordSolution(state, res); + // Дальше не продолжаем поиск + return; + } + // Перебор всех возможных выборов + for (let choice of choices) { + // Обрезка: проверка допустимости выбора + if (isValid(state, choice)) { + // Попытка: сделать выбор и обновить состояние + makeChoice(state, choice); + backtrack(state, choices, res); + // Откат: отменить выбор и восстановить предыдущее состояние + undoChoice(state, choice); + } + } +} +``` + +```dart title="" +/* Каркас алгоритма поиска с возвратом */ +void backtrack(State state, List, List res) { + // Проверка, является ли текущее состояние решением + if (isSolution(state)) { + // Запись решения + recordSolution(state, res); + // Дальше не продолжаем поиск + return; + } + // Перебор всех возможных выборов + for (Choice choice in choices) { + // Обрезка: проверка допустимости выбора + if (isValid(state, choice)) { + // Попытка: сделать выбор и обновить состояние + makeChoice(state, choice); + backtrack(state, choices, res); + // Откат: отменить выбор и восстановить предыдущее состояние + undoChoice(state, choice); + } + } +} +``` + +```rust title="" +/* Каркас алгоритма поиска с возвратом */ +fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { + // Проверка, является ли текущее состояние решением + if is_solution(state) { + // Запись решения + record_solution(state, res); + // Дальше не продолжаем поиск + return; + } + // Перебор всех возможных выборов + for choice in choices { + // Обрезка: проверка допустимости выбора + if is_valid(state, choice) { + // Попытка: сделать выбор и обновить состояние + make_choice(state, choice); + backtrack(state, choices, res); + // Откат: отменить выбор и восстановить предыдущее состояние + undo_choice(state, choice); + } + } +} +``` + +```c title="" +/* Каркас алгоритма поиска с возвратом */ +void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { + // Проверка, является ли текущее состояние решением + if (isSolution(state)) { + // Запись решения + recordSolution(state, res, numRes); + // Дальше не продолжаем поиск + return; + } + // Перебор всех возможных выборов + for (int i = 0; i < numChoices; i++) { + // Обрезка: проверка допустимости выбора + if (isValid(state, &choices[i])) { + // Попытка: сделать выбор и обновить состояние + makeChoice(state, &choices[i]); + backtrack(state, choices, numChoices, res, numRes); + // Откат: отменить выбор и восстановить предыдущее состояние + undoChoice(state, &choices[i]); + } + } +} +``` + +```kotlin title="" +/* Каркас алгоритма поиска с возвратом */ +fun backtrack(state: State?, choices: List, res: List?) { + // Проверка, является ли текущее состояние решением + if (isSolution(state)) { + // Запись решения + recordSolution(state, res) + // Дальше не продолжаем поиск + return + } + // Перебор всех возможных выборов + for (choice in choices) { + // Обрезка: проверка допустимости выбора + if (isValid(state, choice)) { + // Попытка: сделать выбор и обновить состояние + makeChoice(state, choice) + backtrack(state, choices, res) + // Откат: отменить выбор и восстановить предыдущее состояние + undoChoice(state, choice) + } + } +} +``` + +```ruby title="" +### Каркас алгоритма поиска с возвратом ### +def backtrack(state, choices, res) + # Проверка, является ли текущее состояние решением + if is_solution?(state) + # Запись решения + record_solution(state, res) + return + end + + # Перебор всех возможных выборов + for choice in choices + # Обрезка: проверка допустимости выбора + if is_valid?(state, choice) + # Попытка: сделать выбор и обновить состояние + make_choice(state, choice) + backtrack(state, choices, res) + # Откат: отменить выбор и восстановить предыдущее состояние + undo_choice(state, choice) + end + end +end +``` diff --git a/ru/codes/snippets/chapter_computational_complexity/space_complexity.md b/ru/codes/snippets/chapter_computational_complexity/space_complexity.md new file mode 100644 index 000000000..62bc6df35 --- /dev/null +++ b/ru/codes/snippets/chapter_computational_complexity/space_complexity.md @@ -0,0 +1,682 @@ + +```python title="" +class Node: + """Класс""" + def __init__(self, x: int): + self.val: int = x # Значение узла + self.next: Node | None = None # Ссылка на следующий узел + +def function() -> int: + """Функция""" + # Выполнить некоторые операции... + return 0 + +def algorithm(n) -> int: # Входные данные + A = 0 # Временные данные (константа, обычно обозначается заглавной буквой) + b = 0 # Временные данные (переменная) + node = Node(0) # Временные данные (объект) + c = function() # Пространство кадра стека (вызов функции) + return A + b + c # Выходные данные +``` + +```cpp title="" +/* Структура */ +struct Node { + int val; + Node *next; + Node(int x) : val(x), next(nullptr) {} +}; + +/* Функция */ +int func() { + // Выполнить некоторые операции... + return 0; +} + +int algorithm(int n) { // Входные данные + const int a = 0; // Временные данные (константа) + int b = 0; // Временные данные (переменная) + Node* node = new Node(0); // Временные данные (объект) + int c = func(); // Пространство кадра стека (вызов функции) + return a + b + c; // Выходные данные +} +``` + +```java title="" +/* Класс */ +class Node { + int val; + Node next; + Node(int x) { val = x; } +} + +/* Функция */ +int function() { + // Выполнить некоторые операции... + return 0; +} + +int algorithm(int n) { // Входные данные + final int a = 0; // Временные данные (константа) + int b = 0; // Временные данные (переменная) + Node node = new Node(0); // Временные данные (объект) + int c = function(); // Пространство кадра стека (вызов функции) + return a + b + c; // Выходные данные +} +``` + +```csharp title="" +/* Класс */ +class Node(int x) { + int val = x; + Node next; +} + +/* Функция */ +int Function() { + // Выполнить некоторые операции... + return 0; +} + +int Algorithm(int n) { // Входные данные + const int a = 0; // Временные данные (константа) + int b = 0; // Временные данные (переменная) + Node node = new(0); // Временные данные (объект) + int c = Function(); // Пространство кадра стека (вызов функции) + return a + b + c; // Выходные данные +} +``` + +```go title="" +/* Структура */ +type node struct { + val int + next *node +} + +/* Создать структуру node */ +func newNode(val int) *node { + return &node{val: val} +} + +/* Функция */ +func function() int { + // Выполнить некоторые операции... + return 0 +} + +func algorithm(n int) int { // Входные данные + const a = 0 // Временные данные (константа) + b := 0 // Временные данные (переменная) + newNode(0) // Временные данные (объект) + c := function() // Пространство кадра стека (вызов функции) + return a + b + c // Выходные данные +} +``` + +```swift title="" +/* Класс */ +class Node { + var val: Int + var next: Node? + + init(x: Int) { + val = x + } +} + +/* Функция */ +func function() -> Int { + // Выполнить некоторые операции... + return 0 +} + +func algorithm(n: Int) -> Int { // Входные данные + let a = 0 // Временные данные (константа) + var b = 0 // Временные данные (переменная) + let node = Node(x: 0) // Временные данные (объект) + let c = function() // Пространство кадра стека (вызов функции) + return a + b + c // Выходные данные +} +``` + +```javascript title="" +/* Класс */ +class Node { + val; + next; + constructor(val) { + this.val = val === undefined ? 0 : val; // Значение узла + this.next = null; // Ссылка на следующий узел + } +} + +/* Функция */ +function constFunc() { + // Выполнить некоторые операции + return 0; +} + +function algorithm(n) { // Входные данные + const a = 0; // Временные данные (константа) + let b = 0; // Временные данные (переменная) + const node = new Node(0); // Временные данные (объект) + const c = constFunc(); // Пространство кадра стека (вызов функции) + return a + b + c; // Выходные данные +} +``` + +```typescript title="" +/* Класс */ +class Node { + val: number; + next: Node | null; + constructor(val?: number) { + this.val = val === undefined ? 0 : val; // Значение узла + this.next = null; // Ссылка на следующий узел + } +} + +/* Функция */ +function constFunc(): number { + // Выполнить некоторые операции + return 0; +} + +function algorithm(n: number): number { // Входные данные + const a = 0; // Временные данные (константа) + let b = 0; // Временные данные (переменная) + const node = new Node(0); // Временные данные (объект) + const c = constFunc(); // Пространство кадра стека (вызов функции) + return a + b + c; // Выходные данные +} +``` + +```dart title="" +/* Класс */ +class Node { + int val; + Node next; + Node(this.val, [this.next]); +} + +/* Функция */ +int function() { + // Выполнить некоторые операции... + return 0; +} + +int algorithm(int n) { // Входные данные + const int a = 0; // Временные данные (константа) + int b = 0; // Временные данные (переменная) + Node node = Node(0); // Временные данные (объект) + int c = function(); // Пространство кадра стека (вызов функции) + return a + b + c; // Выходные данные +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* Структура */ +struct Node { + val: i32, + next: Option>>, +} + +/* Создать структуру Node */ +impl Node { + fn new(val: i32) -> Self { + Self { val: val, next: None } + } +} + +/* Функция */ +fn function() -> i32 { + // Выполнить некоторые операции... + return 0; +} + +fn algorithm(n: i32) -> i32 { // Входные данные + const a: i32 = 0; // Временные данные (константа) + let mut b = 0; // Временные данные (переменная) + let node = Node::new(0); // Временные данные (объект) + let c = function(); // Пространство кадра стека (вызов функции) + return a + b + c; // Выходные данные +} +``` + +```c title="" +/* Функция */ +int func() { + // Выполнить некоторые операции... + return 0; +} + +int algorithm(int n) { // Входные данные + const int a = 0; // Временные данные (константа) + int b = 0; // Временные данные (переменная) + int c = func(); // Пространство кадра стека (вызов функции) + return a + b + c; // Выходные данные +} +``` + +```kotlin title="" +/* Класс */ +class Node(var _val: Int) { + var next: Node? = null +} + +/* Функция */ +fun function(): Int { + // Выполнить некоторые операции... + return 0 +} + +fun algorithm(n: Int): Int { // Входные данные + val a = 0 // Временные данные (константа) + var b = 0 // Временные данные (переменная) + val node = Node(0) // Временные данные (объект) + val c = function() // Пространство кадра стека (вызов функции) + return a + b + c // Выходные данные +} +``` + +```ruby title="" +### Класс ### +class Node + attr_accessor :val # Значение узла + attr_accessor :next # Ссылка на следующий узел + + def initialize(x) + @val = x + end +end + +### Функция ### +def function + # Выполнить некоторые операции... + 0 +end + +### Алгоритм ### +def algorithm(n) # Входные данные + a = 0 # Временные данные (константа) + b = 0 # Временные данные (переменная) + node = Node.new(0) # Временные данные (объект) + c = function # Пространство кадра стека (вызов функции) + a + b + c # Выходные данные +end +``` + + +```python title="" +def algorithm(n: int): + a = 0 # O(1) + b = [0] * 10000 # O(1) + if n > 10: + nums = [0] * n # O(n) +``` + +```cpp title="" +void algorithm(int n) { + int a = 0; // O(1) + vector b(10000); // O(1) + if (n > 10) + vector nums(n); // O(n) +} +``` + +```java title="" +void algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) + int[] nums = new int[n]; // O(n) +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) { + int[] nums = new int[n]; // O(n) + } +} +``` + +```go title="" +func algorithm(n int) { + a := 0 // O(1) + b := make([]int, 10000) // O(1) + var nums []int + if n > 10 { + nums := make([]int, n) // O(n) + } + fmt.Println(a, b, nums) +} +``` + +```swift title="" +func algorithm(n: Int) { + let a = 0 // O(1) + let b = Array(repeating: 0, count: 10000) // O(1) + if n > 10 { + let nums = Array(repeating: 0, count: n) // O(n) + } +} +``` + +```javascript title="" +function algorithm(n) { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 0; // O(1) + List b = List.filled(10000, 0); // O(1) + if (n > 10) { + List nums = List.filled(n, 0); // O(n) + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let a = 0; // O(1) + let b = [0; 10000]; // O(1) + if n > 10 { + let nums = vec![0; n as usize]; // O(n) + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 0; // O(1) + int b[10000]; // O(1) + if (n > 10) + int nums[n] = {0}; // O(n) +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + val a = 0 // O(1) + val b = IntArray(10000) // O(1) + if (n > 10) { + val nums = IntArray(n) // O(n) + } +} +``` + +```ruby title="" +def algorithm(n) + a = 0 # O(1) + b = Array.new(10000) # O(1) + nums = Array.new(n) if n > 10 # O(n) +end +``` + + +```python title="" +def function() -> int: + # Выполнить некоторые операции + return 0 + +def loop(n: int): + """Пространственная сложность цикла равна O(1)""" + for _ in range(n): + function() + +def recur(n: int): + """Пространственная сложность рекурсии равна O(n)""" + if n == 1: + return + return recur(n - 1) +``` + +```cpp title="" +int func() { + // Выполнить некоторые операции + return 0; +} +/* Пространственная сложность цикла равна O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* Пространственная сложность рекурсии равна O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```java title="" +int function() { + // Выполнить некоторые операции + return 0; +} +/* Пространственная сложность цикла равна O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* Пространственная сложность рекурсии равна O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```csharp title="" +int Function() { + // Выполнить некоторые операции + return 0; +} +/* Пространственная сложность цикла равна O(1) */ +void Loop(int n) { + for (int i = 0; i < n; i++) { + Function(); + } +} +/* Пространственная сложность рекурсии равна O(n) */ +int Recur(int n) { + if (n == 1) return 1; + return Recur(n - 1); +} +``` + +```go title="" +func function() int { + // Выполнить некоторые операции + return 0 +} + +/* Пространственная сложность цикла равна O(1) */ +func loop(n int) { + for i := 0; i < n; i++ { + function() + } +} + +/* Пространственная сложность рекурсии равна O(n) */ +func recur(n int) { + if n == 1 { + return + } + recur(n - 1) +} +``` + +```swift title="" +@discardableResult +func function() -> Int { + // Выполнить некоторые операции + return 0 +} + +/* Пространственная сложность цикла равна O(1) */ +func loop(n: Int) { + for _ in 0 ..< n { + function() + } +} + +/* Пространственная сложность рекурсии равна O(n) */ +func recur(n: Int) { + if n == 1 { + return + } + recur(n: n - 1) +} +``` + +```javascript title="" +function constFunc() { + // Выполнить некоторые операции + return 0; +} +/* Пространственная сложность цикла равна O(1) */ +function loop(n) { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* Пространственная сложность рекурсии равна O(n) */ +function recur(n) { + if (n === 1) return; + return recur(n - 1); +} +``` + +```typescript title="" +function constFunc(): number { + // Выполнить некоторые операции + return 0; +} +/* Пространственная сложность цикла равна O(1) */ +function loop(n: number): void { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* Пространственная сложность рекурсии равна O(n) */ +function recur(n: number): void { + if (n === 1) return; + return recur(n - 1); +} +``` + +```dart title="" +int function() { + // Выполнить некоторые операции + return 0; +} +/* Пространственная сложность цикла равна O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* Пространственная сложность рекурсии равна O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```rust title="" +fn function() -> i32 { + // Выполнить некоторые операции + return 0; +} +/* Пространственная сложность цикла равна O(1) */ +fn loop(n: i32) { + for i in 0..n { + function(); + } +} +/* Пространственная сложность рекурсии равна O(n) */ +fn recur(n: i32) { + if n == 1 { + return; + } + recur(n - 1); +} +``` + +```c title="" +int func() { + // Выполнить некоторые операции + return 0; +} +/* Пространственная сложность цикла равна O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* Пространственная сложность рекурсии равна O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```kotlin title="" +fun function(): Int { + // Выполнить некоторые операции + return 0 +} +/* Пространственная сложность цикла равна O(1) */ +fun loop(n: Int) { + for (i in 0.. +```python title="" +# На некоторой платформе выполнения +def algorithm(n: int): + a = 2 # 1 нс + a = a + 1 # 1 нс + a = a * 2 # 10 нс + # Цикл выполняется n раз + for _ in range(n): # 1 нс + print(0) # 5 нс +``` + +```cpp title="" +// На некоторой платформе выполнения +void algorithm(int n) { + int a = 2; // 1 нс + a = a + 1; // 1 нс + a = a * 2; // 10 нс + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // 1 нс + cout << 0 << endl; // 5 нс + } +} +``` + +```java title="" +// На некоторой платформе выполнения +void algorithm(int n) { + int a = 2; // 1 нс + a = a + 1; // 1 нс + a = a * 2; // 10 нс + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // 1 нс + System.out.println(0); // 5 нс + } +} +``` + +```csharp title="" +// На некоторой платформе выполнения +void Algorithm(int n) { + int a = 2; // 1 нс + a = a + 1; // 1 нс + a = a * 2; // 10 нс + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // 1 нс + Console.WriteLine(0); // 5 нс + } +} +``` + +```go title="" +// На некоторой платформе выполнения +func algorithm(n int) { + a := 2 // 1 нс + a = a + 1 // 1 нс + a = a * 2 // 10 нс + // Цикл выполняется n раз + for i := 0; i < n; i++ { // 1 нс + fmt.Println(a) // 5 нс + } +} +``` + +```swift title="" +// На некоторой платформе выполнения +func algorithm(n: Int) { + var a = 2 // 1 нс + a = a + 1 // 1 нс + a = a * 2 // 10 нс + // Цикл выполняется n раз + for _ in 0 ..< n { // 1 нс + print(0) // 5 нс + } +} +``` + +```javascript title="" +// На некоторой платформе выполнения +function algorithm(n) { + var a = 2; // 1 нс + a = a + 1; // 1 нс + a = a * 2; // 10 нс + // Цикл выполняется n раз + for(let i = 0; i < n; i++) { // 1 нс + console.log(0); // 5 нс + } +} +``` + +```typescript title="" +// На некоторой платформе выполнения +function algorithm(n: number): void { + var a: number = 2; // 1 нс + a = a + 1; // 1 нс + a = a * 2; // 10 нс + // Цикл выполняется n раз + for(let i = 0; i < n; i++) { // 1 нс + console.log(0); // 5 нс + } +} +``` + +```dart title="" +// На некоторой платформе выполнения +void algorithm(int n) { + int a = 2; // 1 нс + a = a + 1; // 1 нс + a = a * 2; // 10 нс + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // 1 нс + print(0); // 5 нс + } +} +``` + +```rust title="" +// На некоторой платформе выполнения +fn algorithm(n: i32) { + let mut a = 2; // 1 нс + a = a + 1; // 1 нс + a = a * 2; // 10 нс + // Цикл выполняется n раз + for _ in 0..n { // 1 нс + println!("{}", 0); // 5 нс + } +} +``` + +```c title="" +// На некоторой платформе выполнения +void algorithm(int n) { + int a = 2; // 1 нс + a = a + 1; // 1 нс + a = a * 2; // 10 нс + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // 1 нс + printf("%d", 0); // 5 нс + } +} +``` + +```kotlin title="" +// На некоторой платформе выполнения +fun algorithm(n: Int) { + var a = 2 // 1 нс + a = a + 1 // 1 нс + a = a * 2 // 10 нс + // Цикл выполняется n раз + for (i in 0.. +```python title="" +# Временная сложность алгоритма A: постоянная +def algorithm_A(n: int): + print(0) +# Временная сложность алгоритма B: линейная +def algorithm_B(n: int): + for _ in range(n): + print(0) +# Временная сложность алгоритма C: постоянная +def algorithm_C(n: int): + for _ in range(1000000): + print(0) +``` + +```cpp title="" +// Временная сложность алгоритма A: постоянная +void algorithm_A(int n) { + cout << 0 << endl; +} +// Временная сложность алгоритма B: линейная +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + cout << 0 << endl; + } +} +// Временная сложность алгоритма C: постоянная +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + cout << 0 << endl; + } +} +``` + +```java title="" +// Временная сложность алгоритма A: постоянная +void algorithm_A(int n) { + System.out.println(0); +} +// Временная сложность алгоритма B: линейная +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + System.out.println(0); + } +} +// Временная сложность алгоритма C: постоянная +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + System.out.println(0); + } +} +``` + +```csharp title="" +// Временная сложность алгоритма A: постоянная +void AlgorithmA(int n) { + Console.WriteLine(0); +} +// Временная сложность алгоритма B: линейная +void AlgorithmB(int n) { + for (int i = 0; i < n; i++) { + Console.WriteLine(0); + } +} +// Временная сложность алгоритма C: постоянная +void AlgorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + Console.WriteLine(0); + } +} +``` + +```go title="" +// Временная сложность алгоритма A: постоянная +func algorithm_A(n int) { + fmt.Println(0) +} +// Временная сложность алгоритма B: линейная +func algorithm_B(n int) { + for i := 0; i < n; i++ { + fmt.Println(0) + } +} +// Временная сложность алгоритма C: постоянная +func algorithm_C(n int) { + for i := 0; i < 1000000; i++ { + fmt.Println(0) + } +} +``` + +```swift title="" +// Временная сложность алгоритма A: постоянная +func algorithmA(n: Int) { + print(0) +} + +// Временная сложность алгоритма B: линейная +func algorithmB(n: Int) { + for _ in 0 ..< n { + print(0) + } +} + +// Временная сложность алгоритма C: постоянная +func algorithmC(n: Int) { + for _ in 0 ..< 1_000_000 { + print(0) + } +} +``` + +```javascript title="" +// Временная сложность алгоритма A: постоянная +function algorithm_A(n) { + console.log(0); +} +// Временная сложность алгоритма B: линейная +function algorithm_B(n) { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// Временная сложность алгоритма C: постоянная +function algorithm_C(n) { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} + +``` + +```typescript title="" +// Временная сложность алгоритма A: постоянная +function algorithm_A(n: number): void { + console.log(0); +} +// Временная сложность алгоритма B: линейная +function algorithm_B(n: number): void { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// Временная сложность алгоритма C: постоянная +function algorithm_C(n: number): void { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} +``` + +```dart title="" +// Временная сложность алгоритма A: постоянная +void algorithmA(int n) { + print(0); +} +// Временная сложность алгоритма B: линейная +void algorithmB(int n) { + for (int i = 0; i < n; i++) { + print(0); + } +} +// Временная сложность алгоритма C: постоянная +void algorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + print(0); + } +} +``` + +```rust title="" +// Временная сложность алгоритма A: постоянная +fn algorithm_A(n: i32) { + println!("{}", 0); +} +// Временная сложность алгоритма B: линейная +fn algorithm_B(n: i32) { + for _ in 0..n { + println!("{}", 0); + } +} +// Временная сложность алгоритма C: постоянная +fn algorithm_C(n: i32) { + for _ in 0..1000000 { + println!("{}", 0); + } +} +``` + +```c title="" +// Временная сложность алгоритма A: постоянная +void algorithm_A(int n) { + printf("%d", 0); +} +// Временная сложность алгоритма B: линейная +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + printf("%d", 0); + } +} +// Временная сложность алгоритма C: постоянная +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + printf("%d", 0); + } +} +``` + +```kotlin title="" +// Временная сложность алгоритма A: постоянная +fun algoritm_A(n: Int) { + println(0) +} +// Временная сложность алгоритма B: линейная +fun algorithm_B(n: Int) { + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +1 + a = a + 1 # +1 + a = a * 2 # +1 + # Цикл выполняется n раз + for i in range(n): # +1 + print(0) # +1 +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // +1 (каждый раз выполняется i ++) + cout << 0 << endl; // +1 + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // +1 (каждый раз выполняется i ++) + System.out.println(0); // +1 + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // +1 (каждый раз выполняется i ++) + Console.WriteLine(0); // +1 + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // Цикл выполняется n раз + for i := 0; i < n; i++ { // +1 + fmt.Println(a) // +1 + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // Цикл выполняется n раз + for _ in 0 ..< n { // +1 + print(0) // +1 + } +} +``` + +```javascript title="" +function algorithm(n) { + var a = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // Цикл выполняется n раз + for(let i = 0; i < n; i++){ // +1 (каждый раз выполняется i ++) + console.log(0); // +1 + } +} +``` + +```typescript title="" +function algorithm(n: number): void{ + var a: number = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // Цикл выполняется n раз + for(let i = 0; i < n; i++){ // +1 (каждый раз выполняется i ++) + console.log(0); // +1 + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // +1 (каждый раз выполняется i ++) + print(0); // +1 + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + + // Цикл выполняется n раз + for _ in 0..n { // +1 (каждый раз выполняется i ++) + println!("{}", 0); // +1 + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // Цикл выполняется n раз + for (int i = 0; i < n; i++) { // +1 (каждый раз выполняется i ++) + printf("%d", 0); // +1 + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // Цикл выполняется n раз + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +0 (прием 1) + a = a + n # +0 (прием 1) + # +n (прием 2) + for i in range(5 * n + 1): + print(0) + # +n*n (прием 3) + for i in range(2 * n): + for j in range(n + 1): + print(0) +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +0 (прием 1) + a = a + n; // +0 (прием 1) + // +n (прием 2) + for (int i = 0; i < 5 * n + 1; i++) { + cout << 0 << endl; + } + // +n*n (прием 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + cout << 0 << endl; + } + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +0 (прием 1) + a = a + n; // +0 (прием 1) + // +n (прием 2) + for (int i = 0; i < 5 * n + 1; i++) { + System.out.println(0); + } + // +n*n (прием 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + System.out.println(0); + } + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +0 (прием 1) + a = a + n; // +0 (прием 1) + // +n (прием 2) + for (int i = 0; i < 5 * n + 1; i++) { + Console.WriteLine(0); + } + // +n*n (прием 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + Console.WriteLine(0); + } + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +0 (прием 1) + a = a + n // +0 (прием 1) + // +n (прием 2) + for i := 0; i < 5 * n + 1; i++ { + fmt.Println(0) + } + // +n*n (прием 3) + for i := 0; i < 2 * n; i++ { + for j := 0; j < n + 1; j++ { + fmt.Println(0) + } + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +0 (прием 1) + a = a + n // +0 (прием 1) + // +n (прием 2) + for _ in 0 ..< (5 * n + 1) { + print(0) + } + // +n*n (прием 3) + for _ in 0 ..< (2 * n) { + for _ in 0 ..< (n + 1) { + print(0) + } + } +} +``` + +```javascript title="" +function algorithm(n) { + let a = 1; // +0 (прием 1) + a = a + n; // +0 (прием 1) + // +n (прием 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n (прием 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + let a = 1; // +0 (прием 1) + a = a + n; // +0 (прием 1) + // +n (прием 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n (прием 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +0 (прием 1) + a = a + n; // +0 (прием 1) + // +n (прием 2) + for (int i = 0; i < 5 * n + 1; i++) { + print(0); + } + // +n*n (прием 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + print(0); + } + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +0 (прием 1) + a = a + n; // +0 (прием 1) + + // +n (прием 2) + for i in 0..(5 * n + 1) { + println!("{}", 0); + } + + // +n*n (прием 3) + for i in 0..(2 * n) { + for j in 0..(n + 1) { + println!("{}", 0); + } + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +0 (прием 1) + a = a + n; // +0 (прием 1) + // +n (прием 2) + for (int i = 0; i < 5 * n + 1; i++) { + printf("%d", 0); + } + // +n*n (прием 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + printf("%d", 0); + } + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +0 (прием 1) + a = a + n // +0 (прием 1) + // +n (прием 2) + for (i in 0..<5 * n + 1) { + println(0) + } + // +n*n (прием 3) + for (i in 0..<2 * n) { + for (j in 0.. +```python title="" +# Инициализируем массивы с использованием различных базовых типов данных +numbers: list[int] = [0] * 5 +decimals: list[float] = [0.0] * 5 +# В Python символы фактически являются строками длины 1 +characters: list[str] = ['0'] * 5 +bools: list[bool] = [False] * 5 +# Списки Python могут свободно хранить различные базовые типы данных и ссылки на объекты +data = [0, 0.0, 'a', False, ListNode(0)] +``` + +```cpp title="" +// Инициализируем массивы с использованием различных базовых типов данных +int numbers[5]; +float decimals[5]; +char characters[5]; +bool bools[5]; +``` + +```java title="" +// Инициализируем массивы с использованием различных базовых типов данных +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +boolean[] bools = new boolean[5]; +``` + +```csharp title="" +// Инициализируем массивы с использованием различных базовых типов данных +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +bool[] bools = new bool[5]; +``` + +```go title="" +// Инициализируем массивы с использованием различных базовых типов данных +var numbers = [5]int{} +var decimals = [5]float64{} +var characters = [5]byte{} +var bools = [5]bool{} +``` + +```swift title="" +// Инициализируем массивы с использованием различных базовых типов данных +let numbers = Array(repeating: 0, count: 5) +let decimals = Array(repeating: 0.0, count: 5) +let characters: [Character] = Array(repeating: "a", count: 5) +let bools = Array(repeating: false, count: 5) +``` + +```javascript title="" +// Массивы JavaScript могут свободно хранить различные базовые типы данных и объекты +const array = [0, 0.0, 'a', false]; +``` + +```typescript title="" +// Инициализируем массивы с использованием различных базовых типов данных +const numbers: number[] = []; +const characters: string[] = []; +const bools: boolean[] = []; +``` + +```dart title="" +// Инициализируем массивы с использованием различных базовых типов данных +List numbers = List.filled(5, 0); +List decimals = List.filled(5, 0.0); +List characters = List.filled(5, 'a'); +List bools = List.filled(5, false); +``` + +```rust title="" +// Инициализируем массивы с использованием различных базовых типов данных +let numbers: Vec = vec![0; 5]; +let decimals: Vec = vec![0.0; 5]; +let characters: Vec = vec!['0'; 5]; +let bools: Vec = vec![false; 5]; +``` + +```c title="" +// Инициализируем массивы с использованием различных базовых типов данных +int numbers[10]; +float decimals[10]; +char characters[10]; +bool bools[10]; +``` + +```kotlin title="" +// Инициализируем массивы с использованием различных базовых типов данных +val numbers = IntArray(5) +val decinals = FloatArray(5) +val characters = CharArray(5) +val bools = BooleanArray(5) +``` + +```ruby title="" +# Списки Ruby могут свободно хранить различные базовые типы данных и ссылки на объекты +data = [0, 0.0, 'a', false, ListNode(0)] +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D1%83%D0%B7%D0%B5%D0%BB%D0%BA%D0%BB%D0%B0%D1%81%D1%81%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D1%81%D0%BB%D0%B5%D0%B4%D1%83%D1%8E%D1%89%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2%20%D1%81%20%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5%D0%BC%20%D0%BD%D0%B5%D1%81%D0%BA%D0%BE%D0%BB%D1%8C%D0%BA%D0%B8%D1%85%20%D0%B1%D0%B0%D0%B7%D0%BE%D0%B2%D1%8B%D1%85%20%D1%82%D0%B8%D0%BF%D0%BE%D0%B2%20%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20%2A%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20%2A%205%0A%20%20%20%20%23%20%D0%92%20Python%20%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB%D1%8B%20%D0%BD%D0%B0%20%D1%81%D0%B0%D0%BC%D0%BE%D0%BC%20%D0%B4%D0%B5%D0%BB%D0%B5%20%D1%8F%D0%B2%D0%BB%D1%8F%D1%8E%D1%82%D1%81%D1%8F%20%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B0%D0%BC%D0%B8%20%D0%B4%D0%BB%D0%B8%D0%BD%D1%8B%201%0A%20%20%20%20characters%20%3D%20%5B%270%27%5D%20%2A%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20%2A%205%0A%20%20%20%20%23%20%D0%A1%D0%BF%D0%B8%D1%81%D0%BA%D0%B8%20%D0%B2%20Python%20%D0%BC%D0%BE%D0%B3%D1%83%D1%82%20%D1%81%D0%B2%D0%BE%D0%B1%D0%BE%D0%B4%D0%BD%D0%BE%20%D1%85%D1%80%D0%B0%D0%BD%D0%B8%D1%82%D1%8C%20%D1%80%D0%B0%D0%B7%D0%BB%D0%B8%D1%87%D0%BD%D1%8B%D0%B5%20%D0%B1%D0%B0%D0%B7%D0%BE%D0%B2%D1%8B%D0%B5%20%D1%82%D0%B8%D0%BF%D1%8B%20%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85%20%D0%B8%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BD%D0%B0%20%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D1%8B%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20%27a%27%2C%20False%2C%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_hashing/hash_algorithm.md b/ru/codes/snippets/chapter_hashing/hash_algorithm.md new file mode 100644 index 000000000..716034d3d --- /dev/null +++ b/ru/codes/snippets/chapter_hashing/hash_algorithm.md @@ -0,0 +1,263 @@ + +```python title="built_in_hash.py" +num = 3 +hash_num = hash(num) +# Хеш-значение целого числа 3 равно 3 + +bol = True +hash_bol = hash(bol) +# Хеш-значение булевого значения True равно 1 + +dec = 3.14159 +hash_dec = hash(dec) +# Хеш-значение числа 3.14159 равно 326484311674566659 + +str = "Hello Algo" +hash_str = hash(str) +# Хеш-значение строки "Hello Algo" равно 4617003410720528961 + +tup = (12836, "Сяо Ха") +hash_tup = hash(tup) +# Хеш-значение кортежа (12836, "Сяо Ха") равно 1029005403108185979 + +obj = ListNode(0) +hash_obj = hash(obj) +# Хеш-значение объекта узла равно 274267521 +``` + +```cpp title="built_in_hash.cpp" +int num = 3; +size_t hashNum = hash()(num); +// Хеш-значение целого числа 3 равно 3 + +bool bol = true; +size_t hashBol = hash()(bol); +// Хеш-значение булевого значения 1 равно 1 + +double dec = 3.14159; +size_t hashDec = hash()(dec); +// Хеш-значение числа 3.14159 равно 4614256650576692846 + +string str = "Hello Algo"; +size_t hashStr = hash()(str); +// Хеш-значение строки "Hello Algo" равно 15466937326284535026 + +// В C++ встроенный std::hash() предоставляет вычисление хеша только для базовых типов данных +// Для массивов и объектов хеш-значение обычно приходится реализовывать самостоятельно +``` + +```java title="built_in_hash.java" +int num = 3; +int hashNum = Integer.hashCode(num); +// Хеш-значение целого числа 3 равно 3 + +boolean bol = true; +int hashBol = Boolean.hashCode(bol); +// Хеш-значение булевого значения true равно 1231 + +double dec = 3.14159; +int hashDec = Double.hashCode(dec); +// Хеш-значение числа 3.14159 равно -1340954729 + +String str = "Hello Algo"; +int hashStr = str.hashCode(); +// Хеш-значение строки "Hello Algo" равно -727081396 + +Object[] arr = { 12836, "Сяо Ха" }; +int hashTup = Arrays.hashCode(arr); +// Хеш-значение массива [12836, Сяо Ха] равно 1151158 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode(); +// Хеш-значение объекта узла utils.ListNode@7dc5e7b4 равно 2110121908 +``` + +```csharp title="built_in_hash.cs" +int num = 3; +int hashNum = num.GetHashCode(); +// Хеш-значение целого числа 3 равно 3; + +bool bol = true; +int hashBol = bol.GetHashCode(); +// Хеш-значение булевого значения true равно 1; + +double dec = 3.14159; +int hashDec = dec.GetHashCode(); +// Хеш-значение числа 3.14159 равно -1340954729; + +string str = "Hello Algo"; +int hashStr = str.GetHashCode(); +// Хеш-значение строки "Hello Algo" равно -586107568; + +object[] arr = [12836, "Сяо Ха"]; +int hashTup = arr.GetHashCode(); +// Хеш-значение массива [12836, Сяо Ха] равно 42931033; + +ListNode obj = new(0); +int hashObj = obj.GetHashCode(); +// Хеш-значение объекта узла 0 равно 39053774; +``` + +```go title="built_in_hash.go" +// В Go нет встроенной функции hash code +``` + +```swift title="built_in_hash.swift" +let num = 3 +let hashNum = num.hashValue +// Хеш-значение целого числа 3 равно 9047044699613009734 + +let bol = true +let hashBol = bol.hashValue +// Хеш-значение булевого значения true равно -4431640247352757451 + +let dec = 3.14159 +let hashDec = dec.hashValue +// Хеш-значение числа 3.14159 равно -2465384235396674631 + +let str = "Hello Algo" +let hashStr = str.hashValue +// Хеш-значение строки "Hello Algo" равно -7850626797806988787 + +let arr = [AnyHashable(12836), AnyHashable("Сяо Ха")] +let hashTup = arr.hashValue +// Хеш-значение массива [AnyHashable(12836), AnyHashable("Сяо Ха")] равно -2308633508154532996 + +let obj = ListNode(x: 0) +let hashObj = obj.hashValue +// Хеш-значение объекта узла utils.ListNode равно -2434780518035996159 +``` + +```javascript title="built_in_hash.js" +// В JavaScript нет встроенной функции hash code +``` + +```typescript title="built_in_hash.ts" +// В TypeScript нет встроенной функции hash code +``` + +```dart title="built_in_hash.dart" +int num = 3; +int hashNum = num.hashCode; +// Хеш-значение целого числа 3 равно 34803 + +bool bol = true; +int hashBol = bol.hashCode; +// Хеш-значение булевого значения true равно 1231 + +double dec = 3.14159; +int hashDec = dec.hashCode; +// Хеш-значение числа 3.14159 равно 2570631074981783 + +String str = "Hello Algo"; +int hashStr = str.hashCode; +// Хеш-значение строки "Hello Algo" равно 468167534 + +List arr = [12836, "Сяо Ха"]; +int hashArr = arr.hashCode; +// Хеш-значение массива [12836, Сяо Ха] равно 976512528 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode; +// Хеш-значение объекта Instance of 'ListNode' равно 1033450432 +``` + +```rust title="built_in_hash.rs" +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +let num = 3; +let mut num_hasher = DefaultHasher::new(); +num.hash(&mut num_hasher); +let hash_num = num_hasher.finish(); +// Хеш-значение целого числа 3 равно 568126464209439262 + +let bol = true; +let mut bol_hasher = DefaultHasher::new(); +bol.hash(&mut bol_hasher); +let hash_bol = bol_hasher.finish(); +// Хеш-значение булевого значения true равно 4952851536318644461 + +let dec: f32 = 3.14159; +let mut dec_hasher = DefaultHasher::new(); +dec.to_bits().hash(&mut dec_hasher); +let hash_dec = dec_hasher.finish(); +// Хеш-значение числа 3.14159 равно 2566941990314602357 + +let str = "Hello Algo"; +let mut str_hasher = DefaultHasher::new(); +str.hash(&mut str_hasher); +let hash_str = str_hasher.finish(); +// Хеш-значение строки "Hello Algo" равно 16092673739211250988 + +let arr = (&12836, &"Сяо Ха"); +let mut tup_hasher = DefaultHasher::new(); +arr.hash(&mut tup_hasher); +let hash_tup = tup_hasher.finish(); +// Хеш-значение кортежа (12836, "Сяо Ха") равно 1885128010422702749 + +let node = ListNode::new(42); +let mut hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut hasher); +let hash = hasher.finish(); +// Хеш-значение объекта RefCell { value: ListNode { val: 42, next: None } } равно 15387811073369036852 +``` + +```c title="built_in_hash.c" +// В C нет встроенной функции hash code +``` + +```kotlin title="built_in_hash.kt" +val num = 3 +val hashNum = num.hashCode() +// Хеш-значение целого числа 3 равно 3 + +val bol = true +val hashBol = bol.hashCode() +// Хеш-значение булевого значения true равно 1231 + +val dec = 3.14159 +val hashDec = dec.hashCode() +// Хеш-значение числа 3.14159 равно -1340954729 + +val str = "Hello Algo" +val hashStr = str.hashCode() +// Хеш-значение строки "Hello Algo" равно -727081396 + +val arr = arrayOf(12836, "Сяо Ха") +val hashTup = arr.hashCode() +// Хеш-значение массива [12836, Сяо Ха] равно 189568618 + +val obj = ListNode(0) +val hashObj = obj.hashCode() +// Хеш-значение объекта узла utils.ListNode@1d81eb93 равно 495053715 +``` + +```ruby title="built_in_hash.rb" +num = 3 +hash_num = num.hash +# Хеш-значение целого числа 3 равно -4385856518450339636 + +bol = true +hash_bol = bol.hash +# Хеш-значение булевого значения true равно -1617938112149317027 + +dec = 3.14159 +hash_dec = dec.hash +# Хеш-значение числа 3.14159 равно -1479186995943067893 + +str = "Hello Algo" +hash_str = str.hash +# Хеш-значение строки "Hello Algo" равно -4075943250025831763 + +tup = [12836, 'Сяо Ха'] +hash_tup = tup.hash +# Хеш-значение кортежа (12836, 'Сяо Ха') равно 1999544809202288822 + +obj = ListNode.new(0) +hash_obj = obj.hash +# Хеш-значение объекта # равно 4302940560806366381 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D1%83%D0%B7%D0%B5%D0%BB%D0%BA%D0%BB%D0%B0%D1%81%D1%81%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D1%81%D0%BB%D0%B5%D0%B4%D1%83%D1%8E%D1%89%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%86%D0%B5%D0%BB%D0%BE%D0%B3%D0%BE%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%203%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%B1%D1%83%D0%BB%D0%B5%D0%B2%D0%B0%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20True%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%203.14159%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20Algo%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8%20%22Hello%20Algo%22%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BA%D0%BE%D1%80%D1%82%D0%B5%D0%B6%D0%B0%20%2812836%2C%20%27%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%27%29%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%B0%20%D1%83%D0%B7%D0%BB%D0%B0%20%3CListNode%20object%20at%200x1058fd810%3E%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_hashing/hash_map.md b/ru/codes/snippets/chapter_hashing/hash_map.md new file mode 100644 index 000000000..a90dbf252 --- /dev/null +++ b/ru/codes/snippets/chapter_hashing/hash_map.md @@ -0,0 +1,457 @@ + +```python title="hash_map.py" +# Инициализация хеш-таблицы +hmap: dict = {} + +# Операция добавления +# Добавить пару ключ-значение (key, value) в хеш-таблицу +hmap[12836] = "Сяо Ха" +hmap[15937] = "Сяо Ло" +hmap[16750] = "Сяо Суань" +hmap[13276] = "Сяо Фа" +hmap[10583] = "Сяо Я" + +# Операция поиска +# Передать в хеш-таблицу ключ key и получить значение value +name: str = hmap[15937] + +# Операция удаления +# Удалить пару ключ-значение (key, value) из хеш-таблицы +hmap.pop(10583) +``` + +```cpp title="hash_map.cpp" +/* Инициализация хеш-таблицы */ +unordered_map map; + +/* Операция добавления */ +// Добавить пару ключ-значение (key, value) в хеш-таблицу +map[12836] = "Сяо Ха"; +map[15937] = "Сяо Ло"; +map[16750] = "Сяо Суань"; +map[13276] = "Сяо Фа"; +map[10583] = "Сяо Я"; + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +string name = map[15937]; + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +map.erase(10583); +``` + +```java title="hash_map.java" +/* Инициализация хеш-таблицы */ +Map map = new HashMap<>(); + +/* Операция добавления */ +// Добавить пару ключ-значение (key, value) в хеш-таблицу +map.put(12836, "Сяо Ха"); +map.put(15937, "Сяо Ло"); +map.put(16750, "Сяо Суань"); +map.put(13276, "Сяо Фа"); +map.put(10583, "Сяо Я"); + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +String name = map.get(15937); + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +map.remove(10583); +``` + +```csharp title="hash_map.cs" +/* Инициализация хеш-таблицы */ +Dictionary map = new() { + /* Операция добавления */ + // Добавить пару ключ-значение (key, value) в хеш-таблицу + { 12836, "Сяо Ха" }, + { 15937, "Сяо Ло" }, + { 16750, "Сяо Суань" }, + { 13276, "Сяо Фа" }, + { 10583, "Сяо Я" } +}; + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +string name = map[15937]; + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +map.Remove(10583); +``` + +```go title="hash_map_test.go" +/* Инициализация хеш-таблицы */ +hmap := make(map[int]string) + +/* Операция добавления */ +// Добавить пару ключ-значение (key, value) в хеш-таблицу +hmap[12836] = "Сяо Ха" +hmap[15937] = "Сяо Ло" +hmap[16750] = "Сяо Суань" +hmap[13276] = "Сяо Фа" +hmap[10583] = "Сяо Я" + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +name := hmap[15937] + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +delete(hmap, 10583) +``` + +```swift title="hash_map.swift" +/* Инициализация хеш-таблицы */ +var map: [Int: String] = [:] + +/* Операция добавления */ +// Добавить пару ключ-значение (key, value) в хеш-таблицу +map[12836] = "Сяо Ха" +map[15937] = "Сяо Ло" +map[16750] = "Сяо Суань" +map[13276] = "Сяо Фа" +map[10583] = "Сяо Я" + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +let name = map[15937]! + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +map.removeValue(forKey: 10583) +``` + +```javascript title="hash_map.js" +/* Инициализация хеш-таблицы */ +const map = new Map(); +/* Операция добавления */ +// Добавить пару ключ-значение (key, value) в хеш-таблицу +map.set(12836, 'Сяо Ха'); +map.set(15937, 'Сяо Ло'); +map.set(16750, 'Сяо Суань'); +map.set(13276, 'Сяо Фа'); +map.set(10583, 'Сяо Я'); + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +let name = map.get(15937); + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +map.delete(10583); +``` + +```typescript title="hash_map.ts" +/* Инициализация хеш-таблицы */ +const map = new Map(); +/* Операция добавления */ +// Добавить пару ключ-значение (key, value) в хеш-таблицу +map.set(12836, 'Сяо Ха'); +map.set(15937, 'Сяо Ло'); +map.set(16750, 'Сяо Суань'); +map.set(13276, 'Сяо Фа'); +map.set(10583, 'Сяо Я'); +console.info('\nПосле добавления хеш-таблица имеет вид\nKey -> Value'); +console.info(map); + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +let name = map.get(15937); +console.info('\nПо номеру 15937 найдено имя ' + name); + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +map.delete(10583); +console.info('\nПосле удаления 10583 хеш-таблица имеет вид\nKey -> Value'); +console.info(map); +``` + +```dart title="hash_map.dart" +/* Инициализация хеш-таблицы */ +Map map = {}; + +/* Операция добавления */ +// Добавить пару ключ-значение (key, value) в хеш-таблицу +map[12836] = "Сяо Ха"; +map[15937] = "Сяо Ло"; +map[16750] = "Сяо Суань"; +map[13276] = "Сяо Фа"; +map[10583] = "Сяо Я"; + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +String name = map[15937]; + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +map.remove(10583); +``` + +```rust title="hash_map.rs" +use std::collections::HashMap; + +/* Инициализация хеш-таблицы */ +let mut map: HashMap = HashMap::new(); + +/* Операция добавления */ +// Добавить пару ключ-значение (key, value) в хеш-таблицу +map.insert(12836, "Сяо Ха".to_string()); +map.insert(15937, "Сяо Ло".to_string()); +map.insert(16750, "Сяо Суань".to_string()); +map.insert(13279, "Сяо Фа".to_string()); +map.insert(10583, "Сяо Я".to_string()); + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +let _name: Option<&String> = map.get(&15937); + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +let _removed_value: Option = map.remove(&10583); +``` + +```c title="hash_map.c" +// В C нет встроенной хеш-таблицы +``` + +```kotlin title="hash_map.kt" +/* Инициализация хеш-таблицы */ +val map = HashMap() + +/* Операция добавления */ +// Добавить пару ключ-значение (key, value) в хеш-таблицу +map[12836] = "Сяо Ха" +map[15937] = "Сяо Ло" +map[16750] = "Сяо Суань" +map[13276] = "Сяо Фа" +map[10583] = "Сяо Я" + +/* Операция поиска */ +// Передать в хеш-таблицу ключ key и получить значение value +val name = map[15937] + +/* Операция удаления */ +// Удалить пару ключ-значение (key, value) из хеш-таблицы +map.remove(10583) +``` + +```ruby title="hash_map.rb" +# Инициализация хеш-таблицы +hmap = {} + +# Операция добавления +# Добавить пару ключ-значение (key, value) в хеш-таблицу +hmap[12836] = "Сяо Ха" +hmap[15937] = "Сяо Ло" +hmap[16750] = "Сяо Суань" +hmap[13276] = "Сяо Фа" +hmap[10583] = "Сяо Я" + +# Операция поиска +# Передать в хеш-таблицу ключ key и получить значение value +name = hmap[15937] + +# Операция удаления +# Удалить пару ключ-значение (key, value) из хеш-таблицы +hmap.delete(10583) +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D0%B4%D0%BE%D0%B1%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%20%D0%BF%D0%B0%D1%80%D1%83%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%9B%D0%BE%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A1%D1%83%D0%B0%D0%BD%D1%8C%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A4%D0%B0%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%D0%A3%D1%82%D0%B5%D0%BD%D0%BE%D0%BA%22%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D0%BF%D0%BE%D0%B8%D1%81%D0%BA%D0%B0%0A%20%20%20%20%23%20%D0%9F%D0%B5%D1%80%D0%B5%D0%B4%D0%B0%D1%82%D1%8C%20%D0%BA%D0%BB%D1%8E%D1%87%20key%20%D0%B2%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%20%D0%B8%20%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20value%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D1%83%D0%B4%D0%B0%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F%0A%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D0%B8%D0%B7%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%8B%20%D0%BF%D0%B0%D1%80%D1%83%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%28key%2C%20value%29%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="hash_map.py" +# Обход хеш-таблицы +# Обход пар ключ-значение key->value +for key, value in hmap.items(): + print(key, "->", value) +# Обход только ключей key +for key in hmap.keys(): + print(key) +# Обход только значений value +for value in hmap.values(): + print(value) +``` + +```cpp title="hash_map.cpp" +/* Обход хеш-таблицы */ +// Обход пар ключ-значение key->value +for (auto kv: map) { + cout << kv.first << " -> " << kv.second << endl; +} +// Обход key->value с помощью итератора +for (auto iter = map.begin(); iter != map.end(); iter++) { + cout << iter->first << "->" << iter->second << endl; +} +``` + +```java title="hash_map.java" +/* Обход хеш-таблицы */ +// Обход пар ключ-значение key->value +for (Map.Entry kv: map.entrySet()) { + System.out.println(kv.getKey() + " -> " + kv.getValue()); +} +// Обход только ключей key +for (int key: map.keySet()) { + System.out.println(key); +} +// Обход только значений value +for (String val: map.values()) { + System.out.println(val); +} +``` + +```csharp title="hash_map.cs" +/* Обход хеш-таблицы */ +// Обход пар ключ-значение Key->Value +foreach (var kv in map) { + Console.WriteLine(kv.Key + " -> " + kv.Value); +} +// Обход только ключей key +foreach (int key in map.Keys) { + Console.WriteLine(key); +} +// Обход только значений value +foreach (string val in map.Values) { + Console.WriteLine(val); +} +``` + +```go title="hash_map_test.go" +/* Обход хеш-таблицы */ +// Обход пар ключ-значение key->value +for key, value := range hmap { + fmt.Println(key, "->", value) +} +// Обход только ключей key +for key := range hmap { + fmt.Println(key) +} +// Обход только значений value +for _, value := range hmap { + fmt.Println(value) +} +``` + +```swift title="hash_map.swift" +/* Обход хеш-таблицы */ +// Обход пар ключ-значение Key->Value +for (key, value) in map { + print("\(key) -> \(value)") +} +// Обход только ключей Key +for key in map.keys { + print(key) +} +// Обход только значений Value +for value in map.values { + print(value) +} +``` + +```javascript title="hash_map.js" +/* Обход хеш-таблицы */ +console.info('\nОбход пар ключ-значение Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\nОбход только ключей Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\nОбход только значений Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```typescript title="hash_map.ts" +/* Обход хеш-таблицы */ +console.info('\nОбход пар ключ-значение Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\nОбход только ключей Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\nОбход только значений Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```dart title="hash_map.dart" +/* Обход хеш-таблицы */ +// Обход пар ключ-значение Key->Value +map.forEach((key, value) { + print('$key -> $value'); +}); + +// Обход только ключей Key +map.keys.forEach((key) { + print(key); +}); + +// Обход только значений Value +map.values.forEach((value) { + print(value); +}); +``` + +```rust title="hash_map.rs" +/* Обход хеш-таблицы */ +// Обход пар ключ-значение Key->Value +for (key, value) in &map { + println!("{key} -> {value}"); +} + +// Обход только ключей Key +for key in map.keys() { + println!("{key}"); +} + +// Обход только значений Value +for value in map.values() { + println!("{value}"); +} +``` + +```c title="hash_map.c" +// В C нет встроенной хеш-таблицы +``` + +```kotlin title="hash_map.kt" +/* Обход хеш-таблицы */ +// Обход пар ключ-значение key->value +for ((key, value) in map) { + println("$key -> $value") +} +// Обход только ключей key +for (key in map.keys) { + println(key) +} +// Обход только значений value +for (_val in map.values) { + println(_val) +} +``` + +```ruby title="hash_map.rb" +# Обход хеш-таблицы +# Обход пар ключ-значение key->value +hmap.entries.each { |key, value| puts "#{key} -> #{value}" } + +# Обход только ключей key +hmap.keys.each { |key| puts key } + +# Обход только значений value +hmap.values.each { |val| puts val } +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D0%B4%D0%BE%D0%B1%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%20%D0%BF%D0%B0%D1%80%D1%83%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%9B%D0%BE%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A1%D1%83%D0%B0%D0%BD%D1%8C%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A4%D0%B0%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%D0%A3%D1%82%D0%B5%D0%BD%D0%BE%D0%BA%22%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%B5%D1%80%D0%B5%D0%B1%D1%80%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20%23%20%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%BF%D0%B0%D1%80%D0%B0%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%D0%BE%D1%82%D0%B4%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%BA%D0%BB%D1%8E%D1%87%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%D0%BE%D1%82%D0%B4%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_heap/heap.md b/ru/codes/snippets/chapter_heap/heap.md new file mode 100644 index 000000000..b1b88149f --- /dev/null +++ b/ru/codes/snippets/chapter_heap/heap.md @@ -0,0 +1,350 @@ + +```python title="heap.py" +# Инициализация минимальной кучи +min_heap, flag = [], 1 +# Инициализация максимальной кучи +max_heap, flag = [], -1 + +# Модуль heapq в Python по умолчанию реализует минимальную кучу +# Если инвертировать знак элемента перед добавлением, то отношение порядка перевернется и так реализуется максимальная куча +# В этом примере flag = 1 соответствует минимальной куче, а flag = -1 - максимальной + +# Добавление элементов в кучу +heapq.heappush(max_heap, flag * 1) +heapq.heappush(max_heap, flag * 3) +heapq.heappush(max_heap, flag * 2) +heapq.heappush(max_heap, flag * 5) +heapq.heappush(max_heap, flag * 4) + +# Получение элемента на вершине кучи +peek: int = flag * max_heap[0] # 5 + +# Извлечение элемента с вершины кучи +# Извлеченные элементы образуют последовательность по убыванию +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 + +# Получение размера кучи +size: int = len(max_heap) + +# Проверка, пуста ли куча +is_empty: bool = not max_heap + +# Построение кучи из входного списка +min_heap: list[int] = [1, 3, 2, 5, 4] +heapq.heapify(min_heap) +``` + +```cpp title="heap.cpp" +/* Инициализация кучи */ +// Инициализация минимальной кучи +priority_queue, greater> minHeap; +// Инициализация максимальной кучи +priority_queue, less> maxHeap; + +/* Добавление элементов в кучу */ +maxHeap.push(1); +maxHeap.push(3); +maxHeap.push(2); +maxHeap.push(5); +maxHeap.push(4); + +/* Получение элемента на вершине кучи */ +int peek = maxHeap.top(); // 5 + +/* Извлечение элемента с вершины кучи */ +// Извлеченные элементы образуют последовательность по убыванию +maxHeap.pop(); // 5 +maxHeap.pop(); // 4 +maxHeap.pop(); // 3 +maxHeap.pop(); // 2 +maxHeap.pop(); // 1 + +/* Получение размера кучи */ +int size = maxHeap.size(); + +/* Проверка, пуста ли куча */ +bool isEmpty = maxHeap.empty(); + +/* Построение кучи из входного списка */ +vector input{1, 3, 2, 5, 4}; +priority_queue, greater> minHeap(input.begin(), input.end()); +``` + +```java title="heap.java" +/* Инициализация кучи */ +// Инициализация минимальной кучи +Queue minHeap = new PriorityQueue<>(); +// Инициализация максимальной кучи (достаточно изменить Comparator через lambda) +Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + +/* Добавление элементов в кучу */ +maxHeap.offer(1); +maxHeap.offer(3); +maxHeap.offer(2); +maxHeap.offer(5); +maxHeap.offer(4); + +/* Получение элемента на вершине кучи */ +int peek = maxHeap.peek(); // 5 + +/* Извлечение элемента с вершины кучи */ +// Извлеченные элементы образуют последовательность по убыванию +peek = maxHeap.poll(); // 5 +peek = maxHeap.poll(); // 4 +peek = maxHeap.poll(); // 3 +peek = maxHeap.poll(); // 2 +peek = maxHeap.poll(); // 1 + +/* Получение размера кучи */ +int size = maxHeap.size(); + +/* Проверка, пуста ли куча */ +boolean isEmpty = maxHeap.isEmpty(); + +/* Построение кучи из входного списка */ +minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +``` + +```csharp title="heap.cs" +/* Инициализация кучи */ +// Инициализация минимальной кучи +PriorityQueue minHeap = new(); +// Инициализация максимальной кучи (достаточно изменить Comparer через lambda) +PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + +/* Добавление элементов в кучу */ +maxHeap.Enqueue(1, 1); +maxHeap.Enqueue(3, 3); +maxHeap.Enqueue(2, 2); +maxHeap.Enqueue(5, 5); +maxHeap.Enqueue(4, 4); + +/* Получение элемента на вершине кучи */ +int peek = maxHeap.Peek();//5 + +/* Извлечение элемента с вершины кучи */ +// Извлеченные элементы образуют последовательность по убыванию +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 + +/* Получение размера кучи */ +int size = maxHeap.Count; + +/* Проверка, пуста ли куча */ +bool isEmpty = maxHeap.Count == 0; + +/* Построение кучи из входного списка */ +minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +``` + +```go title="heap.go" +// В Go можно построить целочисленную максимальную кучу, реализовав heap.Interface +// Для реализации heap.Interface также нужно реализовать sort.Interface +type intHeap []any + +// Метод Push из heap.Interface, реализует добавление элемента в кучу +func (h *intHeap) Push(x any) { + // Push и Pop используют pointer receiver + // Потому что они не только изменяют содержимое среза, но и его длину + *h = append(*h, x.(int)) +} + +// Метод Pop из heap.Interface, реализует извлечение элемента с вершины кучи +func (h *intHeap) Pop() any { + // Извлекаемый элемент хранится в конце + last := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return last +} + +// Метод Len из sort.Interface +func (h *intHeap) Len() int { + return len(*h) +} + +// Метод Less из sort.Interface +func (h *intHeap) Less(i, j int) bool { + // Для минимальной кучи здесь нужно заменить сравнение на < + return (*h)[i].(int) > (*h)[j].(int) +} + +// Метод Swap из sort.Interface +func (h *intHeap) Swap(i, j int) { + (*h)[i], (*h)[j] = (*h)[j], (*h)[i] +} + +// Top получает элемент на вершине кучи +func (h *intHeap) Top() any { + return (*h)[0] +} + +/* Driver Code */ +func TestHeap(t *testing.T) { + /* Инициализация кучи */ + // Инициализация максимальной кучи + maxHeap := &intHeap{} + heap.Init(maxHeap) + /* Добавление элементов в кучу */ + // Вызываем методы heap.Interface для добавления элементов + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 4) + heap.Push(maxHeap, 5) + + /* Получение элемента на вершине кучи */ + top := maxHeap.Top() + fmt.Printf("Элемент на вершине кучи: %d\n", top) + + /* Извлечение элемента с вершины кучи */ + // Вызываем методы heap.Interface для удаления элементов + heap.Pop(maxHeap) // 5 + heap.Pop(maxHeap) // 4 + heap.Pop(maxHeap) // 3 + heap.Pop(maxHeap) // 2 + heap.Pop(maxHeap) // 1 + + /* Получение размера кучи */ + size := len(*maxHeap) + fmt.Printf("Число элементов в куче: %d\n", size) + + /* Проверка, пуста ли куча */ + isEmpty := len(*maxHeap) == 0 + fmt.Printf("Пуста ли куча: %t\n", isEmpty) +} +``` + +```swift title="heap.swift" +/* Инициализация кучи */ +// Тип Heap в Swift поддерживает и max-heap, и min-heap, но требует swift-collections +var heap = Heap() + +/* Добавление элементов в кучу */ +heap.insert(1) +heap.insert(3) +heap.insert(2) +heap.insert(5) +heap.insert(4) + +/* Получение элемента на вершине кучи */ +var peek = heap.max()! + +/* Извлечение элемента с вершины кучи */ +peek = heap.removeMax() // 5 +peek = heap.removeMax() // 4 +peek = heap.removeMax() // 3 +peek = heap.removeMax() // 2 +peek = heap.removeMax() // 1 + +/* Получение размера кучи */ +let size = heap.count + +/* Проверка, пуста ли куча */ +let isEmpty = heap.isEmpty + +/* Построение кучи из входного списка */ +let heap2 = Heap([1, 3, 2, 5, 4]) +``` + +```javascript title="heap.js" +// В JavaScript нет встроенного класса Heap +``` + +```typescript title="heap.ts" +// В TypeScript нет встроенного класса Heap +``` + +```dart title="heap.dart" +// В Dart нет встроенного класса Heap +``` + +```rust title="heap.rs" +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +/* Инициализация кучи */ +// Инициализация минимальной кучи +let mut min_heap = BinaryHeap::>::new(); +// Инициализация максимальной кучи +let mut max_heap = BinaryHeap::new(); + +/* Добавление элементов в кучу */ +max_heap.push(1); +max_heap.push(3); +max_heap.push(2); +max_heap.push(5); +max_heap.push(4); + +/* Получение элемента на вершине кучи */ +let peek = max_heap.peek().unwrap(); // 5 + +/* Извлечение элемента с вершины кучи */ +// Извлеченные элементы образуют последовательность по убыванию +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 + +/* Получение размера кучи */ +let size = max_heap.len(); + +/* Проверка, пуста ли куча */ +let is_empty = max_heap.is_empty(); + +/* Построение кучи из входного списка */ +let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +``` + +```c title="heap.c" +// В C нет встроенного класса Heap +``` + +```kotlin title="heap.kt" +/* Инициализация кучи */ +// Инициализация минимальной кучи +var minHeap = PriorityQueue() +// Инициализация максимальной кучи (достаточно изменить Comparator через lambda) +val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + +/* Добавление элементов в кучу */ +maxHeap.offer(1) +maxHeap.offer(3) +maxHeap.offer(2) +maxHeap.offer(5) +maxHeap.offer(4) + +/* Получение элемента на вершине кучи */ +var peek = maxHeap.peek() // 5 + +/* Извлечение элемента с вершины кучи */ +// Извлеченные элементы образуют последовательность по убыванию +peek = maxHeap.poll() // 5 +peek = maxHeap.poll() // 4 +peek = maxHeap.poll() // 3 +peek = maxHeap.poll() // 2 +peek = maxHeap.poll() // 1 + +/* Получение размера кучи */ +val size = maxHeap.size + +/* Проверка, пуста ли куча */ +val isEmpty = maxHeap.isEmpty() + +/* Построение кучи из входного списка */ +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +``` + +```ruby title="heap.rb" +# В Ruby нет встроенного класса Heap +``` + + +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20min-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20max-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9C%D0%BE%D0%B4%D1%83%D0%BB%D1%8C%20heapq%20%D0%B2%20Python%20%D0%BF%D0%BE%20%D1%83%D0%BC%D0%BE%D0%BB%D1%87%D0%B0%D0%BD%D0%B8%D1%8E%20%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D1%83%D0%B5%D1%82%20min-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20%23%20%D0%95%D1%81%D0%BB%D0%B8%20%D0%BF%D0%B5%D1%80%D0%B5%D0%B4%20%D0%BF%D0%BE%D0%BC%D0%B5%D1%89%D0%B5%D0%BD%D0%B8%D0%B5%D0%BC%20%D0%B2%20%D0%BA%D1%83%D1%87%D1%83%20%D0%B1%D1%80%D0%B0%D1%82%D1%8C%20%D0%BE%D1%82%D1%80%D0%B8%D1%86%D0%B0%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%2C%20%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%20%D0%BE%D0%B1%D1%80%D0%B0%D1%82%D0%B8%D1%82%D1%8C%20%D0%BE%D1%82%D0%BD%D0%BE%D1%88%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BF%D0%BE%D1%80%D1%8F%D0%B4%D0%BA%D0%B0%20%D0%B8%20%D1%82%D0%B5%D0%BC%20%D1%81%D0%B0%D0%BC%D1%8B%D0%BC%20%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20max-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20%23%20%D0%92%20%D1%8D%D1%82%D0%BE%D0%BC%20%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D0%B5%20flag%20%3D%201%20%D1%81%D0%BE%D0%BE%D1%82%D0%B2%D0%B5%D1%82%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82%20min-%D0%BA%D1%83%D1%87%D0%B5%2C%20%D0%B0%20flag%20%3D%20-1%20%D1%81%D0%BE%D0%BE%D1%82%D0%B2%D0%B5%D1%82%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82%20max-%D0%BA%D1%83%D1%87%D0%B5%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5%20%D0%B8%D0%B7%20%D0%BA%D1%83%D1%87%D0%B8%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%8B%20%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D1%83%D1%8E%D1%82%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C%20%D0%BE%D1%82%20%D0%B1%D0%BE%D0%BB%D1%8C%D1%88%D0%B5%D0%B3%D0%BE%20%D0%BA%20%D0%BC%D0%B5%D0%BD%D1%8C%D1%88%D0%B5%D0%BC%D1%83%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D1%80%D0%B0%D0%B7%D0%BC%D0%B5%D1%80%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%BA%D1%83%D1%87%D0%B0%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%92%D1%85%D0%BE%D0%B4%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D0%B8%D0%BF%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_preface/suggestions.md b/ru/codes/snippets/chapter_preface/suggestions.md new file mode 100644 index 000000000..f7187836c --- /dev/null +++ b/ru/codes/snippets/chapter_preface/suggestions.md @@ -0,0 +1,139 @@ + +```python title="" +"""Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п.""" + +# Содержательный комментарий: подробно поясняет код + +""" +Многострочный +комментарий +""" +``` + +```cpp title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```java title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```csharp title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```go title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```swift title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```javascript title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```typescript title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```dart title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```rust title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +// Многострочный +// комментарий +``` + +```c title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```kotlin title="" +/* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ + +// Содержательный комментарий: подробно поясняет код + +/** + * Многострочный + * комментарий + */ +``` + +```ruby title="" +### Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. ### + +# Содержательный комментарий: подробно поясняет код + +# Многострочный +# комментарий +``` diff --git a/ru/codes/snippets/chapter_stack_and_queue/deque.md b/ru/codes/snippets/chapter_stack_and_queue/deque.md new file mode 100644 index 000000000..6fa64b46b --- /dev/null +++ b/ru/codes/snippets/chapter_stack_and_queue/deque.md @@ -0,0 +1,339 @@ + +```python title="deque.py" +from collections import deque + +# Инициализация двусторонней очереди +deq: deque[int] = deque() + +# Поместить элементы в очередь +deq.append(2) # Добавить в хвост +deq.append(5) +deq.append(4) +deq.appendleft(3) # Добавить в голову +deq.appendleft(1) + +# Просмотреть элементы +front: int = deq[0] # Элемент в голове +rear: int = deq[-1] # Элемент в хвосте + +# Извлечь элементы из очереди +pop_front: int = deq.popleft() # Извлечь элемент из головы +pop_rear: int = deq.pop() # Извлечь элемент из хвоста + +# Получить длину двусторонней очереди +size: int = len(deq) + +# Проверить, пуста ли двусторонняя очередь +is_empty: bool = len(deq) == 0 +``` + +```cpp title="deque.cpp" +/* Инициализация двусторонней очереди */ +deque deque; + +/* Поместить элементы в очередь */ +deque.push_back(2); // Добавить в хвост +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // Добавить в голову +deque.push_front(1); + +/* Просмотреть элементы */ +int front = deque.front(); // Элемент в голове +int back = deque.back(); // Элемент в хвосте + +/* Извлечь элементы из очереди */ +deque.pop_front(); // Извлечь элемент из головы +deque.pop_back(); // Извлечь элемент из хвоста + +/* Получить длину двусторонней очереди */ +int size = deque.size(); + +/* Проверить, пуста ли двусторонняя очередь */ +bool empty = deque.empty(); +``` + +```java title="deque.java" +/* Инициализация двусторонней очереди */ +Deque deque = new LinkedList<>(); + +/* Поместить элементы в очередь */ +deque.offerLast(2); // Добавить в хвост +deque.offerLast(5); +deque.offerLast(4); +deque.offerFirst(3); // Добавить в голову +deque.offerFirst(1); + +/* Просмотреть элементы */ +int peekFirst = deque.peekFirst(); // Элемент в голове +int peekLast = deque.peekLast(); // Элемент в хвосте + +/* Извлечь элементы из очереди */ +int popFirst = deque.pollFirst(); // Извлечь элемент из головы +int popLast = deque.pollLast(); // Извлечь элемент из хвоста + +/* Получить длину двусторонней очереди */ +int size = deque.size(); + +/* Проверить, пуста ли двусторонняя очередь */ +boolean isEmpty = deque.isEmpty(); +``` + +```csharp title="deque.cs" +/* Инициализация двусторонней очереди */ +// В C# двустороннюю очередь обычно моделируют через связный список LinkedList +LinkedList deque = new(); + +/* Поместить элементы в очередь */ +deque.AddLast(2); // Добавить в хвост +deque.AddLast(5); +deque.AddLast(4); +deque.AddFirst(3); // Добавить в голову +deque.AddFirst(1); + +/* Просмотреть элементы */ +int peekFirst = deque.First.Value; // Элемент в голове +int peekLast = deque.Last.Value; // Элемент в хвосте + +/* Извлечь элементы из очереди */ +deque.RemoveFirst(); // Извлечь элемент из головы +deque.RemoveLast(); // Извлечь элемент из хвоста + +/* Получить длину двусторонней очереди */ +int size = deque.Count; + +/* Проверить, пуста ли двусторонняя очередь */ +bool isEmpty = deque.Count == 0; +``` + +```go title="deque_test.go" +/* Инициализация двусторонней очереди */ +// В Go list обычно используется как двусторонняя очередь +deque := list.New() + +/* Поместить элементы в очередь */ +deque.PushBack(2) // Добавить в хвост +deque.PushBack(5) +deque.PushBack(4) +deque.PushFront(3) // Добавить в голову +deque.PushFront(1) + +/* Просмотреть элементы */ +front := deque.Front() // Элемент в голове +rear := deque.Back() // Элемент в хвосте + +/* Извлечь элементы из очереди */ +deque.Remove(front) // Извлечь элемент из головы +deque.Remove(rear) // Извлечь элемент из хвоста + +/* Получить длину двусторонней очереди */ +size := deque.Len() + +/* Проверить, пуста ли двусторонняя очередь */ +isEmpty := deque.Len() == 0 +``` + +```swift title="deque.swift" +/* Инициализация двусторонней очереди */ +// В Swift нет встроенного класса двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь +var deque: [Int] = [] + +/* Поместить элементы в очередь */ +deque.append(2) // Добавить в хвост +deque.append(5) +deque.append(4) +deque.insert(3, at: 0) // Добавить в голову +deque.insert(1, at: 0) + +/* Просмотреть элементы */ +let peekFirst = deque.first! // Элемент в голове +let peekLast = deque.last! // Элемент в хвосте + +/* Извлечь элементы из очереди */ +// При моделировании через Array сложность popFirst равна O(n) +let popFirst = deque.removeFirst() // Извлечь элемент из головы +let popLast = deque.removeLast() // Извлечь элемент из хвоста + +/* Получить длину двусторонней очереди */ +let size = deque.count + +/* Проверить, пуста ли двусторонняя очередь */ +let isEmpty = deque.isEmpty +``` + +```javascript title="deque.js" +/* Инициализация двусторонней очереди */ +// В JavaScript нет встроенной двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь +const deque = []; + +/* Поместить элементы в очередь */ +deque.push(2); +deque.push(5); +deque.push(4); +// Обратите внимание: поскольку это массив, метод unshift() имеет сложность O(n) +deque.unshift(3); +deque.unshift(1); + +/* Просмотреть элементы */ +const peekFirst = deque[0]; +const peekLast = deque[deque.length - 1]; + +/* Извлечь элементы из очереди */ +// Обратите внимание: поскольку это массив, метод shift() имеет сложность O(n) +const popFront = deque.shift(); +const popBack = deque.pop(); + +/* Получить длину двусторонней очереди */ +const size = deque.length; + +/* Проверить, пуста ли двусторонняя очередь */ +const isEmpty = size === 0; +``` + +```typescript title="deque.ts" +/* Инициализация двусторонней очереди */ +// В TypeScript нет встроенной двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь +const deque: number[] = []; + +/* Поместить элементы в очередь */ +deque.push(2); +deque.push(5); +deque.push(4); +// Обратите внимание: поскольку это массив, метод unshift() имеет сложность O(n) +deque.unshift(3); +deque.unshift(1); + +/* Просмотреть элементы */ +const peekFirst: number = deque[0]; +const peekLast: number = deque[deque.length - 1]; + +/* Извлечь элементы из очереди */ +// Обратите внимание: поскольку это массив, метод shift() имеет сложность O(n) +const popFront: number = deque.shift() as number; +const popBack: number = deque.pop() as number; + +/* Получить длину двусторонней очереди */ +const size: number = deque.length; + +/* Проверить, пуста ли двусторонняя очередь */ +const isEmpty: boolean = size === 0; +``` + +```dart title="deque.dart" +/* Инициализация двусторонней очереди */ +// В Dart Queue определена как двусторонняя очередь +Queue deque = Queue(); + +/* Поместить элементы в очередь */ +deque.addLast(2); // Добавить в хвост +deque.addLast(5); +deque.addLast(4); +deque.addFirst(3); // Добавить в голову +deque.addFirst(1); + +/* Просмотреть элементы */ +int peekFirst = deque.first; // Элемент в голове +int peekLast = deque.last; // Элемент в хвосте + +/* Извлечь элементы из очереди */ +int popFirst = deque.removeFirst(); // Извлечь элемент из головы +int popLast = deque.removeLast(); // Извлечь элемент из хвоста + +/* Получить длину двусторонней очереди */ +int size = deque.length; + +/* Проверить, пуста ли двусторонняя очередь */ +bool isEmpty = deque.isEmpty; +``` + +```rust title="deque.rs" +/* Инициализация двусторонней очереди */ +let mut deque: VecDeque = VecDeque::new(); + +/* Поместить элементы в очередь */ +deque.push_back(2); // Добавить в хвост +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // Добавить в голову +deque.push_front(1); + +/* Просмотреть элементы */ +if let Some(front) = deque.front() { // Элемент в голове +} +if let Some(rear) = deque.back() { // Элемент в хвосте +} + +/* Извлечь элементы из очереди */ +if let Some(pop_front) = deque.pop_front() { // Извлечь элемент из головы +} +if let Some(pop_rear) = deque.pop_back() { // Извлечь элемент из хвоста +} + +/* Получить длину двусторонней очереди */ +let size = deque.len(); + +/* Проверить, пуста ли двусторонняя очередь */ +let is_empty = deque.is_empty(); +``` + +```c title="deque.c" +// В C нет встроенной двусторонней очереди +``` + +```kotlin title="deque.kt" +/* Инициализация двусторонней очереди */ +val deque = LinkedList() + +/* Поместить элементы в очередь */ +deque.offerLast(2) // Добавить в хвост +deque.offerLast(5) +deque.offerLast(4) +deque.offerFirst(3) // Добавить в голову +deque.offerFirst(1) + +/* Просмотреть элементы */ +val peekFirst = deque.peekFirst() // Элемент в голове +val peekLast = deque.peekLast() // Элемент в хвосте + +/* Извлечь элементы из очереди */ +val popFirst = deque.pollFirst() // Извлечь элемент из головы +val popLast = deque.pollLast() // Извлечь элемент из хвоста + +/* Получить длину двусторонней очереди */ +val size = deque.size + +/* Проверить, пуста ли двусторонняя очередь */ +val isEmpty = deque.isEmpty() +``` + +```ruby title="deque.rb" +# Инициализация двусторонней очереди +# В Ruby нет встроенной двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь +deque = [] + +# Поместить элементы в очередь +deque << 2 +deque << 5 +deque << 4 +# Обратите внимание: поскольку это массив, метод Array#unshift имеет сложность O(n) +deque.unshift(3) +deque.unshift(1) + +# Просмотреть элементы +peek_first = deque.first +peek_last = deque.last + +# Извлечь элементы из очереди +# Обратите внимание: поскольку это массив, метод Array#shift имеет сложность O(n) +pop_front = deque.shift +pop_back = deque.pop + +# Получить длину двусторонней очереди +size = deque.length + +# Проверить, пуста ли двусторонняя очередь +is_empty = size.zero? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8E%D1%8E%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BC%D0%B5%D1%81%D1%82%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20deq.append%282%29%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D1%83%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8F%D1%8F%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20print%28%22%D0%AD%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20front%20%3D%22%2C%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20print%28%22%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20rear%20%3D%22%2C%20rear%29%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%B0%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20print%28%22%D0%AD%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%2C%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9%20%D0%B8%D0%B7%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D1%8B%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%2C%20pop_front%20%3D%22%2C%20pop_front%29%0A%20%20%20%20print%28%22deque%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20%D0%B8%D0%B7%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D1%8B%20%3D%22%2C%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20print%28%22%D0%AD%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%2C%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9%20%D0%B8%D0%B7%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%D0%B0%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%2C%20pop_rear%20%3D%22%2C%20pop_rear%29%0A%20%20%20%20print%28%22deque%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20%D0%B8%D0%B7%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%D0%B0%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BB%D0%B8%D0%BD%D1%83%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D0%B5%D0%B9%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22%D0%94%D0%BB%D0%B8%D0%BD%D0%B0%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D0%B5%D0%B9%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8F%D1%8F%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22%D0%9F%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8F%D1%8F%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_stack_and_queue/queue.md b/ru/codes/snippets/chapter_stack_and_queue/queue.md new file mode 100644 index 000000000..1a0ccc6be --- /dev/null +++ b/ru/codes/snippets/chapter_stack_and_queue/queue.md @@ -0,0 +1,313 @@ + +```python title="queue.py" +from collections import deque + +# Инициализация очереди +# В Python обычно используют двустороннюю очередь deque как обычную очередь +# Хотя queue.Queue() является "чистой" очередью, она не слишком удобна, поэтому ее не рекомендуют +que: deque[int] = deque() + +# Поместить элементы в очередь +que.append(1) +que.append(3) +que.append(2) +que.append(5) +que.append(4) + +# Просмотреть элемент в голове очереди +front: int = que[0] + +# Извлечь элемент из очереди +pop: int = que.popleft() + +# Получить длину очереди +size: int = len(que) + +# Проверить, пуста ли очередь +is_empty: bool = len(que) == 0 +``` + +```cpp title="queue.cpp" +/* Инициализация очереди */ +queue queue; + +/* Поместить элементы в очередь */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* Просмотреть элемент в голове очереди */ +int front = queue.front(); + +/* Извлечь элемент из очереди */ +queue.pop(); + +/* Получить длину очереди */ +int size = queue.size(); + +/* Проверить, пуста ли очередь */ +bool empty = queue.empty(); +``` + +```java title="queue.java" +/* Инициализация очереди */ +Queue queue = new LinkedList<>(); + +/* Поместить элементы в очередь */ +queue.offer(1); +queue.offer(3); +queue.offer(2); +queue.offer(5); +queue.offer(4); + +/* Просмотреть элемент в голове очереди */ +int peek = queue.peek(); + +/* Извлечь элемент из очереди */ +int pop = queue.poll(); + +/* Получить длину очереди */ +int size = queue.size(); + +/* Проверить, пуста ли очередь */ +boolean isEmpty = queue.isEmpty(); +``` + +```csharp title="queue.cs" +/* Инициализация очереди */ +Queue queue = new(); + +/* Поместить элементы в очередь */ +queue.Enqueue(1); +queue.Enqueue(3); +queue.Enqueue(2); +queue.Enqueue(5); +queue.Enqueue(4); + +/* Просмотреть элемент в голове очереди */ +int peek = queue.Peek(); + +/* Извлечь элемент из очереди */ +int pop = queue.Dequeue(); + +/* Получить длину очереди */ +int size = queue.Count; + +/* Проверить, пуста ли очередь */ +bool isEmpty = queue.Count == 0; +``` + +```go title="queue_test.go" +/* Инициализация очереди */ +// В Go очередь обычно реализуют через list +queue := list.New() + +/* Поместить элементы в очередь */ +queue.PushBack(1) +queue.PushBack(3) +queue.PushBack(2) +queue.PushBack(5) +queue.PushBack(4) + +/* Просмотреть элемент в голове очереди */ +peek := queue.Front() + +/* Извлечь элемент из очереди */ +pop := queue.Front() +queue.Remove(pop) + +/* Получить длину очереди */ +size := queue.Len() + +/* Проверить, пуста ли очередь */ +isEmpty := queue.Len() == 0 +``` + +```swift title="queue.swift" +/* Инициализация очереди */ +// В Swift нет встроенного класса очереди, поэтому можно использовать Array как очередь +var queue: [Int] = [] + +/* Поместить элементы в очередь */ +queue.append(1) +queue.append(3) +queue.append(2) +queue.append(5) +queue.append(4) + +/* Просмотреть элемент в голове очереди */ +let peek = queue.first! + +/* Извлечь элемент из очереди */ +// Поскольку в основе лежит массив, removeFirst имеет сложность O(n) +let pop = queue.removeFirst() + +/* Получить длину очереди */ +let size = queue.count + +/* Проверить, пуста ли очередь */ +let isEmpty = queue.isEmpty +``` + +```javascript title="queue.js" +/* Инициализация очереди */ +// В JavaScript нет встроенной очереди, поэтому можно использовать Array как очередь +const queue = []; + +/* Поместить элементы в очередь */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* Просмотреть элемент в голове очереди */ +const peek = queue[0]; + +/* Извлечь элемент из очереди */ +// В основе лежит массив, поэтому shift() имеет сложность O(n) +const pop = queue.shift(); + +/* Получить длину очереди */ +const size = queue.length; + +/* Проверить, пуста ли очередь */ +const empty = queue.length === 0; +``` + +```typescript title="queue.ts" +/* Инициализация очереди */ +// В TypeScript нет встроенной очереди, поэтому можно использовать Array как очередь +const queue: number[] = []; + +/* Поместить элементы в очередь */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* Просмотреть элемент в голове очереди */ +const peek = queue[0]; + +/* Извлечь элемент из очереди */ +// В основе лежит массив, поэтому shift() имеет сложность O(n) +const pop = queue.shift(); + +/* Получить длину очереди */ +const size = queue.length; + +/* Проверить, пуста ли очередь */ +const empty = queue.length === 0; +``` + +```dart title="queue.dart" +/* Инициализация очереди */ +// В Dart класс Queue является двусторонней очередью и может использоваться как обычная очередь +Queue queue = Queue(); + +/* Поместить элементы в очередь */ +queue.add(1); +queue.add(3); +queue.add(2); +queue.add(5); +queue.add(4); + +/* Просмотреть элемент в голове очереди */ +int peek = queue.first; + +/* Извлечь элемент из очереди */ +int pop = queue.removeFirst(); + +/* Получить длину очереди */ +int size = queue.length; + +/* Проверить, пуста ли очередь */ +bool isEmpty = queue.isEmpty; +``` + +```rust title="queue.rs" +/* Инициализация двусторонней очереди */ +// В Rust двусторонняя очередь может использоваться как обычная очередь +let mut deque: VecDeque = VecDeque::new(); + +/* Поместить элементы в очередь */ +deque.push_back(1); +deque.push_back(3); +deque.push_back(2); +deque.push_back(5); +deque.push_back(4); + +/* Просмотреть элемент в голове очереди */ +if let Some(front) = deque.front() { +} + +/* Извлечь элемент из очереди */ +if let Some(pop) = deque.pop_front() { +} + +/* Получить длину очереди */ +let size = deque.len(); + +/* Проверить, пуста ли очередь */ +let is_empty = deque.is_empty(); +``` + +```c title="queue.c" +// В C нет встроенной очереди +``` + +```kotlin title="queue.kt" +/* Инициализация очереди */ +val queue = LinkedList() + +/* Поместить элементы в очередь */ +queue.offer(1) +queue.offer(3) +queue.offer(2) +queue.offer(5) +queue.offer(4) + +/* Просмотреть элемент в голове очереди */ +val peek = queue.peek() + +/* Извлечь элемент из очереди */ +val pop = queue.poll() + +/* Получить длину очереди */ +val size = queue.size + +/* Проверить, пуста ли очередь */ +val isEmpty = queue.isEmpty() +``` + +```ruby title="queue.rb" +# Инициализация очереди +# Встроенная очередь в Ruby (Thread::Queue) не имеет методов peek и traverse, поэтому можно использовать Array как очередь +queue = [] + +# Поместить элементы в очередь +queue.push(1) +queue.push(3) +queue.push(2) +queue.push(5) +queue.push(4) + +# Просмотреть элемент очереди +peek = queue.first + +# Извлечь элемент из очереди +# Обратите внимание: поскольку это массив, метод Array#shift имеет сложность O(n) +pop = queue.shift + +# Получить длину очереди +size = queue.length + +# Проверить, пуста ли очередь +is_empty = queue.empty? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20%23%20%D0%92%20Python%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8E%D1%8E%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20deque%20%D0%BE%D0%B1%D1%8B%D1%87%D0%BD%D0%BE%20%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D1%83%D1%8E%D1%82%20%D0%BA%D0%B0%D0%BA%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20%23%20%D0%A5%D0%BE%D1%82%D1%8F%20queue.Queue%28%29%20%D1%8F%D0%B2%D0%BB%D1%8F%D0%B5%D1%82%D1%81%D1%8F%20%D0%BD%D0%B0%D1%81%D1%82%D0%BE%D1%8F%D1%89%D0%B8%D0%BC%20%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%BE%D0%BC%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%2C%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%D1%81%D1%8F%20%D0%B8%D0%BC%20%D0%BD%D0%B5%20%D1%81%D0%BB%D0%B8%D1%88%D0%BA%D0%BE%D0%BC%20%D1%83%D0%B4%D0%BE%D0%B1%D0%BD%D0%BE%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BC%D0%B5%D1%81%D1%82%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22%D0%AD%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20front%20%3D%22%2C%20front%29%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22que%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BB%D0%B8%D0%BD%D1%83%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22%D0%94%D0%BB%D0%B8%D0%BD%D0%B0%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22%D0%9F%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_stack_and_queue/stack.md b/ru/codes/snippets/chapter_stack_and_queue/stack.md new file mode 100644 index 000000000..84313a9c7 --- /dev/null +++ b/ru/codes/snippets/chapter_stack_and_queue/stack.md @@ -0,0 +1,304 @@ + +```python title="stack.py" +# Инициализация стека +# В Python нет встроенного класса стека, поэтому можно использовать list как стек +stack: list[int] = [] + +# Поместить элементы в стек +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +# Просмотреть верхний элемент +peek: int = stack[-1] + +# Извлечь элемент +pop: int = stack.pop() + +# Получить длину стека +size: int = len(stack) + +# Проверить, пуст ли стек +is_empty: bool = len(stack) == 0 +``` + +```cpp title="stack.cpp" +/* Инициализация стека */ +stack stack; + +/* Поместить элементы в стек */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Просмотреть верхний элемент */ +int top = stack.top(); + +/* Извлечь элемент */ +stack.pop(); // Без возвращаемого значения + +/* Получить длину стека */ +int size = stack.size(); + +/* Проверить, пуст ли стек */ +bool empty = stack.empty(); +``` + +```java title="stack.java" +/* Инициализация стека */ +Stack stack = new Stack<>(); + +/* Поместить элементы в стек */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Просмотреть верхний элемент */ +int peek = stack.peek(); + +/* Извлечь элемент */ +int pop = stack.pop(); + +/* Получить длину стека */ +int size = stack.size(); + +/* Проверить, пуст ли стек */ +boolean isEmpty = stack.isEmpty(); +``` + +```csharp title="stack.cs" +/* Инициализация стека */ +Stack stack = new(); + +/* Поместить элементы в стек */ +stack.Push(1); +stack.Push(3); +stack.Push(2); +stack.Push(5); +stack.Push(4); + +/* Просмотреть верхний элемент */ +int peek = stack.Peek(); + +/* Извлечь элемент */ +int pop = stack.Pop(); + +/* Получить длину стека */ +int size = stack.Count; + +/* Проверить, пуст ли стек */ +bool isEmpty = stack.Count == 0; +``` + +```go title="stack_test.go" +/* Инициализация стека */ +// В Go рекомендуется использовать Slice как стек +var stack []int + +/* Поместить элементы в стек */ +stack = append(stack, 1) +stack = append(stack, 3) +stack = append(stack, 2) +stack = append(stack, 5) +stack = append(stack, 4) + +/* Просмотреть верхний элемент */ +peek := stack[len(stack)-1] + +/* Извлечь элемент */ +pop := stack[len(stack)-1] +stack = stack[:len(stack)-1] + +/* Получить длину стека */ +size := len(stack) + +/* Проверить, пуст ли стек */ +isEmpty := len(stack) == 0 +``` + +```swift title="stack.swift" +/* Инициализация стека */ +// В Swift нет встроенного класса стека, поэтому можно использовать Array как стек +var stack: [Int] = [] + +/* Поместить элементы в стек */ +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +/* Просмотреть верхний элемент */ +let peek = stack.last! + +/* Извлечь элемент */ +let pop = stack.removeLast() + +/* Получить длину стека */ +let size = stack.count + +/* Проверить, пуст ли стек */ +let isEmpty = stack.isEmpty +``` + +```javascript title="stack.js" +/* Инициализация стека */ +// В JavaScript нет встроенного класса стека, поэтому можно использовать Array как стек +const stack = []; + +/* Поместить элементы в стек */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Просмотреть верхний элемент */ +const peek = stack[stack.length-1]; + +/* Извлечь элемент */ +const pop = stack.pop(); + +/* Получить длину стека */ +const size = stack.length; + +/* Проверить, пуст ли стек */ +const is_empty = stack.length === 0; +``` + +```typescript title="stack.ts" +/* Инициализация стека */ +// В TypeScript нет встроенного класса стека, поэтому можно использовать Array как стек +const stack: number[] = []; + +/* Поместить элементы в стек */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Просмотреть верхний элемент */ +const peek = stack[stack.length - 1]; + +/* Извлечь элемент */ +const pop = stack.pop(); + +/* Получить длину стека */ +const size = stack.length; + +/* Проверить, пуст ли стек */ +const is_empty = stack.length === 0; +``` + +```dart title="stack.dart" +/* Инициализация стека */ +// В Dart нет встроенного класса стека, поэтому можно использовать List как стек +List stack = []; + +/* Поместить элементы в стек */ +stack.add(1); +stack.add(3); +stack.add(2); +stack.add(5); +stack.add(4); + +/* Просмотреть верхний элемент */ +int peek = stack.last; + +/* Извлечь элемент */ +int pop = stack.removeLast(); + +/* Получить длину стека */ +int size = stack.length; + +/* Проверить, пуст ли стек */ +bool isEmpty = stack.isEmpty; +``` + +```rust title="stack.rs" +/* Инициализация стека */ +// Используем Vec как стек +let mut stack: Vec = Vec::new(); + +/* Поместить элементы в стек */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* Просмотреть верхний элемент */ +let top = stack.last().unwrap(); + +/* Извлечь элемент */ +let pop = stack.pop().unwrap(); + +/* Получить длину стека */ +let size = stack.len(); + +/* Проверить, пуст ли стек */ +let is_empty = stack.is_empty(); +``` + +```c title="stack.c" +// В C нет встроенного стека +``` + +```kotlin title="stack.kt" +/* Инициализация стека */ +val stack = Stack() + +/* Поместить элементы в стек */ +stack.push(1) +stack.push(3) +stack.push(2) +stack.push(5) +stack.push(4) + +/* Просмотреть верхний элемент */ +val peek = stack.peek() + +/* Извлечь элемент */ +val pop = stack.pop() + +/* Получить длину стека */ +val size = stack.size + +/* Проверить, пуст ли стек */ +val isEmpty = stack.isEmpty() +``` + +```ruby title="stack.rb" +# Инициализация стека +# В Ruby нет встроенного класса стека, поэтому можно использовать Array как стек +stack = [] + +# Поместить элементы в стек +stack << 1 +stack << 3 +stack << 2 +stack << 5 +stack << 4 + +# Просмотреть верхний элемент +peek = stack.last + +# Извлечь элемент +pop = stack.pop + +# Получить длину стека +size = stack.length + +# Проверить, пуст ли стек +is_empty = stack.empty? +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D1%82%D0%B5%D0%BA%0A%20%20%20%20%23%20%D0%92%20Python%20%D0%BD%D0%B5%D1%82%20%D0%B2%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%BD%D0%BE%D0%B3%D0%BE%20%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%B0%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%2C%20%D0%BF%D0%BE%D1%8D%D1%82%D0%BE%D0%BC%D1%83%20list%20%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%20%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BA%D0%B0%D0%BA%20%D1%81%D1%82%D0%B5%D0%BA%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BC%D0%B5%D1%81%D1%82%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D1%81%D1%82%D0%B5%D0%BA%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22%D1%81%D1%82%D0%B5%D0%BA%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22%D0%92%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%20peek%20%3D%22%2C%20peek%29%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9%20%D0%B8%D0%B7%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%D0%9F%D0%BE%D1%81%D0%BB%D0%B5%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BB%D0%B8%D0%BD%D1%83%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22%D0%94%D0%BB%D0%B8%D0%BD%D0%B0%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%82%D1%83%D1%80%D0%B0%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22%D0%9F%D1%83%D1%81%D1%82%20%D0%BB%D0%B8%20%D1%81%D1%82%D0%B5%D0%BA%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_tree/array_representation_of_tree.md b/ru/codes/snippets/chapter_tree/array_representation_of_tree.md new file mode 100644 index 000000000..049eeac37 --- /dev/null +++ b/ru/codes/snippets/chapter_tree/array_representation_of_tree.md @@ -0,0 +1,78 @@ + +```python title="" +# Представление двоичного дерева массивом +# Используем None для обозначения пустых позиций +tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] +``` + +```cpp title="" +/* Представление двоичного дерева массивом */ +// Используем максимальное значение int, INT_MAX, для обозначения пустых позиций +vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```java title="" +/* Представление двоичного дерева массивом */ +// Используя обертку Integer для int, можно применять null для обозначения пустых позиций +Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; +``` + +```csharp title="" +/* Представление двоичного дерева массивом */ +// Используя nullable-тип int? , можно применять null для обозначения пустых позиций +int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```go title="" +/* Представление двоичного дерева массивом */ +// Используем срез типа any, чтобы можно было применять nil для обозначения пустых позиций +tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} +``` + +```swift title="" +/* Представление двоичного дерева массивом */ +// Используя nullable-тип Int? , можно применять nil для обозначения пустых позиций +let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` + +```javascript title="" +/* Представление двоичного дерева массивом */ +// Используем null для обозначения пустых позиций +let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```typescript title="" +/* Представление двоичного дерева массивом */ +// Используем null для обозначения пустых позиций +let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```dart title="" +/* Представление двоичного дерева массивом */ +// Используя nullable-тип int? , можно применять null для обозначения пустых позиций +List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```rust title="" +/* Представление двоичного дерева массивом */ +// Используем None для обозначения пустых позиций +let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; +``` + +```c title="" +/* Представление двоичного дерева массивом */ +// Используем максимальное значение int для обозначения пустых позиций, поэтому узлы не должны принимать значение INT_MAX +int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```kotlin title="" +/* Представление двоичного дерева массивом */ +// Используем null для обозначения пустых позиций +val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) +``` + +```ruby title="" +### Представление двоичного дерева массивом ### +# Используем nil для обозначения пустых позиций +tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` diff --git a/ru/codes/snippets/chapter_tree/avl_tree.md b/ru/codes/snippets/chapter_tree/avl_tree.md new file mode 100644 index 000000000..71d36132d --- /dev/null +++ b/ru/codes/snippets/chapter_tree/avl_tree.md @@ -0,0 +1,182 @@ + +```python title="" +class TreeNode: + """Класс узла AVL-дерева""" + def __init__(self, val: int): + self.val: int = val # Значение узла + self.height: int = 0 # Высота узла + self.left: TreeNode | None = None # Ссылка на левого дочернего узла + self.right: TreeNode | None = None # Ссылка на правого дочернего узла +``` + +```cpp title="" +/* Класс узла AVL-дерева */ +struct TreeNode { + int val{}; // Значение узла + int height = 0; // Высота узла + TreeNode *left{}; // Левый дочерний узел + TreeNode *right{}; // Правый дочерний узел + TreeNode() = default; + explicit TreeNode(int x) : val(x){} +}; +``` + +```java title="" +/* Класс узла AVL-дерева */ +class TreeNode { + public int val; // Значение узла + public int height; // Высота узла + public TreeNode left; // Левый дочерний узел + public TreeNode right; // Правый дочерний узел + public TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* Класс узла AVL-дерева */ +class TreeNode(int? x) { + public int? val = x; // Значение узла + public int height; // Высота узла + public TreeNode? left; // Ссылка на левого дочернего узла + public TreeNode? right; // Ссылка на правого дочернего узла +} +``` + +```go title="" +/* Структура узла AVL-дерева */ +type TreeNode struct { + Val int // Значение узла + Height int // Высота узла + Left *TreeNode // Ссылка на левого дочернего узла + Right *TreeNode // Ссылка на правого дочернего узла +} +``` + +```swift title="" +/* Класс узла AVL-дерева */ +class TreeNode { + var val: Int // Значение узла + var height: Int // Высота узла + var left: TreeNode? // Левый дочерний узел + var right: TreeNode? // Правый дочерний узел + + init(x: Int) { + val = x + height = 0 + } +} +``` + +```javascript title="" +/* Класс узла AVL-дерева */ +class TreeNode { + val; // Значение узла + height; // Высота узла + left; // Указатель на левого дочернего узла + right; // Указатель на правого дочернего узла + constructor(val, left, right, height) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* Класс узла AVL-дерева */ +class TreeNode { + val: number; // Значение узла + height: number; // Высота узла + left: TreeNode | null; // Указатель на левого дочернего узла + right: TreeNode | null; // Указатель на правого дочернего узла + constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```dart title="" +/* Класс узла AVL-дерева */ +class TreeNode { + int val; // Значение узла + int height; // Высота узла + TreeNode? left; // Левый дочерний узел + TreeNode? right; // Правый дочерний узел + TreeNode(this.val, [this.height = 0, this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* Структура узла AVL-дерева */ +struct TreeNode { + val: i32, // Значение узла + height: i32, // Высота узла + left: Option>>, // Левый дочерний узел + right: Option>>, // Правый дочерний узел +} + +impl TreeNode { + /* Конструктор */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + height: 0, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* Структура узла AVL-дерева */ +typedef struct TreeNode { + int val; + int height; + struct TreeNode *left; + struct TreeNode *right; +} TreeNode; + +/* Конструктор */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* Класс узла AVL-дерева */ +class TreeNode(val _val: Int) { // Значение узла + var height: Int = 0 // Высота узла + var left: TreeNode? = null // Левый дочерний узел + var right: TreeNode? = null // Правый дочерний узел +} +``` + +```ruby title="" +### Класс узла AVL-дерева ### +class TreeNode + attr_accessor :val # Значение узла + attr_accessor :height # Высота узла + attr_accessor :left # Ссылка на левого дочернего узла + attr_accessor :right # Ссылка на правого дочернего узла + + def initialize(val) + @val = val + @height = 0 + end +end +``` diff --git a/ru/codes/snippets/chapter_tree/binary_tree.md b/ru/codes/snippets/chapter_tree/binary_tree.md new file mode 100644 index 000000000..bc9c2bf15 --- /dev/null +++ b/ru/codes/snippets/chapter_tree/binary_tree.md @@ -0,0 +1,502 @@ + +```python title="" +class TreeNode: + """Класс узла двоичного дерева""" + def __init__(self, val: int): + self.val: int = val # Значение узла + self.left: TreeNode | None = None # Ссылка на левого дочернего узла + self.right: TreeNode | None = None # Ссылка на правого дочернего узла +``` + +```cpp title="" +/* Структура узла двоичного дерева */ +struct TreeNode { + int val; // Значение узла + TreeNode *left; // Указатель на левого дочернего узла + TreeNode *right; // Указатель на правого дочернего узла + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; +``` + +```java title="" +/* Класс узла двоичного дерева */ +class TreeNode { + int val; // Значение узла + TreeNode left; // Ссылка на левого дочернего узла + TreeNode right; // Ссылка на правого дочернего узла + TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* Класс узла двоичного дерева */ +class TreeNode(int? x) { + public int? val = x; // Значение узла + public TreeNode? left; // Ссылка на левого дочернего узла + public TreeNode? right; // Ссылка на правого дочернего узла +} +``` + +```go title="" +/* Структура узла двоичного дерева */ +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} +/* Конструктор */ +func NewTreeNode(v int) *TreeNode { + return &TreeNode{ + Left: nil, // Указатель на левого дочернего узла + Right: nil, // Указатель на правого дочернего узла + Val: v, // Значение узла + } +} +``` + +```swift title="" +/* Класс узла двоичного дерева */ +class TreeNode { + var val: Int // Значение узла + var left: TreeNode? // Ссылка на левого дочернего узла + var right: TreeNode? // Ссылка на правого дочернего узла + + init(x: Int) { + val = x + } +} +``` + +```javascript title="" +/* Класс узла двоичного дерева */ +class TreeNode { + val; // Значение узла + left; // Указатель на левого дочернего узла + right; // Указатель на правого дочернего узла + constructor(val, left, right) { + this.val = val === undefined ? 0 : val; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* Класс узла двоичного дерева */ +class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; // Значение узла + this.left = left === undefined ? null : left; // Ссылка на левого дочернего узла + this.right = right === undefined ? null : right; // Ссылка на правого дочернего узла + } +} +``` + +```dart title="" +/* Класс узла двоичного дерева */ +class TreeNode { + int val; // Значение узла + TreeNode? left; // Ссылка на левого дочернего узла + TreeNode? right; // Ссылка на правого дочернего узла + TreeNode(this.val, [this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* Структура узла двоичного дерева */ +struct TreeNode { + val: i32, // Значение узла + left: Option>>, // Ссылка на левого дочернего узла + right: Option>>, // Ссылка на правого дочернего узла +} + +impl TreeNode { + /* Конструктор */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* Структура узла двоичного дерева */ +typedef struct TreeNode { + int val; // Значение узла + int height; // Высота узла + struct TreeNode *left; // Указатель на левого дочернего узла + struct TreeNode *right; // Указатель на правого дочернего узла +} TreeNode; + +/* Конструктор */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* Класс узла двоичного дерева */ +class TreeNode(val _val: Int) { // Значение узла + var left: TreeNode? = null // Ссылка на левого дочернего узла + var right: TreeNode? = null // Ссылка на правого дочернего узла +} +``` + +```ruby title="" +### Класс узла двоичного дерева ### +class TreeNode + attr_accessor :val # Значение узла + attr_accessor :left # Ссылка на левого дочернего узла + attr_accessor :right # Ссылка на правого дочернего узла + + def initialize(val) + @val = val + end +end +``` + + +```python title="binary_tree.py" +# Инициализация двоичного дерева +# Инициализация узлов +n1 = TreeNode(val=1) +n2 = TreeNode(val=2) +n3 = TreeNode(val=3) +n4 = TreeNode(val=4) +n5 = TreeNode(val=5) +# Построение ссылок (указателей) между узлами +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```cpp title="binary_tree.cpp" +/* Инициализация двоичного дерева */ +// Инициализация узлов +TreeNode* n1 = new TreeNode(1); +TreeNode* n2 = new TreeNode(2); +TreeNode* n3 = new TreeNode(3); +TreeNode* n4 = new TreeNode(4); +TreeNode* n5 = new TreeNode(5); +// Построение ссылок (указателей) между узлами +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```java title="binary_tree.java" +// Инициализация узлов +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// Построение ссылок (указателей) между узлами +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```csharp title="binary_tree.cs" +/* Инициализация двоичного дерева */ +// Инициализация узлов +TreeNode n1 = new(1); +TreeNode n2 = new(2); +TreeNode n3 = new(3); +TreeNode n4 = new(4); +TreeNode n5 = new(5); +// Построение ссылок (указателей) между узлами +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```go title="binary_tree.go" +/* Инициализация двоичного дерева */ +// Инициализация узлов +n1 := NewTreeNode(1) +n2 := NewTreeNode(2) +n3 := NewTreeNode(3) +n4 := NewTreeNode(4) +n5 := NewTreeNode(5) +// Построение ссылок (указателей) между узлами +n1.Left = n2 +n1.Right = n3 +n2.Left = n4 +n2.Right = n5 +``` + +```swift title="binary_tree.swift" +// Инициализация узлов +let n1 = TreeNode(x: 1) +let n2 = TreeNode(x: 2) +let n3 = TreeNode(x: 3) +let n4 = TreeNode(x: 4) +let n5 = TreeNode(x: 5) +// Построение ссылок (указателей) между узлами +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```javascript title="binary_tree.js" +/* Инициализация двоичного дерева */ +// Инициализация узлов +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// Построение ссылок (указателей) между узлами +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```typescript title="binary_tree.ts" +/* Инициализация двоичного дерева */ +// Инициализация узлов +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// Построение ссылок (указателей) между узлами +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```dart title="binary_tree.dart" +/* Инициализация двоичного дерева */ +// Инициализация узлов +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// Построение ссылок (указателей) между узлами +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```rust title="binary_tree.rs" +// Инициализация узлов +let n1 = TreeNode::new(1); +let n2 = TreeNode::new(2); +let n3 = TreeNode::new(3); +let n4 = TreeNode::new(4); +let n5 = TreeNode::new(5); +// Построение ссылок (указателей) между узлами +n1.borrow_mut().left = Some(n2.clone()); +n1.borrow_mut().right = Some(n3); +n2.borrow_mut().left = Some(n4); +n2.borrow_mut().right = Some(n5); +``` + +```c title="binary_tree.c" +/* Инициализация двоичного дерева */ +// Инициализация узлов +TreeNode *n1 = newTreeNode(1); +TreeNode *n2 = newTreeNode(2); +TreeNode *n3 = newTreeNode(3); +TreeNode *n4 = newTreeNode(4); +TreeNode *n5 = newTreeNode(5); +// Построение ссылок (указателей) между узлами +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```kotlin title="binary_tree.kt" +// Инициализация узлов +val n1 = TreeNode(1) +val n2 = TreeNode(2) +val n3 = TreeNode(3) +val n4 = TreeNode(4) +val n5 = TreeNode(5) +// Построение ссылок (указателей) между узлами +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```ruby title="binary_tree.rb" +# Инициализация двоичного дерева +# Инициализация узлов +n1 = TreeNode.new(1) +n2 = TreeNode.new(2) +n3 = TreeNode.new(3) +n4 = TreeNode.new(4) +n5 = TreeNode.new(5) +# Построение ссылок (указателей) между узлами +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%D0%9A%D0%BB%D0%B0%D1%81%D1%81%20%D1%83%D0%B7%D0%BB%D0%B0%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B3%D0%BE%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%B0%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BB%D0%B5%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BF%D1%80%D0%B0%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B5%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%BE%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%D0%9F%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B8%D1%82%D1%8C%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20%D1%83%D0%B7%D0%BB%D0%B0%D0%BC%D0%B8%20%28%D1%83%D0%BA%D0%B0%D0%B7%D0%B0%D1%82%D0%B5%D0%BB%D0%B8%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="binary_tree.py" +# Вставка и удаление узлов +p = TreeNode(0) +# Вставить узел P между n1 -> n2 +n1.left = p +p.left = n2 +# Удалить узел P +n1.left = n2 +``` + +```cpp title="binary_tree.cpp" +/* Вставка и удаление узлов */ +TreeNode* P = new TreeNode(0); +// Вставить узел P между n1 -> n2 +n1->left = P; +P->left = n2; +// Удалить узел P +n1->left = n2; +// Освободить память +delete P; +``` + +```java title="binary_tree.java" +TreeNode P = new TreeNode(0); +// Вставить узел P между n1 -> n2 +n1.left = P; +P.left = n2; +// Удалить узел P +n1.left = n2; +``` + +```csharp title="binary_tree.cs" +/* Вставка и удаление узлов */ +TreeNode P = new(0); +// Вставить узел P между n1 -> n2 +n1.left = P; +P.left = n2; +// Удалить узел P +n1.left = n2; +``` + +```go title="binary_tree.go" +/* Вставка и удаление узлов */ +// Вставить узел P между n1 -> n2 +p := NewTreeNode(0) +n1.Left = p +p.Left = n2 +// Удалить узел P +n1.Left = n2 +``` + +```swift title="binary_tree.swift" +let P = TreeNode(x: 0) +// Вставить узел P между n1 -> n2 +n1.left = P +P.left = n2 +// Удалить узел P +n1.left = n2 +``` + +```javascript title="binary_tree.js" +/* Вставка и удаление узлов */ +let P = new TreeNode(0); +// Вставить узел P между n1 -> n2 +n1.left = P; +P.left = n2; +// Удалить узел P +n1.left = n2; +``` + +```typescript title="binary_tree.ts" +/* Вставка и удаление узлов */ +const P = new TreeNode(0); +// Вставить узел P между n1 -> n2 +n1.left = P; +P.left = n2; +// Удалить узел P +n1.left = n2; +``` + +```dart title="binary_tree.dart" +/* Вставка и удаление узлов */ +TreeNode P = new TreeNode(0); +// Вставить узел P между n1 -> n2 +n1.left = P; +P.left = n2; +// Удалить узел P +n1.left = n2; +``` + +```rust title="binary_tree.rs" +let p = TreeNode::new(0); +// Вставить узел P между n1 -> n2 +n1.borrow_mut().left = Some(p.clone()); +p.borrow_mut().left = Some(n2.clone()); +// Удалить узел p +n1.borrow_mut().left = Some(n2); +``` + +```c title="binary_tree.c" +/* Вставка и удаление узлов */ +TreeNode *P = newTreeNode(0); +// Вставить узел P между n1 -> n2 +n1->left = P; +P->left = n2; +// Удалить узел P +n1->left = n2; +// Освободить память +free(P); +``` + +```kotlin title="binary_tree.kt" +val P = TreeNode(0) +// Вставить узел P между n1 -> n2 +n1.left = P +P.left = n2 +// Удалить узел P +n1.left = n2 +``` + +```ruby title="binary_tree.rb" +# Вставка и удаление узлов +_p = TreeNode.new(0) +# Вставить узел _p между n1 -> n2 +n1.left = _p +_p.left = n2 +# Удалить узел +n1.left = n2 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%D0%9A%D0%BB%D0%B0%D1%81%D1%81%20%D1%83%D0%B7%D0%BB%D0%B0%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B3%D0%BE%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%B0%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BB%D0%B5%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BF%D1%80%D0%B0%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B5%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%BE%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%D0%9F%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B8%D1%82%D1%8C%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20%D1%83%D0%B7%D0%BB%D0%B0%D0%BC%D0%B8%20%28%D1%83%D0%BA%D0%B0%D0%B7%D0%B0%D1%82%D0%B5%D0%BB%D0%B8%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%BA%D0%B0%20%D0%B8%20%D1%83%D0%B4%D0%B0%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%BE%D0%B2%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%20P%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20n1%20-%3E%20n2%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/docs/chapter_array_and_linkedlist/array.md b/ru/docs/chapter_array_and_linkedlist/array.md index 3b6730751..8e7673f6f 100644 --- a/ru/docs/chapter_array_and_linkedlist/array.md +++ b/ru/docs/chapter_array_and_linkedlist/array.md @@ -10,125 +10,13 @@ Существует два способа инициализации массива: без начальных значений и с заданными начальными значениями. Если начальные значения не указаны, большинство языков программирования инициализируют элементы массива нулями: -=== "Python" - - ```python title="array.py" - # Инициализация массива - arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="array.cpp" - /* Инициализация массива */ - // Хранится в стеке - int arr[5] = {}; - int nums[5] = { 1, 3, 2, 5, 4 }; - // Хранится в куче (требуется ручное освобождение памяти) - int* arr1 = new int[5] {}; - int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="array.java" - /* Инициализация массива */ - int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } - int[] nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "C#" - - ```csharp title="array.cs" - /* Инициализация массива */ - int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] - int[] nums = [1, 3, 2, 5, 4]; - ``` - -=== "Go" - - ```go title="array.go" - /* Инициализация массива */ - var arr [5]int - // В Go указание длины ([5]int) создает массив, а отсутствие длины ([]int) - срез - // Поскольку длина массива в Go определяется на этапе компиляции, для задания длины можно использовать только константы - // Чтобы упростить реализацию метода extend(), ниже будем рассматривать срезы (Slice) как массивы (Array) - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="array.swift" - /* Инициализация массива */ - let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] - let nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="array.js" - /* Инициализация массива */ - var arr = new Array(5).fill(0); - var nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="array.ts" - /* Инициализация массива */ - let arr: number[] = new Array(5).fill(0); - let nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="array.dart" - /* Инициализация массива */ - List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="array.rs" - /* Инициализация массива */ - let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] - let slice: &[i32] = &[0; 5]; - // В Rust указание длины ([i32; 5]) создает массив, а отсутствие длины (&[i32]) - срез - // Поскольку длина массива в Rust определяется на этапе компиляции, для задания длины можно использовать только константы - // Vector в Rust обычно используется как динамический массив - // Чтобы упростить реализацию метода extend(), ниже будем рассматривать vector как массив (array) - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="array.c" - /* Инициализация массива */ - int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } - int nums[5] = { 1, 3, 2, 5, 4 }; - ``` - -=== "Kotlin" - - ```kotlin title="array.kt" - /* Инициализация массива */ - var arr = IntArray(5) // { 0, 0, 0, 0, 0 } - var nums = intArrayOf(1, 3, 2, 5, 4) - ``` - -=== "Ruby" - - ```ruby title="array.rb" - # Инициализация массива - arr = Array.new(5, 0) - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_array +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_array_tutor ### Доступ к элементам diff --git a/ru/docs/chapter_array_and_linkedlist/linked_list.md b/ru/docs/chapter_array_and_linkedlist/linked_list.md index 3b2e59e3e..b3fbce904 100644 --- a/ru/docs/chapter_array_and_linkedlist/linked_list.md +++ b/ru/docs/chapter_array_and_linkedlist/linked_list.md @@ -16,174 +16,9 @@ Как показано в коде ниже, узел связного списка `ListNode` хранит не только значение, но и дополнительную ссылку (указатель). Поэтому **при одинаковом объеме данных связный список занимает больше памяти, чем массив**. -=== "Python" - - ```python title="" - class ListNode: - """Класс узла связного списка""" - def __init__(self, val: int): - self.val: int = val # Значение узла - self.next: ListNode | None = None # Ссылка на следующий узел - ``` - -=== "C++" - - ```cpp title="" - /* Структура узла связного списка */ - struct ListNode { - int val; // Значение узла - ListNode *next; // Указатель на следующий узел - ListNode(int x) : val(x), next(nullptr) {} // Конструктор - }; - ``` - -=== "Java" - - ```java title="" - /* Класс узла связного списка */ - class ListNode { - int val; // Значение узла - ListNode next; // Ссылка на следующий узел - ListNode(int x) { val = x; } // Конструктор - } - ``` - -=== "C#" - - ```csharp title="" - /* Класс узла связного списка */ - class ListNode(int x) { // Конструктор - int val = x; // Значение узла - ListNode? next; // Ссылка на следующий узел - } - ``` - -=== "Go" - - ```go title="" - /* Структура узла связного списка */ - type ListNode struct { - Val int // Значение узла - Next *ListNode // Указатель на следующий узел - } - - // NewListNode — функция-конструктор, создающая новый связный список. - func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* Класс узла связного списка */ - class ListNode { - var val: Int // Значение узла - var next: ListNode? // Ссылка на следующий узел - - init(x: Int) { // Конструктор - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* Класс узла связного списка */ - class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // Значение узла - this.next = (next === undefined ? null : next); // Ссылка на следующий узел - } - } - ``` - -=== "TS" - - ```typescript title="" - /* Класс узла связного списка */ - class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // Значение узла - this.next = next === undefined ? null : next; // Ссылка на следующий узел - } - } - ``` - -=== "Dart" - - ```dart title="" - /* Класс узла связного списка */ - class ListNode { - int val; // Значение узла - ListNode? next; // Ссылка на следующий узел - ListNode(this.val, [this.next]); // Конструктор - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - /* Класс узла связного списка */ - #[derive(Debug)] - struct ListNode { - val: i32, // Значение узла - next: Option>>, // Указатель на следующий узел - } - ``` - -=== "C" - - ```c title="" - /* Структура узла связного списка */ - typedef struct ListNode { - int val; // Значение узла - struct ListNode *next; // Указатель на следующий узел - } ListNode; - - /* Конструктор */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Класс узла связного списка */ - // Конструктор - class ListNode(x: Int) { - val _val: Int = x // Значение узла - var next: ListNode? = null // Ссылка на следующий узел - } - ``` - -=== "Ruby" - - ```ruby title="" - # Класс узла связного списка - class ListNode - attr_accessor :val # Значение узла - attr_accessor :next # Ссылка на следующий узел - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end - end - ``` +```snippet +list_node_class +``` ## Основные операции со связным списком @@ -191,231 +26,13 @@ Построение связного списка состоит из двух шагов: сначала нужно инициализировать объекты всех узлов, затем установить ссылочные связи между ними. После завершения инициализации мы можем, начиная с головы списка, последовательно проходить все узлы по ссылке `next`. -=== "Python" - - ```python title="linked_list.py" - # Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 - # Инициализация каждого узла - n0 = ListNode(1) - n1 = ListNode(3) - n2 = ListNode(2) - n3 = ListNode(5) - n4 = ListNode(4) - # Построение ссылок между узлами - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "C++" - - ```cpp title="linked_list.cpp" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - ListNode* n0 = new ListNode(1); - ListNode* n1 = new ListNode(3); - ListNode* n2 = new ListNode(2); - ListNode* n3 = new ListNode(5); - ListNode* n4 = new ListNode(4); - // Построение ссылок между узлами - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Java" - - ```java title="linked_list.java" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - ListNode n0 = new ListNode(1); - ListNode n1 = new ListNode(3); - ListNode n2 = new ListNode(2); - ListNode n3 = new ListNode(5); - ListNode n4 = new ListNode(4); - // Построение ссылок между узлами - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "C#" - - ```csharp title="linked_list.cs" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - ListNode n0 = new(1); - ListNode n1 = new(3); - ListNode n2 = new(2); - ListNode n3 = new(5); - ListNode n4 = new(4); - // Построение ссылок между узлами - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Go" - - ```go title="linked_list.go" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - n0 := NewListNode(1) - n1 := NewListNode(3) - n2 := NewListNode(2) - n3 := NewListNode(5) - n4 := NewListNode(4) - // Построение ссылок между узлами - n0.Next = n1 - n1.Next = n2 - n2.Next = n3 - n3.Next = n4 - ``` - -=== "Swift" - - ```swift title="linked_list.swift" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - let n0 = ListNode(x: 1) - let n1 = ListNode(x: 3) - let n2 = ListNode(x: 2) - let n3 = ListNode(x: 5) - let n4 = ListNode(x: 4) - // Построение ссылок между узлами - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "JS" - - ```javascript title="linked_list.js" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // Построение ссылок между узлами - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "TS" - - ```typescript title="linked_list.ts" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // Построение ссылок между узлами - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Dart" - - ```dart title="linked_list.dart" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */\ - // Инициализация каждого узла - ListNode n0 = ListNode(1); - ListNode n1 = ListNode(3); - ListNode n2 = ListNode(2); - ListNode n3 = ListNode(5); - ListNode n4 = ListNode(4); - // Построение ссылок между узлами - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Rust" - - ```rust title="linked_list.rs" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); - let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); - let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); - let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); - let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); - - // Построение ссылок между узлами - n0.borrow_mut().next = Some(n1.clone()); - n1.borrow_mut().next = Some(n2.clone()); - n2.borrow_mut().next = Some(n3.clone()); - n3.borrow_mut().next = Some(n4.clone()); - ``` - -=== "C" - - ```c title="linked_list.c" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - ListNode* n0 = newListNode(1); - ListNode* n1 = newListNode(3); - ListNode* n2 = newListNode(2); - ListNode* n3 = newListNode(5); - ListNode* n4 = newListNode(4); - // Построение ссылок между узлами - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Kotlin" - - ```kotlin title="linked_list.kt" - /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ - // Инициализация каждого узла - val n0 = ListNode(1) - val n1 = ListNode(3) - val n2 = ListNode(2) - val n3 = ListNode(5) - val n4 = ListNode(4) - // Построение ссылок между узлами - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Ruby" - - ```ruby title="linked_list.rb" - # Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 - # Инициализация каждого узла - n0 = ListNode.new(1) - n1 = ListNode.new(3) - n2 = ListNode.new(2) - n3 = ListNode.new(5) - n4 = ListNode.new(4) - # Построение ссылок между узлами - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` +```snippet +init_linked_list +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D1%83%D0%B7%D0%B5%D0%BB%D0%BA%D0%BB%D0%B0%D1%81%D1%81%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D1%81%D0%BB%D0%B5%D0%B4%D1%83%D1%8E%D1%89%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BA%D0%B0%D0%B6%D0%B4%D1%8B%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20%D0%9F%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B8%D1%82%D1%8C%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20%D1%83%D0%B7%D0%BB%D0%B0%D0%BC%D0%B8%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_linked_list_tutor Массив в целом - это одна переменная: например, массив `nums` содержит элементы `nums[0]` , `nums[1]` и т.д. Связный список же состоит из множества независимых объектов-узлов. **Обычно в качестве обозначения всего связного списка используют головной узел**. Например, в приведенном выше коде связный список можно обозначить как `n0` . @@ -482,203 +99,9 @@ - **Кольцевой (циклический) список**: если заставить хвостовой узел односвязного списка указывать на головной, то есть соединить хвост с головой, получится циклический список. В циклическом списке любой узел можно рассматривать как головной. - **Двусвязный список**: по сравнению с односвязным списком двусвязный хранит ссылки в двух направлениях. Определение узла двусвязного списка включает как ссылку на следующий узел, так и ссылку на предыдущий узел. По сравнению с односвязным списком двусвязный более гибок и позволяет обходить список в обе стороны, но за это приходится платить дополнительной памятью. -=== "Python" - - ```python title="" - class ListNode: - """Класс узла двусвязного списка""" - def __init__(self, val: int): - self.val: int = val # Значение узла - self.next: ListNode | None = None # Ссылка на следующий узел - self.prev: ListNode | None = None # Ссылка на предыдущий узел - ``` - -=== "C++" - - ```cpp title="" - /* Структура узла двусвязного списка */ - struct ListNode { - int val; // Значение узла - ListNode *next; // Указатель на следующий узел - ListNode *prev; // Указатель на предыдущий узел - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // Конструктор - }; - ``` - -=== "Java" - - ```java title="" - /* Класс узла двусвязного списка */ - class ListNode { - int val; // Значение узла - ListNode next; // Ссылка на следующий узел - ListNode prev; // Ссылка на предыдущий узел - ListNode(int x) { val = x; } // Конструктор - } - ``` - -=== "C#" - - ```csharp title="" - /* Класс узла двусвязного списка */ - class ListNode(int x) { // Конструктор - int val = x; // Значение узла - ListNode next; // Ссылка на следующий узел - ListNode prev; // Ссылка на предыдущий узел - } - ``` - -=== "Go" - - ```go title="" - /* Структура узла двусвязного списка */ - type DoublyListNode struct { - Val int // Значение узла - Next *DoublyListNode // Указатель на следующий узел - Prev *DoublyListNode // Указатель на предыдущий узел - } - - // NewDoublyListNode инициализирует узел двусвязного списка. - func NewDoublyListNode(val int) *DoublyListNode { - return &DoublyListNode{ - Val: val, - Next: nil, - Prev: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* Класс узла двусвязного списка */ - class ListNode { - var val: Int // Значение узла - var next: ListNode? // Ссылка на следующий узел - var prev: ListNode? // Ссылка на предыдущий узел - - init(x: Int) { // Конструктор - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* Класс узла двусвязного списка */ - class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // Значение узла - this.next = next === undefined ? null : next; // Ссылка на следующий узел - this.prev = prev === undefined ? null : prev; // Ссылка на предыдущий узел - } - } - ``` - -=== "TS" - - ```typescript title="" - /* Класс узла двусвязного списка */ - class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // Значение узла - this.next = next === undefined ? null : next; // Ссылка на следующий узел - this.prev = prev === undefined ? null : prev; // Ссылка на предыдущий узел - } - } - ``` - -=== "Dart" - - ```dart title="" - /* Класс узла двусвязного списка */ - class ListNode { - int val; // Значение узла - ListNode? next; // Ссылка на следующий узел - ListNode? prev; // Ссылка на предыдущий узел - ListNode(this.val, [this.next, this.prev]); // Конструктор - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* Тип узла двусвязного списка */ - #[derive(Debug)] - struct ListNode { - val: i32, // Значение узла - next: Option>>, // Указатель на следующий узел - prev: Option>>, // Указатель на предыдущий узел - } - - /* Конструктор */ - impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } - } - ``` - -=== "C" - - ```c title="" - /* Структура узла двусвязного списка */ - typedef struct ListNode { - int val; // Значение узла - struct ListNode *next; // Указатель на следующий узел - struct ListNode *prev; // Указатель на предыдущий узел - } ListNode; - - /* Конструктор */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Класс узла двусвязного списка */ - // Конструктор - class ListNode(x: Int) { - val _val: Int = x // Значение узла - var next: ListNode? = null // Ссылка на следующий узел - var prev: ListNode? = null // Ссылка на предыдущий узел - } - ``` - -=== "Ruby" - - ```ruby title="" - # Класс узла двусвязного списка - class ListNode - attr_accessor :val # Значение узла - attr_accessor :next # Ссылка на следующий узел - attr_accessor :prev # Ссылка на предыдущий узел - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end - end - ``` +```snippet +doubly_list_node_class +``` ![Распространенные типы связных списков](linked_list.assets/linkedlist_common_types.svg) diff --git a/ru/docs/chapter_array_and_linkedlist/list.md b/ru/docs/chapter_array_and_linkedlist/list.md index 479aa0d46..b2f2e0c3e 100644 --- a/ru/docs/chapter_array_and_linkedlist/list.md +++ b/ru/docs/chapter_array_and_linkedlist/list.md @@ -17,934 +17,73 @@ Обычно используются два метода инициализации: без начальных значений и с заданием начальных значений: -=== "Python" - - ```python title="list.py" - # Инициализация списка - # Без начальных значений - nums1: list[int] = [] - # С начальными значениями - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Инициализация списка */ - // Обратите внимание: в C++ vector соответствует описываемому здесь nums - // Без начальных значений - vector nums1; - // С начальными значениями - vector nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="list.java" - /* Инициализация списка */ - // Без начальных значений - List nums1 = new ArrayList<>(); - // С начальными значениями (обратите внимание: элементы массива должны использовать обертку Integer[] вместо int[]) - Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; - List nums = new ArrayList<>(Arrays.asList(numbers)); - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Инициализация списка */ - // Без начальных значений - List nums1 = []; - // С начальными значениями - int[] numbers = [1, 3, 2, 5, 4]; - List nums = [.. numbers]; - ``` - -=== "Go" - - ```go title="list_test.go" - /* Инициализация списка */ - // Без начальных значений - nums1 := []int{} - // С начальными значениями - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Инициализация списка */ - // Без начальных значений - let nums1: [Int] = [] - // С начальными значениями - var nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="list.js" - /* Инициализация списка */ - // Без начальных значений - const nums1 = []; - // С начальными значениями - const nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Инициализация списка */ - // Без начальных значений - const nums1: number[] = []; - // С начальными значениями - const nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Инициализация списка */ - // Без начальных значений - List nums1 = []; - // С начальными значениями - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Инициализация списка */ - // Без начальных значений - let nums1: Vec = Vec::new(); - // С начальными значениями - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="list.c" - // В C нет встроенного динамического массива - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Инициализация списка */ - // Без начальных значений - var nums1 = listOf() - // С начальными значениями - var numbers = arrayOf(1, 3, 2, 5, 4) - var nums = numbers.toMutableList() - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Инициализация списка - # Без начальных значений - nums1 = [] - # С начальными значениями - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_list +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20%23%20%D0%91%D0%B5%D0%B7%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D1%85%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B9%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%D0%A1%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%BC%D0%B8%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%D0%BC%D0%B8%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_list_tutor ### Доступ к элементам Поскольку в этом разделе список рассматривается как структура на основе динамического массива, доступ к элементам и изменение их значений можно выполнять за $O(1)$ времени, что очень эффективно. -=== "Python" - - ```python title="list.py" - # Доступ к элементу - num: int = nums[1] # Доступ к элементу по индексу 1 - - # Изменение элемента - nums[1] = 0 # Изменить значение элемента с индексом 1 на 0 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Доступ к элементу */ - int num = nums[1]; // Доступ к элементу по индексу 1 - - /* Изменение элемента */ - nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "Java" - - ```java title="list.java" - /* Доступ к элементу */ - int num = nums.get(1); // Доступ к элементу по индексу 1 - - /* Изменение элемента */ - nums.set(1, 0); // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Доступ к элементу */ - int num = nums[1]; // Доступ к элементу по индексу 1 - - /* Изменение элемента */ - nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "Go" - - ```go title="list_test.go" - /* Доступ к элементу */ - num := nums[1] // Доступ к элементу по индексу 1 - - /* Изменение элемента */ - nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Доступ к элементу */ - let num = nums[1] // Доступ к элементу по индексу 1 - - /* Изменение элемента */ - nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "JS" - - ```javascript title="list.js" - /* Доступ к элементу */ - const num = nums[1]; // Доступ к элементу по индексу 1 - - /* Изменение элемента */ - nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Доступ к элементу */ - const num: number = nums[1]; // Доступ к элементу по индексу 1 - - /* Изменение элемента */ - nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Доступ к элементу */ - int num = nums[1]; // Доступ к элементу по индексу 1 - - /* Изменение элемента */ - nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Доступ к элементу */ - let num: i32 = nums[1]; // Доступ к элементу по индексу 1 - /* Изменение элемента */ - nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "C" - - ```c title="list.c" - // В C нет встроенного динамического массива - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Доступ к элементу */ - val num = nums[1] // Доступ к элементу по индексу 1 - /* Изменение элемента */ - nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Доступ к элементу - num = nums[1] # Доступ к элементу по индексу 1 - # Изменение элемента - nums[1] = 0 # Изменить значение элемента с индексом 1 на 0 - ``` +```snippet +access_element +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%D0%94%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D1%83%201%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%BC%D0%B5%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%D0%98%D0%B7%D0%BC%D0%B5%D0%BD%D0%B8%D1%82%D1%8C%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%20%D1%81%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D0%BE%D0%BC%201%20%D0%BD%D0%B0%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor access_element_tutor ### Вставка и удаление элементов В отличие от массива в списке можно свободно добавлять и удалять элементы. Сложность добавления элемента в конец списка составляет $O(1)$ , но вставка и удаление элементов имеют ту же сложность $O(n)$, что и в массиве. -=== "Python" - - ```python title="list.py" - # Очистить список - nums.clear() - - # Добавить элементы в конец - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - # Вставить элемент в середину - nums.insert(3, 6) # Вставить число 6 по индексу 3 - - # Удалить элемент - nums.pop(3) # Удалить элемент по индексу 3 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Очистить список */ - nums.clear(); - - /* Добавить элементы в конец */ - nums.push_back(1); - nums.push_back(3); - nums.push_back(2); - nums.push_back(5); - nums.push_back(4); - - /* Вставить элемент в середину */ - nums.insert(nums.begin() + 3, 6); // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums.erase(nums.begin() + 3); // Удалить элемент по индексу 3 - ``` - -=== "Java" - - ```java title="list.java" - /* Очистить список */ - nums.clear(); - - /* Добавить элементы в конец */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* Вставить элемент в середину */ - nums.add(3, 6); // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums.remove(3); // Удалить элемент по индексу 3 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Очистить список */ - nums.Clear(); - - /* Добавить элементы в конец */ - nums.Add(1); - nums.Add(3); - nums.Add(2); - nums.Add(5); - nums.Add(4); - - /* Вставить элемент в середину */ - nums.Insert(3, 6); // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums.RemoveAt(3); // Удалить элемент по индексу 3 - ``` - -=== "Go" - - ```go title="list_test.go" - /* Очистить список */ - nums = nil - - /* Добавить элементы в конец */ - nums = append(nums, 1) - nums = append(nums, 3) - nums = append(nums, 2) - nums = append(nums, 5) - nums = append(nums, 4) - - /* Вставить элемент в середину */ - nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums = append(nums[:3], nums[4:]...) // Удалить элемент по индексу 3 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Очистить список */ - nums.removeAll() - - /* Добавить элементы в конец */ - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - /* Вставить элемент в середину */ - nums.insert(6, at: 3) // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums.remove(at: 3) // Удалить элемент по индексу 3 - ``` - -=== "JS" - - ```javascript title="list.js" - /* Очистить список */ - nums.length = 0; - - /* Добавить элементы в конец */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* Вставить элемент в середину */ - nums.splice(3, 0, 6); // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums.splice(3, 1); // Удалить элемент по индексу 3 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Очистить список */ - nums.length = 0; - - /* Добавить элементы в конец */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* Вставить элемент в середину */ - nums.splice(3, 0, 6); // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums.splice(3, 1); // Удалить элемент по индексу 3 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Очистить список */ - nums.clear(); - - /* Добавить элементы в конец */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* Вставить элемент в середину */ - nums.insert(3, 6); // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums.removeAt(3); // Удалить элемент по индексу 3 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Очистить список */ - nums.clear(); - - /* Добавить элементы в конец */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* Вставить элемент в середину */ - nums.insert(3, 6); // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums.remove(3); // Удалить элемент по индексу 3 - ``` - -=== "C" - - ```c title="list.c" - // В C нет встроенного динамического массива - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Очистить список */ - nums.clear(); - - /* Добавить элементы в конец */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* Вставить элемент в середину */ - nums.add(3, 6); // Вставить число 6 по индексу 3 - - /* Удалить элемент */ - nums.remove(3); // Удалить элемент по индексу 3 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Очистить список - nums.clear - - # Добавить элементы в конец - nums << 1 - nums << 3 - nums << 2 - nums << 5 - nums << 4 - - # Вставить элемент в середину - nums.insert(3, 6) # Вставить число 6 по индексу 3 - - # Удалить элемент - nums.delete_at(3) # Удалить элемент по индексу 3 - ``` +```snippet +insert_remove_element +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%A1%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%BC%D0%B8%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%D0%BC%D0%B8%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D1%87%D0%B8%D1%81%D1%82%D0%B8%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BA%D0%BE%D0%BD%D0%B5%D1%86%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D1%81%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%D0%BD%D1%83%0A%20%20%20%20nums.insert%283%2C%206%29%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%87%D0%B8%D1%81%D0%BB%D0%BE%206%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D1%83%203%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D1%83%203&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_element_tutor ### Обход списка Как и массив, список можно обходить по индексу или напрямую по элементам. -=== "Python" - - ```python title="list.py" - # Обход списка по индексам - count = 0 - for i in range(len(nums)): - count += nums[i] - - # Прямой обход элементов списка - for num in nums: - count += num - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Обход списка по индексам */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums[i]; - } - - /* Прямой обход элементов списка */ - count = 0; - for (int num : nums) { - count += num; - } - ``` - -=== "Java" - - ```java title="list.java" - /* Обход списка по индексам */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums.get(i); - } - - /* Прямой обход элементов списка */ - for (int num : nums) { - count += num; - } - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Обход списка по индексам */ - int count = 0; - for (int i = 0; i < nums.Count; i++) { - count += nums[i]; - } - - /* Прямой обход элементов списка */ - count = 0; - foreach (int num in nums) { - count += num; - } - ``` - -=== "Go" - - ```go title="list_test.go" - /* Обход списка по индексам */ - count := 0 - for i := 0; i < len(nums); i++ { - count += nums[i] - } - - /* Прямой обход элементов списка */ - count = 0 - for _, num := range nums { - count += num - } - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Обход списка по индексам */ - var count = 0 - for i in nums.indices { - count += nums[i] - } - - /* Прямой обход элементов списка */ - count = 0 - for num in nums { - count += num - } - ``` - -=== "JS" - - ```javascript title="list.js" - /* Обход списка по индексам */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* Прямой обход элементов списка */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Обход списка по индексам */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* Прямой обход элементов списка */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Обход списка по индексам */ - int count = 0; - for (var i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* Прямой обход элементов списка */ - count = 0; - for (var num in nums) { - count += num; - } - ``` - -=== "Rust" - - ```rust title="list.rs" - // Обход списка по индексам - let mut _count = 0; - for i in 0..nums.len() { - _count += nums[i]; - } - - // Прямой обход элементов списка - _count = 0; - for num in &nums { - _count += num; - } - ``` - -=== "C" - - ```c title="list.c" - // В C нет встроенного динамического массива - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Обход списка по индексам */ - var count = 0 - for (i in nums.indices) { - count += nums[i] - } - - /* Прямой обход элементов списка */ - for (num in nums) { - count += num - } - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Обход списка по индексам - count = 0 - for i in 0...nums.length - count += nums[i] - end - - # Прямой обход элементов списка - count = 0 - for num in nums - count += num - end - ``` +```snippet +iterate_list +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%B1%D1%85%D0%BE%D0%B4%D0%B8%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D0%B0%D0%BC%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%D0%9D%D0%B5%D0%BF%D0%BE%D1%81%D1%80%D0%B5%D0%B4%D1%81%D1%82%D0%B2%D0%B5%D0%BD%D0%BD%D0%BE%20%D0%BE%D0%B1%D1%85%D0%BE%D0%B4%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%8B%20%D1%81%D0%BF%D0%B8%D1%81%D0%BA%D0%B0%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor iterate_list_tutor ### Конкатенация списков Создав новый список `nums1` , мы можем присоединить его в конец исходного списка. -=== "Python" - - ```python title="list.py" - # Конкатенация двух списков - nums1: list[int] = [6, 8, 7, 10, 9] - nums += nums1 # Присоединить список nums1 к концу nums - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Конкатенация двух списков */ - vector nums1 = { 6, 8, 7, 10, 9 }; - // Присоединить список nums1 к концу nums - nums.insert(nums.end(), nums1.begin(), nums1.end()); - ``` - -=== "Java" - - ```java title="list.java" - /* Конкатенация двух списков */ - List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); - nums.addAll(nums1); // Присоединить список nums1 к концу nums - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Конкатенация двух списков */ - List nums1 = [6, 8, 7, 10, 9]; - nums.AddRange(nums1); // Присоединить список nums1 к концу nums - ``` - -=== "Go" - - ```go title="list_test.go" - /* Конкатенация двух списков */ - nums1 := []int{6, 8, 7, 10, 9} - nums = append(nums, nums1...) // Присоединить список nums1 к концу nums - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Конкатенация двух списков */ - let nums1 = [6, 8, 7, 10, 9] - nums.append(contentsOf: nums1) // Присоединить список nums1 к концу nums - ``` - -=== "JS" - - ```javascript title="list.js" - /* Конкатенация двух списков */ - const nums1 = [6, 8, 7, 10, 9]; - nums.push(...nums1); // Присоединить список nums1 к концу nums - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Конкатенация двух списков */ - const nums1: number[] = [6, 8, 7, 10, 9]; - nums.push(...nums1); // Присоединить список nums1 к концу nums - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Конкатенация двух списков */ - List nums1 = [6, 8, 7, 10, 9]; - nums.addAll(nums1); // Присоединить список nums1 к концу nums - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Конкатенация двух списков */ - let nums1: Vec = vec![6, 8, 7, 10, 9]; - nums.extend(nums1); - ``` - -=== "C" - - ```c title="list.c" - // В C нет встроенного динамического массива - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Конкатенация двух списков */ - val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() - nums.addAll(nums1) // Присоединить список nums1 к концу nums - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Конкатенация двух списков - nums1 = [6, 8, 7, 10, 9] - nums += nums1 - ``` +```snippet +concat_list +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%B1%D1%8A%D0%B5%D0%B4%D0%B8%D0%BD%D0%B8%D1%82%D1%8C%20%D0%B4%D0%B2%D0%B0%20%D1%81%D0%BF%D0%B8%D1%81%D0%BA%D0%B0%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%D0%9F%D1%80%D0%B8%D1%81%D0%BE%D0%B5%D0%B4%D0%B8%D0%BD%D0%B8%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%20nums1%20%D0%BA%20nums&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor concat_list_tutor ### Сортировка списка После сортировки списка мы сможем применять алгоритмы «двоичный поиск» и «два указателя», которые очень часто встречаются в задачах по массивам. -=== "Python" - - ```python title="list.py" - # Отсортировать список - nums.sort() # После сортировки элементы списка идут по возрастанию - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* Отсортировать список */ - sort(nums.begin(), nums.end()); // После сортировки элементы списка идут по возрастанию - ``` - -=== "Java" - - ```java title="list.java" - /* Отсортировать список */ - Collections.sort(nums); // После сортировки элементы списка идут по возрастанию - ``` - -=== "C#" - - ```csharp title="list.cs" - /* Отсортировать список */ - nums.Sort(); // После сортировки элементы списка идут по возрастанию - ``` - -=== "Go" - - ```go title="list_test.go" - /* Отсортировать список */ - sort.Ints(nums) // После сортировки элементы списка идут по возрастанию - ``` - -=== "Swift" - - ```swift title="list.swift" - /* Отсортировать список */ - nums.sort() // После сортировки элементы списка идут по возрастанию - ``` - -=== "JS" - - ```javascript title="list.js" - /* Отсортировать список */ - nums.sort((a, b) => a - b); // После сортировки элементы списка идут по возрастанию - ``` - -=== "TS" - - ```typescript title="list.ts" - /* Отсортировать список */ - nums.sort((a, b) => a - b); // После сортировки элементы списка идут по возрастанию - ``` - -=== "Dart" - - ```dart title="list.dart" - /* Отсортировать список */ - nums.sort(); // После сортировки элементы списка идут по возрастанию - ``` - -=== "Rust" - - ```rust title="list.rs" - /* Отсортировать список */ - nums.sort(); // После сортировки элементы списка идут по возрастанию - ``` - -=== "C" - - ```c title="list.c" - // В C нет встроенного динамического массива - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* Отсортировать список */ - nums.sort() // После сортировки элементы списка идут по возрастанию - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # Отсортировать список - nums = nums.sort { |a, b| a <=> b } # После сортировки элементы списка идут по возрастанию - ``` +```snippet +sort_list +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D1%82%D1%81%D0%BE%D1%80%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums.sort%28%29%20%20%23%20%D0%9F%D0%BE%D1%81%D0%BB%D0%B5%20%D1%81%D0%BE%D1%80%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B8%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%8B%20%D1%81%D0%BF%D0%B8%D1%81%D0%BA%D0%B0%20%D1%80%D0%B0%D1%81%D0%BF%D0%BE%D0%BB%D0%B0%D0%B3%D0%B0%D1%8E%D1%82%D1%81%D1%8F%20%D0%BF%D0%BE%20%D0%B2%D0%BE%D0%B7%D1%80%D0%B0%D1%81%D1%82%D0%B0%D0%BD%D0%B8%D1%8E&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor sort_list_tutor ## Реализация списка diff --git a/ru/docs/chapter_backtracking/backtracking_algorithm.md b/ru/docs/chapter_backtracking/backtracking_algorithm.md index dd06bedd8..61498bce5 100644 --- a/ru/docs/chapter_backtracking/backtracking_algorithm.md +++ b/ru/docs/chapter_backtracking/backtracking_algorithm.md @@ -95,339 +95,9 @@ В следующем каркасе кода `state` обозначает текущее состояние задачи, а `choices` - список выборов, доступных в текущем состоянии: -=== "Python" - - ```python title="" - def backtrack(state: State, choices: list[choice], res: list[state]): - """Каркас алгоритма поиска с возвратом""" - # Проверка, является ли текущее состояние решением - if is_solution(state): - # Запись решения - record_solution(state, res) - # Дальше не продолжаем поиск - return - # Перебор всех возможных выборов - for choice in choices: - # Обрезка: проверка допустимости выбора - if is_valid(state, choice): - # Попытка: сделать выбор и обновить состояние - make_choice(state, choice) - backtrack(state, choices, res) - # Откат: отменить выбор и восстановить предыдущее состояние - undo_choice(state, choice) - ``` - -=== "C++" - - ```cpp title="" - /* Каркас алгоритма поиска с возвратом */ - void backtrack(State *state, vector &choices, vector &res) { - // Проверка, является ли текущее состояние решением - if (isSolution(state)) { - // Запись решения - recordSolution(state, res); - // Дальше не продолжаем поиск - return; - } - // Перебор всех возможных выборов - for (Choice choice : choices) { - // Обрезка: проверка допустимости выбора - if (isValid(state, choice)) { - // Попытка: сделать выбор и обновить состояние - makeChoice(state, choice); - backtrack(state, choices, res); - // Откат: отменить выбор и восстановить предыдущее состояние - undoChoice(state, choice); - } - } - } - ``` - -=== "Java" - - ```java title="" - /* Каркас алгоритма поиска с возвратом */ - void backtrack(State state, List choices, List res) { - // Проверка, является ли текущее состояние решением - if (isSolution(state)) { - // Запись решения - recordSolution(state, res); - // Дальше не продолжаем поиск - return; - } - // Перебор всех возможных выборов - for (Choice choice : choices) { - // Обрезка: проверка допустимости выбора - if (isValid(state, choice)) { - // Попытка: сделать выбор и обновить состояние - makeChoice(state, choice); - backtrack(state, choices, res); - // Откат: отменить выбор и восстановить предыдущее состояние - undoChoice(state, choice); - } - } - } - ``` - -=== "C#" - - ```csharp title="" - /* Каркас алгоритма поиска с возвратом */ - void Backtrack(State state, List choices, List res) { - // Проверка, является ли текущее состояние решением - if (IsSolution(state)) { - // Запись решения - RecordSolution(state, res); - // Дальше не продолжаем поиск - return; - } - // Перебор всех возможных выборов - foreach (Choice choice in choices) { - // Обрезка: проверка допустимости выбора - if (IsValid(state, choice)) { - // Попытка: сделать выбор и обновить состояние - MakeChoice(state, choice); - Backtrack(state, choices, res); - // Откат: отменить выбор и восстановить предыдущее состояние - UndoChoice(state, choice); - } - } - } - ``` - -=== "Go" - - ```go title="" - /* Каркас алгоритма поиска с возвратом */ - func backtrack(state *State, choices []Choice, res *[]State) { - // Проверка, является ли текущее состояние решением - if isSolution(state) { - // Запись решения - recordSolution(state, res) - // Дальше не продолжаем поиск - return - } - // Перебор всех возможных выборов - for _, choice := range choices { - // Обрезка: проверка допустимости выбора - if isValid(state, choice) { - // Попытка: сделать выбор и обновить состояние - makeChoice(state, choice) - backtrack(state, choices, res) - // Откат: отменить выбор и восстановить предыдущее состояние - undoChoice(state, choice) - } - } - } - ``` - -=== "Swift" - - ```swift title="" - /* Каркас алгоритма поиска с возвратом */ - func backtrack(state: inout State, choices: [Choice], res: inout [State]) { - // Проверка, является ли текущее состояние решением - if isSolution(state: state) { - // Запись решения - recordSolution(state: state, res: &res) - // Дальше не продолжаем поиск - return - } - // Перебор всех возможных выборов - for choice in choices { - // Обрезка: проверка допустимости выбора - if isValid(state: state, choice: choice) { - // Попытка: сделать выбор и обновить состояние - makeChoice(state: &state, choice: choice) - backtrack(state: &state, choices: choices, res: &res) - // Откат: отменить выбор и восстановить предыдущее состояние - undoChoice(state: &state, choice: choice) - } - } - } - ``` - -=== "JS" - - ```javascript title="" - /* Каркас алгоритма поиска с возвратом */ - function backtrack(state, choices, res) { - // Проверка, является ли текущее состояние решением - if (isSolution(state)) { - // Запись решения - recordSolution(state, res); - // Дальше не продолжаем поиск - return; - } - // Перебор всех возможных выборов - for (let choice of choices) { - // Обрезка: проверка допустимости выбора - if (isValid(state, choice)) { - // Попытка: сделать выбор и обновить состояние - makeChoice(state, choice); - backtrack(state, choices, res); - // Откат: отменить выбор и восстановить предыдущее состояние - undoChoice(state, choice); - } - } - } - ``` - -=== "TS" - - ```typescript title="" - /* Каркас алгоритма поиска с возвратом */ - function backtrack(state: State, choices: Choice[], res: State[]): void { - // Проверка, является ли текущее состояние решением - if (isSolution(state)) { - // Запись решения - recordSolution(state, res); - // Дальше не продолжаем поиск - return; - } - // Перебор всех возможных выборов - for (let choice of choices) { - // Обрезка: проверка допустимости выбора - if (isValid(state, choice)) { - // Попытка: сделать выбор и обновить состояние - makeChoice(state, choice); - backtrack(state, choices, res); - // Откат: отменить выбор и восстановить предыдущее состояние - undoChoice(state, choice); - } - } - } - ``` - -=== "Dart" - - ```dart title="" - /* Каркас алгоритма поиска с возвратом */ - void backtrack(State state, List, List res) { - // Проверка, является ли текущее состояние решением - if (isSolution(state)) { - // Запись решения - recordSolution(state, res); - // Дальше не продолжаем поиск - return; - } - // Перебор всех возможных выборов - for (Choice choice in choices) { - // Обрезка: проверка допустимости выбора - if (isValid(state, choice)) { - // Попытка: сделать выбор и обновить состояние - makeChoice(state, choice); - backtrack(state, choices, res); - // Откат: отменить выбор и восстановить предыдущее состояние - undoChoice(state, choice); - } - } - } - ``` - -=== "Rust" - - ```rust title="" - /* Каркас алгоритма поиска с возвратом */ - fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { - // Проверка, является ли текущее состояние решением - if is_solution(state) { - // Запись решения - record_solution(state, res); - // Дальше не продолжаем поиск - return; - } - // Перебор всех возможных выборов - for choice in choices { - // Обрезка: проверка допустимости выбора - if is_valid(state, choice) { - // Попытка: сделать выбор и обновить состояние - make_choice(state, choice); - backtrack(state, choices, res); - // Откат: отменить выбор и восстановить предыдущее состояние - undo_choice(state, choice); - } - } - } - ``` - -=== "C" - - ```c title="" - /* Каркас алгоритма поиска с возвратом */ - void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { - // Проверка, является ли текущее состояние решением - if (isSolution(state)) { - // Запись решения - recordSolution(state, res, numRes); - // Дальше не продолжаем поиск - return; - } - // Перебор всех возможных выборов - for (int i = 0; i < numChoices; i++) { - // Обрезка: проверка допустимости выбора - if (isValid(state, &choices[i])) { - // Попытка: сделать выбор и обновить состояние - makeChoice(state, &choices[i]); - backtrack(state, choices, numChoices, res, numRes); - // Откат: отменить выбор и восстановить предыдущее состояние - undoChoice(state, &choices[i]); - } - } - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Каркас алгоритма поиска с возвратом */ - fun backtrack(state: State?, choices: List, res: List?) { - // Проверка, является ли текущее состояние решением - if (isSolution(state)) { - // Запись решения - recordSolution(state, res) - // Дальше не продолжаем поиск - return - } - // Перебор всех возможных выборов - for (choice in choices) { - // Обрезка: проверка допустимости выбора - if (isValid(state, choice)) { - // Попытка: сделать выбор и обновить состояние - makeChoice(state, choice) - backtrack(state, choices, res) - // Откат: отменить выбор и восстановить предыдущее состояние - undoChoice(state, choice) - } - } - } - ``` - -=== "Ruby" - - ```ruby title="" - ### Каркас алгоритма поиска с возвратом ### - def backtrack(state, choices, res) - # Проверка, является ли текущее состояние решением - if is_solution?(state) - # Запись решения - record_solution(state, res) - return - end - - # Перебор всех возможных выборов - for choice in choices - # Обрезка: проверка допустимости выбора - if is_valid?(state, choice) - # Попытка: сделать выбор и обновить состояние - make_choice(state, choice) - backtrack(state, choices, res) - # Откат: отменить выбор и восстановить предыдущее состояние - undo_choice(state, choice) - end - end - end - ``` +```snippet +backtrack_framework +``` Теперь, опираясь на этот каркас, решим пример 3. Состояние `state` здесь - это путь обхода узлов, выбор `choices` - левый и правый потомки текущего узла, а результат `res` - список путей: diff --git a/ru/docs/chapter_computational_complexity/space_complexity.md b/ru/docs/chapter_computational_complexity/space_complexity.md index 945e29c3b..300508300 100644 --- a/ru/docs/chapter_computational_complexity/space_complexity.md +++ b/ru/docs/chapter_computational_complexity/space_complexity.md @@ -24,342 +24,9 @@ Ниже приведен соответствующий код: -=== "Python" - - ```python title="" - class Node: - """Класс""" - def __init__(self, x: int): - self.val: int = x # Значение узла - self.next: Node | None = None # Ссылка на следующий узел - - def function() -> int: - """Функция""" - # Выполнить некоторые операции... - return 0 - - def algorithm(n) -> int: # Входные данные - A = 0 # Временные данные (константа, обычно обозначается заглавной буквой) - b = 0 # Временные данные (переменная) - node = Node(0) # Временные данные (объект) - c = function() # Пространство кадра стека (вызов функции) - return A + b + c # Выходные данные - ``` - -=== "C++" - - ```cpp title="" - /* Структура */ - struct Node { - int val; - Node *next; - Node(int x) : val(x), next(nullptr) {} - }; - - /* Функция */ - int func() { - // Выполнить некоторые операции... - return 0; - } - - int algorithm(int n) { // Входные данные - const int a = 0; // Временные данные (константа) - int b = 0; // Временные данные (переменная) - Node* node = new Node(0); // Временные данные (объект) - int c = func(); // Пространство кадра стека (вызов функции) - return a + b + c; // Выходные данные - } - ``` - -=== "Java" - - ```java title="" - /* Класс */ - class Node { - int val; - Node next; - Node(int x) { val = x; } - } - - /* Функция */ - int function() { - // Выполнить некоторые операции... - return 0; - } - - int algorithm(int n) { // Входные данные - final int a = 0; // Временные данные (константа) - int b = 0; // Временные данные (переменная) - Node node = new Node(0); // Временные данные (объект) - int c = function(); // Пространство кадра стека (вызов функции) - return a + b + c; // Выходные данные - } - ``` - -=== "C#" - - ```csharp title="" - /* Класс */ - class Node(int x) { - int val = x; - Node next; - } - - /* Функция */ - int Function() { - // Выполнить некоторые операции... - return 0; - } - - int Algorithm(int n) { // Входные данные - const int a = 0; // Временные данные (константа) - int b = 0; // Временные данные (переменная) - Node node = new(0); // Временные данные (объект) - int c = Function(); // Пространство кадра стека (вызов функции) - return a + b + c; // Выходные данные - } - ``` - -=== "Go" - - ```go title="" - /* Структура */ - type node struct { - val int - next *node - } - - /* Создать структуру node */ - func newNode(val int) *node { - return &node{val: val} - } - - /* Функция */ - func function() int { - // Выполнить некоторые операции... - return 0 - } - - func algorithm(n int) int { // Входные данные - const a = 0 // Временные данные (константа) - b := 0 // Временные данные (переменная) - newNode(0) // Временные данные (объект) - c := function() // Пространство кадра стека (вызов функции) - return a + b + c // Выходные данные - } - ``` - -=== "Swift" - - ```swift title="" - /* Класс */ - class Node { - var val: Int - var next: Node? - - init(x: Int) { - val = x - } - } - - /* Функция */ - func function() -> Int { - // Выполнить некоторые операции... - return 0 - } - - func algorithm(n: Int) -> Int { // Входные данные - let a = 0 // Временные данные (константа) - var b = 0 // Временные данные (переменная) - let node = Node(x: 0) // Временные данные (объект) - let c = function() // Пространство кадра стека (вызов функции) - return a + b + c // Выходные данные - } - ``` - -=== "JS" - - ```javascript title="" - /* Класс */ - class Node { - val; - next; - constructor(val) { - this.val = val === undefined ? 0 : val; // Значение узла - this.next = null; // Ссылка на следующий узел - } - } - - /* Функция */ - function constFunc() { - // Выполнить некоторые операции - return 0; - } - - function algorithm(n) { // Входные данные - const a = 0; // Временные данные (константа) - let b = 0; // Временные данные (переменная) - const node = new Node(0); // Временные данные (объект) - const c = constFunc(); // Пространство кадра стека (вызов функции) - return a + b + c; // Выходные данные - } - ``` - -=== "TS" - - ```typescript title="" - /* Класс */ - class Node { - val: number; - next: Node | null; - constructor(val?: number) { - this.val = val === undefined ? 0 : val; // Значение узла - this.next = null; // Ссылка на следующий узел - } - } - - /* Функция */ - function constFunc(): number { - // Выполнить некоторые операции - return 0; - } - - function algorithm(n: number): number { // Входные данные - const a = 0; // Временные данные (константа) - let b = 0; // Временные данные (переменная) - const node = new Node(0); // Временные данные (объект) - const c = constFunc(); // Пространство кадра стека (вызов функции) - return a + b + c; // Выходные данные - } - ``` - -=== "Dart" - - ```dart title="" - /* Класс */ - class Node { - int val; - Node next; - Node(this.val, [this.next]); - } - - /* Функция */ - int function() { - // Выполнить некоторые операции... - return 0; - } - - int algorithm(int n) { // Входные данные - const int a = 0; // Временные данные (константа) - int b = 0; // Временные данные (переменная) - Node node = Node(0); // Временные данные (объект) - int c = function(); // Пространство кадра стека (вызов функции) - return a + b + c; // Выходные данные - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* Структура */ - struct Node { - val: i32, - next: Option>>, - } - - /* Создать структуру Node */ - impl Node { - fn new(val: i32) -> Self { - Self { val: val, next: None } - } - } - - /* Функция */ - fn function() -> i32 { - // Выполнить некоторые операции... - return 0; - } - - fn algorithm(n: i32) -> i32 { // Входные данные - const a: i32 = 0; // Временные данные (константа) - let mut b = 0; // Временные данные (переменная) - let node = Node::new(0); // Временные данные (объект) - let c = function(); // Пространство кадра стека (вызов функции) - return a + b + c; // Выходные данные - } - ``` - -=== "C" - - ```c title="" - /* Функция */ - int func() { - // Выполнить некоторые операции... - return 0; - } - - int algorithm(int n) { // Входные данные - const int a = 0; // Временные данные (константа) - int b = 0; // Временные данные (переменная) - int c = func(); // Пространство кадра стека (вызов функции) - return a + b + c; // Выходные данные - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Класс */ - class Node(var _val: Int) { - var next: Node? = null - } - - /* Функция */ - fun function(): Int { - // Выполнить некоторые операции... - return 0 - } - - fun algorithm(n: Int): Int { // Входные данные - val a = 0 // Временные данные (константа) - var b = 0 // Временные данные (переменная) - val node = Node(0) // Временные данные (объект) - val c = function() // Пространство кадра стека (вызов функции) - return a + b + c // Выходные данные - } - ``` - -=== "Ruby" - - ```ruby title="" - ### Класс ### - class Node - attr_accessor :val # Значение узла - attr_accessor :next # Ссылка на следующий узел - - def initialize(x) - @val = x - end - end - - ### Функция ### - def function - # Выполнить некоторые операции... - 0 - end - - ### Алгоритм ### - def algorithm(n) # Входные данные - a = 0 # Временные данные (константа) - b = 0 # Временные данные (переменная) - node = Node.new(0) # Временные данные (объект) - c = function # Пространство кадра стека (вызов функции) - a + b + c # Выходные данные - end - ``` +```snippet +space_categories +``` ## Метод вывода @@ -372,428 +39,15 @@ 1. **Ориентир на худшие входные данные**: когда $n < 10$ , пространственная сложность равна $O(1)$ ; но когда $n > 10$ , инициализированный массив `nums` занимает $O(n)$ пространства, поэтому худшая пространственная сложность равна $O(n)$ . 2. **Ориентир на пиковое использование памяти во время выполнения**: например, до выполнения последней строки программа занимает $O(1)$ пространства. При инициализации массива `nums` она занимает $O(n)$ пространства, поэтому худшая пространственная сложность также равна $O(n)$ . -=== "Python" - - ```python title="" - def algorithm(n: int): - a = 0 # O(1) - b = [0] * 10000 # O(1) - if n > 10: - nums = [0] * n # O(n) - ``` - -=== "C++" - - ```cpp title="" - void algorithm(int n) { - int a = 0; // O(1) - vector b(10000); // O(1) - if (n > 10) - vector nums(n); // O(n) - } - ``` - -=== "Java" - - ```java title="" - void algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) - int[] nums = new int[n]; // O(n) - } - ``` - -=== "C#" - - ```csharp title="" - void Algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) { - int[] nums = new int[n]; // O(n) - } - } - ``` - -=== "Go" - - ```go title="" - func algorithm(n int) { - a := 0 // O(1) - b := make([]int, 10000) // O(1) - var nums []int - if n > 10 { - nums := make([]int, n) // O(n) - } - fmt.Println(a, b, nums) - } - ``` - -=== "Swift" - - ```swift title="" - func algorithm(n: Int) { - let a = 0 // O(1) - let b = Array(repeating: 0, count: 10000) // O(1) - if n > 10 { - let nums = Array(repeating: 0, count: n) // O(n) - } - } - ``` - -=== "JS" - - ```javascript title="" - function algorithm(n) { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "TS" - - ```typescript title="" - function algorithm(n: number): void { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "Dart" - - ```dart title="" - void algorithm(int n) { - int a = 0; // O(1) - List b = List.filled(10000, 0); // O(1) - if (n > 10) { - List nums = List.filled(n, 0); // O(n) - } - } - ``` - -=== "Rust" - - ```rust title="" - fn algorithm(n: i32) { - let a = 0; // O(1) - let b = [0; 10000]; // O(1) - if n > 10 { - let nums = vec![0; n as usize]; // O(n) - } - } - ``` - -=== "C" - - ```c title="" - void algorithm(int n) { - int a = 0; // O(1) - int b[10000]; // O(1) - if (n > 10) - int nums[n] = {0}; // O(n) - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun algorithm(n: Int) { - val a = 0 // O(1) - val b = IntArray(10000) // O(1) - if (n > 10) { - val nums = IntArray(n) // O(n) - } - } - ``` - -=== "Ruby" - - ```ruby title="" - def algorithm(n) - a = 0 # O(1) - b = Array.new(10000) # O(1) - nums = Array.new(n) if n > 10 # O(n) - end - ``` +```snippet +worst_case_space +``` **В рекурсивных функциях необходимо учитывать пространство кадров стека**. Рассмотрим следующий код: -=== "Python" - - ```python title="" - def function() -> int: - # Выполнить некоторые операции - return 0 - - def loop(n: int): - """Пространственная сложность цикла равна O(1)""" - for _ in range(n): - function() - - def recur(n: int): - """Пространственная сложность рекурсии равна O(n)""" - if n == 1: - return - return recur(n - 1) - ``` - -=== "C++" - - ```cpp title="" - int func() { - // Выполнить некоторые операции - return 0; - } - /* Пространственная сложность цикла равна O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* Пространственная сложность рекурсии равна O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Java" - - ```java title="" - int function() { - // Выполнить некоторые операции - return 0; - } - /* Пространственная сложность цикла равна O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* Пространственная сложность рекурсии равна O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "C#" - - ```csharp title="" - int Function() { - // Выполнить некоторые операции - return 0; - } - /* Пространственная сложность цикла равна O(1) */ - void Loop(int n) { - for (int i = 0; i < n; i++) { - Function(); - } - } - /* Пространственная сложность рекурсии равна O(n) */ - int Recur(int n) { - if (n == 1) return 1; - return Recur(n - 1); - } - ``` - -=== "Go" - - ```go title="" - func function() int { - // Выполнить некоторые операции - return 0 - } - - /* Пространственная сложность цикла равна O(1) */ - func loop(n int) { - for i := 0; i < n; i++ { - function() - } - } - - /* Пространственная сложность рекурсии равна O(n) */ - func recur(n int) { - if n == 1 { - return - } - recur(n - 1) - } - ``` - -=== "Swift" - - ```swift title="" - @discardableResult - func function() -> Int { - // Выполнить некоторые операции - return 0 - } - - /* Пространственная сложность цикла равна O(1) */ - func loop(n: Int) { - for _ in 0 ..< n { - function() - } - } - - /* Пространственная сложность рекурсии равна O(n) */ - func recur(n: Int) { - if n == 1 { - return - } - recur(n: n - 1) - } - ``` - -=== "JS" - - ```javascript title="" - function constFunc() { - // Выполнить некоторые операции - return 0; - } - /* Пространственная сложность цикла равна O(1) */ - function loop(n) { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* Пространственная сложность рекурсии равна O(n) */ - function recur(n) { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "TS" - - ```typescript title="" - function constFunc(): number { - // Выполнить некоторые операции - return 0; - } - /* Пространственная сложность цикла равна O(1) */ - function loop(n: number): void { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* Пространственная сложность рекурсии равна O(n) */ - function recur(n: number): void { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "Dart" - - ```dart title="" - int function() { - // Выполнить некоторые операции - return 0; - } - /* Пространственная сложность цикла равна O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* Пространственная сложность рекурсии равна O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Rust" - - ```rust title="" - fn function() -> i32 { - // Выполнить некоторые операции - return 0; - } - /* Пространственная сложность цикла равна O(1) */ - fn loop(n: i32) { - for i in 0..n { - function(); - } - } - /* Пространственная сложность рекурсии равна O(n) */ - fn recur(n: i32) { - if n == 1 { - return; - } - recur(n - 1); - } - ``` - -=== "C" - - ```c title="" - int func() { - // Выполнить некоторые операции - return 0; - } - /* Пространственная сложность цикла равна O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* Пространственная сложность рекурсии равна O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun function(): Int { - // Выполнить некоторые операции - return 0 - } - /* Пространственная сложность цикла равна O(1) */ - fun loop(n: Int) { - for (i in 0.. numbers = List.filled(5, 0); - List decimals = List.filled(5, 0.0); - List characters = List.filled(5, 'a'); - List bools = List.filled(5, false); - ``` - -=== "Rust" - - ```rust title="" - // Инициализируем массивы с использованием различных базовых типов данных - let numbers: Vec = vec![0; 5]; - let decimals: Vec = vec![0.0; 5]; - let characters: Vec = vec!['0'; 5]; - let bools: Vec = vec![false; 5]; - ``` - -=== "C" - - ```c title="" - // Инициализируем массивы с использованием различных базовых типов данных - int numbers[10]; - float decimals[10]; - char characters[10]; - bool bools[10]; - ``` - -=== "Kotlin" - - ```kotlin title="" - // Инициализируем массивы с использованием различных базовых типов данных - val numbers = IntArray(5) - val decinals = FloatArray(5) - val characters = CharArray(5) - val bools = BooleanArray(5) - ``` - -=== "Ruby" - - ```ruby title="" - # Списки Ruby могут свободно хранить различные базовые типы данных и ссылки на объекты - data = [0, 0.0, 'a', false, ListNode(0)] - ``` +```snippet +basic_type_arrays +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D1%83%D0%B7%D0%B5%D0%BB%D0%BA%D0%BB%D0%B0%D1%81%D1%81%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D1%81%D0%BB%D0%B5%D0%B4%D1%83%D1%8E%D1%89%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2%20%D1%81%20%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5%D0%BC%20%D0%BD%D0%B5%D1%81%D0%BA%D0%BE%D0%BB%D1%8C%D0%BA%D0%B8%D1%85%20%D0%B1%D0%B0%D0%B7%D0%BE%D0%B2%D1%8B%D1%85%20%D1%82%D0%B8%D0%BF%D0%BE%D0%B2%20%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20%2A%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20%2A%205%0A%20%20%20%20%23%20%D0%92%20Python%20%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB%D1%8B%20%D0%BD%D0%B0%20%D1%81%D0%B0%D0%BC%D0%BE%D0%BC%20%D0%B4%D0%B5%D0%BB%D0%B5%20%D1%8F%D0%B2%D0%BB%D1%8F%D1%8E%D1%82%D1%81%D1%8F%20%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B0%D0%BC%D0%B8%20%D0%B4%D0%BB%D0%B8%D0%BD%D1%8B%201%0A%20%20%20%20characters%20%3D%20%5B%270%27%5D%20%2A%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20%2A%205%0A%20%20%20%20%23%20%D0%A1%D0%BF%D0%B8%D1%81%D0%BA%D0%B8%20%D0%B2%20Python%20%D0%BC%D0%BE%D0%B3%D1%83%D1%82%20%D1%81%D0%B2%D0%BE%D0%B1%D0%BE%D0%B4%D0%BD%D0%BE%20%D1%85%D1%80%D0%B0%D0%BD%D0%B8%D1%82%D1%8C%20%D1%80%D0%B0%D0%B7%D0%BB%D0%B8%D1%87%D0%BD%D1%8B%D0%B5%20%D0%B1%D0%B0%D0%B7%D0%BE%D0%B2%D1%8B%D0%B5%20%D1%82%D0%B8%D0%BF%D1%8B%20%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85%20%D0%B8%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BD%D0%B0%20%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D1%8B%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20%27a%27%2C%20False%2C%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor basic_type_arrays_tutor diff --git a/ru/docs/chapter_hashing/hash_algorithm.md b/ru/docs/chapter_hashing/hash_algorithm.md index dec85fe77..6f721c22a 100644 --- a/ru/docs/chapter_hashing/hash_algorithm.md +++ b/ru/docs/chapter_hashing/hash_algorithm.md @@ -113,295 +113,13 @@ $$ Обратите внимание: определения и способы вычисления встроенных хеш-значений в разных языках программирования отличаются. -=== "Python" - - ```python title="built_in_hash.py" - num = 3 - hash_num = hash(num) - # Хеш-значение целого числа 3 равно 3 - - bol = True - hash_bol = hash(bol) - # Хеш-значение булевого значения True равно 1 - - dec = 3.14159 - hash_dec = hash(dec) - # Хеш-значение числа 3.14159 равно 326484311674566659 - - str = "Hello Algo" - hash_str = hash(str) - # Хеш-значение строки "Hello Algo" равно 4617003410720528961 - - tup = (12836, "Сяо Ха") - hash_tup = hash(tup) - # Хеш-значение кортежа (12836, "Сяо Ха") равно 1029005403108185979 - - obj = ListNode(0) - hash_obj = hash(obj) - # Хеш-значение объекта узла равно 274267521 - ``` - -=== "C++" - - ```cpp title="built_in_hash.cpp" - int num = 3; - size_t hashNum = hash()(num); - // Хеш-значение целого числа 3 равно 3 - - bool bol = true; - size_t hashBol = hash()(bol); - // Хеш-значение булевого значения 1 равно 1 - - double dec = 3.14159; - size_t hashDec = hash()(dec); - // Хеш-значение числа 3.14159 равно 4614256650576692846 - - string str = "Hello Algo"; - size_t hashStr = hash()(str); - // Хеш-значение строки "Hello Algo" равно 15466937326284535026 - - // В C++ встроенный std::hash() предоставляет вычисление хеша только для базовых типов данных - // Для массивов и объектов хеш-значение обычно приходится реализовывать самостоятельно - ``` - -=== "Java" - - ```java title="built_in_hash.java" - int num = 3; - int hashNum = Integer.hashCode(num); - // Хеш-значение целого числа 3 равно 3 - - boolean bol = true; - int hashBol = Boolean.hashCode(bol); - // Хеш-значение булевого значения true равно 1231 - - double dec = 3.14159; - int hashDec = Double.hashCode(dec); - // Хеш-значение числа 3.14159 равно -1340954729 - - String str = "Hello Algo"; - int hashStr = str.hashCode(); - // Хеш-значение строки "Hello Algo" равно -727081396 - - Object[] arr = { 12836, "Сяо Ха" }; - int hashTup = Arrays.hashCode(arr); - // Хеш-значение массива [12836, Сяо Ха] равно 1151158 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode(); - // Хеш-значение объекта узла utils.ListNode@7dc5e7b4 равно 2110121908 - ``` - -=== "C#" - - ```csharp title="built_in_hash.cs" - int num = 3; - int hashNum = num.GetHashCode(); - // Хеш-значение целого числа 3 равно 3; - - bool bol = true; - int hashBol = bol.GetHashCode(); - // Хеш-значение булевого значения true равно 1; - - double dec = 3.14159; - int hashDec = dec.GetHashCode(); - // Хеш-значение числа 3.14159 равно -1340954729; - - string str = "Hello Algo"; - int hashStr = str.GetHashCode(); - // Хеш-значение строки "Hello Algo" равно -586107568; - - object[] arr = [12836, "Сяо Ха"]; - int hashTup = arr.GetHashCode(); - // Хеш-значение массива [12836, Сяо Ха] равно 42931033; - - ListNode obj = new(0); - int hashObj = obj.GetHashCode(); - // Хеш-значение объекта узла 0 равно 39053774; - ``` - -=== "Go" - - ```go title="built_in_hash.go" - // В Go нет встроенной функции hash code - ``` - -=== "Swift" - - ```swift title="built_in_hash.swift" - let num = 3 - let hashNum = num.hashValue - // Хеш-значение целого числа 3 равно 9047044699613009734 - - let bol = true - let hashBol = bol.hashValue - // Хеш-значение булевого значения true равно -4431640247352757451 - - let dec = 3.14159 - let hashDec = dec.hashValue - // Хеш-значение числа 3.14159 равно -2465384235396674631 - - let str = "Hello Algo" - let hashStr = str.hashValue - // Хеш-значение строки "Hello Algo" равно -7850626797806988787 - - let arr = [AnyHashable(12836), AnyHashable("Сяо Ха")] - let hashTup = arr.hashValue - // Хеш-значение массива [AnyHashable(12836), AnyHashable("Сяо Ха")] равно -2308633508154532996 - - let obj = ListNode(x: 0) - let hashObj = obj.hashValue - // Хеш-значение объекта узла utils.ListNode равно -2434780518035996159 - ``` - -=== "JS" - - ```javascript title="built_in_hash.js" - // В JavaScript нет встроенной функции hash code - ``` - -=== "TS" - - ```typescript title="built_in_hash.ts" - // В TypeScript нет встроенной функции hash code - ``` - -=== "Dart" - - ```dart title="built_in_hash.dart" - int num = 3; - int hashNum = num.hashCode; - // Хеш-значение целого числа 3 равно 34803 - - bool bol = true; - int hashBol = bol.hashCode; - // Хеш-значение булевого значения true равно 1231 - - double dec = 3.14159; - int hashDec = dec.hashCode; - // Хеш-значение числа 3.14159 равно 2570631074981783 - - String str = "Hello Algo"; - int hashStr = str.hashCode; - // Хеш-значение строки "Hello Algo" равно 468167534 - - List arr = [12836, "Сяо Ха"]; - int hashArr = arr.hashCode; - // Хеш-значение массива [12836, Сяо Ха] равно 976512528 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode; - // Хеш-значение объекта Instance of 'ListNode' равно 1033450432 - ``` - -=== "Rust" - - ```rust title="built_in_hash.rs" - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - - let num = 3; - let mut num_hasher = DefaultHasher::new(); - num.hash(&mut num_hasher); - let hash_num = num_hasher.finish(); - // Хеш-значение целого числа 3 равно 568126464209439262 - - let bol = true; - let mut bol_hasher = DefaultHasher::new(); - bol.hash(&mut bol_hasher); - let hash_bol = bol_hasher.finish(); - // Хеш-значение булевого значения true равно 4952851536318644461 - - let dec: f32 = 3.14159; - let mut dec_hasher = DefaultHasher::new(); - dec.to_bits().hash(&mut dec_hasher); - let hash_dec = dec_hasher.finish(); - // Хеш-значение числа 3.14159 равно 2566941990314602357 - - let str = "Hello Algo"; - let mut str_hasher = DefaultHasher::new(); - str.hash(&mut str_hasher); - let hash_str = str_hasher.finish(); - // Хеш-значение строки "Hello Algo" равно 16092673739211250988 - - let arr = (&12836, &"Сяо Ха"); - let mut tup_hasher = DefaultHasher::new(); - arr.hash(&mut tup_hasher); - let hash_tup = tup_hasher.finish(); - // Хеш-значение кортежа (12836, "Сяо Ха") равно 1885128010422702749 - - let node = ListNode::new(42); - let mut hasher = DefaultHasher::new(); - node.borrow().val.hash(&mut hasher); - let hash = hasher.finish(); - // Хеш-значение объекта RefCell { value: ListNode { val: 42, next: None } } равно 15387811073369036852 - ``` - -=== "C" - - ```c title="built_in_hash.c" - // В C нет встроенной функции hash code - ``` - -=== "Kotlin" - - ```kotlin title="built_in_hash.kt" - val num = 3 - val hashNum = num.hashCode() - // Хеш-значение целого числа 3 равно 3 - - val bol = true - val hashBol = bol.hashCode() - // Хеш-значение булевого значения true равно 1231 - - val dec = 3.14159 - val hashDec = dec.hashCode() - // Хеш-значение числа 3.14159 равно -1340954729 - - val str = "Hello Algo" - val hashStr = str.hashCode() - // Хеш-значение строки "Hello Algo" равно -727081396 - - val arr = arrayOf(12836, "Сяо Ха") - val hashTup = arr.hashCode() - // Хеш-значение массива [12836, Сяо Ха] равно 189568618 - - val obj = ListNode(0) - val hashObj = obj.hashCode() - // Хеш-значение объекта узла utils.ListNode@1d81eb93 равно 495053715 - ``` - -=== "Ruby" - - ```ruby title="built_in_hash.rb" - num = 3 - hash_num = num.hash - # Хеш-значение целого числа 3 равно -4385856518450339636 - - bol = true - hash_bol = bol.hash - # Хеш-значение булевого значения true равно -1617938112149317027 - - dec = 3.14159 - hash_dec = dec.hash - # Хеш-значение числа 3.14159 равно -1479186995943067893 - - str = "Hello Algo" - hash_str = str.hash - # Хеш-значение строки "Hello Algo" равно -4075943250025831763 - - tup = [12836, 'Сяо Ха'] - hash_tup = tup.hash - # Хеш-значение кортежа (12836, 'Сяо Ха') равно 1999544809202288822 - - obj = ListNode.new(0) - hash_obj = obj.hash - # Хеш-значение объекта # равно 4302940560806366381 - ``` +```snippet +builtin_hash +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D1%83%D0%B7%D0%B5%D0%BB%D0%BA%D0%BB%D0%B0%D1%81%D1%81%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D1%81%D0%BB%D0%B5%D0%B4%D1%83%D1%8E%D1%89%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%86%D0%B5%D0%BB%D0%BE%D0%B3%D0%BE%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%203%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%B1%D1%83%D0%BB%D0%B5%D0%B2%D0%B0%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20True%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%203.14159%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20Algo%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8%20%22Hello%20Algo%22%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BA%D0%BE%D1%80%D1%82%D0%B5%D0%B6%D0%B0%20%2812836%2C%20%27%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%27%29%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%B0%20%D1%83%D0%B7%D0%BB%D0%B0%20%3CListNode%20object%20at%200x1058fd810%3E%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor builtin_hash_tutor Во многих языках программирования **в качестве `key` хеш-таблицы можно использовать только неизменяемые объекты** . Если, например, использовать список (динамический массив) как `key` , то после изменения содержимого списка изменится и его хеш-значение, из-за чего мы уже не сможем найти прежнее `value` в хеш-таблице. diff --git a/ru/docs/chapter_hashing/hash_map.md b/ru/docs/chapter_hashing/hash_map.md index 6179d3dc4..88fdba54b 100644 --- a/ru/docs/chapter_hashing/hash_map.md +++ b/ru/docs/chapter_hashing/hash_map.md @@ -26,517 +26,23 @@ К базовым операциям хеш-таблицы относятся инициализация, поиск, добавление пар ключ-значение и удаление пар ключ-значение. Пример кода приведен ниже: -=== "Python" - - ```python title="hash_map.py" - # Инициализация хеш-таблицы - hmap: dict = {} - - # Операция добавления - # Добавить пару ключ-значение (key, value) в хеш-таблицу - hmap[12836] = "Сяо Ха" - hmap[15937] = "Сяо Ло" - hmap[16750] = "Сяо Суань" - hmap[13276] = "Сяо Фа" - hmap[10583] = "Сяо Я" - - # Операция поиска - # Передать в хеш-таблицу ключ key и получить значение value - name: str = hmap[15937] - - # Операция удаления - # Удалить пару ключ-значение (key, value) из хеш-таблицы - hmap.pop(10583) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* Инициализация хеш-таблицы */ - unordered_map map; - - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - map[12836] = "Сяо Ха"; - map[15937] = "Сяо Ло"; - map[16750] = "Сяо Суань"; - map[13276] = "Сяо Фа"; - map[10583] = "Сяо Я"; - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - string name = map[15937]; - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - map.erase(10583); - ``` - -=== "Java" - - ```java title="hash_map.java" - /* Инициализация хеш-таблицы */ - Map map = new HashMap<>(); - - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - map.put(12836, "Сяо Ха"); - map.put(15937, "Сяо Ло"); - map.put(16750, "Сяо Суань"); - map.put(13276, "Сяо Фа"); - map.put(10583, "Сяо Я"); - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - String name = map.get(15937); - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - map.remove(10583); - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* Инициализация хеш-таблицы */ - Dictionary map = new() { - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - { 12836, "Сяо Ха" }, - { 15937, "Сяо Ло" }, - { 16750, "Сяо Суань" }, - { 13276, "Сяо Фа" }, - { 10583, "Сяо Я" } - }; - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - string name = map[15937]; - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - map.Remove(10583); - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* Инициализация хеш-таблицы */ - hmap := make(map[int]string) - - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - hmap[12836] = "Сяо Ха" - hmap[15937] = "Сяо Ло" - hmap[16750] = "Сяо Суань" - hmap[13276] = "Сяо Фа" - hmap[10583] = "Сяо Я" - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - name := hmap[15937] - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - delete(hmap, 10583) - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* Инициализация хеш-таблицы */ - var map: [Int: String] = [:] - - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - map[12836] = "Сяо Ха" - map[15937] = "Сяо Ло" - map[16750] = "Сяо Суань" - map[13276] = "Сяо Фа" - map[10583] = "Сяо Я" - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - let name = map[15937]! - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - map.removeValue(forKey: 10583) - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* Инициализация хеш-таблицы */ - const map = new Map(); - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - map.set(12836, 'Сяо Ха'); - map.set(15937, 'Сяо Ло'); - map.set(16750, 'Сяо Суань'); - map.set(13276, 'Сяо Фа'); - map.set(10583, 'Сяо Я'); - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - let name = map.get(15937); - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - map.delete(10583); - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* Инициализация хеш-таблицы */ - const map = new Map(); - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - map.set(12836, 'Сяо Ха'); - map.set(15937, 'Сяо Ло'); - map.set(16750, 'Сяо Суань'); - map.set(13276, 'Сяо Фа'); - map.set(10583, 'Сяо Я'); - console.info('\nПосле добавления хеш-таблица имеет вид\nKey -> Value'); - console.info(map); - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - let name = map.get(15937); - console.info('\nПо номеру 15937 найдено имя ' + name); - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - map.delete(10583); - console.info('\nПосле удаления 10583 хеш-таблица имеет вид\nKey -> Value'); - console.info(map); - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* Инициализация хеш-таблицы */ - Map map = {}; - - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - map[12836] = "Сяо Ха"; - map[15937] = "Сяо Ло"; - map[16750] = "Сяо Суань"; - map[13276] = "Сяо Фа"; - map[10583] = "Сяо Я"; - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - String name = map[15937]; - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - map.remove(10583); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - use std::collections::HashMap; - - /* Инициализация хеш-таблицы */ - let mut map: HashMap = HashMap::new(); - - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - map.insert(12836, "Сяо Ха".to_string()); - map.insert(15937, "Сяо Ло".to_string()); - map.insert(16750, "Сяо Суань".to_string()); - map.insert(13279, "Сяо Фа".to_string()); - map.insert(10583, "Сяо Я".to_string()); - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - let _name: Option<&String> = map.get(&15937); - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - let _removed_value: Option = map.remove(&10583); - ``` - -=== "C" - - ```c title="hash_map.c" - // В C нет встроенной хеш-таблицы - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* Инициализация хеш-таблицы */ - val map = HashMap() - - /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу - map[12836] = "Сяо Ха" - map[15937] = "Сяо Ло" - map[16750] = "Сяо Суань" - map[13276] = "Сяо Фа" - map[10583] = "Сяо Я" - - /* Операция поиска */ - // Передать в хеш-таблицу ключ key и получить значение value - val name = map[15937] - - /* Операция удаления */ - // Удалить пару ключ-значение (key, value) из хеш-таблицы - map.remove(10583) - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # Инициализация хеш-таблицы - hmap = {} - - # Операция добавления - # Добавить пару ключ-значение (key, value) в хеш-таблицу - hmap[12836] = "Сяо Ха" - hmap[15937] = "Сяо Ло" - hmap[16750] = "Сяо Суань" - hmap[13276] = "Сяо Фа" - hmap[10583] = "Сяо Я" - - # Операция поиска - # Передать в хеш-таблицу ключ key и получить значение value - name = hmap[15937] - - # Операция удаления - # Удалить пару ключ-значение (key, value) из хеш-таблицы - hmap.delete(10583) - ``` +```snippet +hash_map_operations +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D0%B4%D0%BE%D0%B1%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%20%D0%BF%D0%B0%D1%80%D1%83%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%9B%D0%BE%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A1%D1%83%D0%B0%D0%BD%D1%8C%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A4%D0%B0%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%D0%A3%D1%82%D0%B5%D0%BD%D0%BE%D0%BA%22%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D0%BF%D0%BE%D0%B8%D1%81%D0%BA%D0%B0%0A%20%20%20%20%23%20%D0%9F%D0%B5%D1%80%D0%B5%D0%B4%D0%B0%D1%82%D1%8C%20%D0%BA%D0%BB%D1%8E%D1%87%20key%20%D0%B2%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%20%D0%B8%20%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20value%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D1%83%D0%B4%D0%B0%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F%0A%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D0%B8%D0%B7%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%8B%20%D0%BF%D0%B0%D1%80%D1%83%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%28key%2C%20value%29%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_operations_tutor Существует три распространенных способа обхода хеш-таблицы: обход пар ключ-значение, обход ключей и обход значений. Примеры кода приведены ниже: -=== "Python" - - ```python title="hash_map.py" - # Обход хеш-таблицы - # Обход пар ключ-значение key->value - for key, value in hmap.items(): - print(key, "->", value) - # Обход только ключей key - for key in hmap.keys(): - print(key) - # Обход только значений value - for value in hmap.values(): - print(value) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* Обход хеш-таблицы */ - // Обход пар ключ-значение key->value - for (auto kv: map) { - cout << kv.first << " -> " << kv.second << endl; - } - // Обход key->value с помощью итератора - for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; - } - ``` - -=== "Java" - - ```java title="hash_map.java" - /* Обход хеш-таблицы */ - // Обход пар ключ-значение key->value - for (Map.Entry kv: map.entrySet()) { - System.out.println(kv.getKey() + " -> " + kv.getValue()); - } - // Обход только ключей key - for (int key: map.keySet()) { - System.out.println(key); - } - // Обход только значений value - for (String val: map.values()) { - System.out.println(val); - } - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* Обход хеш-таблицы */ - // Обход пар ключ-значение Key->Value - foreach (var kv in map) { - Console.WriteLine(kv.Key + " -> " + kv.Value); - } - // Обход только ключей key - foreach (int key in map.Keys) { - Console.WriteLine(key); - } - // Обход только значений value - foreach (string val in map.Values) { - Console.WriteLine(val); - } - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* Обход хеш-таблицы */ - // Обход пар ключ-значение key->value - for key, value := range hmap { - fmt.Println(key, "->", value) - } - // Обход только ключей key - for key := range hmap { - fmt.Println(key) - } - // Обход только значений value - for _, value := range hmap { - fmt.Println(value) - } - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* Обход хеш-таблицы */ - // Обход пар ключ-значение Key->Value - for (key, value) in map { - print("\(key) -> \(value)") - } - // Обход только ключей Key - for key in map.keys { - print(key) - } - // Обход только значений Value - for value in map.values { - print(value) - } - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* Обход хеш-таблицы */ - console.info('\nОбход пар ключ-значение Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\nОбход только ключей Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\nОбход только значений Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* Обход хеш-таблицы */ - console.info('\nОбход пар ключ-значение Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\nОбход только ключей Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\nОбход только значений Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* Обход хеш-таблицы */ - // Обход пар ключ-значение Key->Value - map.forEach((key, value) { - print('$key -> $value'); - }); - - // Обход только ключей Key - map.keys.forEach((key) { - print(key); - }); - - // Обход только значений Value - map.values.forEach((value) { - print(value); - }); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - /* Обход хеш-таблицы */ - // Обход пар ключ-значение Key->Value - for (key, value) in &map { - println!("{key} -> {value}"); - } - - // Обход только ключей Key - for key in map.keys() { - println!("{key}"); - } - - // Обход только значений Value - for value in map.values() { - println!("{value}"); - } - ``` - -=== "C" - - ```c title="hash_map.c" - // В C нет встроенной хеш-таблицы - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* Обход хеш-таблицы */ - // Обход пар ключ-значение key->value - for ((key, value) in map) { - println("$key -> $value") - } - // Обход только ключей key - for (key in map.keys) { - println(key) - } - // Обход только значений value - for (_val in map.values) { - println(_val) - } - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # Обход хеш-таблицы - # Обход пар ключ-значение key->value - hmap.entries.each { |key, value| puts "#{key} -> #{value}" } - - # Обход только ключей key - hmap.keys.each { |key| puts key } - - # Обход только значений value - hmap.values.each { |val| puts val } - ``` +```snippet +hash_map_traversal +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D0%B4%D0%BE%D0%B1%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%20%D0%BF%D0%B0%D1%80%D1%83%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%9B%D0%BE%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A1%D1%83%D0%B0%D0%BD%D1%8C%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A4%D0%B0%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%D0%A3%D1%82%D0%B5%D0%BD%D0%BE%D0%BA%22%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%B5%D1%80%D0%B5%D0%B1%D1%80%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20%23%20%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%BF%D0%B0%D1%80%D0%B0%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%D0%BE%D1%82%D0%B4%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%BA%D0%BB%D1%8E%D1%87%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%D0%BE%D1%82%D0%B4%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_traversal_tutor ## Простая реализация хеш-таблицы diff --git a/ru/docs/chapter_heap/heap.md b/ru/docs/chapter_heap/heap.md index 405807edd..1c264543c 100644 --- a/ru/docs/chapter_heap/heap.md +++ b/ru/docs/chapter_heap/heap.md @@ -35,382 +35,13 @@ Подобно сортировкам «по возрастанию» и «по убыванию», мы можем переключаться между «минимальной кучей» и «максимальной кучей», изменяя `flag` или модифицируя `Comparator` . Код приведен ниже: -=== "Python" - - ```python title="heap.py" - # Инициализация минимальной кучи - min_heap, flag = [], 1 - # Инициализация максимальной кучи - max_heap, flag = [], -1 - - # Модуль heapq в Python по умолчанию реализует минимальную кучу - # Если инвертировать знак элемента перед добавлением, то отношение порядка перевернется и так реализуется максимальная куча - # В этом примере flag = 1 соответствует минимальной куче, а flag = -1 - максимальной - - # Добавление элементов в кучу - heapq.heappush(max_heap, flag * 1) - heapq.heappush(max_heap, flag * 3) - heapq.heappush(max_heap, flag * 2) - heapq.heappush(max_heap, flag * 5) - heapq.heappush(max_heap, flag * 4) - - # Получение элемента на вершине кучи - peek: int = flag * max_heap[0] # 5 - - # Извлечение элемента с вершины кучи - # Извлеченные элементы образуют последовательность по убыванию - val = flag * heapq.heappop(max_heap) # 5 - val = flag * heapq.heappop(max_heap) # 4 - val = flag * heapq.heappop(max_heap) # 3 - val = flag * heapq.heappop(max_heap) # 2 - val = flag * heapq.heappop(max_heap) # 1 - - # Получение размера кучи - size: int = len(max_heap) - - # Проверка, пуста ли куча - is_empty: bool = not max_heap - - # Построение кучи из входного списка - min_heap: list[int] = [1, 3, 2, 5, 4] - heapq.heapify(min_heap) - ``` - -=== "C++" - - ```cpp title="heap.cpp" - /* Инициализация кучи */ - // Инициализация минимальной кучи - priority_queue, greater> minHeap; - // Инициализация максимальной кучи - priority_queue, less> maxHeap; - - /* Добавление элементов в кучу */ - maxHeap.push(1); - maxHeap.push(3); - maxHeap.push(2); - maxHeap.push(5); - maxHeap.push(4); - - /* Получение элемента на вершине кучи */ - int peek = maxHeap.top(); // 5 - - /* Извлечение элемента с вершины кучи */ - // Извлеченные элементы образуют последовательность по убыванию - maxHeap.pop(); // 5 - maxHeap.pop(); // 4 - maxHeap.pop(); // 3 - maxHeap.pop(); // 2 - maxHeap.pop(); // 1 - - /* Получение размера кучи */ - int size = maxHeap.size(); - - /* Проверка, пуста ли куча */ - bool isEmpty = maxHeap.empty(); - - /* Построение кучи из входного списка */ - vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); - ``` - -=== "Java" - - ```java title="heap.java" - /* Инициализация кучи */ - // Инициализация минимальной кучи - Queue minHeap = new PriorityQueue<>(); - // Инициализация максимальной кучи (достаточно изменить Comparator через lambda) - Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); - - /* Добавление элементов в кучу */ - maxHeap.offer(1); - maxHeap.offer(3); - maxHeap.offer(2); - maxHeap.offer(5); - maxHeap.offer(4); - - /* Получение элемента на вершине кучи */ - int peek = maxHeap.peek(); // 5 - - /* Извлечение элемента с вершины кучи */ - // Извлеченные элементы образуют последовательность по убыванию - peek = maxHeap.poll(); // 5 - peek = maxHeap.poll(); // 4 - peek = maxHeap.poll(); // 3 - peek = maxHeap.poll(); // 2 - peek = maxHeap.poll(); // 1 - - /* Получение размера кучи */ - int size = maxHeap.size(); - - /* Проверка, пуста ли куча */ - boolean isEmpty = maxHeap.isEmpty(); - - /* Построение кучи из входного списка */ - minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); - ``` - -=== "C#" - - ```csharp title="heap.cs" - /* Инициализация кучи */ - // Инициализация минимальной кучи - PriorityQueue minHeap = new(); - // Инициализация максимальной кучи (достаточно изменить Comparer через lambda) - PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); - - /* Добавление элементов в кучу */ - maxHeap.Enqueue(1, 1); - maxHeap.Enqueue(3, 3); - maxHeap.Enqueue(2, 2); - maxHeap.Enqueue(5, 5); - maxHeap.Enqueue(4, 4); - - /* Получение элемента на вершине кучи */ - int peek = maxHeap.Peek();//5 - - /* Извлечение элемента с вершины кучи */ - // Извлеченные элементы образуют последовательность по убыванию - peek = maxHeap.Dequeue(); // 5 - peek = maxHeap.Dequeue(); // 4 - peek = maxHeap.Dequeue(); // 3 - peek = maxHeap.Dequeue(); // 2 - peek = maxHeap.Dequeue(); // 1 - - /* Получение размера кучи */ - int size = maxHeap.Count; - - /* Проверка, пуста ли куча */ - bool isEmpty = maxHeap.Count == 0; - - /* Построение кучи из входного списка */ - minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); - ``` - -=== "Go" - - ```go title="heap.go" - // В Go можно построить целочисленную максимальную кучу, реализовав heap.Interface - // Для реализации heap.Interface также нужно реализовать sort.Interface - type intHeap []any - - // Метод Push из heap.Interface, реализует добавление элемента в кучу - func (h *intHeap) Push(x any) { - // Push и Pop используют pointer receiver - // Потому что они не только изменяют содержимое среза, но и его длину - *h = append(*h, x.(int)) - } - - // Метод Pop из heap.Interface, реализует извлечение элемента с вершины кучи - func (h *intHeap) Pop() any { - // Извлекаемый элемент хранится в конце - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last - } - - // Метод Len из sort.Interface - func (h *intHeap) Len() int { - return len(*h) - } - - // Метод Less из sort.Interface - func (h *intHeap) Less(i, j int) bool { - // Для минимальной кучи здесь нужно заменить сравнение на < - return (*h)[i].(int) > (*h)[j].(int) - } - - // Метод Swap из sort.Interface - func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] - } - - // Top получает элемент на вершине кучи - func (h *intHeap) Top() any { - return (*h)[0] - } - - /* Driver Code */ - func TestHeap(t *testing.T) { - /* Инициализация кучи */ - // Инициализация максимальной кучи - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* Добавление элементов в кучу */ - // Вызываем методы heap.Interface для добавления элементов - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* Получение элемента на вершине кучи */ - top := maxHeap.Top() - fmt.Printf("Элемент на вершине кучи: %d\n", top) - - /* Извлечение элемента с вершины кучи */ - // Вызываем методы heap.Interface для удаления элементов - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 - - /* Получение размера кучи */ - size := len(*maxHeap) - fmt.Printf("Число элементов в куче: %d\n", size) - - /* Проверка, пуста ли куча */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("Пуста ли куча: %t\n", isEmpty) - } - ``` - -=== "Swift" - - ```swift title="heap.swift" - /* Инициализация кучи */ - // Тип Heap в Swift поддерживает и max-heap, и min-heap, но требует swift-collections - var heap = Heap() - - /* Добавление элементов в кучу */ - heap.insert(1) - heap.insert(3) - heap.insert(2) - heap.insert(5) - heap.insert(4) - - /* Получение элемента на вершине кучи */ - var peek = heap.max()! - - /* Извлечение элемента с вершины кучи */ - peek = heap.removeMax() // 5 - peek = heap.removeMax() // 4 - peek = heap.removeMax() // 3 - peek = heap.removeMax() // 2 - peek = heap.removeMax() // 1 - - /* Получение размера кучи */ - let size = heap.count - - /* Проверка, пуста ли куча */ - let isEmpty = heap.isEmpty - - /* Построение кучи из входного списка */ - let heap2 = Heap([1, 3, 2, 5, 4]) - ``` - -=== "JS" - - ```javascript title="heap.js" - // В JavaScript нет встроенного класса Heap - ``` - -=== "TS" - - ```typescript title="heap.ts" - // В TypeScript нет встроенного класса Heap - ``` - -=== "Dart" - - ```dart title="heap.dart" - // В Dart нет встроенного класса Heap - ``` - -=== "Rust" - - ```rust title="heap.rs" - use std::collections::BinaryHeap; - use std::cmp::Reverse; - - /* Инициализация кучи */ - // Инициализация минимальной кучи - let mut min_heap = BinaryHeap::>::new(); - // Инициализация максимальной кучи - let mut max_heap = BinaryHeap::new(); - - /* Добавление элементов в кучу */ - max_heap.push(1); - max_heap.push(3); - max_heap.push(2); - max_heap.push(5); - max_heap.push(4); - - /* Получение элемента на вершине кучи */ - let peek = max_heap.peek().unwrap(); // 5 - - /* Извлечение элемента с вершины кучи */ - // Извлеченные элементы образуют последовательность по убыванию - let peek = max_heap.pop().unwrap(); // 5 - let peek = max_heap.pop().unwrap(); // 4 - let peek = max_heap.pop().unwrap(); // 3 - let peek = max_heap.pop().unwrap(); // 2 - let peek = max_heap.pop().unwrap(); // 1 - - /* Получение размера кучи */ - let size = max_heap.len(); - - /* Проверка, пуста ли куча */ - let is_empty = max_heap.is_empty(); - - /* Построение кучи из входного списка */ - let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); - ``` - -=== "C" - - ```c title="heap.c" - // В C нет встроенного класса Heap - ``` - -=== "Kotlin" - - ```kotlin title="heap.kt" - /* Инициализация кучи */ - // Инициализация минимальной кучи - var minHeap = PriorityQueue() - // Инициализация максимальной кучи (достаточно изменить Comparator через lambda) - val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } - - /* Добавление элементов в кучу */ - maxHeap.offer(1) - maxHeap.offer(3) - maxHeap.offer(2) - maxHeap.offer(5) - maxHeap.offer(4) - - /* Получение элемента на вершине кучи */ - var peek = maxHeap.peek() // 5 - - /* Извлечение элемента с вершины кучи */ - // Извлеченные элементы образуют последовательность по убыванию - peek = maxHeap.poll() // 5 - peek = maxHeap.poll() // 4 - peek = maxHeap.poll() // 3 - peek = maxHeap.poll() // 2 - peek = maxHeap.poll() // 1 - - /* Получение размера кучи */ - val size = maxHeap.size - - /* Проверка, пуста ли куча */ - val isEmpty = maxHeap.isEmpty() - - /* Построение кучи из входного списка */ - minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) - ``` - -=== "Ruby" - - ```ruby title="heap.rb" - # В Ruby нет встроенного класса Heap - ``` +```snippet +heap_operations +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20min-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20max-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9C%D0%BE%D0%B4%D1%83%D0%BB%D1%8C%20heapq%20%D0%B2%20Python%20%D0%BF%D0%BE%20%D1%83%D0%BC%D0%BE%D0%BB%D1%87%D0%B0%D0%BD%D0%B8%D1%8E%20%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D1%83%D0%B5%D1%82%20min-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20%23%20%D0%95%D1%81%D0%BB%D0%B8%20%D0%BF%D0%B5%D1%80%D0%B5%D0%B4%20%D0%BF%D0%BE%D0%BC%D0%B5%D1%89%D0%B5%D0%BD%D0%B8%D0%B5%D0%BC%20%D0%B2%20%D0%BA%D1%83%D1%87%D1%83%20%D0%B1%D1%80%D0%B0%D1%82%D1%8C%20%D0%BE%D1%82%D1%80%D0%B8%D1%86%D0%B0%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%2C%20%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%20%D0%BE%D0%B1%D1%80%D0%B0%D1%82%D0%B8%D1%82%D1%8C%20%D0%BE%D1%82%D0%BD%D0%BE%D1%88%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BF%D0%BE%D1%80%D1%8F%D0%B4%D0%BA%D0%B0%20%D0%B8%20%D1%82%D0%B5%D0%BC%20%D1%81%D0%B0%D0%BC%D1%8B%D0%BC%20%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20max-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20%23%20%D0%92%20%D1%8D%D1%82%D0%BE%D0%BC%20%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D0%B5%20flag%20%3D%201%20%D1%81%D0%BE%D0%BE%D1%82%D0%B2%D0%B5%D1%82%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82%20min-%D0%BA%D1%83%D1%87%D0%B5%2C%20%D0%B0%20flag%20%3D%20-1%20%D1%81%D0%BE%D0%BE%D1%82%D0%B2%D0%B5%D1%82%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82%20max-%D0%BA%D1%83%D1%87%D0%B5%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5%20%D0%B8%D0%B7%20%D0%BA%D1%83%D1%87%D0%B8%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%8B%20%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D1%83%D1%8E%D1%82%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C%20%D0%BE%D1%82%20%D0%B1%D0%BE%D0%BB%D1%8C%D1%88%D0%B5%D0%B3%D0%BE%20%D0%BA%20%D0%BC%D0%B5%D0%BD%D1%8C%D1%88%D0%B5%D0%BC%D1%83%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D1%80%D0%B0%D0%B7%D0%BC%D0%B5%D1%80%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%BA%D1%83%D1%87%D0%B0%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%92%D1%85%D0%BE%D0%B4%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D0%B8%D0%BF%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor heap_operations_tutor ## Реализация кучи diff --git a/ru/docs/chapter_preface/suggestions.md b/ru/docs/chapter_preface/suggestions.md index 932df09bb..b96663340 100644 --- a/ru/docs/chapter_preface/suggestions.md +++ b/ru/docs/chapter_preface/suggestions.md @@ -13,170 +13,9 @@ - Когда термины различаются между языками программирования, в качестве стандарта используется Python. Например, `None` применяется для обозначения «пустого» значения. - В некоторых местах книга отходит от стандартов комментирования программного кода ради более компактного оформления. Комментарии в основном делятся на три типа: заголовочные, содержательные и многострочные. -=== "Python" - - ```python title="" - """Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п.""" - - # Содержательный комментарий: подробно поясняет код - - """ - Многострочный - комментарий - """ - ``` - -=== "C++" - - ```cpp title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "Java" - - ```java title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "C#" - - ```csharp title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "Go" - - ```go title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "Swift" - - ```swift title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "JS" - - ```javascript title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "TS" - - ```typescript title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "Dart" - - ```dart title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "Rust" - - ```rust title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - // Многострочный - // комментарий - ``` - -=== "C" - - ```c title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. */ - - // Содержательный комментарий: подробно поясняет код - - /** - * Многострочный - * комментарий - */ - ``` - -=== "Ruby" - - ```ruby title="" - ### Комментарий-заголовок: используется для обозначения функций, классов, тестовых примеров и т. п. ### - - # Содержательный комментарий: подробно поясняет код - - # Многострочный - # комментарий - ``` +```snippet +comment_style +``` ## Эффективное обучение с помощью анимированных иллюстраций diff --git a/ru/docs/chapter_stack_and_queue/deque.md b/ru/docs/chapter_stack_and_queue/deque.md index 353fa7598..40bee982b 100644 --- a/ru/docs/chapter_stack_and_queue/deque.md +++ b/ru/docs/chapter_stack_and_queue/deque.md @@ -21,371 +21,13 @@ Точно так же мы можем напрямую использовать уже реализованные в языках программирования классы двусторонней очереди: -=== "Python" - - ```python title="deque.py" - from collections import deque - - # Инициализация двусторонней очереди - deq: deque[int] = deque() - - # Поместить элементы в очередь - deq.append(2) # Добавить в хвост - deq.append(5) - deq.append(4) - deq.appendleft(3) # Добавить в голову - deq.appendleft(1) - - # Просмотреть элементы - front: int = deq[0] # Элемент в голове - rear: int = deq[-1] # Элемент в хвосте - - # Извлечь элементы из очереди - pop_front: int = deq.popleft() # Извлечь элемент из головы - pop_rear: int = deq.pop() # Извлечь элемент из хвоста - - # Получить длину двусторонней очереди - size: int = len(deq) - - # Проверить, пуста ли двусторонняя очередь - is_empty: bool = len(deq) == 0 - ``` - -=== "C++" - - ```cpp title="deque.cpp" - /* Инициализация двусторонней очереди */ - deque deque; - - /* Поместить элементы в очередь */ - deque.push_back(2); // Добавить в хвост - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // Добавить в голову - deque.push_front(1); - - /* Просмотреть элементы */ - int front = deque.front(); // Элемент в голове - int back = deque.back(); // Элемент в хвосте - - /* Извлечь элементы из очереди */ - deque.pop_front(); // Извлечь элемент из головы - deque.pop_back(); // Извлечь элемент из хвоста - - /* Получить длину двусторонней очереди */ - int size = deque.size(); - - /* Проверить, пуста ли двусторонняя очередь */ - bool empty = deque.empty(); - ``` - -=== "Java" - - ```java title="deque.java" - /* Инициализация двусторонней очереди */ - Deque deque = new LinkedList<>(); - - /* Поместить элементы в очередь */ - deque.offerLast(2); // Добавить в хвост - deque.offerLast(5); - deque.offerLast(4); - deque.offerFirst(3); // Добавить в голову - deque.offerFirst(1); - - /* Просмотреть элементы */ - int peekFirst = deque.peekFirst(); // Элемент в голове - int peekLast = deque.peekLast(); // Элемент в хвосте - - /* Извлечь элементы из очереди */ - int popFirst = deque.pollFirst(); // Извлечь элемент из головы - int popLast = deque.pollLast(); // Извлечь элемент из хвоста - - /* Получить длину двусторонней очереди */ - int size = deque.size(); - - /* Проверить, пуста ли двусторонняя очередь */ - boolean isEmpty = deque.isEmpty(); - ``` - -=== "C#" - - ```csharp title="deque.cs" - /* Инициализация двусторонней очереди */ - // В C# двустороннюю очередь обычно моделируют через связный список LinkedList - LinkedList deque = new(); - - /* Поместить элементы в очередь */ - deque.AddLast(2); // Добавить в хвост - deque.AddLast(5); - deque.AddLast(4); - deque.AddFirst(3); // Добавить в голову - deque.AddFirst(1); - - /* Просмотреть элементы */ - int peekFirst = deque.First.Value; // Элемент в голове - int peekLast = deque.Last.Value; // Элемент в хвосте - - /* Извлечь элементы из очереди */ - deque.RemoveFirst(); // Извлечь элемент из головы - deque.RemoveLast(); // Извлечь элемент из хвоста - - /* Получить длину двусторонней очереди */ - int size = deque.Count; - - /* Проверить, пуста ли двусторонняя очередь */ - bool isEmpty = deque.Count == 0; - ``` - -=== "Go" - - ```go title="deque_test.go" - /* Инициализация двусторонней очереди */ - // В Go list обычно используется как двусторонняя очередь - deque := list.New() - - /* Поместить элементы в очередь */ - deque.PushBack(2) // Добавить в хвост - deque.PushBack(5) - deque.PushBack(4) - deque.PushFront(3) // Добавить в голову - deque.PushFront(1) - - /* Просмотреть элементы */ - front := deque.Front() // Элемент в голове - rear := deque.Back() // Элемент в хвосте - - /* Извлечь элементы из очереди */ - deque.Remove(front) // Извлечь элемент из головы - deque.Remove(rear) // Извлечь элемент из хвоста - - /* Получить длину двусторонней очереди */ - size := deque.Len() - - /* Проверить, пуста ли двусторонняя очередь */ - isEmpty := deque.Len() == 0 - ``` - -=== "Swift" - - ```swift title="deque.swift" - /* Инициализация двусторонней очереди */ - // В Swift нет встроенного класса двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь - var deque: [Int] = [] - - /* Поместить элементы в очередь */ - deque.append(2) // Добавить в хвост - deque.append(5) - deque.append(4) - deque.insert(3, at: 0) // Добавить в голову - deque.insert(1, at: 0) - - /* Просмотреть элементы */ - let peekFirst = deque.first! // Элемент в голове - let peekLast = deque.last! // Элемент в хвосте - - /* Извлечь элементы из очереди */ - // При моделировании через Array сложность popFirst равна O(n) - let popFirst = deque.removeFirst() // Извлечь элемент из головы - let popLast = deque.removeLast() // Извлечь элемент из хвоста - - /* Получить длину двусторонней очереди */ - let size = deque.count - - /* Проверить, пуста ли двусторонняя очередь */ - let isEmpty = deque.isEmpty - ``` - -=== "JS" - - ```javascript title="deque.js" - /* Инициализация двусторонней очереди */ - // В JavaScript нет встроенной двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь - const deque = []; - - /* Поместить элементы в очередь */ - deque.push(2); - deque.push(5); - deque.push(4); - // Обратите внимание: поскольку это массив, метод unshift() имеет сложность O(n) - deque.unshift(3); - deque.unshift(1); - - /* Просмотреть элементы */ - const peekFirst = deque[0]; - const peekLast = deque[deque.length - 1]; - - /* Извлечь элементы из очереди */ - // Обратите внимание: поскольку это массив, метод shift() имеет сложность O(n) - const popFront = deque.shift(); - const popBack = deque.pop(); - - /* Получить длину двусторонней очереди */ - const size = deque.length; - - /* Проверить, пуста ли двусторонняя очередь */ - const isEmpty = size === 0; - ``` - -=== "TS" - - ```typescript title="deque.ts" - /* Инициализация двусторонней очереди */ - // В TypeScript нет встроенной двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь - const deque: number[] = []; - - /* Поместить элементы в очередь */ - deque.push(2); - deque.push(5); - deque.push(4); - // Обратите внимание: поскольку это массив, метод unshift() имеет сложность O(n) - deque.unshift(3); - deque.unshift(1); - - /* Просмотреть элементы */ - const peekFirst: number = deque[0]; - const peekLast: number = deque[deque.length - 1]; - - /* Извлечь элементы из очереди */ - // Обратите внимание: поскольку это массив, метод shift() имеет сложность O(n) - const popFront: number = deque.shift() as number; - const popBack: number = deque.pop() as number; - - /* Получить длину двусторонней очереди */ - const size: number = deque.length; - - /* Проверить, пуста ли двусторонняя очередь */ - const isEmpty: boolean = size === 0; - ``` - -=== "Dart" - - ```dart title="deque.dart" - /* Инициализация двусторонней очереди */ - // В Dart Queue определена как двусторонняя очередь - Queue deque = Queue(); - - /* Поместить элементы в очередь */ - deque.addLast(2); // Добавить в хвост - deque.addLast(5); - deque.addLast(4); - deque.addFirst(3); // Добавить в голову - deque.addFirst(1); - - /* Просмотреть элементы */ - int peekFirst = deque.first; // Элемент в голове - int peekLast = deque.last; // Элемент в хвосте - - /* Извлечь элементы из очереди */ - int popFirst = deque.removeFirst(); // Извлечь элемент из головы - int popLast = deque.removeLast(); // Извлечь элемент из хвоста - - /* Получить длину двусторонней очереди */ - int size = deque.length; - - /* Проверить, пуста ли двусторонняя очередь */ - bool isEmpty = deque.isEmpty; - ``` - -=== "Rust" - - ```rust title="deque.rs" - /* Инициализация двусторонней очереди */ - let mut deque: VecDeque = VecDeque::new(); - - /* Поместить элементы в очередь */ - deque.push_back(2); // Добавить в хвост - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // Добавить в голову - deque.push_front(1); - - /* Просмотреть элементы */ - if let Some(front) = deque.front() { // Элемент в голове - } - if let Some(rear) = deque.back() { // Элемент в хвосте - } - - /* Извлечь элементы из очереди */ - if let Some(pop_front) = deque.pop_front() { // Извлечь элемент из головы - } - if let Some(pop_rear) = deque.pop_back() { // Извлечь элемент из хвоста - } - - /* Получить длину двусторонней очереди */ - let size = deque.len(); - - /* Проверить, пуста ли двусторонняя очередь */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="deque.c" - // В C нет встроенной двусторонней очереди - ``` - -=== "Kotlin" - - ```kotlin title="deque.kt" - /* Инициализация двусторонней очереди */ - val deque = LinkedList() - - /* Поместить элементы в очередь */ - deque.offerLast(2) // Добавить в хвост - deque.offerLast(5) - deque.offerLast(4) - deque.offerFirst(3) // Добавить в голову - deque.offerFirst(1) - - /* Просмотреть элементы */ - val peekFirst = deque.peekFirst() // Элемент в голове - val peekLast = deque.peekLast() // Элемент в хвосте - - /* Извлечь элементы из очереди */ - val popFirst = deque.pollFirst() // Извлечь элемент из головы - val popLast = deque.pollLast() // Извлечь элемент из хвоста - - /* Получить длину двусторонней очереди */ - val size = deque.size - - /* Проверить, пуста ли двусторонняя очередь */ - val isEmpty = deque.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="deque.rb" - # Инициализация двусторонней очереди - # В Ruby нет встроенной двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь - deque = [] - - # Поместить элементы в очередь - deque << 2 - deque << 5 - deque << 4 - # Обратите внимание: поскольку это массив, метод Array#unshift имеет сложность O(n) - deque.unshift(3) - deque.unshift(1) - - # Просмотреть элементы - peek_first = deque.first - peek_last = deque.last - - # Извлечь элементы из очереди - # Обратите внимание: поскольку это массив, метод Array#shift имеет сложность O(n) - pop_front = deque.shift - pop_back = deque.pop - - # Получить длину двусторонней очереди - size = deque.length - - # Проверить, пуста ли двусторонняя очередь - is_empty = size.zero? - ``` +```snippet +deque_operations +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8E%D1%8E%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BC%D0%B5%D1%81%D1%82%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20deq.append%282%29%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D1%83%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8F%D1%8F%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20print%28%22%D0%AD%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20front%20%3D%22%2C%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20print%28%22%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20rear%20%3D%22%2C%20rear%29%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%B0%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20print%28%22%D0%AD%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%2C%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9%20%D0%B8%D0%B7%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D1%8B%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%2C%20pop_front%20%3D%22%2C%20pop_front%29%0A%20%20%20%20print%28%22deque%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20%D0%B8%D0%B7%20%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D1%8B%20%3D%22%2C%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20print%28%22%D0%AD%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%2C%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9%20%D0%B8%D0%B7%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%D0%B0%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%2C%20pop_rear%20%3D%22%2C%20pop_rear%29%0A%20%20%20%20print%28%22deque%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20%D0%B8%D0%B7%20%D1%85%D0%B2%D0%BE%D1%81%D1%82%D0%B0%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BB%D0%B8%D0%BD%D1%83%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D0%B5%D0%B9%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22%D0%94%D0%BB%D0%B8%D0%BD%D0%B0%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D0%B5%D0%B9%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8F%D1%8F%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22%D0%9F%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8F%D1%8F%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor deque_operations_tutor ## Реализация двусторонней очереди * diff --git a/ru/docs/chapter_stack_and_queue/queue.md b/ru/docs/chapter_stack_and_queue/queue.md index a4ee259b8..dc38fd5c3 100644 --- a/ru/docs/chapter_stack_and_queue/queue.md +++ b/ru/docs/chapter_stack_and_queue/queue.md @@ -20,345 +20,13 @@ Обычно достаточно использовать готовые классы очереди, предоставляемые языками программирования: -=== "Python" - - ```python title="queue.py" - from collections import deque - - # Инициализация очереди - # В Python обычно используют двустороннюю очередь deque как обычную очередь - # Хотя queue.Queue() является "чистой" очередью, она не слишком удобна, поэтому ее не рекомендуют - que: deque[int] = deque() - - # Поместить элементы в очередь - que.append(1) - que.append(3) - que.append(2) - que.append(5) - que.append(4) - - # Просмотреть элемент в голове очереди - front: int = que[0] - - # Извлечь элемент из очереди - pop: int = que.popleft() - - # Получить длину очереди - size: int = len(que) - - # Проверить, пуста ли очередь - is_empty: bool = len(que) == 0 - ``` - -=== "C++" - - ```cpp title="queue.cpp" - /* Инициализация очереди */ - queue queue; - - /* Поместить элементы в очередь */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* Просмотреть элемент в голове очереди */ - int front = queue.front(); - - /* Извлечь элемент из очереди */ - queue.pop(); - - /* Получить длину очереди */ - int size = queue.size(); - - /* Проверить, пуста ли очередь */ - bool empty = queue.empty(); - ``` - -=== "Java" - - ```java title="queue.java" - /* Инициализация очереди */ - Queue queue = new LinkedList<>(); - - /* Поместить элементы в очередь */ - queue.offer(1); - queue.offer(3); - queue.offer(2); - queue.offer(5); - queue.offer(4); - - /* Просмотреть элемент в голове очереди */ - int peek = queue.peek(); - - /* Извлечь элемент из очереди */ - int pop = queue.poll(); - - /* Получить длину очереди */ - int size = queue.size(); - - /* Проверить, пуста ли очередь */ - boolean isEmpty = queue.isEmpty(); - ``` - -=== "C#" - - ```csharp title="queue.cs" - /* Инициализация очереди */ - Queue queue = new(); - - /* Поместить элементы в очередь */ - queue.Enqueue(1); - queue.Enqueue(3); - queue.Enqueue(2); - queue.Enqueue(5); - queue.Enqueue(4); - - /* Просмотреть элемент в голове очереди */ - int peek = queue.Peek(); - - /* Извлечь элемент из очереди */ - int pop = queue.Dequeue(); - - /* Получить длину очереди */ - int size = queue.Count; - - /* Проверить, пуста ли очередь */ - bool isEmpty = queue.Count == 0; - ``` - -=== "Go" - - ```go title="queue_test.go" - /* Инициализация очереди */ - // В Go очередь обычно реализуют через list - queue := list.New() - - /* Поместить элементы в очередь */ - queue.PushBack(1) - queue.PushBack(3) - queue.PushBack(2) - queue.PushBack(5) - queue.PushBack(4) - - /* Просмотреть элемент в голове очереди */ - peek := queue.Front() - - /* Извлечь элемент из очереди */ - pop := queue.Front() - queue.Remove(pop) - - /* Получить длину очереди */ - size := queue.Len() - - /* Проверить, пуста ли очередь */ - isEmpty := queue.Len() == 0 - ``` - -=== "Swift" - - ```swift title="queue.swift" - /* Инициализация очереди */ - // В Swift нет встроенного класса очереди, поэтому можно использовать Array как очередь - var queue: [Int] = [] - - /* Поместить элементы в очередь */ - queue.append(1) - queue.append(3) - queue.append(2) - queue.append(5) - queue.append(4) - - /* Просмотреть элемент в голове очереди */ - let peek = queue.first! - - /* Извлечь элемент из очереди */ - // Поскольку в основе лежит массив, removeFirst имеет сложность O(n) - let pop = queue.removeFirst() - - /* Получить длину очереди */ - let size = queue.count - - /* Проверить, пуста ли очередь */ - let isEmpty = queue.isEmpty - ``` - -=== "JS" - - ```javascript title="queue.js" - /* Инициализация очереди */ - // В JavaScript нет встроенной очереди, поэтому можно использовать Array как очередь - const queue = []; - - /* Поместить элементы в очередь */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* Просмотреть элемент в голове очереди */ - const peek = queue[0]; - - /* Извлечь элемент из очереди */ - // В основе лежит массив, поэтому shift() имеет сложность O(n) - const pop = queue.shift(); - - /* Получить длину очереди */ - const size = queue.length; - - /* Проверить, пуста ли очередь */ - const empty = queue.length === 0; - ``` - -=== "TS" - - ```typescript title="queue.ts" - /* Инициализация очереди */ - // В TypeScript нет встроенной очереди, поэтому можно использовать Array как очередь - const queue: number[] = []; - - /* Поместить элементы в очередь */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* Просмотреть элемент в голове очереди */ - const peek = queue[0]; - - /* Извлечь элемент из очереди */ - // В основе лежит массив, поэтому shift() имеет сложность O(n) - const pop = queue.shift(); - - /* Получить длину очереди */ - const size = queue.length; - - /* Проверить, пуста ли очередь */ - const empty = queue.length === 0; - ``` - -=== "Dart" - - ```dart title="queue.dart" - /* Инициализация очереди */ - // В Dart класс Queue является двусторонней очередью и может использоваться как обычная очередь - Queue queue = Queue(); - - /* Поместить элементы в очередь */ - queue.add(1); - queue.add(3); - queue.add(2); - queue.add(5); - queue.add(4); - - /* Просмотреть элемент в голове очереди */ - int peek = queue.first; - - /* Извлечь элемент из очереди */ - int pop = queue.removeFirst(); - - /* Получить длину очереди */ - int size = queue.length; - - /* Проверить, пуста ли очередь */ - bool isEmpty = queue.isEmpty; - ``` - -=== "Rust" - - ```rust title="queue.rs" - /* Инициализация двусторонней очереди */ - // В Rust двусторонняя очередь может использоваться как обычная очередь - let mut deque: VecDeque = VecDeque::new(); - - /* Поместить элементы в очередь */ - deque.push_back(1); - deque.push_back(3); - deque.push_back(2); - deque.push_back(5); - deque.push_back(4); - - /* Просмотреть элемент в голове очереди */ - if let Some(front) = deque.front() { - } - - /* Извлечь элемент из очереди */ - if let Some(pop) = deque.pop_front() { - } - - /* Получить длину очереди */ - let size = deque.len(); - - /* Проверить, пуста ли очередь */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="queue.c" - // В C нет встроенной очереди - ``` - -=== "Kotlin" - - ```kotlin title="queue.kt" - /* Инициализация очереди */ - val queue = LinkedList() - - /* Поместить элементы в очередь */ - queue.offer(1) - queue.offer(3) - queue.offer(2) - queue.offer(5) - queue.offer(4) - - /* Просмотреть элемент в голове очереди */ - val peek = queue.peek() - - /* Извлечь элемент из очереди */ - val pop = queue.poll() - - /* Получить длину очереди */ - val size = queue.size - - /* Проверить, пуста ли очередь */ - val isEmpty = queue.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="queue.rb" - # Инициализация очереди - # Встроенная очередь в Ruby (Thread::Queue) не имеет методов peek и traverse, поэтому можно использовать Array как очередь - queue = [] - - # Поместить элементы в очередь - queue.push(1) - queue.push(3) - queue.push(2) - queue.push(5) - queue.push(4) - - # Просмотреть элемент очереди - peek = queue.first - - # Извлечь элемент из очереди - # Обратите внимание: поскольку это массив, метод Array#shift имеет сложность O(n) - pop = queue.shift - - # Получить длину очереди - size = queue.length - - # Проверить, пуста ли очередь - is_empty = queue.empty? - ``` +```snippet +queue_operations +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20%23%20%D0%92%20Python%20%D0%B4%D0%B2%D1%83%D1%81%D1%82%D0%BE%D1%80%D0%BE%D0%BD%D0%BD%D1%8E%D1%8E%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20deque%20%D0%BE%D0%B1%D1%8B%D1%87%D0%BD%D0%BE%20%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D1%83%D1%8E%D1%82%20%D0%BA%D0%B0%D0%BA%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20%23%20%D0%A5%D0%BE%D1%82%D1%8F%20queue.Queue%28%29%20%D1%8F%D0%B2%D0%BB%D1%8F%D0%B5%D1%82%D1%81%D1%8F%20%D0%BD%D0%B0%D1%81%D1%82%D0%BE%D1%8F%D1%89%D0%B8%D0%BC%20%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%BE%D0%BC%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%2C%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%D1%81%D1%8F%20%D0%B8%D0%BC%20%D0%BD%D0%B5%20%D1%81%D0%BB%D0%B8%D1%88%D0%BA%D0%BE%D0%BC%20%D1%83%D0%B4%D0%BE%D0%B1%D0%BD%D0%BE%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BC%D0%B5%D1%81%D1%82%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22%D0%AD%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D0%B5%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20front%20%3D%22%2C%20front%29%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9%20%D0%B8%D0%B7%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22que%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BB%D0%B8%D0%BD%D1%83%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22%D0%94%D0%BB%D0%B8%D0%BD%D0%B0%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D0%B8%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22%D0%9F%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%BE%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor queue_operations_tutor ## Реализация очереди diff --git a/ru/docs/chapter_stack_and_queue/stack.md b/ru/docs/chapter_stack_and_queue/stack.md index c3ab638d1..15262f4a9 100644 --- a/ru/docs/chapter_stack_and_queue/stack.md +++ b/ru/docs/chapter_stack_and_queue/stack.md @@ -22,336 +22,13 @@ Обычно достаточно использовать встроенный стек, предоставляемый языком программирования. Однако в некоторых языках специальный класс стека может отсутствовать. В таком случае можно использовать массив или связный список как стек и в логике программы игнорировать операции, не относящиеся к стеку. -=== "Python" - - ```python title="stack.py" - # Инициализация стека - # В Python нет встроенного класса стека, поэтому можно использовать list как стек - stack: list[int] = [] - - # Поместить элементы в стек - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - # Просмотреть верхний элемент - peek: int = stack[-1] - - # Извлечь элемент - pop: int = stack.pop() - - # Получить длину стека - size: int = len(stack) - - # Проверить, пуст ли стек - is_empty: bool = len(stack) == 0 - ``` - -=== "C++" - - ```cpp title="stack.cpp" - /* Инициализация стека */ - stack stack; - - /* Поместить элементы в стек */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Просмотреть верхний элемент */ - int top = stack.top(); - - /* Извлечь элемент */ - stack.pop(); // Без возвращаемого значения - - /* Получить длину стека */ - int size = stack.size(); - - /* Проверить, пуст ли стек */ - bool empty = stack.empty(); - ``` - -=== "Java" - - ```java title="stack.java" - /* Инициализация стека */ - Stack stack = new Stack<>(); - - /* Поместить элементы в стек */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Просмотреть верхний элемент */ - int peek = stack.peek(); - - /* Извлечь элемент */ - int pop = stack.pop(); - - /* Получить длину стека */ - int size = stack.size(); - - /* Проверить, пуст ли стек */ - boolean isEmpty = stack.isEmpty(); - ``` - -=== "C#" - - ```csharp title="stack.cs" - /* Инициализация стека */ - Stack stack = new(); - - /* Поместить элементы в стек */ - stack.Push(1); - stack.Push(3); - stack.Push(2); - stack.Push(5); - stack.Push(4); - - /* Просмотреть верхний элемент */ - int peek = stack.Peek(); - - /* Извлечь элемент */ - int pop = stack.Pop(); - - /* Получить длину стека */ - int size = stack.Count; - - /* Проверить, пуст ли стек */ - bool isEmpty = stack.Count == 0; - ``` - -=== "Go" - - ```go title="stack_test.go" - /* Инициализация стека */ - // В Go рекомендуется использовать Slice как стек - var stack []int - - /* Поместить элементы в стек */ - stack = append(stack, 1) - stack = append(stack, 3) - stack = append(stack, 2) - stack = append(stack, 5) - stack = append(stack, 4) - - /* Просмотреть верхний элемент */ - peek := stack[len(stack)-1] - - /* Извлечь элемент */ - pop := stack[len(stack)-1] - stack = stack[:len(stack)-1] - - /* Получить длину стека */ - size := len(stack) - - /* Проверить, пуст ли стек */ - isEmpty := len(stack) == 0 - ``` - -=== "Swift" - - ```swift title="stack.swift" - /* Инициализация стека */ - // В Swift нет встроенного класса стека, поэтому можно использовать Array как стек - var stack: [Int] = [] - - /* Поместить элементы в стек */ - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - /* Просмотреть верхний элемент */ - let peek = stack.last! - - /* Извлечь элемент */ - let pop = stack.removeLast() - - /* Получить длину стека */ - let size = stack.count - - /* Проверить, пуст ли стек */ - let isEmpty = stack.isEmpty - ``` - -=== "JS" - - ```javascript title="stack.js" - /* Инициализация стека */ - // В JavaScript нет встроенного класса стека, поэтому можно использовать Array как стек - const stack = []; - - /* Поместить элементы в стек */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Просмотреть верхний элемент */ - const peek = stack[stack.length-1]; - - /* Извлечь элемент */ - const pop = stack.pop(); - - /* Получить длину стека */ - const size = stack.length; - - /* Проверить, пуст ли стек */ - const is_empty = stack.length === 0; - ``` - -=== "TS" - - ```typescript title="stack.ts" - /* Инициализация стека */ - // В TypeScript нет встроенного класса стека, поэтому можно использовать Array как стек - const stack: number[] = []; - - /* Поместить элементы в стек */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Просмотреть верхний элемент */ - const peek = stack[stack.length - 1]; - - /* Извлечь элемент */ - const pop = stack.pop(); - - /* Получить длину стека */ - const size = stack.length; - - /* Проверить, пуст ли стек */ - const is_empty = stack.length === 0; - ``` - -=== "Dart" - - ```dart title="stack.dart" - /* Инициализация стека */ - // В Dart нет встроенного класса стека, поэтому можно использовать List как стек - List stack = []; - - /* Поместить элементы в стек */ - stack.add(1); - stack.add(3); - stack.add(2); - stack.add(5); - stack.add(4); - - /* Просмотреть верхний элемент */ - int peek = stack.last; - - /* Извлечь элемент */ - int pop = stack.removeLast(); - - /* Получить длину стека */ - int size = stack.length; - - /* Проверить, пуст ли стек */ - bool isEmpty = stack.isEmpty; - ``` - -=== "Rust" - - ```rust title="stack.rs" - /* Инициализация стека */ - // Используем Vec как стек - let mut stack: Vec = Vec::new(); - - /* Поместить элементы в стек */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* Просмотреть верхний элемент */ - let top = stack.last().unwrap(); - - /* Извлечь элемент */ - let pop = stack.pop().unwrap(); - - /* Получить длину стека */ - let size = stack.len(); - - /* Проверить, пуст ли стек */ - let is_empty = stack.is_empty(); - ``` - -=== "C" - - ```c title="stack.c" - // В C нет встроенного стека - ``` - -=== "Kotlin" - - ```kotlin title="stack.kt" - /* Инициализация стека */ - val stack = Stack() - - /* Поместить элементы в стек */ - stack.push(1) - stack.push(3) - stack.push(2) - stack.push(5) - stack.push(4) - - /* Просмотреть верхний элемент */ - val peek = stack.peek() - - /* Извлечь элемент */ - val pop = stack.pop() - - /* Получить длину стека */ - val size = stack.size - - /* Проверить, пуст ли стек */ - val isEmpty = stack.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="stack.rb" - # Инициализация стека - # В Ruby нет встроенного класса стека, поэтому можно использовать Array как стек - stack = [] - - # Поместить элементы в стек - stack << 1 - stack << 3 - stack << 2 - stack << 5 - stack << 4 - - # Просмотреть верхний элемент - peek = stack.last - - # Извлечь элемент - pop = stack.pop - - # Получить длину стека - size = stack.length - - # Проверить, пуст ли стек - is_empty = stack.empty? - ``` +```snippet +stack_operations +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D1%82%D0%B5%D0%BA%0A%20%20%20%20%23%20%D0%92%20Python%20%D0%BD%D0%B5%D1%82%20%D0%B2%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%BD%D0%BE%D0%B3%D0%BE%20%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%B0%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%2C%20%D0%BF%D0%BE%D1%8D%D1%82%D0%BE%D0%BC%D1%83%20list%20%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%20%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BA%D0%B0%D0%BA%20%D1%81%D1%82%D0%B5%D0%BA%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BC%D0%B5%D1%81%D1%82%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D1%81%D1%82%D0%B5%D0%BA%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22%D1%81%D1%82%D0%B5%D0%BA%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22%D0%92%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%20peek%20%3D%22%2C%20peek%29%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9%20%D0%B8%D0%B7%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%D0%9F%D0%BE%D1%81%D0%BB%D0%B5%20%D0%B8%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BB%D0%B8%D0%BD%D1%83%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22%D0%94%D0%BB%D0%B8%D0%BD%D0%B0%20%D1%81%D1%82%D0%B5%D0%BA%D0%B0%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%82%D1%83%D1%80%D0%B0%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22%D0%9F%D1%83%D1%81%D1%82%20%D0%BB%D0%B8%20%D1%81%D1%82%D0%B5%D0%BA%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor stack_operations_tutor ## Реализация стека diff --git a/ru/docs/chapter_tree/array_representation_of_tree.md b/ru/docs/chapter_tree/array_representation_of_tree.md index b00051b7c..a65b0b2aa 100644 --- a/ru/docs/chapter_tree/array_representation_of_tree.md +++ b/ru/docs/chapter_tree/array_representation_of_tree.md @@ -24,109 +24,9 @@ Чтобы решить эту проблему, **мы можем явно записывать все `None` в последовательности обхода по уровням** . Как показано на рисунке ниже, после такой обработки последовательность обхода по уровням уже сможет однозначно задавать двоичное дерево. Пример кода приведен ниже: -=== "Python" - - ```python title="" - # Представление двоичного дерева массивом - # Используем None для обозначения пустых позиций - tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] - ``` - -=== "C++" - - ```cpp title="" - /* Представление двоичного дерева массивом */ - // Используем максимальное значение int, INT_MAX, для обозначения пустых позиций - vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Java" - - ```java title="" - /* Представление двоичного дерева массивом */ - // Используя обертку Integer для int, можно применять null для обозначения пустых позиций - Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; - ``` - -=== "C#" - - ```csharp title="" - /* Представление двоичного дерева массивом */ - // Используя nullable-тип int? , можно применять null для обозначения пустых позиций - int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Go" - - ```go title="" - /* Представление двоичного дерева массивом */ - // Используем срез типа any, чтобы можно было применять nil для обозначения пустых позиций - tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} - ``` - -=== "Swift" - - ```swift title="" - /* Представление двоичного дерева массивом */ - // Используя nullable-тип Int? , можно применять nil для обозначения пустых позиций - let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` - -=== "JS" - - ```javascript title="" - /* Представление двоичного дерева массивом */ - // Используем null для обозначения пустых позиций - let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "TS" - - ```typescript title="" - /* Представление двоичного дерева массивом */ - // Используем null для обозначения пустых позиций - let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Dart" - - ```dart title="" - /* Представление двоичного дерева массивом */ - // Используя nullable-тип int? , можно применять null для обозначения пустых позиций - List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Rust" - - ```rust title="" - /* Представление двоичного дерева массивом */ - // Используем None для обозначения пустых позиций - let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; - ``` - -=== "C" - - ```c title="" - /* Представление двоичного дерева массивом */ - // Используем максимальное значение int для обозначения пустых позиций, поэтому узлы не должны принимать значение INT_MAX - int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Представление двоичного дерева массивом */ - // Используем null для обозначения пустых позиций - val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) - ``` - -=== "Ruby" - - ```ruby title="" - ### Представление двоичного дерева массивом ### - # Используем nil для обозначения пустых позиций - tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` +```snippet +tree_array_representation +``` ![Представление произвольного двоичного дерева массивом](array_representation_of_tree.assets/array_representation_with_empty.svg) diff --git a/ru/docs/chapter_tree/avl_tree.md b/ru/docs/chapter_tree/avl_tree.md index ae74ffecb..16d19e67e 100644 --- a/ru/docs/chapter_tree/avl_tree.md +++ b/ru/docs/chapter_tree/avl_tree.md @@ -20,213 +20,9 @@ AVL-дерево одновременно является и двоичным Поскольку операции AVL-дерева требуют получать высоту узла, нам нужно добавить в класс узла переменную `height` : -=== "Python" - - ```python title="" - class TreeNode: - """Класс узла AVL-дерева""" - def __init__(self, val: int): - self.val: int = val # Значение узла - self.height: int = 0 # Высота узла - self.left: TreeNode | None = None # Ссылка на левого дочернего узла - self.right: TreeNode | None = None # Ссылка на правого дочернего узла - ``` - -=== "C++" - - ```cpp title="" - /* Класс узла AVL-дерева */ - struct TreeNode { - int val{}; // Значение узла - int height = 0; // Высота узла - TreeNode *left{}; // Левый дочерний узел - TreeNode *right{}; // Правый дочерний узел - TreeNode() = default; - explicit TreeNode(int x) : val(x){} - }; - ``` - -=== "Java" - - ```java title="" - /* Класс узла AVL-дерева */ - class TreeNode { - public int val; // Значение узла - public int height; // Высота узла - public TreeNode left; // Левый дочерний узел - public TreeNode right; // Правый дочерний узел - public TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* Класс узла AVL-дерева */ - class TreeNode(int? x) { - public int? val = x; // Значение узла - public int height; // Высота узла - public TreeNode? left; // Ссылка на левого дочернего узла - public TreeNode? right; // Ссылка на правого дочернего узла - } - ``` - -=== "Go" - - ```go title="" - /* Структура узла AVL-дерева */ - type TreeNode struct { - Val int // Значение узла - Height int // Высота узла - Left *TreeNode // Ссылка на левого дочернего узла - Right *TreeNode // Ссылка на правого дочернего узла - } - ``` - -=== "Swift" - - ```swift title="" - /* Класс узла AVL-дерева */ - class TreeNode { - var val: Int // Значение узла - var height: Int // Высота узла - var left: TreeNode? // Левый дочерний узел - var right: TreeNode? // Правый дочерний узел - - init(x: Int) { - val = x - height = 0 - } - } - ``` - -=== "JS" - - ```javascript title="" - /* Класс узла AVL-дерева */ - class TreeNode { - val; // Значение узла - height; // Высота узла - left; // Указатель на левого дочернего узла - right; // Указатель на правого дочернего узла - constructor(val, left, right, height) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* Класс узла AVL-дерева */ - class TreeNode { - val: number; // Значение узла - height: number; // Высота узла - left: TreeNode | null; // Указатель на левого дочернего узла - right: TreeNode | null; // Указатель на правого дочернего узла - constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "Dart" - - ```dart title="" - /* Класс узла AVL-дерева */ - class TreeNode { - int val; // Значение узла - int height; // Высота узла - TreeNode? left; // Левый дочерний узел - TreeNode? right; // Правый дочерний узел - TreeNode(this.val, [this.height = 0, this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* Структура узла AVL-дерева */ - struct TreeNode { - val: i32, // Значение узла - height: i32, // Высота узла - left: Option>>, // Левый дочерний узел - right: Option>>, // Правый дочерний узел - } - - impl TreeNode { - /* Конструктор */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - height: 0, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* Структура узла AVL-дерева */ - typedef struct TreeNode { - int val; - int height; - struct TreeNode *left; - struct TreeNode *right; - } TreeNode; - - /* Конструктор */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Класс узла AVL-дерева */ - class TreeNode(val _val: Int) { // Значение узла - var height: Int = 0 // Высота узла - var left: TreeNode? = null // Левый дочерний узел - var right: TreeNode? = null // Правый дочерний узел - } - ``` - -=== "Ruby" - - ```ruby title="" - ### Класс узла AVL-дерева ### - class TreeNode - attr_accessor :val # Значение узла - attr_accessor :height # Высота узла - attr_accessor :left # Ссылка на левого дочернего узла - attr_accessor :right # Ссылка на правого дочернего узла - - def initialize(val) - @val = val - @height = 0 - end - end - ``` +```snippet +avl_tree_node +``` «Высота узла» означает расстояние от этого узла до самого удаленного листового узла, то есть число пройденных «ребер». Особенно важно помнить, что высота листового узла равна $0$ , а высота пустого узла равна $-1$ . Мы создадим две вспомогательные функции: одну для получения высоты узла, другую для ее обновления: diff --git a/ru/docs/chapter_tree/binary_tree.md b/ru/docs/chapter_tree/binary_tree.md index fcfdf3118..2d5a12a4f 100644 --- a/ru/docs/chapter_tree/binary_tree.md +++ b/ru/docs/chapter_tree/binary_tree.md @@ -2,204 +2,9 @@ Двоичное дерево (binary tree) - это нелинейная структура данных, представляющая отношения между «предками» и «потомками» и отражающая логику «разделяй и властвуй». Подобно связному списку, базовой единицей двоичного дерева является узел. Каждый узел содержит значение, ссылку на левого дочернего узла и ссылку на правого дочернего узла. -=== "Python" - - ```python title="" - class TreeNode: - """Класс узла двоичного дерева""" - def __init__(self, val: int): - self.val: int = val # Значение узла - self.left: TreeNode | None = None # Ссылка на левого дочернего узла - self.right: TreeNode | None = None # Ссылка на правого дочернего узла - ``` - -=== "C++" - - ```cpp title="" - /* Структура узла двоичного дерева */ - struct TreeNode { - int val; // Значение узла - TreeNode *left; // Указатель на левого дочернего узла - TreeNode *right; // Указатель на правого дочернего узла - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - }; - ``` - -=== "Java" - - ```java title="" - /* Класс узла двоичного дерева */ - class TreeNode { - int val; // Значение узла - TreeNode left; // Ссылка на левого дочернего узла - TreeNode right; // Ссылка на правого дочернего узла - TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* Класс узла двоичного дерева */ - class TreeNode(int? x) { - public int? val = x; // Значение узла - public TreeNode? left; // Ссылка на левого дочернего узла - public TreeNode? right; // Ссылка на правого дочернего узла - } - ``` - -=== "Go" - - ```go title="" - /* Структура узла двоичного дерева */ - type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode - } - /* Конструктор */ - func NewTreeNode(v int) *TreeNode { - return &TreeNode{ - Left: nil, // Указатель на левого дочернего узла - Right: nil, // Указатель на правого дочернего узла - Val: v, // Значение узла - } - } - ``` - -=== "Swift" - - ```swift title="" - /* Класс узла двоичного дерева */ - class TreeNode { - var val: Int // Значение узла - var left: TreeNode? // Ссылка на левого дочернего узла - var right: TreeNode? // Ссылка на правого дочернего узла - - init(x: Int) { - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* Класс узла двоичного дерева */ - class TreeNode { - val; // Значение узла - left; // Указатель на левого дочернего узла - right; // Указатель на правого дочернего узла - constructor(val, left, right) { - this.val = val === undefined ? 0 : val; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* Класс узла двоичного дерева */ - class TreeNode { - val: number; - left: TreeNode | null; - right: TreeNode | null; - - constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; // Значение узла - this.left = left === undefined ? null : left; // Ссылка на левого дочернего узла - this.right = right === undefined ? null : right; // Ссылка на правого дочернего узла - } - } - ``` - -=== "Dart" - - ```dart title="" - /* Класс узла двоичного дерева */ - class TreeNode { - int val; // Значение узла - TreeNode? left; // Ссылка на левого дочернего узла - TreeNode? right; // Ссылка на правого дочернего узла - TreeNode(this.val, [this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* Структура узла двоичного дерева */ - struct TreeNode { - val: i32, // Значение узла - left: Option>>, // Ссылка на левого дочернего узла - right: Option>>, // Ссылка на правого дочернего узла - } - - impl TreeNode { - /* Конструктор */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* Структура узла двоичного дерева */ - typedef struct TreeNode { - int val; // Значение узла - int height; // Высота узла - struct TreeNode *left; // Указатель на левого дочернего узла - struct TreeNode *right; // Указатель на правого дочернего узла - } TreeNode; - - /* Конструктор */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* Класс узла двоичного дерева */ - class TreeNode(val _val: Int) { // Значение узла - var left: TreeNode? = null // Ссылка на левого дочернего узла - var right: TreeNode? = null // Ссылка на правого дочернего узла - } - ``` - -=== "Ruby" - - ```ruby title="" - ### Класс узла двоичного дерева ### - class TreeNode - attr_accessor :val # Значение узла - attr_accessor :left # Ссылка на левого дочернего узла - attr_accessor :right # Ссылка на правого дочернего узла - - def initialize(val) - @val = val - end - end - ``` +```snippet +tree_node_class +``` Каждый узел имеет две ссылки (указателя), которые соответственно указывают на левого дочернего узла (left-child node) и правого дочернего узла (right-child node). Данный узел называется родительским узлом (parent node) для этих двух дочерних узлов. Если задан некоторый узел двоичного дерева, то дерево, образованное его левым дочерним узлом и всеми узлами ниже него, называется левым поддеревом (left subtree) этого узла. Аналогично определяется правое поддерево (right subtree). @@ -232,226 +37,13 @@ Как и в связном списке, сначала инициализируются узлы, а затем между ними строятся ссылки (указатели). -=== "Python" - - ```python title="binary_tree.py" - # Инициализация двоичного дерева - # Инициализация узлов - n1 = TreeNode(val=1) - n2 = TreeNode(val=2) - n3 = TreeNode(val=3) - n4 = TreeNode(val=4) - n5 = TreeNode(val=5) - # Построение ссылок (указателей) между узлами - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* Инициализация двоичного дерева */ - // Инициализация узлов - TreeNode* n1 = new TreeNode(1); - TreeNode* n2 = new TreeNode(2); - TreeNode* n3 = new TreeNode(3); - TreeNode* n4 = new TreeNode(4); - TreeNode* n5 = new TreeNode(5); - // Построение ссылок (указателей) между узлами - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Java" - - ```java title="binary_tree.java" - // Инициализация узлов - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // Построение ссылок (указателей) между узлами - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* Инициализация двоичного дерева */ - // Инициализация узлов - TreeNode n1 = new(1); - TreeNode n2 = new(2); - TreeNode n3 = new(3); - TreeNode n4 = new(4); - TreeNode n5 = new(5); - // Построение ссылок (указателей) между узлами - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* Инициализация двоичного дерева */ - // Инициализация узлов - n1 := NewTreeNode(1) - n2 := NewTreeNode(2) - n3 := NewTreeNode(3) - n4 := NewTreeNode(4) - n5 := NewTreeNode(5) - // Построение ссылок (указателей) между узлами - n1.Left = n2 - n1.Right = n3 - n2.Left = n4 - n2.Right = n5 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - // Инициализация узлов - let n1 = TreeNode(x: 1) - let n2 = TreeNode(x: 2) - let n3 = TreeNode(x: 3) - let n4 = TreeNode(x: 4) - let n5 = TreeNode(x: 5) - // Построение ссылок (указателей) между узлами - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* Инициализация двоичного дерева */ - // Инициализация узлов - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // Построение ссылок (указателей) между узлами - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* Инициализация двоичного дерева */ - // Инициализация узлов - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // Построение ссылок (указателей) между узлами - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* Инициализация двоичного дерева */ - // Инициализация узлов - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // Построение ссылок (указателей) между узлами - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - // Инициализация узлов - let n1 = TreeNode::new(1); - let n2 = TreeNode::new(2); - let n3 = TreeNode::new(3); - let n4 = TreeNode::new(4); - let n5 = TreeNode::new(5); - // Построение ссылок (указателей) между узлами - n1.borrow_mut().left = Some(n2.clone()); - n1.borrow_mut().right = Some(n3); - n2.borrow_mut().left = Some(n4); - n2.borrow_mut().right = Some(n5); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* Инициализация двоичного дерева */ - // Инициализация узлов - TreeNode *n1 = newTreeNode(1); - TreeNode *n2 = newTreeNode(2); - TreeNode *n3 = newTreeNode(3); - TreeNode *n4 = newTreeNode(4); - TreeNode *n5 = newTreeNode(5); - // Построение ссылок (указателей) между узлами - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - // Инициализация узлов - val n1 = TreeNode(1) - val n2 = TreeNode(2) - val n3 = TreeNode(3) - val n4 = TreeNode(4) - val n5 = TreeNode(5) - // Построение ссылок (указателей) между узлами - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # Инициализация двоичного дерева - # Инициализация узлов - n1 = TreeNode.new(1) - n2 = TreeNode.new(2) - n3 = TreeNode.new(3) - n4 = TreeNode.new(4) - n5 = TreeNode.new(5) - # Построение ссылок (указателей) между узлами - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` +```snippet +init_binary_tree +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%D0%9A%D0%BB%D0%B0%D1%81%D1%81%20%D1%83%D0%B7%D0%BB%D0%B0%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B3%D0%BE%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%B0%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BB%D0%B5%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BF%D1%80%D0%B0%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B5%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%BE%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%D0%9F%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B8%D1%82%D1%8C%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20%D1%83%D0%B7%D0%BB%D0%B0%D0%BC%D0%B8%20%28%D1%83%D0%BA%D0%B0%D0%B7%D0%B0%D1%82%D0%B5%D0%BB%D0%B8%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_binary_tree_tutor ### Вставка и удаление узлов @@ -459,165 +51,13 @@ ![Вставка и удаление узлов в двоичном дереве](binary_tree.assets/binary_tree_add_remove.svg) -=== "Python" - - ```python title="binary_tree.py" - # Вставка и удаление узлов - p = TreeNode(0) - # Вставить узел P между n1 -> n2 - n1.left = p - p.left = n2 - # Удалить узел P - n1.left = n2 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* Вставка и удаление узлов */ - TreeNode* P = new TreeNode(0); - // Вставить узел P между n1 -> n2 - n1->left = P; - P->left = n2; - // Удалить узел P - n1->left = n2; - // Освободить память - delete P; - ``` - -=== "Java" - - ```java title="binary_tree.java" - TreeNode P = new TreeNode(0); - // Вставить узел P между n1 -> n2 - n1.left = P; - P.left = n2; - // Удалить узел P - n1.left = n2; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* Вставка и удаление узлов */ - TreeNode P = new(0); - // Вставить узел P между n1 -> n2 - n1.left = P; - P.left = n2; - // Удалить узел P - n1.left = n2; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* Вставка и удаление узлов */ - // Вставить узел P между n1 -> n2 - p := NewTreeNode(0) - n1.Left = p - p.Left = n2 - // Удалить узел P - n1.Left = n2 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - let P = TreeNode(x: 0) - // Вставить узел P между n1 -> n2 - n1.left = P - P.left = n2 - // Удалить узел P - n1.left = n2 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* Вставка и удаление узлов */ - let P = new TreeNode(0); - // Вставить узел P между n1 -> n2 - n1.left = P; - P.left = n2; - // Удалить узел P - n1.left = n2; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* Вставка и удаление узлов */ - const P = new TreeNode(0); - // Вставить узел P между n1 -> n2 - n1.left = P; - P.left = n2; - // Удалить узел P - n1.left = n2; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* Вставка и удаление узлов */ - TreeNode P = new TreeNode(0); - // Вставить узел P между n1 -> n2 - n1.left = P; - P.left = n2; - // Удалить узел P - n1.left = n2; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - let p = TreeNode::new(0); - // Вставить узел P между n1 -> n2 - n1.borrow_mut().left = Some(p.clone()); - p.borrow_mut().left = Some(n2.clone()); - // Удалить узел p - n1.borrow_mut().left = Some(n2); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* Вставка и удаление узлов */ - TreeNode *P = newTreeNode(0); - // Вставить узел P между n1 -> n2 - n1->left = P; - P->left = n2; - // Удалить узел P - n1->left = n2; - // Освободить память - free(P); - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - val P = TreeNode(0) - // Вставить узел P между n1 -> n2 - n1.left = P - P.left = n2 - // Удалить узел P - n1.left = n2 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # Вставка и удаление узлов - _p = TreeNode.new(0) - # Вставить узел _p между n1 -> n2 - n1.left = _p - _p.left = n2 - # Удалить узел - n1.left = n2 - ``` +```snippet +insert_remove_node +``` ??? pythontutor "Визуализация выполнения" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%D0%9A%D0%BB%D0%B0%D1%81%D1%81%20%D1%83%D0%B7%D0%BB%D0%B0%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B3%D0%BE%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%B0%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BB%D0%B5%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BF%D1%80%D0%B0%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B5%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%BE%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%D0%9F%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B8%D1%82%D1%8C%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20%D1%83%D0%B7%D0%BB%D0%B0%D0%BC%D0%B8%20%28%D1%83%D0%BA%D0%B0%D0%B7%D0%B0%D1%82%D0%B5%D0%BB%D0%B8%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%BA%D0%B0%20%D0%B8%20%D1%83%D0%B4%D0%B0%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%BE%D0%B2%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%20P%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20n1%20-%3E%20n2%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_node_tutor !!! tip diff --git a/zh-hant/codes/snippets/chapter_array_and_linkedlist/array.md b/zh-hant/codes/snippets/chapter_array_and_linkedlist/array.md new file mode 100644 index 000000000..482b522ce --- /dev/null +++ b/zh-hant/codes/snippets/chapter_array_and_linkedlist/array.md @@ -0,0 +1,93 @@ + +```python title="array.py" +# 初始化陣列 +arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="array.cpp" +/* 初始化陣列 */ +// 儲存在堆疊上 +int arr[5] = {}; +int nums[5] = { 1, 3, 2, 5, 4 }; +// 儲存在堆積上(需要手動釋放空間) +int* arr1 = new int[5] {}; +int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +``` + +```java title="array.java" +/* 初始化陣列 */ +int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } +int[] nums = { 1, 3, 2, 5, 4 }; +``` + +```csharp title="array.cs" +/* 初始化陣列 */ +int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] +int[] nums = [1, 3, 2, 5, 4]; +``` + +```go title="array.go" +/* 初始化陣列 */ +var arr [5]int +// 在 Go 中,指定長度時([5]int)為陣列,不指定長度時([]int)為切片 +// 由於 Go 的陣列被設計為在編譯期確定長度,因此只能使用常數來指定長度 +// 為了方便實現擴容 extend() 方法,以下將切片(Slice)看作陣列(Array) +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="array.swift" +/* 初始化陣列 */ +let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] +let nums = [1, 3, 2, 5, 4] +``` + +```javascript title="array.js" +/* 初始化陣列 */ +var arr = new Array(5).fill(0); +var nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="array.ts" +/* 初始化陣列 */ +let arr: number[] = new Array(5).fill(0); +let nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="array.dart" +/* 初始化陣列 */ +List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="array.rs" +/* 初始化陣列 */ +let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] +let slice: &[i32] = &[0; 5]; +// 在 Rust 中,指定長度時([i32; 5])為陣列,不指定長度時(&[i32])為切片 +// 由於 Rust 的陣列被設計為在編譯期確定長度,因此只能使用常數來指定長度 +// Vector 是 Rust 一般情況下用作動態陣列的型別 +// 為了方便實現擴容 extend() 方法,以下將 vector 看作陣列(array) +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="array.c" +/* 初始化陣列 */ +int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } +int nums[5] = { 1, 3, 2, 5, 4 }; +``` + +```kotlin title="array.kt" +/* 初始化陣列 */ +var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +var nums = intArrayOf(1, 3, 2, 5, 4) +``` + +```ruby title="array.rb" +# 初始化陣列 +arr = Array.new(5, 0) +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%99%A3%E5%88%97%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/zh-hant/codes/snippets/chapter_array_and_linkedlist/linked_list.md new file mode 100644 index 000000000..1939b0fa3 --- /dev/null +++ b/zh-hant/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -0,0 +1,516 @@ + +```python title="" +class ListNode: + """鏈結串列節點類別""" + def __init__(self, val: int): + self.val: int = val # 節點值 + self.next: ListNode | None = None # 指向下一節點的引用 +``` + +```cpp title="" +/* 鏈結串列節點結構體 */ +struct ListNode { + int val; // 節點值 + ListNode *next; // 指向下一節點的指標 + ListNode(int x) : val(x), next(nullptr) {} // 建構子 +}; +``` + +```java title="" +/* 鏈結串列節點類別 */ +class ListNode { + int val; // 節點值 + ListNode next; // 指向下一節點的引用 + ListNode(int x) { val = x; } // 建構子 +} +``` + +```csharp title="" +/* 鏈結串列節點類別 */ +class ListNode(int x) { //建構子 + int val = x; // 節點值 + ListNode? next; // 指向下一節點的引用 +} +``` + +```go title="" +/* 鏈結串列節點結構體 */ +type ListNode struct { + Val int // 節點值 + Next *ListNode // 指向下一節點的指標 +} + +// NewListNode 建構子,建立一個新的鏈結串列 +func NewListNode(val int) *ListNode { + return &ListNode{ + Val: val, + Next: nil, + } +} +``` + +```swift title="" +/* 鏈結串列節點類別 */ +class ListNode { + var val: Int // 節點值 + var next: ListNode? // 指向下一節點的引用 + + init(x: Int) { // 建構子 + val = x + } +} +``` + +```javascript title="" +/* 鏈結串列節點類別 */ +class ListNode { + constructor(val, next) { + this.val = (val === undefined ? 0 : val); // 節點值 + this.next = (next === undefined ? null : next); // 指向下一節點的引用 + } +} +``` + +```typescript title="" +/* 鏈結串列節點類別 */ +class ListNode { + val: number; + next: ListNode | null; + constructor(val?: number, next?: ListNode | null) { + this.val = val === undefined ? 0 : val; // 節點值 + this.next = next === undefined ? null : next; // 指向下一節點的引用 + } +} +``` + +```dart title="" +/* 鏈結串列節點類別 */ +class ListNode { + int val; // 節點值 + ListNode? next; // 指向下一節點的引用 + ListNode(this.val, [this.next]); // 建構子 +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; +/* 鏈結串列節點類別 */ +#[derive(Debug)] +struct ListNode { + val: i32, // 節點值 + next: Option>>, // 指向下一節點的指標 +} +``` + +```c title="" +/* 鏈結串列節點結構體 */ +typedef struct ListNode { + int val; // 節點值 + struct ListNode *next; // 指向下一節點的指標 +} ListNode; + +/* 建構子 */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + return node; +} +``` + +```kotlin title="" +/* 鏈結串列節點類別 */ +// 建構子 +class ListNode(x: Int) { + val _val: Int = x // 節點值 + var next: ListNode? = null // 指向下一個節點的引用 +} +``` + +```ruby title="" +# 鏈結串列節點類別 +class ListNode + attr_accessor :val # 節點值 + attr_accessor :next # 指向下一節點的引用 + + def initialize(val=0, next_node=nil) + @val = val + @next = next_node + end +end +``` + + +```python title="linked_list.py" +# 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 +# 初始化各個節點 +n0 = ListNode(1) +n1 = ListNode(3) +n2 = ListNode(2) +n3 = ListNode(5) +n4 = ListNode(4) +# 構建節點之間的引用 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```cpp title="linked_list.cpp" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +ListNode* n0 = new ListNode(1); +ListNode* n1 = new ListNode(3); +ListNode* n2 = new ListNode(2); +ListNode* n3 = new ListNode(5); +ListNode* n4 = new ListNode(4); +// 構建節點之間的引用 +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```java title="linked_list.java" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +ListNode n0 = new ListNode(1); +ListNode n1 = new ListNode(3); +ListNode n2 = new ListNode(2); +ListNode n3 = new ListNode(5); +ListNode n4 = new ListNode(4); +// 構建節點之間的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```csharp title="linked_list.cs" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +ListNode n0 = new(1); +ListNode n1 = new(3); +ListNode n2 = new(2); +ListNode n3 = new(5); +ListNode n4 = new(4); +// 構建節點之間的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```go title="linked_list.go" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +n0 := NewListNode(1) +n1 := NewListNode(3) +n2 := NewListNode(2) +n3 := NewListNode(5) +n4 := NewListNode(4) +// 構建節點之間的引用 +n0.Next = n1 +n1.Next = n2 +n2.Next = n3 +n3.Next = n4 +``` + +```swift title="linked_list.swift" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +let n0 = ListNode(x: 1) +let n1 = ListNode(x: 3) +let n2 = ListNode(x: 2) +let n3 = ListNode(x: 5) +let n4 = ListNode(x: 4) +// 構建節點之間的引用 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + +```javascript title="linked_list.js" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// 構建節點之間的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```typescript title="linked_list.ts" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +const n0 = new ListNode(1); +const n1 = new ListNode(3); +const n2 = new ListNode(2); +const n3 = new ListNode(5); +const n4 = new ListNode(4); +// 構建節點之間的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```dart title="linked_list.dart" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */\ +// 初始化各個節點 +ListNode n0 = ListNode(1); +ListNode n1 = ListNode(3); +ListNode n2 = ListNode(2); +ListNode n3 = ListNode(5); +ListNode n4 = ListNode(4); +// 構建節點之間的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```rust title="linked_list.rs" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); +let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); +let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); +let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); +let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); + +// 構建節點之間的引用 +n0.borrow_mut().next = Some(n1.clone()); +n1.borrow_mut().next = Some(n2.clone()); +n2.borrow_mut().next = Some(n3.clone()); +n3.borrow_mut().next = Some(n4.clone()); +``` + +```c title="linked_list.c" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +ListNode* n0 = newListNode(1); +ListNode* n1 = newListNode(3); +ListNode* n2 = newListNode(2); +ListNode* n3 = newListNode(5); +ListNode* n4 = newListNode(4); +// 構建節點之間的引用 +n0->next = n1; +n1->next = n2; +n2->next = n3; +n3->next = n4; +``` + +```kotlin title="linked_list.kt" +/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化各個節點 +val n0 = ListNode(1) +val n1 = ListNode(3) +val n2 = ListNode(2) +val n3 = ListNode(5) +val n4 = ListNode(4) +// 構建節點之間的引用 +n0.next = n1; +n1.next = n2; +n2.next = n3; +n3.next = n4; +``` + +```ruby title="linked_list.rb" +# 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 +# 初始化各個節點 +n0 = ListNode.new(1) +n1 = ListNode.new(3) +n2 = ListNode.new(2) +n3 = ListNode.new(5) +n4 = ListNode.new(4) +# 構建節點之間的引用 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%BE%8C%E7%B9%BC%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%90%84%E5%80%8B%E7%AF%80%E9%BB%9E%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20%E6%A7%8B%E5%BB%BA%E7%AF%80%E9%BB%9E%E4%B9%8B%E9%96%93%E7%9A%84%E5%BC%95%E7%94%A8%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="" +class ListNode: + """雙向鏈結串列節點類別""" + def __init__(self, val: int): + self.val: int = val # 節點值 + self.next: ListNode | None = None # 指向後繼節點的引用 + self.prev: ListNode | None = None # 指向前驅節點的引用 +``` + +```cpp title="" +/* 雙向鏈結串列節點結構體 */ +struct ListNode { + int val; // 節點值 + ListNode *next; // 指向後繼節點的指標 + ListNode *prev; // 指向前驅節點的指標 + ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 建構子 +}; +``` + +```java title="" +/* 雙向鏈結串列節點類別 */ +class ListNode { + int val; // 節點值 + ListNode next; // 指向後繼節點的引用 + ListNode prev; // 指向前驅節點的引用 + ListNode(int x) { val = x; } // 建構子 +} +``` + +```csharp title="" +/* 雙向鏈結串列節點類別 */ +class ListNode(int x) { // 建構子 + int val = x; // 節點值 + ListNode next; // 指向後繼節點的引用 + ListNode prev; // 指向前驅節點的引用 +} +``` + +```go title="" +/* 雙向鏈結串列節點結構體 */ +type DoublyListNode struct { + Val int // 節點值 + Next *DoublyListNode // 指向後繼節點的指標 + Prev *DoublyListNode // 指向前驅節點的指標 +} + +// NewDoublyListNode 初始化 +func NewDoublyListNode(val int) *DoublyListNode { + return &DoublyListNode{ + Val: val, + Next: nil, + Prev: nil, + } +} +``` + +```swift title="" +/* 雙向鏈結串列節點類別 */ +class ListNode { + var val: Int // 節點值 + var next: ListNode? // 指向後繼節點的引用 + var prev: ListNode? // 指向前驅節點的引用 + + init(x: Int) { // 建構子 + val = x + } +} +``` + +```javascript title="" +/* 雙向鏈結串列節點類別 */ +class ListNode { + constructor(val, next, prev) { + this.val = val === undefined ? 0 : val; // 節點值 + this.next = next === undefined ? null : next; // 指向後繼節點的引用 + this.prev = prev === undefined ? null : prev; // 指向前驅節點的引用 + } +} +``` + +```typescript title="" +/* 雙向鏈結串列節點類別 */ +class ListNode { + val: number; + next: ListNode | null; + prev: ListNode | null; + constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { + this.val = val === undefined ? 0 : val; // 節點值 + this.next = next === undefined ? null : next; // 指向後繼節點的引用 + this.prev = prev === undefined ? null : prev; // 指向前驅節點的引用 + } +} +``` + +```dart title="" +/* 雙向鏈結串列節點類別 */ +class ListNode { + int val; // 節點值 + ListNode? next; // 指向後繼節點的引用 + ListNode? prev; // 指向前驅節點的引用 + ListNode(this.val, [this.next, this.prev]); // 建構子 +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 雙向鏈結串列節點型別 */ +#[derive(Debug)] +struct ListNode { + val: i32, // 節點值 + next: Option>>, // 指向後繼節點的指標 + prev: Option>>, // 指向前驅節點的指標 +} + +/* 建構子 */ +impl ListNode { + fn new(val: i32) -> Self { + ListNode { + val, + next: None, + prev: None, + } + } +} +``` + +```c title="" +/* 雙向鏈結串列節點結構體 */ +typedef struct ListNode { + int val; // 節點值 + struct ListNode *next; // 指向後繼節點的指標 + struct ListNode *prev; // 指向前驅節點的指標 +} ListNode; + +/* 建構子 */ +ListNode *newListNode(int val) { + ListNode *node; + node = (ListNode *) malloc(sizeof(ListNode)); + node->val = val; + node->next = NULL; + node->prev = NULL; + return node; +} +``` + +```kotlin title="" +/* 雙向鏈結串列節點類別 */ +// 建構子 +class ListNode(x: Int) { + val _val: Int = x // 節點值 + var next: ListNode? = null // 指向後繼節點的引用 + var prev: ListNode? = null // 指向前驅節點的引用 +} +``` + +```ruby title="" +# 雙向鏈結串列節點類別 +class ListNode + attr_accessor :val # 節點值 + attr_accessor :next # 指向後繼節點的引用 + attr_accessor :prev # 指向前驅節點的引用 + + def initialize(val=0, next_node=nil, prev_node=nil) + @val = val + @next = next_node + @prev = prev_node + end +end +``` diff --git a/zh-hant/codes/snippets/chapter_array_and_linkedlist/list.md b/zh-hant/codes/snippets/chapter_array_and_linkedlist/list.md new file mode 100644 index 000000000..aacf2931d --- /dev/null +++ b/zh-hant/codes/snippets/chapter_array_and_linkedlist/list.md @@ -0,0 +1,752 @@ + +```python title="list.py" +# 初始化串列 +# 無初始值 +nums1: list[int] = [] +# 有初始值 +nums: list[int] = [1, 3, 2, 5, 4] +``` + +```cpp title="list.cpp" +/* 初始化串列 */ +// 需注意,C++ 中 vector 即是本文描述的 nums +// 無初始值 +vector nums1; +// 有初始值 +vector nums = { 1, 3, 2, 5, 4 }; +``` + +```java title="list.java" +/* 初始化串列 */ +// 無初始值 +List nums1 = new ArrayList<>(); +// 有初始值(注意陣列的元素型別需為 int[] 的包裝類別 Integer[]) +Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; +List nums = new ArrayList<>(Arrays.asList(numbers)); +``` + +```csharp title="list.cs" +/* 初始化串列 */ +// 無初始值 +List nums1 = []; +// 有初始值 +int[] numbers = [1, 3, 2, 5, 4]; +List nums = [.. numbers]; +``` + +```go title="list_test.go" +/* 初始化串列 */ +// 無初始值 +nums1 := []int{} +// 有初始值 +nums := []int{1, 3, 2, 5, 4} +``` + +```swift title="list.swift" +/* 初始化串列 */ +// 無初始值 +let nums1: [Int] = [] +// 有初始值 +var nums = [1, 3, 2, 5, 4] +``` + +```javascript title="list.js" +/* 初始化串列 */ +// 無初始值 +const nums1 = []; +// 有初始值 +const nums = [1, 3, 2, 5, 4]; +``` + +```typescript title="list.ts" +/* 初始化串列 */ +// 無初始值 +const nums1: number[] = []; +// 有初始值 +const nums: number[] = [1, 3, 2, 5, 4]; +``` + +```dart title="list.dart" +/* 初始化串列 */ +// 無初始值 +List nums1 = []; +// 有初始值 +List nums = [1, 3, 2, 5, 4]; +``` + +```rust title="list.rs" +/* 初始化串列 */ +// 無初始值 +let nums1: Vec = Vec::new(); +// 有初始值 +let nums: Vec = vec![1, 3, 2, 5, 4]; +``` + +```c title="list.c" +// C 未提供內建動態陣列 +``` + +```kotlin title="list.kt" +/* 初始化串列 */ +// 無初始值 +var nums1 = listOf() +// 有初始值 +var numbers = arrayOf(1, 3, 2, 5, 4) +var nums = numbers.toMutableList() +``` + +```ruby title="list.rb" +# 初始化串列 +# 無初始值 +nums1 = [] +# 有初始值 +nums = [1, 3, 2, 5, 4] +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20%23%20%E7%84%A1%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 訪問元素 +num: int = nums[1] # 訪問索引 1 處的元素 + +# 更新元素 +nums[1] = 0 # 將索引 1 處的元素更新為 0 +``` + +```cpp title="list.cpp" +/* 訪問元素 */ +int num = nums[1]; // 訪問索引 1 處的元素 + +/* 更新元素 */ +nums[1] = 0; // 將索引 1 處的元素更新為 0 +``` + +```java title="list.java" +/* 訪問元素 */ +int num = nums.get(1); // 訪問索引 1 處的元素 + +/* 更新元素 */ +nums.set(1, 0); // 將索引 1 處的元素更新為 0 +``` + +```csharp title="list.cs" +/* 訪問元素 */ +int num = nums[1]; // 訪問索引 1 處的元素 + +/* 更新元素 */ +nums[1] = 0; // 將索引 1 處的元素更新為 0 +``` + +```go title="list_test.go" +/* 訪問元素 */ +num := nums[1] // 訪問索引 1 處的元素 + +/* 更新元素 */ +nums[1] = 0 // 將索引 1 處的元素更新為 0 +``` + +```swift title="list.swift" +/* 訪問元素 */ +let num = nums[1] // 訪問索引 1 處的元素 + +/* 更新元素 */ +nums[1] = 0 // 將索引 1 處的元素更新為 0 +``` + +```javascript title="list.js" +/* 訪問元素 */ +const num = nums[1]; // 訪問索引 1 處的元素 + +/* 更新元素 */ +nums[1] = 0; // 將索引 1 處的元素更新為 0 +``` + +```typescript title="list.ts" +/* 訪問元素 */ +const num: number = nums[1]; // 訪問索引 1 處的元素 + +/* 更新元素 */ +nums[1] = 0; // 將索引 1 處的元素更新為 0 +``` + +```dart title="list.dart" +/* 訪問元素 */ +int num = nums[1]; // 訪問索引 1 處的元素 + +/* 更新元素 */ +nums[1] = 0; // 將索引 1 處的元素更新為 0 +``` + +```rust title="list.rs" +/* 訪問元素 */ +let num: i32 = nums[1]; // 訪問索引 1 處的元素 +/* 更新元素 */ +nums[1] = 0; // 將索引 1 處的元素更新為 0 +``` + +```c title="list.c" +// C 未提供內建動態陣列 +``` + +```kotlin title="list.kt" +/* 訪問元素 */ +val num = nums[1] // 訪問索引 1 處的元素 +/* 更新元素 */ +nums[1] = 0 // 將索引 1 處的元素更新為 0 +``` + +```ruby title="list.rb" +# 訪問元素 +num = nums[1] # 訪問索引 1 處的元素 +# 更新元素 +nums[1] = 0 # 將索引 1 處的元素更新為 0 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E5%85%83%E7%B4%A0%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E8%A8%AA%E5%95%8F%E7%B4%A2%E5%BC%95%201%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%87%E7%B4%A2%E5%BC%95%201%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E7%82%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 清空串列 +nums.clear() + +# 在尾部新增元素 +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +# 在中間插入元素 +nums.insert(3, 6) # 在索引 3 處插入數字 6 + +# 刪除元素 +nums.pop(3) # 刪除索引 3 處的元素 +``` + +```cpp title="list.cpp" +/* 清空串列 */ +nums.clear(); + +/* 在尾部新增元素 */ +nums.push_back(1); +nums.push_back(3); +nums.push_back(2); +nums.push_back(5); +nums.push_back(4); + +/* 在中間插入元素 */ +nums.insert(nums.begin() + 3, 6); // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums.erase(nums.begin() + 3); // 刪除索引 3 處的元素 +``` + +```java title="list.java" +/* 清空串列 */ +nums.clear(); + +/* 在尾部新增元素 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 在中間插入元素 */ +nums.add(3, 6); // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums.remove(3); // 刪除索引 3 處的元素 +``` + +```csharp title="list.cs" +/* 清空串列 */ +nums.Clear(); + +/* 在尾部新增元素 */ +nums.Add(1); +nums.Add(3); +nums.Add(2); +nums.Add(5); +nums.Add(4); + +/* 在中間插入元素 */ +nums.Insert(3, 6); // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums.RemoveAt(3); // 刪除索引 3 處的元素 +``` + +```go title="list_test.go" +/* 清空串列 */ +nums = nil + +/* 在尾部新增元素 */ +nums = append(nums, 1) +nums = append(nums, 3) +nums = append(nums, 2) +nums = append(nums, 5) +nums = append(nums, 4) + +/* 在中間插入元素 */ +nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums = append(nums[:3], nums[4:]...) // 刪除索引 3 處的元素 +``` + +```swift title="list.swift" +/* 清空串列 */ +nums.removeAll() + +/* 在尾部新增元素 */ +nums.append(1) +nums.append(3) +nums.append(2) +nums.append(5) +nums.append(4) + +/* 在中間插入元素 */ +nums.insert(6, at: 3) // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums.remove(at: 3) // 刪除索引 3 處的元素 +``` + +```javascript title="list.js" +/* 清空串列 */ +nums.length = 0; + +/* 在尾部新增元素 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 在中間插入元素 */ +nums.splice(3, 0, 6); // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums.splice(3, 1); // 刪除索引 3 處的元素 +``` + +```typescript title="list.ts" +/* 清空串列 */ +nums.length = 0; + +/* 在尾部新增元素 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 在中間插入元素 */ +nums.splice(3, 0, 6); // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums.splice(3, 1); // 刪除索引 3 處的元素 +``` + +```dart title="list.dart" +/* 清空串列 */ +nums.clear(); + +/* 在尾部新增元素 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 在中間插入元素 */ +nums.insert(3, 6); // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums.removeAt(3); // 刪除索引 3 處的元素 +``` + +```rust title="list.rs" +/* 清空串列 */ +nums.clear(); + +/* 在尾部新增元素 */ +nums.push(1); +nums.push(3); +nums.push(2); +nums.push(5); +nums.push(4); + +/* 在中間插入元素 */ +nums.insert(3, 6); // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums.remove(3); // 刪除索引 3 處的元素 +``` + +```c title="list.c" +// C 未提供內建動態陣列 +``` + +```kotlin title="list.kt" +/* 清空串列 */ +nums.clear(); + +/* 在尾部新增元素 */ +nums.add(1); +nums.add(3); +nums.add(2); +nums.add(5); +nums.add(4); + +/* 在中間插入元素 */ +nums.add(3, 6); // 在索引 3 處插入數字 6 + +/* 刪除元素 */ +nums.remove(3); // 刪除索引 3 處的元素 +``` + +```ruby title="list.rb" +# 清空串列 +nums.clear + +# 在尾部新增元素 +nums << 1 +nums << 3 +nums << 2 +nums << 5 +nums << 4 + +# 在中間插入元素 +nums.insert(3, 6) # 在索引 3 處插入數字 6 + +# 刪除元素 +nums.delete_at(3) # 刪除索引 3 處的元素 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B8%85%E7%A9%BA%E4%B8%B2%E5%88%97%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E5%B0%BE%E9%83%A8%E6%96%B0%E5%A2%9E%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E4%B8%AD%E9%96%93%E6%8F%92%E5%85%A5%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.insert%283%2C%206%29%20%20%23%20%E5%9C%A8%E7%B4%A2%E5%BC%95%203%20%E8%99%95%E6%8F%92%E5%85%A5%E6%95%B8%E5%AD%97%206%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E7%B4%A2%E5%BC%95%203%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 透過索引走訪串列 +count = 0 +for i in range(len(nums)): + count += nums[i] + +# 直接走訪串列元素 +for num in nums: + count += num +``` + +```cpp title="list.cpp" +/* 透過索引走訪串列 */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums[i]; +} + +/* 直接走訪串列元素 */ +count = 0; +for (int num : nums) { + count += num; +} +``` + +```java title="list.java" +/* 透過索引走訪串列 */ +int count = 0; +for (int i = 0; i < nums.size(); i++) { + count += nums.get(i); +} + +/* 直接走訪串列元素 */ +for (int num : nums) { + count += num; +} +``` + +```csharp title="list.cs" +/* 透過索引走訪串列 */ +int count = 0; +for (int i = 0; i < nums.Count; i++) { + count += nums[i]; +} + +/* 直接走訪串列元素 */ +count = 0; +foreach (int num in nums) { + count += num; +} +``` + +```go title="list_test.go" +/* 透過索引走訪串列 */ +count := 0 +for i := 0; i < len(nums); i++ { + count += nums[i] +} + +/* 直接走訪串列元素 */ +count = 0 +for _, num := range nums { + count += num +} +``` + +```swift title="list.swift" +/* 透過索引走訪串列 */ +var count = 0 +for i in nums.indices { + count += nums[i] +} + +/* 直接走訪串列元素 */ +count = 0 +for num in nums { + count += num +} +``` + +```javascript title="list.js" +/* 透過索引走訪串列 */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* 直接走訪串列元素 */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```typescript title="list.ts" +/* 透過索引走訪串列 */ +let count = 0; +for (let i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* 直接走訪串列元素 */ +count = 0; +for (const num of nums) { + count += num; +} +``` + +```dart title="list.dart" +/* 透過索引走訪串列 */ +int count = 0; +for (var i = 0; i < nums.length; i++) { + count += nums[i]; +} + +/* 直接走訪串列元素 */ +count = 0; +for (var num in nums) { + count += num; +} +``` + +```rust title="list.rs" +// 透過索引走訪串列 +let mut _count = 0; +for i in 0..nums.len() { + _count += nums[i]; +} + +// 直接走訪串列元素 +_count = 0; +for num in &nums { + _count += num; +} +``` + +```c title="list.c" +// C 未提供內建動態陣列 +``` + +```kotlin title="list.kt" +/* 透過索引走訪串列 */ +var count = 0 +for (i in nums.indices) { + count += nums[i] +} + +/* 直接走訪串列元素 */ +for (num in nums) { + count += num +} +``` + +```ruby title="list.rb" +# 透過索引走訪串列 +count = 0 +for i in 0...nums.length + count += nums[i] +end + +# 直接走訪串列元素 +count = 0 +for num in nums + count += num +end +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%80%8F%E9%81%8E%E7%B4%A2%E5%BC%95%E8%B5%B0%E8%A8%AA%E4%B8%B2%E5%88%97%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%E7%9B%B4%E6%8E%A5%E8%B5%B0%E8%A8%AA%E4%B8%B2%E5%88%97%E5%85%83%E7%B4%A0%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 拼接兩個串列 +nums1: list[int] = [6, 8, 7, 10, 9] +nums += nums1 # 將串列 nums1 拼接到 nums 之後 +``` + +```cpp title="list.cpp" +/* 拼接兩個串列 */ +vector nums1 = { 6, 8, 7, 10, 9 }; +// 將串列 nums1 拼接到 nums 之後 +nums.insert(nums.end(), nums1.begin(), nums1.end()); +``` + +```java title="list.java" +/* 拼接兩個串列 */ +List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); +nums.addAll(nums1); // 將串列 nums1 拼接到 nums 之後 +``` + +```csharp title="list.cs" +/* 拼接兩個串列 */ +List nums1 = [6, 8, 7, 10, 9]; +nums.AddRange(nums1); // 將串列 nums1 拼接到 nums 之後 +``` + +```go title="list_test.go" +/* 拼接兩個串列 */ +nums1 := []int{6, 8, 7, 10, 9} +nums = append(nums, nums1...) // 將串列 nums1 拼接到 nums 之後 +``` + +```swift title="list.swift" +/* 拼接兩個串列 */ +let nums1 = [6, 8, 7, 10, 9] +nums.append(contentsOf: nums1) // 將串列 nums1 拼接到 nums 之後 +``` + +```javascript title="list.js" +/* 拼接兩個串列 */ +const nums1 = [6, 8, 7, 10, 9]; +nums.push(...nums1); // 將串列 nums1 拼接到 nums 之後 +``` + +```typescript title="list.ts" +/* 拼接兩個串列 */ +const nums1: number[] = [6, 8, 7, 10, 9]; +nums.push(...nums1); // 將串列 nums1 拼接到 nums 之後 +``` + +```dart title="list.dart" +/* 拼接兩個串列 */ +List nums1 = [6, 8, 7, 10, 9]; +nums.addAll(nums1); // 將串列 nums1 拼接到 nums 之後 +``` + +```rust title="list.rs" +/* 拼接兩個串列 */ +let nums1: Vec = vec![6, 8, 7, 10, 9]; +nums.extend(nums1); +``` + +```c title="list.c" +// C 未提供內建動態陣列 +``` + +```kotlin title="list.kt" +/* 拼接兩個串列 */ +val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() +nums.addAll(nums1) // 將串列 nums1 拼接到 nums 之後 +``` + +```ruby title="list.rb" +# 拼接兩個串列 +nums1 = [6, 8, 7, 10, 9] +nums += nums1 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8B%BC%E6%8E%A5%E5%85%A9%E5%80%8B%E4%B8%B2%E5%88%97%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%E5%B0%87%E4%B8%B2%E5%88%97%20nums1%20%E6%8B%BC%E6%8E%A5%E5%88%B0%20nums%20%E4%B9%8B%E5%BE%8C&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="list.py" +# 排序串列 +nums.sort() # 排序後,串列元素從小到大排列 +``` + +```cpp title="list.cpp" +/* 排序串列 */ +sort(nums.begin(), nums.end()); // 排序後,串列元素從小到大排列 +``` + +```java title="list.java" +/* 排序串列 */ +Collections.sort(nums); // 排序後,串列元素從小到大排列 +``` + +```csharp title="list.cs" +/* 排序串列 */ +nums.Sort(); // 排序後,串列元素從小到大排列 +``` + +```go title="list_test.go" +/* 排序串列 */ +sort.Ints(nums) // 排序後,串列元素從小到大排列 +``` + +```swift title="list.swift" +/* 排序串列 */ +nums.sort() // 排序後,串列元素從小到大排列 +``` + +```javascript title="list.js" +/* 排序串列 */ +nums.sort((a, b) => a - b); // 排序後,串列元素從小到大排列 +``` + +```typescript title="list.ts" +/* 排序串列 */ +nums.sort((a, b) => a - b); // 排序後,串列元素從小到大排列 +``` + +```dart title="list.dart" +/* 排序串列 */ +nums.sort(); // 排序後,串列元素從小到大排列 +``` + +```rust title="list.rs" +/* 排序串列 */ +nums.sort(); // 排序後,串列元素從小到大排列 +``` + +```c title="list.c" +// C 未提供內建動態陣列 +``` + +```kotlin title="list.kt" +/* 排序串列 */ +nums.sort() // 排序後,串列元素從小到大排列 +``` + +```ruby title="list.rb" +# 排序串列 +nums = nums.sort { |a, b| a <=> b } # 排序後,串列元素從小到大排列 +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8E%92%E5%BA%8F%E4%B8%B2%E5%88%97%0A%20%20%20%20nums.sort%28%29%20%20%23%20%E6%8E%92%E5%BA%8F%E5%BE%8C%EF%BC%8C%E4%B8%B2%E5%88%97%E5%85%83%E7%B4%A0%E5%BE%9E%E5%B0%8F%E5%88%B0%E5%A4%A7%E6%8E%92%E5%88%97&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_backtracking/backtracking_algorithm.md b/zh-hant/codes/snippets/chapter_backtracking/backtracking_algorithm.md new file mode 100644 index 000000000..4c9832a21 --- /dev/null +++ b/zh-hant/codes/snippets/chapter_backtracking/backtracking_algorithm.md @@ -0,0 +1,308 @@ + +```python title="" +def backtrack(state: State, choices: list[choice], res: list[state]): + """回溯演算法框架""" + # 判斷是否為解 + if is_solution(state): + # 記錄解 + record_solution(state, res) + # 不再繼續搜尋 + return + # 走訪所有選擇 + for choice in choices: + # 剪枝:判斷選擇是否合法 + if is_valid(state, choice): + # 嘗試:做出選擇,更新狀態 + make_choice(state, choice) + backtrack(state, choices, res) + # 回退:撤銷選擇,恢復到之前的狀態 + undo_choice(state, choice) +``` + +```cpp title="" +/* 回溯演算法框架 */ +void backtrack(State *state, vector &choices, vector &res) { + // 判斷是否為解 + if (isSolution(state)) { + // 記錄解 + recordSolution(state, res); + // 不再繼續搜尋 + return; + } + // 走訪所有選擇 + for (Choice choice : choices) { + // 剪枝:判斷選擇是否合法 + if (isValid(state, choice)) { + // 嘗試:做出選擇,更新狀態 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤銷選擇,恢復到之前的狀態 + undoChoice(state, choice); + } + } +} +``` + +```java title="" +/* 回溯演算法框架 */ +void backtrack(State state, List choices, List res) { + // 判斷是否為解 + if (isSolution(state)) { + // 記錄解 + recordSolution(state, res); + // 不再繼續搜尋 + return; + } + // 走訪所有選擇 + for (Choice choice : choices) { + // 剪枝:判斷選擇是否合法 + if (isValid(state, choice)) { + // 嘗試:做出選擇,更新狀態 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤銷選擇,恢復到之前的狀態 + undoChoice(state, choice); + } + } +} +``` + +```csharp title="" +/* 回溯演算法框架 */ +void Backtrack(State state, List choices, List res) { + // 判斷是否為解 + if (IsSolution(state)) { + // 記錄解 + RecordSolution(state, res); + // 不再繼續搜尋 + return; + } + // 走訪所有選擇 + foreach (Choice choice in choices) { + // 剪枝:判斷選擇是否合法 + if (IsValid(state, choice)) { + // 嘗試:做出選擇,更新狀態 + MakeChoice(state, choice); + Backtrack(state, choices, res); + // 回退:撤銷選擇,恢復到之前的狀態 + UndoChoice(state, choice); + } + } +} +``` + +```go title="" +/* 回溯演算法框架 */ +func backtrack(state *State, choices []Choice, res *[]State) { + // 判斷是否為解 + if isSolution(state) { + // 記錄解 + recordSolution(state, res) + // 不再繼續搜尋 + return + } + // 走訪所有選擇 + for _, choice := range choices { + // 剪枝:判斷選擇是否合法 + if isValid(state, choice) { + // 嘗試:做出選擇,更新狀態 + makeChoice(state, choice) + backtrack(state, choices, res) + // 回退:撤銷選擇,恢復到之前的狀態 + undoChoice(state, choice) + } + } +} +``` + +```swift title="" +/* 回溯演算法框架 */ +func backtrack(state: inout State, choices: [Choice], res: inout [State]) { + // 判斷是否為解 + if isSolution(state: state) { + // 記錄解 + recordSolution(state: state, res: &res) + // 不再繼續搜尋 + return + } + // 走訪所有選擇 + for choice in choices { + // 剪枝:判斷選擇是否合法 + if isValid(state: state, choice: choice) { + // 嘗試:做出選擇,更新狀態 + makeChoice(state: &state, choice: choice) + backtrack(state: &state, choices: choices, res: &res) + // 回退:撤銷選擇,恢復到之前的狀態 + undoChoice(state: &state, choice: choice) + } + } +} +``` + +```javascript title="" +/* 回溯演算法框架 */ +function backtrack(state, choices, res) { + // 判斷是否為解 + if (isSolution(state)) { + // 記錄解 + recordSolution(state, res); + // 不再繼續搜尋 + return; + } + // 走訪所有選擇 + for (let choice of choices) { + // 剪枝:判斷選擇是否合法 + if (isValid(state, choice)) { + // 嘗試:做出選擇,更新狀態 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤銷選擇,恢復到之前的狀態 + undoChoice(state, choice); + } + } +} +``` + +```typescript title="" +/* 回溯演算法框架 */ +function backtrack(state: State, choices: Choice[], res: State[]): void { + // 判斷是否為解 + if (isSolution(state)) { + // 記錄解 + recordSolution(state, res); + // 不再繼續搜尋 + return; + } + // 走訪所有選擇 + for (let choice of choices) { + // 剪枝:判斷選擇是否合法 + if (isValid(state, choice)) { + // 嘗試:做出選擇,更新狀態 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤銷選擇,恢復到之前的狀態 + undoChoice(state, choice); + } + } +} +``` + +```dart title="" +/* 回溯演算法框架 */ +void backtrack(State state, List, List res) { + // 判斷是否為解 + if (isSolution(state)) { + // 記錄解 + recordSolution(state, res); + // 不再繼續搜尋 + return; + } + // 走訪所有選擇 + for (Choice choice in choices) { + // 剪枝:判斷選擇是否合法 + if (isValid(state, choice)) { + // 嘗試:做出選擇,更新狀態 + makeChoice(state, choice); + backtrack(state, choices, res); + // 回退:撤銷選擇,恢復到之前的狀態 + undoChoice(state, choice); + } + } +} +``` + +```rust title="" +/* 回溯演算法框架 */ +fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { + // 判斷是否為解 + if is_solution(state) { + // 記錄解 + record_solution(state, res); + // 不再繼續搜尋 + return; + } + // 走訪所有選擇 + for choice in choices { + // 剪枝:判斷選擇是否合法 + if is_valid(state, choice) { + // 嘗試:做出選擇,更新狀態 + make_choice(state, choice); + backtrack(state, choices, res); + // 回退:撤銷選擇,恢復到之前的狀態 + undo_choice(state, choice); + } + } +} +``` + +```c title="" +/* 回溯演算法框架 */ +void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { + // 判斷是否為解 + if (isSolution(state)) { + // 記錄解 + recordSolution(state, res, numRes); + // 不再繼續搜尋 + return; + } + // 走訪所有選擇 + for (int i = 0; i < numChoices; i++) { + // 剪枝:判斷選擇是否合法 + if (isValid(state, &choices[i])) { + // 嘗試:做出選擇,更新狀態 + makeChoice(state, &choices[i]); + backtrack(state, choices, numChoices, res, numRes); + // 回退:撤銷選擇,恢復到之前的狀態 + undoChoice(state, &choices[i]); + } + } +} +``` + +```kotlin title="" +/* 回溯演算法框架 */ +fun backtrack(state: State?, choices: List, res: List?) { + // 判斷是否為解 + if (isSolution(state)) { + // 記錄解 + recordSolution(state, res) + // 不再繼續搜尋 + return + } + // 走訪所有選擇 + for (choice in choices) { + // 剪枝:判斷選擇是否合法 + if (isValid(state, choice)) { + // 嘗試:做出選擇,更新狀態 + makeChoice(state, choice) + backtrack(state, choices, res) + // 回退:撤銷選擇,恢復到之前的狀態 + undoChoice(state, choice) + } + } +} +``` + +```ruby title="" +### 回溯演算法框架 ### +def backtrack(state, choices, res) + # 判斷是否為解 + if is_solution?(state) + # 記錄解 + record_solution(state, res) + return + end + + # 走訪所有選擇 + for choice in choices + # 剪枝:判斷選擇是否合法 + if is_valid?(state, choice) + # 嘗試:做出選擇,更新狀態 + make_choice(state, choice) + backtrack(state, choices, res) + # 回退:撤銷選擇,恢復到之前的狀態 + undo_choice(state, choice) + end + end +end +``` diff --git a/zh-hant/codes/snippets/chapter_computational_complexity/space_complexity.md b/zh-hant/codes/snippets/chapter_computational_complexity/space_complexity.md new file mode 100644 index 000000000..77d41635b --- /dev/null +++ b/zh-hant/codes/snippets/chapter_computational_complexity/space_complexity.md @@ -0,0 +1,682 @@ + +```python title="" +class Node: + """類別""" + def __init__(self, x: int): + self.val: int = x # 節點值 + self.next: Node | None = None # 指向下一節點的引用 + +def function() -> int: + """函式""" + # 執行某些操作... + return 0 + +def algorithm(n) -> int: # 輸入資料 + A = 0 # 暫存資料(常數,一般用大寫字母表示) + b = 0 # 暫存資料(變數) + node = Node(0) # 暫存資料(物件) + c = function() # 堆疊幀空間(呼叫函式) + return A + b + c # 輸出資料 +``` + +```cpp title="" +/* 結構體 */ +struct Node { + int val; + Node *next; + Node(int x) : val(x), next(nullptr) {} +}; + +/* 函式 */ +int func() { + // 執行某些操作... + return 0; +} + +int algorithm(int n) { // 輸入資料 + const int a = 0; // 暫存資料(常數) + int b = 0; // 暫存資料(變數) + Node* node = new Node(0); // 暫存資料(物件) + int c = func(); // 堆疊幀空間(呼叫函式) + return a + b + c; // 輸出資料 +} +``` + +```java title="" +/* 類別 */ +class Node { + int val; + Node next; + Node(int x) { val = x; } +} + +/* 函式 */ +int function() { + // 執行某些操作... + return 0; +} + +int algorithm(int n) { // 輸入資料 + final int a = 0; // 暫存資料(常數) + int b = 0; // 暫存資料(變數) + Node node = new Node(0); // 暫存資料(物件) + int c = function(); // 堆疊幀空間(呼叫函式) + return a + b + c; // 輸出資料 +} +``` + +```csharp title="" +/* 類別 */ +class Node(int x) { + int val = x; + Node next; +} + +/* 函式 */ +int Function() { + // 執行某些操作... + return 0; +} + +int Algorithm(int n) { // 輸入資料 + const int a = 0; // 暫存資料(常數) + int b = 0; // 暫存資料(變數) + Node node = new(0); // 暫存資料(物件) + int c = Function(); // 堆疊幀空間(呼叫函式) + return a + b + c; // 輸出資料 +} +``` + +```go title="" +/* 結構體 */ +type node struct { + val int + next *node +} + +/* 建立 node 結構體 */ +func newNode(val int) *node { + return &node{val: val} +} + +/* 函式 */ +func function() int { + // 執行某些操作... + return 0 +} + +func algorithm(n int) int { // 輸入資料 + const a = 0 // 暫存資料(常數) + b := 0 // 暫存資料(變數) + newNode(0) // 暫存資料(物件) + c := function() // 堆疊幀空間(呼叫函式) + return a + b + c // 輸出資料 +} +``` + +```swift title="" +/* 類別 */ +class Node { + var val: Int + var next: Node? + + init(x: Int) { + val = x + } +} + +/* 函式 */ +func function() -> Int { + // 執行某些操作... + return 0 +} + +func algorithm(n: Int) -> Int { // 輸入資料 + let a = 0 // 暫存資料(常數) + var b = 0 // 暫存資料(變數) + let node = Node(x: 0) // 暫存資料(物件) + let c = function() // 堆疊幀空間(呼叫函式) + return a + b + c // 輸出資料 +} +``` + +```javascript title="" +/* 類別 */ +class Node { + val; + next; + constructor(val) { + this.val = val === undefined ? 0 : val; // 節點值 + this.next = null; // 指向下一節點的引用 + } +} + +/* 函式 */ +function constFunc() { + // 執行某些操作 + return 0; +} + +function algorithm(n) { // 輸入資料 + const a = 0; // 暫存資料(常數) + let b = 0; // 暫存資料(變數) + const node = new Node(0); // 暫存資料(物件) + const c = constFunc(); // 堆疊幀空間(呼叫函式) + return a + b + c; // 輸出資料 +} +``` + +```typescript title="" +/* 類別 */ +class Node { + val: number; + next: Node | null; + constructor(val?: number) { + this.val = val === undefined ? 0 : val; // 節點值 + this.next = null; // 指向下一節點的引用 + } +} + +/* 函式 */ +function constFunc(): number { + // 執行某些操作 + return 0; +} + +function algorithm(n: number): number { // 輸入資料 + const a = 0; // 暫存資料(常數) + let b = 0; // 暫存資料(變數) + const node = new Node(0); // 暫存資料(物件) + const c = constFunc(); // 堆疊幀空間(呼叫函式) + return a + b + c; // 輸出資料 +} +``` + +```dart title="" +/* 類別 */ +class Node { + int val; + Node next; + Node(this.val, [this.next]); +} + +/* 函式 */ +int function() { + // 執行某些操作... + return 0; +} + +int algorithm(int n) { // 輸入資料 + const int a = 0; // 暫存資料(常數) + int b = 0; // 暫存資料(變數) + Node node = Node(0); // 暫存資料(物件) + int c = function(); // 堆疊幀空間(呼叫函式) + return a + b + c; // 輸出資料 +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 結構體 */ +struct Node { + val: i32, + next: Option>>, +} + +/* 建立 Node 結構體 */ +impl Node { + fn new(val: i32) -> Self { + Self { val: val, next: None } + } +} + +/* 函式 */ +fn function() -> i32 { + // 執行某些操作... + return 0; +} + +fn algorithm(n: i32) -> i32 { // 輸入資料 + const a: i32 = 0; // 暫存資料(常數) + let mut b = 0; // 暫存資料(變數) + let node = Node::new(0); // 暫存資料(物件) + let c = function(); // 堆疊幀空間(呼叫函式) + return a + b + c; // 輸出資料 +} +``` + +```c title="" +/* 函式 */ +int func() { + // 執行某些操作... + return 0; +} + +int algorithm(int n) { // 輸入資料 + const int a = 0; // 暫存資料(常數) + int b = 0; // 暫存資料(變數) + int c = func(); // 堆疊幀空間(呼叫函式) + return a + b + c; // 輸出資料 +} +``` + +```kotlin title="" +/* 類別 */ +class Node(var _val: Int) { + var next: Node? = null +} + +/* 函式 */ +fun function(): Int { + // 執行某些操作... + return 0 +} + +fun algorithm(n: Int): Int { // 輸入資料 + val a = 0 // 暫存資料(常數) + var b = 0 // 暫存資料(變數) + val node = Node(0) // 暫存資料(物件) + val c = function() // 堆疊幀空間(呼叫函式) + return a + b + c // 輸出資料 +} +``` + +```ruby title="" +### 類別 ### +class Node + attr_accessor :val # 節點值 + attr_accessor :next # 指向下一節點的引用 + + def initialize(x) + @val = x + end +end + +### 函式 ### +def function + # 執行某些操作... + 0 +end + +### 演算法 ### +def algorithm(n) # 輸入資料 + a = 0 # 暫存資料(常數) + b = 0 # 暫存資料(變數) + node = Node.new(0) # 暫存資料(物件) + c = function # 堆疊幀空間(呼叫函式) + a + b + c # 輸出資料 +end +``` + + +```python title="" +def algorithm(n: int): + a = 0 # O(1) + b = [0] * 10000 # O(1) + if n > 10: + nums = [0] * n # O(n) +``` + +```cpp title="" +void algorithm(int n) { + int a = 0; // O(1) + vector b(10000); // O(1) + if (n > 10) + vector nums(n); // O(n) +} +``` + +```java title="" +void algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) + int[] nums = new int[n]; // O(n) +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 0; // O(1) + int[] b = new int[10000]; // O(1) + if (n > 10) { + int[] nums = new int[n]; // O(n) + } +} +``` + +```go title="" +func algorithm(n int) { + a := 0 // O(1) + b := make([]int, 10000) // O(1) + var nums []int + if n > 10 { + nums := make([]int, n) // O(n) + } + fmt.Println(a, b, nums) +} +``` + +```swift title="" +func algorithm(n: Int) { + let a = 0 // O(1) + let b = Array(repeating: 0, count: 10000) // O(1) + if n > 10 { + let nums = Array(repeating: 0, count: n) // O(n) + } +} +``` + +```javascript title="" +function algorithm(n) { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + const a = 0; // O(1) + const b = new Array(10000); // O(1) + if (n > 10) { + const nums = new Array(n); // O(n) + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 0; // O(1) + List b = List.filled(10000, 0); // O(1) + if (n > 10) { + List nums = List.filled(n, 0); // O(n) + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let a = 0; // O(1) + let b = [0; 10000]; // O(1) + if n > 10 { + let nums = vec![0; n as usize]; // O(n) + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 0; // O(1) + int b[10000]; // O(1) + if (n > 10) + int nums[n] = {0}; // O(n) +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + val a = 0 // O(1) + val b = IntArray(10000) // O(1) + if (n > 10) { + val nums = IntArray(n) // O(n) + } +} +``` + +```ruby title="" +def algorithm(n) + a = 0 # O(1) + b = Array.new(10000) # O(1) + nums = Array.new(n) if n > 10 # O(n) +end +``` + + +```python title="" +def function() -> int: + # 執行某些操作 + return 0 + +def loop(n: int): + """迴圈的空間複雜度為 O(1)""" + for _ in range(n): + function() + +def recur(n: int): + """遞迴的空間複雜度為 O(n)""" + if n == 1: + return + return recur(n - 1) +``` + +```cpp title="" +int func() { + // 執行某些操作 + return 0; +} +/* 迴圈的空間複雜度為 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* 遞迴的空間複雜度為 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```java title="" +int function() { + // 執行某些操作 + return 0; +} +/* 迴圈的空間複雜度為 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* 遞迴的空間複雜度為 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```csharp title="" +int Function() { + // 執行某些操作 + return 0; +} +/* 迴圈的空間複雜度為 O(1) */ +void Loop(int n) { + for (int i = 0; i < n; i++) { + Function(); + } +} +/* 遞迴的空間複雜度為 O(n) */ +int Recur(int n) { + if (n == 1) return 1; + return Recur(n - 1); +} +``` + +```go title="" +func function() int { + // 執行某些操作 + return 0 +} + +/* 迴圈的空間複雜度為 O(1) */ +func loop(n int) { + for i := 0; i < n; i++ { + function() + } +} + +/* 遞迴的空間複雜度為 O(n) */ +func recur(n int) { + if n == 1 { + return + } + recur(n - 1) +} +``` + +```swift title="" +@discardableResult +func function() -> Int { + // 執行某些操作 + return 0 +} + +/* 迴圈的空間複雜度為 O(1) */ +func loop(n: Int) { + for _ in 0 ..< n { + function() + } +} + +/* 遞迴的空間複雜度為 O(n) */ +func recur(n: Int) { + if n == 1 { + return + } + recur(n: n - 1) +} +``` + +```javascript title="" +function constFunc() { + // 執行某些操作 + return 0; +} +/* 迴圈的空間複雜度為 O(1) */ +function loop(n) { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* 遞迴的空間複雜度為 O(n) */ +function recur(n) { + if (n === 1) return; + return recur(n - 1); +} +``` + +```typescript title="" +function constFunc(): number { + // 執行某些操作 + return 0; +} +/* 迴圈的空間複雜度為 O(1) */ +function loop(n: number): void { + for (let i = 0; i < n; i++) { + constFunc(); + } +} +/* 遞迴的空間複雜度為 O(n) */ +function recur(n: number): void { + if (n === 1) return; + return recur(n - 1); +} +``` + +```dart title="" +int function() { + // 執行某些操作 + return 0; +} +/* 迴圈的空間複雜度為 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + function(); + } +} +/* 遞迴的空間複雜度為 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```rust title="" +fn function() -> i32 { + // 執行某些操作 + return 0; +} +/* 迴圈的空間複雜度為 O(1) */ +fn loop(n: i32) { + for i in 0..n { + function(); + } +} +/* 遞迴的空間複雜度為 O(n) */ +fn recur(n: i32) { + if n == 1 { + return; + } + recur(n - 1); +} +``` + +```c title="" +int func() { + // 執行某些操作 + return 0; +} +/* 迴圈的空間複雜度為 O(1) */ +void loop(int n) { + for (int i = 0; i < n; i++) { + func(); + } +} +/* 遞迴的空間複雜度為 O(n) */ +void recur(int n) { + if (n == 1) return; + recur(n - 1); +} +``` + +```kotlin title="" +fun function(): Int { + // 執行某些操作 + return 0 +} +/* 迴圈的空間複雜度為 O(1) */ +fun loop(n: Int) { + for (i in 0.. +```python title="" +# 在某執行平臺下 +def algorithm(n: int): + a = 2 # 1 ns + a = a + 1 # 1 ns + a = a * 2 # 10 ns + # 迴圈 n 次 + for _ in range(n): # 1 ns + print(0) # 5 ns +``` + +```cpp title="" +// 在某執行平臺下 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // 1 ns + cout << 0 << endl; // 5 ns + } +} +``` + +```java title="" +// 在某執行平臺下 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // 1 ns + System.out.println(0); // 5 ns + } +} +``` + +```csharp title="" +// 在某執行平臺下 +void Algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // 1 ns + Console.WriteLine(0); // 5 ns + } +} +``` + +```go title="" +// 在某執行平臺下 +func algorithm(n int) { + a := 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // 迴圈 n 次 + for i := 0; i < n; i++ { // 1 ns + fmt.Println(a) // 5 ns + } +} +``` + +```swift title="" +// 在某執行平臺下 +func algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // 迴圈 n 次 + for _ in 0 ..< n { // 1 ns + print(0) // 5 ns + } +} +``` + +```javascript title="" +// 在某執行平臺下 +function algorithm(n) { + var a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 迴圈 n 次 + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```typescript title="" +// 在某執行平臺下 +function algorithm(n: number): void { + var a: number = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 迴圈 n 次 + for(let i = 0; i < n; i++) { // 1 ns + console.log(0); // 5 ns + } +} +``` + +```dart title="" +// 在某執行平臺下 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // 1 ns + print(0); // 5 ns + } +} +``` + +```rust title="" +// 在某執行平臺下 +fn algorithm(n: i32) { + let mut a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 迴圈 n 次 + for _ in 0..n { // 1 ns + println!("{}", 0); // 5 ns + } +} +``` + +```c title="" +// 在某執行平臺下 +void algorithm(int n) { + int a = 2; // 1 ns + a = a + 1; // 1 ns + a = a * 2; // 10 ns + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // 1 ns + printf("%d", 0); // 5 ns + } +} +``` + +```kotlin title="" +// 在某執行平臺下 +fun algorithm(n: Int) { + var a = 2 // 1 ns + a = a + 1 // 1 ns + a = a * 2 // 10 ns + // 迴圈 n 次 + for (i in 0.. +```python title="" +# 演算法 A 的時間複雜度:常數階 +def algorithm_A(n: int): + print(0) +# 演算法 B 的時間複雜度:線性階 +def algorithm_B(n: int): + for _ in range(n): + print(0) +# 演算法 C 的時間複雜度:常數階 +def algorithm_C(n: int): + for _ in range(1000000): + print(0) +``` + +```cpp title="" +// 演算法 A 的時間複雜度:常數階 +void algorithm_A(int n) { + cout << 0 << endl; +} +// 演算法 B 的時間複雜度:線性階 +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + cout << 0 << endl; + } +} +// 演算法 C 的時間複雜度:常數階 +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + cout << 0 << endl; + } +} +``` + +```java title="" +// 演算法 A 的時間複雜度:常數階 +void algorithm_A(int n) { + System.out.println(0); +} +// 演算法 B 的時間複雜度:線性階 +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + System.out.println(0); + } +} +// 演算法 C 的時間複雜度:常數階 +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + System.out.println(0); + } +} +``` + +```csharp title="" +// 演算法 A 的時間複雜度:常數階 +void AlgorithmA(int n) { + Console.WriteLine(0); +} +// 演算法 B 的時間複雜度:線性階 +void AlgorithmB(int n) { + for (int i = 0; i < n; i++) { + Console.WriteLine(0); + } +} +// 演算法 C 的時間複雜度:常數階 +void AlgorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + Console.WriteLine(0); + } +} +``` + +```go title="" +// 演算法 A 的時間複雜度:常數階 +func algorithm_A(n int) { + fmt.Println(0) +} +// 演算法 B 的時間複雜度:線性階 +func algorithm_B(n int) { + for i := 0; i < n; i++ { + fmt.Println(0) + } +} +// 演算法 C 的時間複雜度:常數階 +func algorithm_C(n int) { + for i := 0; i < 1000000; i++ { + fmt.Println(0) + } +} +``` + +```swift title="" +// 演算法 A 的時間複雜度:常數階 +func algorithmA(n: Int) { + print(0) +} + +// 演算法 B 的時間複雜度:線性階 +func algorithmB(n: Int) { + for _ in 0 ..< n { + print(0) + } +} + +// 演算法 C 的時間複雜度:常數階 +func algorithmC(n: Int) { + for _ in 0 ..< 1_000_000 { + print(0) + } +} +``` + +```javascript title="" +// 演算法 A 的時間複雜度:常數階 +function algorithm_A(n) { + console.log(0); +} +// 演算法 B 的時間複雜度:線性階 +function algorithm_B(n) { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// 演算法 C 的時間複雜度:常數階 +function algorithm_C(n) { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} + +``` + +```typescript title="" +// 演算法 A 的時間複雜度:常數階 +function algorithm_A(n: number): void { + console.log(0); +} +// 演算法 B 的時間複雜度:線性階 +function algorithm_B(n: number): void { + for (let i = 0; i < n; i++) { + console.log(0); + } +} +// 演算法 C 的時間複雜度:常數階 +function algorithm_C(n: number): void { + for (let i = 0; i < 1000000; i++) { + console.log(0); + } +} +``` + +```dart title="" +// 演算法 A 的時間複雜度:常數階 +void algorithmA(int n) { + print(0); +} +// 演算法 B 的時間複雜度:線性階 +void algorithmB(int n) { + for (int i = 0; i < n; i++) { + print(0); + } +} +// 演算法 C 的時間複雜度:常數階 +void algorithmC(int n) { + for (int i = 0; i < 1000000; i++) { + print(0); + } +} +``` + +```rust title="" +// 演算法 A 的時間複雜度:常數階 +fn algorithm_A(n: i32) { + println!("{}", 0); +} +// 演算法 B 的時間複雜度:線性階 +fn algorithm_B(n: i32) { + for _ in 0..n { + println!("{}", 0); + } +} +// 演算法 C 的時間複雜度:常數階 +fn algorithm_C(n: i32) { + for _ in 0..1000000 { + println!("{}", 0); + } +} +``` + +```c title="" +// 演算法 A 的時間複雜度:常數階 +void algorithm_A(int n) { + printf("%d", 0); +} +// 演算法 B 的時間複雜度:線性階 +void algorithm_B(int n) { + for (int i = 0; i < n; i++) { + printf("%d", 0); + } +} +// 演算法 C 的時間複雜度:常數階 +void algorithm_C(int n) { + for (int i = 0; i < 1000000; i++) { + printf("%d", 0); + } +} +``` + +```kotlin title="" +// 演算法 A 的時間複雜度:常數階 +fun algoritm_A(n: Int) { + println(0) +} +// 演算法 B 的時間複雜度:線性階 +fun algorithm_B(n: Int) { + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +1 + a = a + 1 # +1 + a = a * 2 # +1 + # 迴圈 n 次 + for i in range(n): # +1 + print(0) # +1 +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // +1(每輪都執行 i ++) + cout << 0 << endl; // +1 + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // +1(每輪都執行 i ++) + System.out.println(0); // +1 + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // +1(每輪都執行 i ++) + Console.WriteLine(0); // +1 + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // 迴圈 n 次 + for i := 0; i < n; i++ { // +1 + fmt.Println(a) // +1 + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // 迴圈 n 次 + for _ in 0 ..< n { // +1 + print(0) // +1 + } +} +``` + +```javascript title="" +function algorithm(n) { + var a = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // 迴圈 n 次 + for(let i = 0; i < n; i++){ // +1(每輪都執行 i ++) + console.log(0); // +1 + } +} +``` + +```typescript title="" +function algorithm(n: number): void{ + var a: number = 1; // +1 + a += 1; // +1 + a *= 2; // +1 + // 迴圈 n 次 + for(let i = 0; i < n; i++){ // +1(每輪都執行 i ++) + console.log(0); // +1 + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // +1(每輪都執行 i ++) + print(0); // +1 + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + + // 迴圈 n 次 + for _ in 0..n { // +1(每輪都執行 i ++) + println!("{}", 0); // +1 + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +1 + a = a + 1; // +1 + a = a * 2; // +1 + // 迴圈 n 次 + for (int i = 0; i < n; i++) { // +1(每輪都執行 i ++) + printf("%d", 0); // +1 + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +1 + a = a + 1 // +1 + a = a * 2 // +1 + // 迴圈 n 次 + for (i in 0.. +```python title="" +def algorithm(n: int): + a = 1 # +0(技巧 1) + a = a + n # +0(技巧 1) + # +n(技巧 2) + for i in range(5 * n + 1): + print(0) + # +n*n(技巧 3) + for i in range(2 * n): + for j in range(n + 1): + print(0) +``` + +```cpp title="" +void algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + cout << 0 << endl; + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + cout << 0 << endl; + } + } +} +``` + +```java title="" +void algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + System.out.println(0); + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + System.out.println(0); + } + } +} +``` + +```csharp title="" +void Algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + Console.WriteLine(0); + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + Console.WriteLine(0); + } + } +} +``` + +```go title="" +func algorithm(n int) { + a := 1 // +0(技巧 1) + a = a + n // +0(技巧 1) + // +n(技巧 2) + for i := 0; i < 5 * n + 1; i++ { + fmt.Println(0) + } + // +n*n(技巧 3) + for i := 0; i < 2 * n; i++ { + for j := 0; j < n + 1; j++ { + fmt.Println(0) + } + } +} +``` + +```swift title="" +func algorithm(n: Int) { + var a = 1 // +0(技巧 1) + a = a + n // +0(技巧 1) + // +n(技巧 2) + for _ in 0 ..< (5 * n + 1) { + print(0) + } + // +n*n(技巧 3) + for _ in 0 ..< (2 * n) { + for _ in 0 ..< (n + 1) { + print(0) + } + } +} +``` + +```javascript title="" +function algorithm(n) { + let a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n(技巧 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```typescript title="" +function algorithm(n: number): void { + let a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (let i = 0; i < 5 * n + 1; i++) { + console.log(0); + } + // +n*n(技巧 3) + for (let i = 0; i < 2 * n; i++) { + for (let j = 0; j < n + 1; j++) { + console.log(0); + } + } +} +``` + +```dart title="" +void algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + print(0); + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + print(0); + } + } +} +``` + +```rust title="" +fn algorithm(n: i32) { + let mut a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + + // +n(技巧 2) + for i in 0..(5 * n + 1) { + println!("{}", 0); + } + + // +n*n(技巧 3) + for i in 0..(2 * n) { + for j in 0..(n + 1) { + println!("{}", 0); + } + } +} +``` + +```c title="" +void algorithm(int n) { + int a = 1; // +0(技巧 1) + a = a + n; // +0(技巧 1) + // +n(技巧 2) + for (int i = 0; i < 5 * n + 1; i++) { + printf("%d", 0); + } + // +n*n(技巧 3) + for (int i = 0; i < 2 * n; i++) { + for (int j = 0; j < n + 1; j++) { + printf("%d", 0); + } + } +} +``` + +```kotlin title="" +fun algorithm(n: Int) { + var a = 1 // +0(技巧 1) + a = a + n // +0(技巧 1) + // +n(技巧 2) + for (i in 0..<5 * n + 1) { + println(0) + } + // +n*n(技巧 3) + for (i in 0..<2 * n) { + for (j in 0.. +```python title="" +# 使用多種基本資料型別來初始化陣列 +numbers: list[int] = [0] * 5 +decimals: list[float] = [0.0] * 5 +# Python 的字元實際上是長度為 1 的字串 +characters: list[str] = ['0'] * 5 +bools: list[bool] = [False] * 5 +# Python 的串列可以自由儲存各種基本資料型別和物件引用 +data = [0, 0.0, 'a', False, ListNode(0)] +``` + +```cpp title="" +// 使用多種基本資料型別來初始化陣列 +int numbers[5]; +float decimals[5]; +char characters[5]; +bool bools[5]; +``` + +```java title="" +// 使用多種基本資料型別來初始化陣列 +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +boolean[] bools = new boolean[5]; +``` + +```csharp title="" +// 使用多種基本資料型別來初始化陣列 +int[] numbers = new int[5]; +float[] decimals = new float[5]; +char[] characters = new char[5]; +bool[] bools = new bool[5]; +``` + +```go title="" +// 使用多種基本資料型別來初始化陣列 +var numbers = [5]int{} +var decimals = [5]float64{} +var characters = [5]byte{} +var bools = [5]bool{} +``` + +```swift title="" +// 使用多種基本資料型別來初始化陣列 +let numbers = Array(repeating: 0, count: 5) +let decimals = Array(repeating: 0.0, count: 5) +let characters: [Character] = Array(repeating: "a", count: 5) +let bools = Array(repeating: false, count: 5) +``` + +```javascript title="" +// JavaScript 的陣列可以自由儲存各種基本資料型別和物件 +const array = [0, 0.0, 'a', false]; +``` + +```typescript title="" +// 使用多種基本資料型別來初始化陣列 +const numbers: number[] = []; +const characters: string[] = []; +const bools: boolean[] = []; +``` + +```dart title="" +// 使用多種基本資料型別來初始化陣列 +List numbers = List.filled(5, 0); +List decimals = List.filled(5, 0.0); +List characters = List.filled(5, 'a'); +List bools = List.filled(5, false); +``` + +```rust title="" +// 使用多種基本資料型別來初始化陣列 +let numbers: Vec = vec![0; 5]; +let decimals: Vec = vec![0.0; 5]; +let characters: Vec = vec!['0'; 5]; +let bools: Vec = vec![false; 5]; +``` + +```c title="" +// 使用多種基本資料型別來初始化陣列 +int numbers[10]; +float decimals[10]; +char characters[10]; +bool bools[10]; +``` + +```kotlin title="" +// 使用多種基本資料型別來初始化陣列 +val numbers = IntArray(5) +val decinals = FloatArray(5) +val characters = CharArray(5) +val bools = BooleanArray(5) +``` + +```ruby title="" +# Ruby 的串列可以自由儲存各種基本資料型別和物件引用 +data = [0, 0.0, 'a', false, ListNode(0)] +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%BE%8C%E7%B9%BC%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%A8%AE%E5%9F%BA%E6%9C%AC%E8%B3%87%E6%96%99%E5%9E%8B%E5%88%A5%E4%BE%86%E5%88%9D%E5%A7%8B%E5%8C%96%E9%99%A3%E5%88%97%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20%2A%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20%2A%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E5%AD%97%E5%85%83%E5%AF%A6%E9%9A%9B%E4%B8%8A%E6%98%AF%E9%95%B7%E5%BA%A6%E7%82%BA%201%20%E7%9A%84%E5%AD%97%E4%B8%B2%0A%20%20%20%20characters%20%3D%20%5B%270%27%5D%20%2A%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20%2A%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E4%B8%B2%E5%88%97%E5%8F%AF%E4%BB%A5%E8%87%AA%E7%94%B1%E5%84%B2%E5%AD%98%E5%90%84%E7%A8%AE%E5%9F%BA%E6%9C%AC%E8%B3%87%E6%96%99%E5%9E%8B%E5%88%A5%E5%92%8C%E7%89%A9%E4%BB%B6%E5%BC%95%E7%94%A8%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20%27a%27%2C%20False%2C%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_hashing/hash_algorithm.md b/zh-hant/codes/snippets/chapter_hashing/hash_algorithm.md new file mode 100644 index 000000000..8b47cfa93 --- /dev/null +++ b/zh-hant/codes/snippets/chapter_hashing/hash_algorithm.md @@ -0,0 +1,263 @@ + +```python title="built_in_hash.py" +num = 3 +hash_num = hash(num) +# 整數 3 的雜湊值為 3 + +bol = True +hash_bol = hash(bol) +# 布林量 True 的雜湊值為 1 + +dec = 3.14159 +hash_dec = hash(dec) +# 小數 3.14159 的雜湊值為 326484311674566659 + +str = "Hello 演算法" +hash_str = hash(str) +# 字串“Hello 演算法”的雜湊值為 4617003410720528961 + +tup = (12836, "小哈") +hash_tup = hash(tup) +# 元組 (12836, '小哈') 的雜湊值為 1029005403108185979 + +obj = ListNode(0) +hash_obj = hash(obj) +# 節點物件 的雜湊值為 274267521 +``` + +```cpp title="built_in_hash.cpp" +int num = 3; +size_t hashNum = hash()(num); +// 整數 3 的雜湊值為 3 + +bool bol = true; +size_t hashBol = hash()(bol); +// 布林量 1 的雜湊值為 1 + +double dec = 3.14159; +size_t hashDec = hash()(dec); +// 小數 3.14159 的雜湊值為 4614256650576692846 + +string str = "Hello 演算法"; +size_t hashStr = hash()(str); +// 字串“Hello 演算法”的雜湊值為 15466937326284535026 + +// 在 C++ 中,內建 std::hash() 僅提供基本資料型別的雜湊值計算 +// 陣列、物件的雜湊值計算需要自行實現 +``` + +```java title="built_in_hash.java" +int num = 3; +int hashNum = Integer.hashCode(num); +// 整數 3 的雜湊值為 3 + +boolean bol = true; +int hashBol = Boolean.hashCode(bol); +// 布林量 true 的雜湊值為 1231 + +double dec = 3.14159; +int hashDec = Double.hashCode(dec); +// 小數 3.14159 的雜湊值為 -1340954729 + +String str = "Hello 演算法"; +int hashStr = str.hashCode(); +// 字串“Hello 演算法”的雜湊值為 -727081396 + +Object[] arr = { 12836, "小哈" }; +int hashTup = Arrays.hashCode(arr); +// 陣列 [12836, 小哈] 的雜湊值為 1151158 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode(); +// 節點物件 utils.ListNode@7dc5e7b4 的雜湊值為 2110121908 +``` + +```csharp title="built_in_hash.cs" +int num = 3; +int hashNum = num.GetHashCode(); +// 整數 3 的雜湊值為 3; + +bool bol = true; +int hashBol = bol.GetHashCode(); +// 布林量 true 的雜湊值為 1; + +double dec = 3.14159; +int hashDec = dec.GetHashCode(); +// 小數 3.14159 的雜湊值為 -1340954729; + +string str = "Hello 演算法"; +int hashStr = str.GetHashCode(); +// 字串“Hello 演算法”的雜湊值為 -586107568; + +object[] arr = [12836, "小哈"]; +int hashTup = arr.GetHashCode(); +// 陣列 [12836, 小哈] 的雜湊值為 42931033; + +ListNode obj = new(0); +int hashObj = obj.GetHashCode(); +// 節點物件 0 的雜湊值為 39053774; +``` + +```go title="built_in_hash.go" +// Go 未提供內建 hash code 函式 +``` + +```swift title="built_in_hash.swift" +let num = 3 +let hashNum = num.hashValue +// 整數 3 的雜湊值為 9047044699613009734 + +let bol = true +let hashBol = bol.hashValue +// 布林量 true 的雜湊值為 -4431640247352757451 + +let dec = 3.14159 +let hashDec = dec.hashValue +// 小數 3.14159 的雜湊值為 -2465384235396674631 + +let str = "Hello 演算法" +let hashStr = str.hashValue +// 字串“Hello 演算法”的雜湊值為 -7850626797806988787 + +let arr = [AnyHashable(12836), AnyHashable("小哈")] +let hashTup = arr.hashValue +// 陣列 [AnyHashable(12836), AnyHashable("小哈")] 的雜湊值為 -2308633508154532996 + +let obj = ListNode(x: 0) +let hashObj = obj.hashValue +// 節點物件 utils.ListNode 的雜湊值為 -2434780518035996159 +``` + +```javascript title="built_in_hash.js" +// JavaScript 未提供內建 hash code 函式 +``` + +```typescript title="built_in_hash.ts" +// TypeScript 未提供內建 hash code 函式 +``` + +```dart title="built_in_hash.dart" +int num = 3; +int hashNum = num.hashCode; +// 整數 3 的雜湊值為 34803 + +bool bol = true; +int hashBol = bol.hashCode; +// 布林值 true 的雜湊值為 1231 + +double dec = 3.14159; +int hashDec = dec.hashCode; +// 小數 3.14159 的雜湊值為 2570631074981783 + +String str = "Hello 演算法"; +int hashStr = str.hashCode; +// 字串“Hello 演算法”的雜湊值為 468167534 + +List arr = [12836, "小哈"]; +int hashArr = arr.hashCode; +// 陣列 [12836, 小哈] 的雜湊值為 976512528 + +ListNode obj = new ListNode(0); +int hashObj = obj.hashCode; +// 節點物件 Instance of 'ListNode' 的雜湊值為 1033450432 +``` + +```rust title="built_in_hash.rs" +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +let num = 3; +let mut num_hasher = DefaultHasher::new(); +num.hash(&mut num_hasher); +let hash_num = num_hasher.finish(); +// 整數 3 的雜湊值為 568126464209439262 + +let bol = true; +let mut bol_hasher = DefaultHasher::new(); +bol.hash(&mut bol_hasher); +let hash_bol = bol_hasher.finish(); +// 布林量 true 的雜湊值為 4952851536318644461 + +let dec: f32 = 3.14159; +let mut dec_hasher = DefaultHasher::new(); +dec.to_bits().hash(&mut dec_hasher); +let hash_dec = dec_hasher.finish(); +// 小數 3.14159 的雜湊值為 2566941990314602357 + +let str = "Hello 演算法"; +let mut str_hasher = DefaultHasher::new(); +str.hash(&mut str_hasher); +let hash_str = str_hasher.finish(); +// 字串“Hello 演算法”的雜湊值為 16092673739211250988 + +let arr = (&12836, &"小哈"); +let mut tup_hasher = DefaultHasher::new(); +arr.hash(&mut tup_hasher); +let hash_tup = tup_hasher.finish(); +// 元組 (12836, "小哈") 的雜湊值為 1885128010422702749 + +let node = ListNode::new(42); +let mut hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut hasher); +let hash = hasher.finish(); +// 節點物件 RefCell { value: ListNode { val: 42, next: None } } 的雜湊值為15387811073369036852 +``` + +```c title="built_in_hash.c" +// C 未提供內建 hash code 函式 +``` + +```kotlin title="built_in_hash.kt" +val num = 3 +val hashNum = num.hashCode() +// 整數 3 的雜湊值為 3 + +val bol = true +val hashBol = bol.hashCode() +// 布林量 true 的雜湊值為 1231 + +val dec = 3.14159 +val hashDec = dec.hashCode() +// 小數 3.14159 的雜湊值為 -1340954729 + +val str = "Hello 演算法" +val hashStr = str.hashCode() +// 字串“Hello 演算法”的雜湊值為 -727081396 + +val arr = arrayOf(12836, "小哈") +val hashTup = arr.hashCode() +// 陣列 [12836, 小哈] 的雜湊值為 189568618 + +val obj = ListNode(0) +val hashObj = obj.hashCode() +// 節點物件 utils.ListNode@1d81eb93 的雜湊值為 495053715 +``` + +```ruby title="built_in_hash.rb" +num = 3 +hash_num = num.hash +# 整數 3 的雜湊值為 -4385856518450339636 + +bol = true +hash_bol = bol.hash +# 布林量 true 的雜湊值為 -1617938112149317027 + +dec = 3.14159 +hash_dec = dec.hash +# 小數 3.14159 的雜湊值為 -1479186995943067893 + +str = "Hello 演算法" +hash_str = str.hash +# 字串“Hello 演算法”的雜湊值為 -4075943250025831763 + +tup = [12836, '小哈'] +hash_tup = tup.hash +# 元組 (12836, '小哈') 的雜湊值為 1999544809202288822 + +obj = ListNode.new(0) +hash_obj = obj.hash +# 節點物件 # 的雜湊值為 4302940560806366381 +``` + + +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%BE%8C%E7%B9%BC%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B8%203%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%E5%B8%83%E6%9E%97%E9%87%8F%20True%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B8%203.14159%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E6%BC%94%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%E5%AD%97%E4%B8%B2%E2%80%9CHello%20%E6%BC%94%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%E5%85%83%E7%B5%84%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E7%89%A9%E4%BB%B6%20%3CListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_hashing/hash_map.md b/zh-hant/codes/snippets/chapter_hashing/hash_map.md new file mode 100644 index 000000000..e7dee5629 --- /dev/null +++ b/zh-hant/codes/snippets/chapter_hashing/hash_map.md @@ -0,0 +1,457 @@ + +```python title="hash_map.py" +# 初始化雜湊表 +hmap: dict = {} + +# 新增操作 +# 在雜湊表中新增鍵值對 (key, value) +hmap[12836] = "小哈" +hmap[15937] = "小囉" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鴨" + +# 查詢操作 +# 向雜湊表中輸入鍵 key ,得到值 value +name: str = hmap[15937] + +# 刪除操作 +# 在雜湊表中刪除鍵值對 (key, value) +hmap.pop(10583) +``` + +```cpp title="hash_map.cpp" +/* 初始化雜湊表 */ +unordered_map map; + +/* 新增操作 */ +// 在雜湊表中新增鍵值對 (key, value) +map[12836] = "小哈"; +map[15937] = "小囉"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鴨"; + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +string name = map[15937]; + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +map.erase(10583); +``` + +```java title="hash_map.java" +/* 初始化雜湊表 */ +Map map = new HashMap<>(); + +/* 新增操作 */ +// 在雜湊表中新增鍵值對 (key, value) +map.put(12836, "小哈"); +map.put(15937, "小囉"); +map.put(16750, "小算"); +map.put(13276, "小法"); +map.put(10583, "小鴨"); + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +String name = map.get(15937); + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +map.remove(10583); +``` + +```csharp title="hash_map.cs" +/* 初始化雜湊表 */ +Dictionary map = new() { + /* 新增操作 */ + // 在雜湊表中新增鍵值對 (key, value) + { 12836, "小哈" }, + { 15937, "小囉" }, + { 16750, "小算" }, + { 13276, "小法" }, + { 10583, "小鴨" } +}; + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +string name = map[15937]; + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +map.Remove(10583); +``` + +```go title="hash_map_test.go" +/* 初始化雜湊表 */ +hmap := make(map[int]string) + +/* 新增操作 */ +// 在雜湊表中新增鍵值對 (key, value) +hmap[12836] = "小哈" +hmap[15937] = "小囉" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鴨" + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +name := hmap[15937] + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +delete(hmap, 10583) +``` + +```swift title="hash_map.swift" +/* 初始化雜湊表 */ +var map: [Int: String] = [:] + +/* 新增操作 */ +// 在雜湊表中新增鍵值對 (key, value) +map[12836] = "小哈" +map[15937] = "小囉" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鴨" + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +let name = map[15937]! + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +map.removeValue(forKey: 10583) +``` + +```javascript title="hash_map.js" +/* 初始化雜湊表 */ +const map = new Map(); +/* 新增操作 */ +// 在雜湊表中新增鍵值對 (key, value) +map.set(12836, '小哈'); +map.set(15937, '小囉'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鴨'); + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +let name = map.get(15937); + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +map.delete(10583); +``` + +```typescript title="hash_map.ts" +/* 初始化雜湊表 */ +const map = new Map(); +/* 新增操作 */ +// 在雜湊表中新增鍵值對 (key, value) +map.set(12836, '小哈'); +map.set(15937, '小囉'); +map.set(16750, '小算'); +map.set(13276, '小法'); +map.set(10583, '小鴨'); +console.info('\n新增完成後,雜湊表為\nKey -> Value'); +console.info(map); + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +let name = map.get(15937); +console.info('\n輸入學號 15937 ,查詢到姓名 ' + name); + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +map.delete(10583); +console.info('\n刪除 10583 後,雜湊表為\nKey -> Value'); +console.info(map); +``` + +```dart title="hash_map.dart" +/* 初始化雜湊表 */ +Map map = {}; + +/* 新增操作 */ +// 在雜湊表中新增鍵值對 (key, value) +map[12836] = "小哈"; +map[15937] = "小囉"; +map[16750] = "小算"; +map[13276] = "小法"; +map[10583] = "小鴨"; + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +String name = map[15937]; + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +map.remove(10583); +``` + +```rust title="hash_map.rs" +use std::collections::HashMap; + +/* 初始化雜湊表 */ +let mut map: HashMap = HashMap::new(); + +/* 新增操作 */ +// 在雜湊表中新增鍵值對 (key, value) +map.insert(12836, "小哈".to_string()); +map.insert(15937, "小囉".to_string()); +map.insert(16750, "小算".to_string()); +map.insert(13279, "小法".to_string()); +map.insert(10583, "小鴨".to_string()); + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +let _name: Option<&String> = map.get(&15937); + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +let _removed_value: Option = map.remove(&10583); +``` + +```c title="hash_map.c" +// C 未提供內建雜湊表 +``` + +```kotlin title="hash_map.kt" +/* 初始化雜湊表 */ +val map = HashMap() + +/* 新增操作 */ +// 在雜湊表中新增鍵值對 (key, value) +map[12836] = "小哈" +map[15937] = "小囉" +map[16750] = "小算" +map[13276] = "小法" +map[10583] = "小鴨" + +/* 查詢操作 */ +// 向雜湊表中輸入鍵 key ,得到值 value +val name = map[15937] + +/* 刪除操作 */ +// 在雜湊表中刪除鍵值對 (key, value) +map.remove(10583) +``` + +```ruby title="hash_map.rb" +# 初始化雜湊表 +hmap = {} + +# 新增操作 +# 在雜湊表中新增鍵值對 (key, value) +hmap[12836] = "小哈" +hmap[15937] = "小囉" +hmap[16750] = "小算" +hmap[13276] = "小法" +hmap[10583] = "小鴨" + +# 查詢操作 +# 向雜湊表中輸入鍵 key ,得到值 value +name = hmap[15937] + +# 刪除操作 +# 在雜湊表中刪除鍵值對 (key, value) +hmap.delete(10583) +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%96%B0%E5%A2%9E%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E6%96%B0%E5%A2%9E%E9%8D%B5%E5%80%BC%E5%B0%8D%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%9B%89%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B4%A8%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%9F%A5%E8%A9%A2%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%90%91%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E8%BC%B8%E5%85%A5%E9%8D%B5%20key%20%EF%BC%8C%E5%BE%97%E5%88%B0%E5%80%BC%20value%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E5%88%AA%E9%99%A4%E9%8D%B5%E5%80%BC%E5%B0%8D%20%28key%2C%20value%29%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="hash_map.py" +# 走訪雜湊表 +# 走訪鍵值對 key->value +for key, value in hmap.items(): + print(key, "->", value) +# 單獨走訪鍵 key +for key in hmap.keys(): + print(key) +# 單獨走訪值 value +for value in hmap.values(): + print(value) +``` + +```cpp title="hash_map.cpp" +/* 走訪雜湊表 */ +// 走訪鍵值對 key->value +for (auto kv: map) { + cout << kv.first << " -> " << kv.second << endl; +} +// 使用迭代器走訪 key->value +for (auto iter = map.begin(); iter != map.end(); iter++) { + cout << iter->first << "->" << iter->second << endl; +} +``` + +```java title="hash_map.java" +/* 走訪雜湊表 */ +// 走訪鍵值對 key->value +for (Map.Entry kv: map.entrySet()) { + System.out.println(kv.getKey() + " -> " + kv.getValue()); +} +// 單獨走訪鍵 key +for (int key: map.keySet()) { + System.out.println(key); +} +// 單獨走訪值 value +for (String val: map.values()) { + System.out.println(val); +} +``` + +```csharp title="hash_map.cs" +/* 走訪雜湊表 */ +// 走訪鍵值對 Key->Value +foreach (var kv in map) { + Console.WriteLine(kv.Key + " -> " + kv.Value); +} +// 單獨走訪鍵 key +foreach (int key in map.Keys) { + Console.WriteLine(key); +} +// 單獨走訪值 value +foreach (string val in map.Values) { + Console.WriteLine(val); +} +``` + +```go title="hash_map_test.go" +/* 走訪雜湊表 */ +// 走訪鍵值對 key->value +for key, value := range hmap { + fmt.Println(key, "->", value) +} +// 單獨走訪鍵 key +for key := range hmap { + fmt.Println(key) +} +// 單獨走訪值 value +for _, value := range hmap { + fmt.Println(value) +} +``` + +```swift title="hash_map.swift" +/* 走訪雜湊表 */ +// 走訪鍵值對 Key->Value +for (key, value) in map { + print("\(key) -> \(value)") +} +// 單獨走訪鍵 Key +for key in map.keys { + print(key) +} +// 單獨走訪值 Value +for value in map.values { + print(value) +} +``` + +```javascript title="hash_map.js" +/* 走訪雜湊表 */ +console.info('\n走訪鍵值對 Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\n單獨走訪鍵 Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\n單獨走訪值 Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```typescript title="hash_map.ts" +/* 走訪雜湊表 */ +console.info('\n走訪鍵值對 Key->Value'); +for (const [k, v] of map.entries()) { + console.info(k + ' -> ' + v); +} +console.info('\n單獨走訪鍵 Key'); +for (const k of map.keys()) { + console.info(k); +} +console.info('\n單獨走訪值 Value'); +for (const v of map.values()) { + console.info(v); +} +``` + +```dart title="hash_map.dart" +/* 走訪雜湊表 */ +// 走訪鍵值對 Key->Value +map.forEach((key, value) { + print('$key -> $value'); +}); + +// 單獨走訪鍵 Key +map.keys.forEach((key) { + print(key); +}); + +// 單獨走訪值 Value +map.values.forEach((value) { + print(value); +}); +``` + +```rust title="hash_map.rs" +/* 走訪雜湊表 */ +// 走訪鍵值對 Key->Value +for (key, value) in &map { + println!("{key} -> {value}"); +} + +// 單獨走訪鍵 Key +for key in map.keys() { + println!("{key}"); +} + +// 單獨走訪值 Value +for value in map.values() { + println!("{value}"); +} +``` + +```c title="hash_map.c" +// C 未提供內建雜湊表 +``` + +```kotlin title="hash_map.kt" +/* 走訪雜湊表 */ +// 走訪鍵值對 key->value +for ((key, value) in map) { + println("$key -> $value") +} +// 單獨走訪鍵 key +for (key in map.keys) { + println(key) +} +// 單獨走訪值 value +for (_val in map.values) { + println(_val) +} +``` + +```ruby title="hash_map.rb" +# 走訪雜湊表 +# 走訪鍵值對 key->value +hmap.entries.each { |key, value| puts "#{key} -> #{value}" } + +# 單獨走訪鍵 key +hmap.keys.each { |key| puts key } + +# 單獨走訪值 value +hmap.values.each { |val| puts val } +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%96%B0%E5%A2%9E%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E6%96%B0%E5%A2%9E%E9%8D%B5%E5%80%BC%E5%B0%8D%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%9B%89%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B4%A8%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%B5%B0%E8%A8%AA%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20%23%20%E8%B5%B0%E8%A8%AA%E9%8D%B5%E5%80%BC%E5%B0%8D%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%E5%96%AE%E7%8D%A8%E8%B5%B0%E8%A8%AA%E9%8D%B5%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%96%AE%E7%8D%A8%E8%B5%B0%E8%A8%AA%E5%80%BC%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_heap/heap.md b/zh-hant/codes/snippets/chapter_heap/heap.md new file mode 100644 index 000000000..96bfd66f1 --- /dev/null +++ b/zh-hant/codes/snippets/chapter_heap/heap.md @@ -0,0 +1,350 @@ + +```python title="heap.py" +# 初始化小頂堆積 +min_heap, flag = [], 1 +# 初始化大頂堆積 +max_heap, flag = [], -1 + +# Python 的 heapq 模組預設實現小頂堆積 +# 考慮將“元素取負”後再入堆積,這樣就可以將大小關係顛倒,從而實現大頂堆積 +# 在本示例中,flag = 1 時對應小頂堆積,flag = -1 時對應大頂堆積 + +# 元素入堆積 +heapq.heappush(max_heap, flag * 1) +heapq.heappush(max_heap, flag * 3) +heapq.heappush(max_heap, flag * 2) +heapq.heappush(max_heap, flag * 5) +heapq.heappush(max_heap, flag * 4) + +# 獲取堆積頂元素 +peek: int = flag * max_heap[0] # 5 + +# 堆積頂元素出堆積 +# 出堆積元素會形成一個從大到小的序列 +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 + +# 獲取堆積大小 +size: int = len(max_heap) + +# 判斷堆積是否為空 +is_empty: bool = not max_heap + +# 輸入串列並建堆積 +min_heap: list[int] = [1, 3, 2, 5, 4] +heapq.heapify(min_heap) +``` + +```cpp title="heap.cpp" +/* 初始化堆積 */ +// 初始化小頂堆積 +priority_queue, greater> minHeap; +// 初始化大頂堆積 +priority_queue, less> maxHeap; + +/* 元素入堆積 */ +maxHeap.push(1); +maxHeap.push(3); +maxHeap.push(2); +maxHeap.push(5); +maxHeap.push(4); + +/* 獲取堆積頂元素 */ +int peek = maxHeap.top(); // 5 + +/* 堆積頂元素出堆積 */ +// 出堆積元素會形成一個從大到小的序列 +maxHeap.pop(); // 5 +maxHeap.pop(); // 4 +maxHeap.pop(); // 3 +maxHeap.pop(); // 2 +maxHeap.pop(); // 1 + +/* 獲取堆積大小 */ +int size = maxHeap.size(); + +/* 判斷堆積是否為空 */ +bool isEmpty = maxHeap.empty(); + +/* 輸入串列並建堆積 */ +vector input{1, 3, 2, 5, 4}; +priority_queue, greater> minHeap(input.begin(), input.end()); +``` + +```java title="heap.java" +/* 初始化堆積 */ +// 初始化小頂堆積 +Queue minHeap = new PriorityQueue<>(); +// 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可) +Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + +/* 元素入堆積 */ +maxHeap.offer(1); +maxHeap.offer(3); +maxHeap.offer(2); +maxHeap.offer(5); +maxHeap.offer(4); + +/* 獲取堆積頂元素 */ +int peek = maxHeap.peek(); // 5 + +/* 堆積頂元素出堆積 */ +// 出堆積元素會形成一個從大到小的序列 +peek = maxHeap.poll(); // 5 +peek = maxHeap.poll(); // 4 +peek = maxHeap.poll(); // 3 +peek = maxHeap.poll(); // 2 +peek = maxHeap.poll(); // 1 + +/* 獲取堆積大小 */ +int size = maxHeap.size(); + +/* 判斷堆積是否為空 */ +boolean isEmpty = maxHeap.isEmpty(); + +/* 輸入串列並建堆積 */ +minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +``` + +```csharp title="heap.cs" +/* 初始化堆積 */ +// 初始化小頂堆積 +PriorityQueue minHeap = new(); +// 初始化大頂堆積(使用 lambda 表示式修改 Comparer 即可) +PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + +/* 元素入堆積 */ +maxHeap.Enqueue(1, 1); +maxHeap.Enqueue(3, 3); +maxHeap.Enqueue(2, 2); +maxHeap.Enqueue(5, 5); +maxHeap.Enqueue(4, 4); + +/* 獲取堆積頂元素 */ +int peek = maxHeap.Peek();//5 + +/* 堆積頂元素出堆積 */ +// 出堆積元素會形成一個從大到小的序列 +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 + +/* 獲取堆積大小 */ +int size = maxHeap.Count; + +/* 判斷堆積是否為空 */ +bool isEmpty = maxHeap.Count == 0; + +/* 輸入串列並建堆積 */ +minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +``` + +```go title="heap.go" +// Go 語言中可以透過實現 heap.Interface 來構建整數大頂堆積 +// 實現 heap.Interface 需要同時實現 sort.Interface +type intHeap []any + +// Push heap.Interface 的方法,實現推入元素到堆積 +func (h *intHeap) Push(x any) { + // Push 和 Pop 使用 pointer receiver 作為參數 + // 因為它們不僅會對切片的內容進行調整,還會修改切片的長度。 + *h = append(*h, x.(int)) +} + +// Pop heap.Interface 的方法,實現彈出堆積頂元素 +func (h *intHeap) Pop() any { + // 待出堆積元素存放在最後 + last := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return last +} + +// Len sort.Interface 的方法 +func (h *intHeap) Len() int { + return len(*h) +} + +// Less sort.Interface 的方法 +func (h *intHeap) Less(i, j int) bool { + // 如果實現小頂堆積,則需要調整為小於號 + return (*h)[i].(int) > (*h)[j].(int) +} + +// Swap sort.Interface 的方法 +func (h *intHeap) Swap(i, j int) { + (*h)[i], (*h)[j] = (*h)[j], (*h)[i] +} + +// Top 獲取堆積頂元素 +func (h *intHeap) Top() any { + return (*h)[0] +} + +/* Driver Code */ +func TestHeap(t *testing.T) { + /* 初始化堆積 */ + // 初始化大頂堆積 + maxHeap := &intHeap{} + heap.Init(maxHeap) + /* 元素入堆積 */ + // 呼叫 heap.Interface 的方法,來新增元素 + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 4) + heap.Push(maxHeap, 5) + + /* 獲取堆積頂元素 */ + top := maxHeap.Top() + fmt.Printf("堆積頂元素為 %d\n", top) + + /* 堆積頂元素出堆積 */ + // 呼叫 heap.Interface 的方法,來移除元素 + heap.Pop(maxHeap) // 5 + heap.Pop(maxHeap) // 4 + heap.Pop(maxHeap) // 3 + heap.Pop(maxHeap) // 2 + heap.Pop(maxHeap) // 1 + + /* 獲取堆積大小 */ + size := len(*maxHeap) + fmt.Printf("堆積元素數量為 %d\n", size) + + /* 判斷堆積是否為空 */ + isEmpty := len(*maxHeap) == 0 + fmt.Printf("堆積是否為空 %t\n", isEmpty) +} +``` + +```swift title="heap.swift" +/* 初始化堆積 */ +// Swift 的 Heap 型別同時支持最大堆積和最小堆積,且需要引入 swift-collections +var heap = Heap() + +/* 元素入堆積 */ +heap.insert(1) +heap.insert(3) +heap.insert(2) +heap.insert(5) +heap.insert(4) + +/* 獲取堆積頂元素 */ +var peek = heap.max()! + +/* 堆積頂元素出堆積 */ +peek = heap.removeMax() // 5 +peek = heap.removeMax() // 4 +peek = heap.removeMax() // 3 +peek = heap.removeMax() // 2 +peek = heap.removeMax() // 1 + +/* 獲取堆積大小 */ +let size = heap.count + +/* 判斷堆積是否為空 */ +let isEmpty = heap.isEmpty + +/* 輸入串列並建堆積 */ +let heap2 = Heap([1, 3, 2, 5, 4]) +``` + +```javascript title="heap.js" +// JavaScript 未提供內建 Heap 類別 +``` + +```typescript title="heap.ts" +// TypeScript 未提供內建 Heap 類別 +``` + +```dart title="heap.dart" +// Dart 未提供內建 Heap 類別 +``` + +```rust title="heap.rs" +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +/* 初始化堆積 */ +// 初始化小頂堆積 +let mut min_heap = BinaryHeap::>::new(); +// 初始化大頂堆積 +let mut max_heap = BinaryHeap::new(); + +/* 元素入堆積 */ +max_heap.push(1); +max_heap.push(3); +max_heap.push(2); +max_heap.push(5); +max_heap.push(4); + +/* 獲取堆積頂元素 */ +let peek = max_heap.peek().unwrap(); // 5 + +/* 堆積頂元素出堆積 */ +// 出堆積元素會形成一個從大到小的序列 +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 + +/* 獲取堆積大小 */ +let size = max_heap.len(); + +/* 判斷堆積是否為空 */ +let is_empty = max_heap.is_empty(); + +/* 輸入串列並建堆積 */ +let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +``` + +```c title="heap.c" +// C 未提供內建 Heap 類別 +``` + +```kotlin title="heap.kt" +/* 初始化堆積 */ +// 初始化小頂堆積 +var minHeap = PriorityQueue() +// 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可) +val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + +/* 元素入堆積 */ +maxHeap.offer(1) +maxHeap.offer(3) +maxHeap.offer(2) +maxHeap.offer(5) +maxHeap.offer(4) + +/* 獲取堆積頂元素 */ +var peek = maxHeap.peek() // 5 + +/* 堆積頂元素出堆積 */ +// 出堆積元素會形成一個從大到小的序列 +peek = maxHeap.poll() // 5 +peek = maxHeap.poll() // 4 +peek = maxHeap.poll() // 3 +peek = maxHeap.poll() // 2 +peek = maxHeap.poll() // 1 + +/* 獲取堆積大小 */ +val size = maxHeap.size + +/* 判斷堆積是否為空 */ +val isEmpty = maxHeap.isEmpty() + +/* 輸入串列並建堆積 */ +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +``` + +```ruby title="heap.rb" +# Ruby 未提供內建 Heap 類別 +``` + + +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E7%B5%84%E9%A0%90%E8%A8%AD%E5%AF%A6%E7%8F%BE%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E8%80%83%E6%85%AE%E5%B0%87%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B2%A0%E2%80%9D%E5%BE%8C%E5%86%8D%E5%85%A5%E5%A0%86%E7%A9%8D%EF%BC%8C%E9%80%99%E6%A8%A3%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%87%E5%A4%A7%E5%B0%8F%E9%97%9C%E4%BF%82%E9%A1%9B%E5%80%92%EF%BC%8C%E5%BE%9E%E8%80%8C%E5%AF%A6%E7%8F%BE%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%99%82%E5%B0%8D%E6%87%89%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%EF%BC%8Cflag%20%3D%20-1%20%E6%99%82%E5%B0%8D%E6%87%89%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%E7%A9%8D%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%A9%8D%E9%A0%82%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E7%A9%8D%E9%A0%82%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E7%A9%8D%E5%85%83%E7%B4%A0%E6%9C%83%E5%BD%A2%E6%88%90%E4%B8%80%E5%80%8B%E5%BE%9E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%A9%8D%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E5%A0%86%E7%A9%8D%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BC%B8%E5%85%A5%E4%B8%B2%E5%88%97%E4%B8%A6%E5%BB%BA%E5%A0%86%E7%A9%8D%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_preface/suggestions.md b/zh-hant/codes/snippets/chapter_preface/suggestions.md new file mode 100644 index 000000000..8e7c8c6b1 --- /dev/null +++ b/zh-hant/codes/snippets/chapter_preface/suggestions.md @@ -0,0 +1,139 @@ + +```python title="" +"""標題註釋,用於標註函式、類別、測試樣例等""" + +# 內容註釋,用於詳解程式碼 + +""" +多行 +註釋 +""" +``` + +```cpp title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```java title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```csharp title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```go title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```swift title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```javascript title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```typescript title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```dart title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```rust title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +// 多行 +// 註釋 +``` + +```c title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```kotlin title="" +/* 標題註釋,用於標註函式、類別、測試樣例等 */ + +// 內容註釋,用於詳解程式碼 + +/** + * 多行 + * 註釋 + */ +``` + +```ruby title="" +### 標題註釋,用於標註函式、類別、測試樣例等 ### + +# 內容註釋,用於詳解程式碼 + +# 多行 +# 註釋 +``` diff --git a/zh-hant/codes/snippets/chapter_stack_and_queue/deque.md b/zh-hant/codes/snippets/chapter_stack_and_queue/deque.md new file mode 100644 index 000000000..42aeb43b6 --- /dev/null +++ b/zh-hant/codes/snippets/chapter_stack_and_queue/deque.md @@ -0,0 +1,339 @@ + +```python title="deque.py" +from collections import deque + +# 初始化雙向佇列 +deq: deque[int] = deque() + +# 元素入列 +deq.append(2) # 新增至佇列尾 +deq.append(5) +deq.append(4) +deq.appendleft(3) # 新增至佇列首 +deq.appendleft(1) + +# 訪問元素 +front: int = deq[0] # 佇列首元素 +rear: int = deq[-1] # 佇列尾元素 + +# 元素出列 +pop_front: int = deq.popleft() # 佇列首元素出列 +pop_rear: int = deq.pop() # 佇列尾元素出列 + +# 獲取雙向佇列的長度 +size: int = len(deq) + +# 判斷雙向佇列是否為空 +is_empty: bool = len(deq) == 0 +``` + +```cpp title="deque.cpp" +/* 初始化雙向佇列 */ +deque deque; + +/* 元素入列 */ +deque.push_back(2); // 新增至佇列尾 +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // 新增至佇列首 +deque.push_front(1); + +/* 訪問元素 */ +int front = deque.front(); // 佇列首元素 +int back = deque.back(); // 佇列尾元素 + +/* 元素出列 */ +deque.pop_front(); // 佇列首元素出列 +deque.pop_back(); // 佇列尾元素出列 + +/* 獲取雙向佇列的長度 */ +int size = deque.size(); + +/* 判斷雙向佇列是否為空 */ +bool empty = deque.empty(); +``` + +```java title="deque.java" +/* 初始化雙向佇列 */ +Deque deque = new LinkedList<>(); + +/* 元素入列 */ +deque.offerLast(2); // 新增至佇列尾 +deque.offerLast(5); +deque.offerLast(4); +deque.offerFirst(3); // 新增至佇列首 +deque.offerFirst(1); + +/* 訪問元素 */ +int peekFirst = deque.peekFirst(); // 佇列首元素 +int peekLast = deque.peekLast(); // 佇列尾元素 + +/* 元素出列 */ +int popFirst = deque.pollFirst(); // 佇列首元素出列 +int popLast = deque.pollLast(); // 佇列尾元素出列 + +/* 獲取雙向佇列的長度 */ +int size = deque.size(); + +/* 判斷雙向佇列是否為空 */ +boolean isEmpty = deque.isEmpty(); +``` + +```csharp title="deque.cs" +/* 初始化雙向佇列 */ +// 在 C# 中,將鏈結串列 LinkedList 看作雙向佇列來使用 +LinkedList deque = new(); + +/* 元素入列 */ +deque.AddLast(2); // 新增至佇列尾 +deque.AddLast(5); +deque.AddLast(4); +deque.AddFirst(3); // 新增至佇列首 +deque.AddFirst(1); + +/* 訪問元素 */ +int peekFirst = deque.First.Value; // 佇列首元素 +int peekLast = deque.Last.Value; // 佇列尾元素 + +/* 元素出列 */ +deque.RemoveFirst(); // 佇列首元素出列 +deque.RemoveLast(); // 佇列尾元素出列 + +/* 獲取雙向佇列的長度 */ +int size = deque.Count; + +/* 判斷雙向佇列是否為空 */ +bool isEmpty = deque.Count == 0; +``` + +```go title="deque_test.go" +/* 初始化雙向佇列 */ +// 在 Go 中,將 list 作為雙向佇列使用 +deque := list.New() + +/* 元素入列 */ +deque.PushBack(2) // 新增至佇列尾 +deque.PushBack(5) +deque.PushBack(4) +deque.PushFront(3) // 新增至佇列首 +deque.PushFront(1) + +/* 訪問元素 */ +front := deque.Front() // 佇列首元素 +rear := deque.Back() // 佇列尾元素 + +/* 元素出列 */ +deque.Remove(front) // 佇列首元素出列 +deque.Remove(rear) // 佇列尾元素出列 + +/* 獲取雙向佇列的長度 */ +size := deque.Len() + +/* 判斷雙向佇列是否為空 */ +isEmpty := deque.Len() == 0 +``` + +```swift title="deque.swift" +/* 初始化雙向佇列 */ +// Swift 沒有內建的雙向佇列類別,可以把 Array 當作雙向佇列來使用 +var deque: [Int] = [] + +/* 元素入列 */ +deque.append(2) // 新增至佇列尾 +deque.append(5) +deque.append(4) +deque.insert(3, at: 0) // 新增至佇列首 +deque.insert(1, at: 0) + +/* 訪問元素 */ +let peekFirst = deque.first! // 佇列首元素 +let peekLast = deque.last! // 佇列尾元素 + +/* 元素出列 */ +// 使用 Array 模擬時 popFirst 的複雜度為 O(n) +let popFirst = deque.removeFirst() // 佇列首元素出列 +let popLast = deque.removeLast() // 佇列尾元素出列 + +/* 獲取雙向佇列的長度 */ +let size = deque.count + +/* 判斷雙向佇列是否為空 */ +let isEmpty = deque.isEmpty +``` + +```javascript title="deque.js" +/* 初始化雙向佇列 */ +// JavaScript 沒有內建的雙端佇列,只能把 Array 當作雙端佇列來使用 +const deque = []; + +/* 元素入列 */ +deque.push(2); +deque.push(5); +deque.push(4); +// 請注意,由於是陣列,unshift() 方法的時間複雜度為 O(n) +deque.unshift(3); +deque.unshift(1); + +/* 訪問元素 */ +const peekFirst = deque[0]; +const peekLast = deque[deque.length - 1]; + +/* 元素出列 */ +// 請注意,由於是陣列,shift() 方法的時間複雜度為 O(n) +const popFront = deque.shift(); +const popBack = deque.pop(); + +/* 獲取雙向佇列的長度 */ +const size = deque.length; + +/* 判斷雙向佇列是否為空 */ +const isEmpty = size === 0; +``` + +```typescript title="deque.ts" +/* 初始化雙向佇列 */ +// TypeScript 沒有內建的雙端佇列,只能把 Array 當作雙端佇列來使用 +const deque: number[] = []; + +/* 元素入列 */ +deque.push(2); +deque.push(5); +deque.push(4); +// 請注意,由於是陣列,unshift() 方法的時間複雜度為 O(n) +deque.unshift(3); +deque.unshift(1); + +/* 訪問元素 */ +const peekFirst: number = deque[0]; +const peekLast: number = deque[deque.length - 1]; + +/* 元素出列 */ +// 請注意,由於是陣列,shift() 方法的時間複雜度為 O(n) +const popFront: number = deque.shift() as number; +const popBack: number = deque.pop() as number; + +/* 獲取雙向佇列的長度 */ +const size: number = deque.length; + +/* 判斷雙向佇列是否為空 */ +const isEmpty: boolean = size === 0; +``` + +```dart title="deque.dart" +/* 初始化雙向佇列 */ +// 在 Dart 中,Queue 被定義為雙向佇列 +Queue deque = Queue(); + +/* 元素入列 */ +deque.addLast(2); // 新增至佇列尾 +deque.addLast(5); +deque.addLast(4); +deque.addFirst(3); // 新增至佇列首 +deque.addFirst(1); + +/* 訪問元素 */ +int peekFirst = deque.first; // 佇列首元素 +int peekLast = deque.last; // 佇列尾元素 + +/* 元素出列 */ +int popFirst = deque.removeFirst(); // 佇列首元素出列 +int popLast = deque.removeLast(); // 佇列尾元素出列 + +/* 獲取雙向佇列的長度 */ +int size = deque.length; + +/* 判斷雙向佇列是否為空 */ +bool isEmpty = deque.isEmpty; +``` + +```rust title="deque.rs" +/* 初始化雙向佇列 */ +let mut deque: VecDeque = VecDeque::new(); + +/* 元素入列 */ +deque.push_back(2); // 新增至佇列尾 +deque.push_back(5); +deque.push_back(4); +deque.push_front(3); // 新增至佇列首 +deque.push_front(1); + +/* 訪問元素 */ +if let Some(front) = deque.front() { // 佇列首元素 +} +if let Some(rear) = deque.back() { // 佇列尾元素 +} + +/* 元素出列 */ +if let Some(pop_front) = deque.pop_front() { // 佇列首元素出列 +} +if let Some(pop_rear) = deque.pop_back() { // 佇列尾元素出列 +} + +/* 獲取雙向佇列的長度 */ +let size = deque.len(); + +/* 判斷雙向佇列是否為空 */ +let is_empty = deque.is_empty(); +``` + +```c title="deque.c" +// C 未提供內建雙向佇列 +``` + +```kotlin title="deque.kt" +/* 初始化雙向佇列 */ +val deque = LinkedList() + +/* 元素入列 */ +deque.offerLast(2) // 新增至佇列尾 +deque.offerLast(5) +deque.offerLast(4) +deque.offerFirst(3) // 新增至佇列首 +deque.offerFirst(1) + +/* 訪問元素 */ +val peekFirst = deque.peekFirst() // 佇列首元素 +val peekLast = deque.peekLast() // 佇列尾元素 + +/* 元素出列 */ +val popFirst = deque.pollFirst() // 佇列首元素出列 +val popLast = deque.pollLast() // 佇列尾元素出列 + +/* 獲取雙向佇列的長度 */ +val size = deque.size + +/* 判斷雙向佇列是否為空 */ +val isEmpty = deque.isEmpty() +``` + +```ruby title="deque.rb" +# 初始化雙向佇列 +# Ruby 沒有內直的雙端佇列,只能把 Array 當作雙端佇列來使用 +deque = [] + +# 元素如隊 +deque << 2 +deque << 5 +deque << 4 +# 請注意,由於是陣列,Array#unshift 方法的時間複雜度為 O(n) +deque.unshift(3) +deque.unshift(1) + +# 訪問元素 +peek_first = deque.first +peek_last = deque.last + +# 元素出列 +# 請注意,由於是陣列, Array#shift 方法的時間複雜度為 O(n) +pop_front = deque.shift +pop_back = deque.pop + +# 獲取雙向佇列的長度 +size = deque.length + +# 判斷雙向佇列是否為空 +is_empty = size.zero? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%88%97%0A%20%20%20%20deq.append%282%29%20%20%23%20%E6%96%B0%E5%A2%9E%E8%87%B3%E4%BD%87%E5%88%97%E5%B0%BE%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20%E6%96%B0%E5%A2%9E%E8%87%B3%E4%BD%87%E5%88%97%E9%A6%96%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22%2C%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%E4%BD%87%E5%88%97%E5%B0%BE%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E5%B0%BE%E5%85%83%E7%B4%A0%20rear%20%3D%22%2C%20rear%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E5%88%97%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%E5%87%BA%E5%88%97%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%A6%96%E5%87%BA%E5%88%97%E5%85%83%E7%B4%A0%20%20pop_front%20%3D%22%2C%20pop_front%29%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%A6%96%E5%87%BA%E5%88%97%E5%BE%8C%20deque%20%3D%22%2C%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20%E4%BD%87%E5%88%97%E5%B0%BE%E5%85%83%E7%B4%A0%E5%87%BA%E5%88%97%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E5%B0%BE%E5%87%BA%E5%88%97%E5%85%83%E7%B4%A0%20%20pop_rear%20%3D%22%2C%20pop_rear%29%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E5%B0%BE%E5%87%BA%E5%88%97%E5%BE%8C%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E7%9A%84%E9%95%B7%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E9%95%B7%E5%BA%A6%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_stack_and_queue/queue.md b/zh-hant/codes/snippets/chapter_stack_and_queue/queue.md new file mode 100644 index 000000000..66cfd0acb --- /dev/null +++ b/zh-hant/codes/snippets/chapter_stack_and_queue/queue.md @@ -0,0 +1,313 @@ + +```python title="queue.py" +from collections import deque + +# 初始化佇列 +# 在 Python 中,我們一般將雙向佇列類別 deque 當作佇列使用 +# 雖然 queue.Queue() 是純正的佇列類別,但不太好用,因此不推薦 +que: deque[int] = deque() + +# 元素入列 +que.append(1) +que.append(3) +que.append(2) +que.append(5) +que.append(4) + +# 訪問佇列首元素 +front: int = que[0] + +# 元素出列 +pop: int = que.popleft() + +# 獲取佇列的長度 +size: int = len(que) + +# 判斷佇列是否為空 +is_empty: bool = len(que) == 0 +``` + +```cpp title="queue.cpp" +/* 初始化佇列 */ +queue queue; + +/* 元素入列 */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 訪問佇列首元素 */ +int front = queue.front(); + +/* 元素出列 */ +queue.pop(); + +/* 獲取佇列的長度 */ +int size = queue.size(); + +/* 判斷佇列是否為空 */ +bool empty = queue.empty(); +``` + +```java title="queue.java" +/* 初始化佇列 */ +Queue queue = new LinkedList<>(); + +/* 元素入列 */ +queue.offer(1); +queue.offer(3); +queue.offer(2); +queue.offer(5); +queue.offer(4); + +/* 訪問佇列首元素 */ +int peek = queue.peek(); + +/* 元素出列 */ +int pop = queue.poll(); + +/* 獲取佇列的長度 */ +int size = queue.size(); + +/* 判斷佇列是否為空 */ +boolean isEmpty = queue.isEmpty(); +``` + +```csharp title="queue.cs" +/* 初始化佇列 */ +Queue queue = new(); + +/* 元素入列 */ +queue.Enqueue(1); +queue.Enqueue(3); +queue.Enqueue(2); +queue.Enqueue(5); +queue.Enqueue(4); + +/* 訪問佇列首元素 */ +int peek = queue.Peek(); + +/* 元素出列 */ +int pop = queue.Dequeue(); + +/* 獲取佇列的長度 */ +int size = queue.Count; + +/* 判斷佇列是否為空 */ +bool isEmpty = queue.Count == 0; +``` + +```go title="queue_test.go" +/* 初始化佇列 */ +// 在 Go 中,將 list 作為佇列來使用 +queue := list.New() + +/* 元素入列 */ +queue.PushBack(1) +queue.PushBack(3) +queue.PushBack(2) +queue.PushBack(5) +queue.PushBack(4) + +/* 訪問佇列首元素 */ +peek := queue.Front() + +/* 元素出列 */ +pop := queue.Front() +queue.Remove(pop) + +/* 獲取佇列的長度 */ +size := queue.Len() + +/* 判斷佇列是否為空 */ +isEmpty := queue.Len() == 0 +``` + +```swift title="queue.swift" +/* 初始化佇列 */ +// Swift 沒有內建的佇列類別,可以把 Array 當作佇列來使用 +var queue: [Int] = [] + +/* 元素入列 */ +queue.append(1) +queue.append(3) +queue.append(2) +queue.append(5) +queue.append(4) + +/* 訪問佇列首元素 */ +let peek = queue.first! + +/* 元素出列 */ +// 由於是陣列,因此 removeFirst 的複雜度為 O(n) +let pop = queue.removeFirst() + +/* 獲取佇列的長度 */ +let size = queue.count + +/* 判斷佇列是否為空 */ +let isEmpty = queue.isEmpty +``` + +```javascript title="queue.js" +/* 初始化佇列 */ +// JavaScript 沒有內建的佇列,可以把 Array 當作佇列來使用 +const queue = []; + +/* 元素入列 */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 訪問佇列首元素 */ +const peek = queue[0]; + +/* 元素出列 */ +// 底層是陣列,因此 shift() 方法的時間複雜度為 O(n) +const pop = queue.shift(); + +/* 獲取佇列的長度 */ +const size = queue.length; + +/* 判斷佇列是否為空 */ +const empty = queue.length === 0; +``` + +```typescript title="queue.ts" +/* 初始化佇列 */ +// TypeScript 沒有內建的佇列,可以把 Array 當作佇列來使用 +const queue: number[] = []; + +/* 元素入列 */ +queue.push(1); +queue.push(3); +queue.push(2); +queue.push(5); +queue.push(4); + +/* 訪問佇列首元素 */ +const peek = queue[0]; + +/* 元素出列 */ +// 底層是陣列,因此 shift() 方法的時間複雜度為 O(n) +const pop = queue.shift(); + +/* 獲取佇列的長度 */ +const size = queue.length; + +/* 判斷佇列是否為空 */ +const empty = queue.length === 0; +``` + +```dart title="queue.dart" +/* 初始化佇列 */ +// 在 Dart 中,佇列類別 Queue 是雙向佇列,也可作為佇列使用 +Queue queue = Queue(); + +/* 元素入列 */ +queue.add(1); +queue.add(3); +queue.add(2); +queue.add(5); +queue.add(4); + +/* 訪問佇列首元素 */ +int peek = queue.first; + +/* 元素出列 */ +int pop = queue.removeFirst(); + +/* 獲取佇列的長度 */ +int size = queue.length; + +/* 判斷佇列是否為空 */ +bool isEmpty = queue.isEmpty; +``` + +```rust title="queue.rs" +/* 初始化雙向佇列 */ +// 在 Rust 中使用雙向佇列作為普通佇列來使用 +let mut deque: VecDeque = VecDeque::new(); + +/* 元素入列 */ +deque.push_back(1); +deque.push_back(3); +deque.push_back(2); +deque.push_back(5); +deque.push_back(4); + +/* 訪問佇列首元素 */ +if let Some(front) = deque.front() { +} + +/* 元素出列 */ +if let Some(pop) = deque.pop_front() { +} + +/* 獲取佇列的長度 */ +let size = deque.len(); + +/* 判斷佇列是否為空 */ +let is_empty = deque.is_empty(); +``` + +```c title="queue.c" +// C 未提供內建佇列 +``` + +```kotlin title="queue.kt" +/* 初始化佇列 */ +val queue = LinkedList() + +/* 元素入列 */ +queue.offer(1) +queue.offer(3) +queue.offer(2) +queue.offer(5) +queue.offer(4) + +/* 訪問佇列首元素 */ +val peek = queue.peek() + +/* 元素出列 */ +val pop = queue.poll() + +/* 獲取佇列的長度 */ +val size = queue.size + +/* 判斷佇列是否為空 */ +val isEmpty = queue.isEmpty() +``` + +```ruby title="queue.rb" +# 初始化佇列 +# Ruby 內建的佇列(Thread::Queue) 沒有 peek 和走訪方法,可以把 Array 當作佇列來使用 +queue = [] + +# 元素入列 +queue.push(1) +queue.push(3) +queue.push(2) +queue.push(5) +queue.push(4) + +# 訪問佇列元素 +peek = queue.first + +# 元素出列 +# 清注意,由於是陣列,Array#shift 方法時間複雜度為 O(n) +pop = queue.shift + +# 獲取佇列的長度 +size = queue.length + +# 判斷佇列是否為空 +is_empty = queue.empty? +``` + + +https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BD%87%E5%88%97%0A%20%20%20%20%23%20%E5%9C%A8%20Python%20%E4%B8%AD%EF%BC%8C%E6%88%91%E5%80%91%E4%B8%80%E8%88%AC%E5%B0%87%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E9%A1%9E%E5%88%A5%20deque%20%E7%9C%8B%E4%BD%9C%E4%BD%87%E5%88%97%E4%BD%BF%E7%94%A8%0A%20%20%20%20%23%20%E9%9B%96%E7%84%B6%20queue.Queue%28%29%20%E6%98%AF%E7%B4%94%E6%AD%A3%E7%9A%84%E4%BD%87%E5%88%97%E9%A1%9E%E5%88%A5%EF%BC%8C%E4%BD%86%E4%B8%8D%E5%A4%AA%E5%A5%BD%E7%94%A8%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%88%97%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22%2C%20front%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E5%88%97%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E5%88%97%E5%85%83%E7%B4%A0%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E5%88%97%E5%BE%8C%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E4%BD%87%E5%88%97%E7%9A%84%E9%95%B7%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%95%B7%E5%BA%A6%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E4%BD%87%E5%88%97%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_stack_and_queue/stack.md b/zh-hant/codes/snippets/chapter_stack_and_queue/stack.md new file mode 100644 index 000000000..25132c404 --- /dev/null +++ b/zh-hant/codes/snippets/chapter_stack_and_queue/stack.md @@ -0,0 +1,304 @@ + +```python title="stack.py" +# 初始化堆疊 +# Python 沒有內建的堆疊類別,可以把 list 當作堆疊來使用 +stack: list[int] = [] + +# 元素入堆疊 +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +# 訪問堆疊頂元素 +peek: int = stack[-1] + +# 元素出堆疊 +pop: int = stack.pop() + +# 獲取堆疊的長度 +size: int = len(stack) + +# 判斷是否為空 +is_empty: bool = len(stack) == 0 +``` + +```cpp title="stack.cpp" +/* 初始化堆疊 */ +stack stack; + +/* 元素入堆疊 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 訪問堆疊頂元素 */ +int top = stack.top(); + +/* 元素出堆疊 */ +stack.pop(); // 無返回值 + +/* 獲取堆疊的長度 */ +int size = stack.size(); + +/* 判斷是否為空 */ +bool empty = stack.empty(); +``` + +```java title="stack.java" +/* 初始化堆疊 */ +Stack stack = new Stack<>(); + +/* 元素入堆疊 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 訪問堆疊頂元素 */ +int peek = stack.peek(); + +/* 元素出堆疊 */ +int pop = stack.pop(); + +/* 獲取堆疊的長度 */ +int size = stack.size(); + +/* 判斷是否為空 */ +boolean isEmpty = stack.isEmpty(); +``` + +```csharp title="stack.cs" +/* 初始化堆疊 */ +Stack stack = new(); + +/* 元素入堆疊 */ +stack.Push(1); +stack.Push(3); +stack.Push(2); +stack.Push(5); +stack.Push(4); + +/* 訪問堆疊頂元素 */ +int peek = stack.Peek(); + +/* 元素出堆疊 */ +int pop = stack.Pop(); + +/* 獲取堆疊的長度 */ +int size = stack.Count; + +/* 判斷是否為空 */ +bool isEmpty = stack.Count == 0; +``` + +```go title="stack_test.go" +/* 初始化堆疊 */ +// 在 Go 中,推薦將 Slice 當作堆疊來使用 +var stack []int + +/* 元素入堆疊 */ +stack = append(stack, 1) +stack = append(stack, 3) +stack = append(stack, 2) +stack = append(stack, 5) +stack = append(stack, 4) + +/* 訪問堆疊頂元素 */ +peek := stack[len(stack)-1] + +/* 元素出堆疊 */ +pop := stack[len(stack)-1] +stack = stack[:len(stack)-1] + +/* 獲取堆疊的長度 */ +size := len(stack) + +/* 判斷是否為空 */ +isEmpty := len(stack) == 0 +``` + +```swift title="stack.swift" +/* 初始化堆疊 */ +// Swift 沒有內建的堆疊類別,可以把 Array 當作堆疊來使用 +var stack: [Int] = [] + +/* 元素入堆疊 */ +stack.append(1) +stack.append(3) +stack.append(2) +stack.append(5) +stack.append(4) + +/* 訪問堆疊頂元素 */ +let peek = stack.last! + +/* 元素出堆疊 */ +let pop = stack.removeLast() + +/* 獲取堆疊的長度 */ +let size = stack.count + +/* 判斷是否為空 */ +let isEmpty = stack.isEmpty +``` + +```javascript title="stack.js" +/* 初始化堆疊 */ +// JavaScript 沒有內建的堆疊類別,可以把 Array 當作堆疊來使用 +const stack = []; + +/* 元素入堆疊 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 訪問堆疊頂元素 */ +const peek = stack[stack.length-1]; + +/* 元素出堆疊 */ +const pop = stack.pop(); + +/* 獲取堆疊的長度 */ +const size = stack.length; + +/* 判斷是否為空 */ +const is_empty = stack.length === 0; +``` + +```typescript title="stack.ts" +/* 初始化堆疊 */ +// TypeScript 沒有內建的堆疊類別,可以把 Array 當作堆疊來使用 +const stack: number[] = []; + +/* 元素入堆疊 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 訪問堆疊頂元素 */ +const peek = stack[stack.length - 1]; + +/* 元素出堆疊 */ +const pop = stack.pop(); + +/* 獲取堆疊的長度 */ +const size = stack.length; + +/* 判斷是否為空 */ +const is_empty = stack.length === 0; +``` + +```dart title="stack.dart" +/* 初始化堆疊 */ +// Dart 沒有內建的堆疊類別,可以把 List 當作堆疊來使用 +List stack = []; + +/* 元素入堆疊 */ +stack.add(1); +stack.add(3); +stack.add(2); +stack.add(5); +stack.add(4); + +/* 訪問堆疊頂元素 */ +int peek = stack.last; + +/* 元素出堆疊 */ +int pop = stack.removeLast(); + +/* 獲取堆疊的長度 */ +int size = stack.length; + +/* 判斷是否為空 */ +bool isEmpty = stack.isEmpty; +``` + +```rust title="stack.rs" +/* 初始化堆疊 */ +// 把 Vec 當作堆疊來使用 +let mut stack: Vec = Vec::new(); + +/* 元素入堆疊 */ +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +/* 訪問堆疊頂元素 */ +let top = stack.last().unwrap(); + +/* 元素出堆疊 */ +let pop = stack.pop().unwrap(); + +/* 獲取堆疊的長度 */ +let size = stack.len(); + +/* 判斷是否為空 */ +let is_empty = stack.is_empty(); +``` + +```c title="stack.c" +// C 未提供內建堆疊 +``` + +```kotlin title="stack.kt" +/* 初始化堆疊 */ +val stack = Stack() + +/* 元素入堆疊 */ +stack.push(1) +stack.push(3) +stack.push(2) +stack.push(5) +stack.push(4) + +/* 訪問堆疊頂元素 */ +val peek = stack.peek() + +/* 元素出堆疊 */ +val pop = stack.pop() + +/* 獲取堆疊的長度 */ +val size = stack.size + +/* 判斷是否為空 */ +val isEmpty = stack.isEmpty() +``` + +```ruby title="stack.rb" +# 初始化堆疊 +# Ruby 沒有內建的堆疊類別,可以把 Array 當作堆疊來使用 +stack = [] + +# 元素入堆疊 +stack << 1 +stack << 3 +stack << 2 +stack << 5 +stack << 4 + +# 訪問堆疊頂元素 +peek = stack.last + +# 元素出堆疊 +pop = stack.pop + +# 獲取堆疊的長度 +size = stack.length + +# 判斷是否為空 +is_empty = stack.empty? +``` + + +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A0%86%E7%96%8A%0A%20%20%20%20%23%20Python%20%E6%B2%92%E6%9C%89%E5%85%A7%E5%BB%BA%E7%9A%84%E5%A0%86%E7%96%8A%E9%A1%9E%E5%88%A5%EF%BC%8C%E5%8F%AF%E4%BB%A5%E6%8A%8A%20list%20%E7%95%B6%E4%BD%9C%E5%A0%86%E7%96%8A%E4%BE%86%E4%BD%BF%E7%94%A8%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%E7%96%8A%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22%E5%A0%86%E7%96%8A%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E5%A0%86%E7%96%8A%E9%A0%82%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22%E5%A0%86%E7%96%8A%E9%A0%82%E5%85%83%E7%B4%A0%20peek%20%3D%22%2C%20peek%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%E7%96%8A%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E5%A0%86%E7%96%8A%E5%85%83%E7%B4%A0%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E5%A0%86%E7%96%8A%E5%BE%8C%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%96%8A%E7%9A%84%E9%95%B7%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22%E5%A0%86%E7%96%8A%E7%9A%84%E9%95%B7%E5%BA%A6%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E5%A0%86%E7%96%8A%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_tree/array_representation_of_tree.md b/zh-hant/codes/snippets/chapter_tree/array_representation_of_tree.md new file mode 100644 index 000000000..4b4b0f05b --- /dev/null +++ b/zh-hant/codes/snippets/chapter_tree/array_representation_of_tree.md @@ -0,0 +1,78 @@ + +```python title="" +# 二元樹的陣列表示 +# 使用 None 來表示空位 +tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] +``` + +```cpp title="" +/* 二元樹的陣列表示 */ +// 使用 int 最大值 INT_MAX 標記空位 +vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```java title="" +/* 二元樹的陣列表示 */ +// 使用 int 的包裝類別 Integer ,就可以使用 null 來標記空位 +Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; +``` + +```csharp title="" +/* 二元樹的陣列表示 */ +// 使用 int? 可空型別 ,就可以使用 null 來標記空位 +int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```go title="" +/* 二元樹的陣列表示 */ +// 使用 any 型別的切片, 就可以使用 nil 來標記空位 +tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} +``` + +```swift title="" +/* 二元樹的陣列表示 */ +// 使用 Int? 可空型別 ,就可以使用 nil 來標記空位 +let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` + +```javascript title="" +/* 二元樹的陣列表示 */ +// 使用 null 來表示空位 +let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```typescript title="" +/* 二元樹的陣列表示 */ +// 使用 null 來表示空位 +let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```dart title="" +/* 二元樹的陣列表示 */ +// 使用 int? 可空型別 ,就可以使用 null 來標記空位 +List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; +``` + +```rust title="" +/* 二元樹的陣列表示 */ +// 使用 None 來標記空位 +let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; +``` + +```c title="" +/* 二元樹的陣列表示 */ +// 使用 int 最大值標記空位,因此要求節點值不能為 INT_MAX +int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; +``` + +```kotlin title="" +/* 二元樹的陣列表示 */ +// 使用 null 來表示空位 +val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) +``` + +```ruby title="" +### 二元樹的陣列表示 ### +# 使用 nil 來表示空位 +tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] +``` diff --git a/zh-hant/codes/snippets/chapter_tree/avl_tree.md b/zh-hant/codes/snippets/chapter_tree/avl_tree.md new file mode 100644 index 000000000..1d221a39a --- /dev/null +++ b/zh-hant/codes/snippets/chapter_tree/avl_tree.md @@ -0,0 +1,182 @@ + +```python title="" +class TreeNode: + """AVL 樹節點類別""" + def __init__(self, val: int): + self.val: int = val # 節點值 + self.height: int = 0 # 節點高度 + self.left: TreeNode | None = None # 左子節點引用 + self.right: TreeNode | None = None # 右子節點引用 +``` + +```cpp title="" +/* AVL 樹節點類別 */ +struct TreeNode { + int val{}; // 節點值 + int height = 0; // 節點高度 + TreeNode *left{}; // 左子節點 + TreeNode *right{}; // 右子節點 + TreeNode() = default; + explicit TreeNode(int x) : val(x){} +}; +``` + +```java title="" +/* AVL 樹節點類別 */ +class TreeNode { + public int val; // 節點值 + public int height; // 節點高度 + public TreeNode left; // 左子節點 + public TreeNode right; // 右子節點 + public TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* AVL 樹節點類別 */ +class TreeNode(int? x) { + public int? val = x; // 節點值 + public int height; // 節點高度 + public TreeNode? left; // 左子節點引用 + public TreeNode? right; // 右子節點引用 +} +``` + +```go title="" +/* AVL 樹節點結構體 */ +type TreeNode struct { + Val int // 節點值 + Height int // 節點高度 + Left *TreeNode // 左子節點引用 + Right *TreeNode // 右子節點引用 +} +``` + +```swift title="" +/* AVL 樹節點類別 */ +class TreeNode { + var val: Int // 節點值 + var height: Int // 節點高度 + var left: TreeNode? // 左子節點 + var right: TreeNode? // 右子節點 + + init(x: Int) { + val = x + height = 0 + } +} +``` + +```javascript title="" +/* AVL 樹節點類別 */ +class TreeNode { + val; // 節點值 + height; //節點高度 + left; // 左子節點指標 + right; // 右子節點指標 + constructor(val, left, right, height) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* AVL 樹節點類別 */ +class TreeNode { + val: number; // 節點值 + height: number; // 節點高度 + left: TreeNode | null; // 左子節點指標 + right: TreeNode | null; // 右子節點指標 + constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; + this.height = height === undefined ? 0 : height; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```dart title="" +/* AVL 樹節點類別 */ +class TreeNode { + int val; // 節點值 + int height; // 節點高度 + TreeNode? left; // 左子節點 + TreeNode? right; // 右子節點 + TreeNode(this.val, [this.height = 0, this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* AVL 樹節點結構體 */ +struct TreeNode { + val: i32, // 節點值 + height: i32, // 節點高度 + left: Option>>, // 左子節點 + right: Option>>, // 右子節點 +} + +impl TreeNode { + /* 建構子 */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + height: 0, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* AVL 樹節點結構體 */ +typedef struct TreeNode { + int val; + int height; + struct TreeNode *left; + struct TreeNode *right; +} TreeNode; + +/* 建構子 */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* AVL 樹節點類別 */ +class TreeNode(val _val: Int) { // 節點值 + var height: Int = 0 // 節點高度 + var left: TreeNode? = null // 左子節點 + var right: TreeNode? = null // 右子節點 +} +``` + +```ruby title="" +### AVL 樹節點類別 ### +class TreeNode + attr_accessor :val # 節點值 + attr_accessor :height # 節點高度 + attr_accessor :left # 左子節點引用 + attr_accessor :right # 右子節點引用 + + def initialize(val) + @val = val + @height = 0 + end +end +``` diff --git a/zh-hant/codes/snippets/chapter_tree/binary_tree.md b/zh-hant/codes/snippets/chapter_tree/binary_tree.md new file mode 100644 index 000000000..b00b5dc2a --- /dev/null +++ b/zh-hant/codes/snippets/chapter_tree/binary_tree.md @@ -0,0 +1,502 @@ + +```python title="" +class TreeNode: + """二元樹節點類別""" + def __init__(self, val: int): + self.val: int = val # 節點值 + self.left: TreeNode | None = None # 左子節點引用 + self.right: TreeNode | None = None # 右子節點引用 +``` + +```cpp title="" +/* 二元樹節點結構體 */ +struct TreeNode { + int val; // 節點值 + TreeNode *left; // 左子節點指標 + TreeNode *right; // 右子節點指標 + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; +``` + +```java title="" +/* 二元樹節點類別 */ +class TreeNode { + int val; // 節點值 + TreeNode left; // 左子節點引用 + TreeNode right; // 右子節點引用 + TreeNode(int x) { val = x; } +} +``` + +```csharp title="" +/* 二元樹節點類別 */ +class TreeNode(int? x) { + public int? val = x; // 節點值 + public TreeNode? left; // 左子節點引用 + public TreeNode? right; // 右子節點引用 +} +``` + +```go title="" +/* 二元樹節點結構體 */ +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} +/* 建構子 */ +func NewTreeNode(v int) *TreeNode { + return &TreeNode{ + Left: nil, // 左子節點指標 + Right: nil, // 右子節點指標 + Val: v, // 節點值 + } +} +``` + +```swift title="" +/* 二元樹節點類別 */ +class TreeNode { + var val: Int // 節點值 + var left: TreeNode? // 左子節點引用 + var right: TreeNode? // 右子節點引用 + + init(x: Int) { + val = x + } +} +``` + +```javascript title="" +/* 二元樹節點類別 */ +class TreeNode { + val; // 節點值 + left; // 左子節點指標 + right; // 右子節點指標 + constructor(val, left, right) { + this.val = val === undefined ? 0 : val; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + +```typescript title="" +/* 二元樹節點類別 */ +class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = val === undefined ? 0 : val; // 節點值 + this.left = left === undefined ? null : left; // 左子節點引用 + this.right = right === undefined ? null : right; // 右子節點引用 + } +} +``` + +```dart title="" +/* 二元樹節點類別 */ +class TreeNode { + int val; // 節點值 + TreeNode? left; // 左子節點引用 + TreeNode? right; // 右子節點引用 + TreeNode(this.val, [this.left, this.right]); +} +``` + +```rust title="" +use std::rc::Rc; +use std::cell::RefCell; + +/* 二元樹節點結構體 */ +struct TreeNode { + val: i32, // 節點值 + left: Option>>, // 左子節點引用 + right: Option>>, // 右子節點引用 +} + +impl TreeNode { + /* 建構子 */ + fn new(val: i32) -> Rc> { + Rc::new(RefCell::new(Self { + val, + left: None, + right: None + })) + } +} +``` + +```c title="" +/* 二元樹節點結構體 */ +typedef struct TreeNode { + int val; // 節點值 + int height; // 節點高度 + struct TreeNode *left; // 左子節點指標 + struct TreeNode *right; // 右子節點指標 +} TreeNode; + +/* 建構子 */ +TreeNode *newTreeNode(int val) { + TreeNode *node; + + node = (TreeNode *)malloc(sizeof(TreeNode)); + node->val = val; + node->height = 0; + node->left = NULL; + node->right = NULL; + return node; +} +``` + +```kotlin title="" +/* 二元樹節點類別 */ +class TreeNode(val _val: Int) { // 節點值 + var left: TreeNode? = null // 左子節點引用 + var right: TreeNode? = null // 右子節點引用 +} +``` + +```ruby title="" +### 二元樹節點類別 ### +class TreeNode + attr_accessor :val # 節點值 + attr_accessor :left # 左子節點引用 + attr_accessor :right # 右子節點引用 + + def initialize(val) + @val = val + end +end +``` + + +```python title="binary_tree.py" +# 初始化二元樹 +# 初始化節點 +n1 = TreeNode(val=1) +n2 = TreeNode(val=2) +n3 = TreeNode(val=3) +n4 = TreeNode(val=4) +n5 = TreeNode(val=5) +# 構建節點之間的引用(指標) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```cpp title="binary_tree.cpp" +/* 初始化二元樹 */ +// 初始化節點 +TreeNode* n1 = new TreeNode(1); +TreeNode* n2 = new TreeNode(2); +TreeNode* n3 = new TreeNode(3); +TreeNode* n4 = new TreeNode(4); +TreeNode* n5 = new TreeNode(5); +// 構建節點之間的引用(指標) +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```java title="binary_tree.java" +// 初始化節點 +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// 構建節點之間的引用(指標) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```csharp title="binary_tree.cs" +/* 初始化二元樹 */ +// 初始化節點 +TreeNode n1 = new(1); +TreeNode n2 = new(2); +TreeNode n3 = new(3); +TreeNode n4 = new(4); +TreeNode n5 = new(5); +// 構建節點之間的引用(指標) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```go title="binary_tree.go" +/* 初始化二元樹 */ +// 初始化節點 +n1 := NewTreeNode(1) +n2 := NewTreeNode(2) +n3 := NewTreeNode(3) +n4 := NewTreeNode(4) +n5 := NewTreeNode(5) +// 構建節點之間的引用(指標) +n1.Left = n2 +n1.Right = n3 +n2.Left = n4 +n2.Right = n5 +``` + +```swift title="binary_tree.swift" +// 初始化節點 +let n1 = TreeNode(x: 1) +let n2 = TreeNode(x: 2) +let n3 = TreeNode(x: 3) +let n4 = TreeNode(x: 4) +let n5 = TreeNode(x: 5) +// 構建節點之間的引用(指標) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```javascript title="binary_tree.js" +/* 初始化二元樹 */ +// 初始化節點 +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// 構建節點之間的引用(指標) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```typescript title="binary_tree.ts" +/* 初始化二元樹 */ +// 初始化節點 +let n1 = new TreeNode(1), + n2 = new TreeNode(2), + n3 = new TreeNode(3), + n4 = new TreeNode(4), + n5 = new TreeNode(5); +// 構建節點之間的引用(指標) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```dart title="binary_tree.dart" +/* 初始化二元樹 */ +// 初始化節點 +TreeNode n1 = new TreeNode(1); +TreeNode n2 = new TreeNode(2); +TreeNode n3 = new TreeNode(3); +TreeNode n4 = new TreeNode(4); +TreeNode n5 = new TreeNode(5); +// 構建節點之間的引用(指標) +n1.left = n2; +n1.right = n3; +n2.left = n4; +n2.right = n5; +``` + +```rust title="binary_tree.rs" +// 初始化節點 +let n1 = TreeNode::new(1); +let n2 = TreeNode::new(2); +let n3 = TreeNode::new(3); +let n4 = TreeNode::new(4); +let n5 = TreeNode::new(5); +// 構建節點之間的引用(指標) +n1.borrow_mut().left = Some(n2.clone()); +n1.borrow_mut().right = Some(n3); +n2.borrow_mut().left = Some(n4); +n2.borrow_mut().right = Some(n5); +``` + +```c title="binary_tree.c" +/* 初始化二元樹 */ +// 初始化節點 +TreeNode *n1 = newTreeNode(1); +TreeNode *n2 = newTreeNode(2); +TreeNode *n3 = newTreeNode(3); +TreeNode *n4 = newTreeNode(4); +TreeNode *n5 = newTreeNode(5); +// 構建節點之間的引用(指標) +n1->left = n2; +n1->right = n3; +n2->left = n4; +n2->right = n5; +``` + +```kotlin title="binary_tree.kt" +// 初始化節點 +val n1 = TreeNode(1) +val n2 = TreeNode(2) +val n3 = TreeNode(3) +val n4 = TreeNode(4) +val n5 = TreeNode(5) +// 構建節點之間的引用(指標) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + +```ruby title="binary_tree.rb" +# 初始化二元樹 +# 初始化節點 +n1 = TreeNode.new(1) +n2 = TreeNode.new(2) +n3 = TreeNode.new(3) +n4 = TreeNode.new(4) +n5 = TreeNode.new(5) +# 構建節點之間的引用(指標) +n1.left = n2 +n1.right = n3 +n2.left = n4 +n2.right = n5 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%85%83%E6%A8%B9%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%85%83%E6%A8%B9%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E7%AF%80%E9%BB%9E%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%A7%8B%E5%BB%BA%E7%AF%80%E9%BB%9E%E4%B9%8B%E9%96%93%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E6%A8%99%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + + +```python title="binary_tree.py" +# 插入與刪除節點 +p = TreeNode(0) +# 在 n1 -> n2 中間插入節點 P +n1.left = p +p.left = n2 +# 刪除節點 P +n1.left = n2 +``` + +```cpp title="binary_tree.cpp" +/* 插入與刪除節點 */ +TreeNode* P = new TreeNode(0); +// 在 n1 -> n2 中間插入節點 P +n1->left = P; +P->left = n2; +// 刪除節點 P +n1->left = n2; +// 釋放記憶體 +delete P; +``` + +```java title="binary_tree.java" +TreeNode P = new TreeNode(0); +// 在 n1 -> n2 中間插入節點 P +n1.left = P; +P.left = n2; +// 刪除節點 P +n1.left = n2; +``` + +```csharp title="binary_tree.cs" +/* 插入與刪除節點 */ +TreeNode P = new(0); +// 在 n1 -> n2 中間插入節點 P +n1.left = P; +P.left = n2; +// 刪除節點 P +n1.left = n2; +``` + +```go title="binary_tree.go" +/* 插入與刪除節點 */ +// 在 n1 -> n2 中間插入節點 P +p := NewTreeNode(0) +n1.Left = p +p.Left = n2 +// 刪除節點 P +n1.Left = n2 +``` + +```swift title="binary_tree.swift" +let P = TreeNode(x: 0) +// 在 n1 -> n2 中間插入節點 P +n1.left = P +P.left = n2 +// 刪除節點 P +n1.left = n2 +``` + +```javascript title="binary_tree.js" +/* 插入與刪除節點 */ +let P = new TreeNode(0); +// 在 n1 -> n2 中間插入節點 P +n1.left = P; +P.left = n2; +// 刪除節點 P +n1.left = n2; +``` + +```typescript title="binary_tree.ts" +/* 插入與刪除節點 */ +const P = new TreeNode(0); +// 在 n1 -> n2 中間插入節點 P +n1.left = P; +P.left = n2; +// 刪除節點 P +n1.left = n2; +``` + +```dart title="binary_tree.dart" +/* 插入與刪除節點 */ +TreeNode P = new TreeNode(0); +// 在 n1 -> n2 中間插入節點 P +n1.left = P; +P.left = n2; +// 刪除節點 P +n1.left = n2; +``` + +```rust title="binary_tree.rs" +let p = TreeNode::new(0); +// 在 n1 -> n2 中間插入節點 P +n1.borrow_mut().left = Some(p.clone()); +p.borrow_mut().left = Some(n2.clone()); +// 刪除節點 p +n1.borrow_mut().left = Some(n2); +``` + +```c title="binary_tree.c" +/* 插入與刪除節點 */ +TreeNode *P = newTreeNode(0); +// 在 n1 -> n2 中間插入節點 P +n1->left = P; +P->left = n2; +// 刪除節點 P +n1->left = n2; +// 釋放記憶體 +free(P); +``` + +```kotlin title="binary_tree.kt" +val P = TreeNode(0) +// 在 n1 -> n2 中間插入節點 P +n1.left = P +P.left = n2 +// 刪除節點 P +n1.left = n2 +``` + +```ruby title="binary_tree.rb" +# 插入與刪除節點 +_p = TreeNode.new(0) +# 在 n1 -> n2 中間插入節點 _p +n1.left = _p +_p.left = n2 +# 刪除節點 +n1.left = n2 +``` + + +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%85%83%E6%A8%B9%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%85%83%E6%A8%B9%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E7%AF%80%E9%BB%9E%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%A7%8B%E5%BB%BA%E7%AF%80%E9%BB%9E%E4%B9%8B%E9%96%93%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E6%A8%99%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E8%88%87%E5%88%AA%E9%99%A4%E7%AF%80%E9%BB%9E%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%96%93%E6%8F%92%E5%85%A5%E7%AF%80%E9%BB%9E%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E7%AF%80%E9%BB%9E%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/docs/chapter_array_and_linkedlist/array.md b/zh-hant/docs/chapter_array_and_linkedlist/array.md index 199a357fd..344df3726 100755 --- a/zh-hant/docs/chapter_array_and_linkedlist/array.md +++ b/zh-hant/docs/chapter_array_and_linkedlist/array.md @@ -10,125 +10,13 @@ 我們可以根據需求選用陣列的兩種初始化方式:無初始值、給定初始值。在未指定初始值的情況下,大多數程式語言會將陣列元素初始化為 $0$ : -=== "Python" - - ```python title="array.py" - # 初始化陣列 - arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="array.cpp" - /* 初始化陣列 */ - // 儲存在堆疊上 - int arr[5] = {}; - int nums[5] = { 1, 3, 2, 5, 4 }; - // 儲存在堆積上(需要手動釋放空間) - int* arr1 = new int[5] {}; - int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="array.java" - /* 初始化陣列 */ - int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } - int[] nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "C#" - - ```csharp title="array.cs" - /* 初始化陣列 */ - int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] - int[] nums = [1, 3, 2, 5, 4]; - ``` - -=== "Go" - - ```go title="array.go" - /* 初始化陣列 */ - var arr [5]int - // 在 Go 中,指定長度時([5]int)為陣列,不指定長度時([]int)為切片 - // 由於 Go 的陣列被設計為在編譯期確定長度,因此只能使用常數來指定長度 - // 為了方便實現擴容 extend() 方法,以下將切片(Slice)看作陣列(Array) - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="array.swift" - /* 初始化陣列 */ - let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] - let nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="array.js" - /* 初始化陣列 */ - var arr = new Array(5).fill(0); - var nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="array.ts" - /* 初始化陣列 */ - let arr: number[] = new Array(5).fill(0); - let nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="array.dart" - /* 初始化陣列 */ - List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="array.rs" - /* 初始化陣列 */ - let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] - let slice: &[i32] = &[0; 5]; - // 在 Rust 中,指定長度時([i32; 5])為陣列,不指定長度時(&[i32])為切片 - // 由於 Rust 的陣列被設計為在編譯期確定長度,因此只能使用常數來指定長度 - // Vector 是 Rust 一般情況下用作動態陣列的型別 - // 為了方便實現擴容 extend() 方法,以下將 vector 看作陣列(array) - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="array.c" - /* 初始化陣列 */ - int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } - int nums[5] = { 1, 3, 2, 5, 4 }; - ``` - -=== "Kotlin" - - ```kotlin title="array.kt" - /* 初始化陣列 */ - var arr = IntArray(5) // { 0, 0, 0, 0, 0 } - var nums = intArrayOf(1, 3, 2, 5, 4) - ``` - -=== "Ruby" - - ```ruby title="array.rb" - # 初始化陣列 - arr = Array.new(5, 0) - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_array +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%99%A3%E5%88%97%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_array_tutor ### 訪問元素 diff --git a/zh-hant/docs/chapter_array_and_linkedlist/linked_list.md b/zh-hant/docs/chapter_array_and_linkedlist/linked_list.md index 1fc346dd8..4558935a8 100755 --- a/zh-hant/docs/chapter_array_and_linkedlist/linked_list.md +++ b/zh-hant/docs/chapter_array_and_linkedlist/linked_list.md @@ -16,174 +16,9 @@ 如以下程式碼所示,鏈結串列節點 `ListNode` 除了包含值,還需額外儲存一個引用(指標)。因此在相同資料量下,**鏈結串列比陣列佔用更多的記憶體空間**。 -=== "Python" - - ```python title="" - class ListNode: - """鏈結串列節點類別""" - def __init__(self, val: int): - self.val: int = val # 節點值 - self.next: ListNode | None = None # 指向下一節點的引用 - ``` - -=== "C++" - - ```cpp title="" - /* 鏈結串列節點結構體 */ - struct ListNode { - int val; // 節點值 - ListNode *next; // 指向下一節點的指標 - ListNode(int x) : val(x), next(nullptr) {} // 建構子 - }; - ``` - -=== "Java" - - ```java title="" - /* 鏈結串列節點類別 */ - class ListNode { - int val; // 節點值 - ListNode next; // 指向下一節點的引用 - ListNode(int x) { val = x; } // 建構子 - } - ``` - -=== "C#" - - ```csharp title="" - /* 鏈結串列節點類別 */ - class ListNode(int x) { //建構子 - int val = x; // 節點值 - ListNode? next; // 指向下一節點的引用 - } - ``` - -=== "Go" - - ```go title="" - /* 鏈結串列節點結構體 */ - type ListNode struct { - Val int // 節點值 - Next *ListNode // 指向下一節點的指標 - } - - // NewListNode 建構子,建立一個新的鏈結串列 - func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 鏈結串列節點類別 */ - class ListNode { - var val: Int // 節點值 - var next: ListNode? // 指向下一節點的引用 - - init(x: Int) { // 建構子 - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 鏈結串列節點類別 */ - class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // 節點值 - this.next = (next === undefined ? null : next); // 指向下一節點的引用 - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 鏈結串列節點類別 */ - class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 節點值 - this.next = next === undefined ? null : next; // 指向下一節點的引用 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 鏈結串列節點類別 */ - class ListNode { - int val; // 節點值 - ListNode? next; // 指向下一節點的引用 - ListNode(this.val, [this.next]); // 建構子 - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - /* 鏈結串列節點類別 */ - #[derive(Debug)] - struct ListNode { - val: i32, // 節點值 - next: Option>>, // 指向下一節點的指標 - } - ``` - -=== "C" - - ```c title="" - /* 鏈結串列節點結構體 */ - typedef struct ListNode { - int val; // 節點值 - struct ListNode *next; // 指向下一節點的指標 - } ListNode; - - /* 建構子 */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 鏈結串列節點類別 */ - // 建構子 - class ListNode(x: Int) { - val _val: Int = x // 節點值 - var next: ListNode? = null // 指向下一個節點的引用 - } - ``` - -=== "Ruby" - - ```ruby title="" - # 鏈結串列節點類別 - class ListNode - attr_accessor :val # 節點值 - attr_accessor :next # 指向下一節點的引用 - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end - end - ``` +```snippet +list_node_class +``` ## 鏈結串列常用操作 @@ -191,231 +26,13 @@ 建立鏈結串列分為兩步,第一步是初始化各個節點物件,第二步是構建節點之間的引用關係。初始化完成後,我們就可以從鏈結串列的頭節點出發,透過引用指向 `next` 依次訪問所有節點。 -=== "Python" - - ```python title="linked_list.py" - # 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 - # 初始化各個節點 - n0 = ListNode(1) - n1 = ListNode(3) - n2 = ListNode(2) - n3 = ListNode(5) - n4 = ListNode(4) - # 構建節點之間的引用 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "C++" - - ```cpp title="linked_list.cpp" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - ListNode* n0 = new ListNode(1); - ListNode* n1 = new ListNode(3); - ListNode* n2 = new ListNode(2); - ListNode* n3 = new ListNode(5); - ListNode* n4 = new ListNode(4); - // 構建節點之間的引用 - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Java" - - ```java title="linked_list.java" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - ListNode n0 = new ListNode(1); - ListNode n1 = new ListNode(3); - ListNode n2 = new ListNode(2); - ListNode n3 = new ListNode(5); - ListNode n4 = new ListNode(4); - // 構建節點之間的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "C#" - - ```csharp title="linked_list.cs" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - ListNode n0 = new(1); - ListNode n1 = new(3); - ListNode n2 = new(2); - ListNode n3 = new(5); - ListNode n4 = new(4); - // 構建節點之間的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Go" - - ```go title="linked_list.go" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - n0 := NewListNode(1) - n1 := NewListNode(3) - n2 := NewListNode(2) - n3 := NewListNode(5) - n4 := NewListNode(4) - // 構建節點之間的引用 - n0.Next = n1 - n1.Next = n2 - n2.Next = n3 - n3.Next = n4 - ``` - -=== "Swift" - - ```swift title="linked_list.swift" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - let n0 = ListNode(x: 1) - let n1 = ListNode(x: 3) - let n2 = ListNode(x: 2) - let n3 = ListNode(x: 5) - let n4 = ListNode(x: 4) - // 構建節點之間的引用 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` - -=== "JS" - - ```javascript title="linked_list.js" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // 構建節點之間的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "TS" - - ```typescript title="linked_list.ts" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - const n0 = new ListNode(1); - const n1 = new ListNode(3); - const n2 = new ListNode(2); - const n3 = new ListNode(5); - const n4 = new ListNode(4); - // 構建節點之間的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Dart" - - ```dart title="linked_list.dart" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */\ - // 初始化各個節點 - ListNode n0 = ListNode(1); - ListNode n1 = ListNode(3); - ListNode n2 = ListNode(2); - ListNode n3 = ListNode(5); - ListNode n4 = ListNode(4); - // 構建節點之間的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Rust" - - ```rust title="linked_list.rs" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); - let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); - let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); - let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); - let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); - - // 構建節點之間的引用 - n0.borrow_mut().next = Some(n1.clone()); - n1.borrow_mut().next = Some(n2.clone()); - n2.borrow_mut().next = Some(n3.clone()); - n3.borrow_mut().next = Some(n4.clone()); - ``` - -=== "C" - - ```c title="linked_list.c" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - ListNode* n0 = newListNode(1); - ListNode* n1 = newListNode(3); - ListNode* n2 = newListNode(2); - ListNode* n3 = newListNode(5); - ListNode* n4 = newListNode(4); - // 構建節點之間的引用 - n0->next = n1; - n1->next = n2; - n2->next = n3; - n3->next = n4; - ``` - -=== "Kotlin" - - ```kotlin title="linked_list.kt" - /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ - // 初始化各個節點 - val n0 = ListNode(1) - val n1 = ListNode(3) - val n2 = ListNode(2) - val n3 = ListNode(5) - val n4 = ListNode(4) - // 構建節點之間的引用 - n0.next = n1; - n1.next = n2; - n2.next = n3; - n3.next = n4; - ``` - -=== "Ruby" - - ```ruby title="linked_list.rb" - # 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 - # 初始化各個節點 - n0 = ListNode.new(1) - n1 = ListNode.new(3) - n2 = ListNode.new(2) - n3 = ListNode.new(5) - n4 = ListNode.new(4) - # 構建節點之間的引用 - n0.next = n1 - n1.next = n2 - n2.next = n3 - n3.next = n4 - ``` +```snippet +init_linked_list +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%BE%8C%E7%B9%BC%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%90%84%E5%80%8B%E7%AF%80%E9%BB%9E%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20%E6%A7%8B%E5%BB%BA%E7%AF%80%E9%BB%9E%E4%B9%8B%E9%96%93%E7%9A%84%E5%BC%95%E7%94%A8%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_linked_list_tutor 陣列整體是一個變數,比如陣列 `nums` 包含元素 `nums[0]` 和 `nums[1]` 等,而鏈結串列是由多個獨立的節點物件組成的。**我們通常將頭節點當作鏈結串列的代稱**,比如以上程式碼中的鏈結串列可記作鏈結串列 `n0` 。 @@ -482,203 +99,9 @@ - **環形鏈結串列**:如果我們令單向鏈結串列的尾節點指向頭節點(首尾相接),則得到一個環形鏈結串列。在環形鏈結串列中,任意節點都可以視作頭節點。 - **雙向鏈結串列**:與單向鏈結串列相比,雙向鏈結串列記錄了兩個方向的引用。雙向鏈結串列的節點定義同時包含指向後繼節點(下一個節點)和前驅節點(上一個節點)的引用(指標)。相較於單向鏈結串列,雙向鏈結串列更具靈活性,可以朝兩個方向走訪鏈結串列,但相應地也需要佔用更多的記憶體空間。 -=== "Python" - - ```python title="" - class ListNode: - """雙向鏈結串列節點類別""" - def __init__(self, val: int): - self.val: int = val # 節點值 - self.next: ListNode | None = None # 指向後繼節點的引用 - self.prev: ListNode | None = None # 指向前驅節點的引用 - ``` - -=== "C++" - - ```cpp title="" - /* 雙向鏈結串列節點結構體 */ - struct ListNode { - int val; // 節點值 - ListNode *next; // 指向後繼節點的指標 - ListNode *prev; // 指向前驅節點的指標 - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 建構子 - }; - ``` - -=== "Java" - - ```java title="" - /* 雙向鏈結串列節點類別 */ - class ListNode { - int val; // 節點值 - ListNode next; // 指向後繼節點的引用 - ListNode prev; // 指向前驅節點的引用 - ListNode(int x) { val = x; } // 建構子 - } - ``` - -=== "C#" - - ```csharp title="" - /* 雙向鏈結串列節點類別 */ - class ListNode(int x) { // 建構子 - int val = x; // 節點值 - ListNode next; // 指向後繼節點的引用 - ListNode prev; // 指向前驅節點的引用 - } - ``` - -=== "Go" - - ```go title="" - /* 雙向鏈結串列節點結構體 */ - type DoublyListNode struct { - Val int // 節點值 - Next *DoublyListNode // 指向後繼節點的指標 - Prev *DoublyListNode // 指向前驅節點的指標 - } - - // NewDoublyListNode 初始化 - func NewDoublyListNode(val int) *DoublyListNode { - return &DoublyListNode{ - Val: val, - Next: nil, - Prev: nil, - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 雙向鏈結串列節點類別 */ - class ListNode { - var val: Int // 節點值 - var next: ListNode? // 指向後繼節點的引用 - var prev: ListNode? // 指向前驅節點的引用 - - init(x: Int) { // 建構子 - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 雙向鏈結串列節點類別 */ - class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // 節點值 - this.next = next === undefined ? null : next; // 指向後繼節點的引用 - this.prev = prev === undefined ? null : prev; // 指向前驅節點的引用 - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 雙向鏈結串列節點類別 */ - class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 節點值 - this.next = next === undefined ? null : next; // 指向後繼節點的引用 - this.prev = prev === undefined ? null : prev; // 指向前驅節點的引用 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 雙向鏈結串列節點類別 */ - class ListNode { - int val; // 節點值 - ListNode? next; // 指向後繼節點的引用 - ListNode? prev; // 指向前驅節點的引用 - ListNode(this.val, [this.next, this.prev]); // 建構子 - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 雙向鏈結串列節點型別 */ - #[derive(Debug)] - struct ListNode { - val: i32, // 節點值 - next: Option>>, // 指向後繼節點的指標 - prev: Option>>, // 指向前驅節點的指標 - } - - /* 建構子 */ - impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } - } - ``` - -=== "C" - - ```c title="" - /* 雙向鏈結串列節點結構體 */ - typedef struct ListNode { - int val; // 節點值 - struct ListNode *next; // 指向後繼節點的指標 - struct ListNode *prev; // 指向前驅節點的指標 - } ListNode; - - /* 建構子 */ - ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 雙向鏈結串列節點類別 */ - // 建構子 - class ListNode(x: Int) { - val _val: Int = x // 節點值 - var next: ListNode? = null // 指向後繼節點的引用 - var prev: ListNode? = null // 指向前驅節點的引用 - } - ``` - -=== "Ruby" - - ```ruby title="" - # 雙向鏈結串列節點類別 - class ListNode - attr_accessor :val # 節點值 - attr_accessor :next # 指向後繼節點的引用 - attr_accessor :prev # 指向前驅節點的引用 - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end - end - ``` +```snippet +doubly_list_node_class +``` ![常見鏈結串列種類](linked_list.assets/linkedlist_common_types.svg) diff --git a/zh-hant/docs/chapter_array_and_linkedlist/list.md b/zh-hant/docs/chapter_array_and_linkedlist/list.md index a3f6d0681..e9c9e5062 100755 --- a/zh-hant/docs/chapter_array_and_linkedlist/list.md +++ b/zh-hant/docs/chapter_array_and_linkedlist/list.md @@ -17,934 +17,73 @@ 我們通常使用“無初始值”和“有初始值”這兩種初始化方法: -=== "Python" - - ```python title="list.py" - # 初始化串列 - # 無初始值 - nums1: list[int] = [] - # 有初始值 - nums: list[int] = [1, 3, 2, 5, 4] - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 初始化串列 */ - // 需注意,C++ 中 vector 即是本文描述的 nums - // 無初始值 - vector nums1; - // 有初始值 - vector nums = { 1, 3, 2, 5, 4 }; - ``` - -=== "Java" - - ```java title="list.java" - /* 初始化串列 */ - // 無初始值 - List nums1 = new ArrayList<>(); - // 有初始值(注意陣列的元素型別需為 int[] 的包裝類別 Integer[]) - Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; - List nums = new ArrayList<>(Arrays.asList(numbers)); - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 初始化串列 */ - // 無初始值 - List nums1 = []; - // 有初始值 - int[] numbers = [1, 3, 2, 5, 4]; - List nums = [.. numbers]; - ``` - -=== "Go" - - ```go title="list_test.go" - /* 初始化串列 */ - // 無初始值 - nums1 := []int{} - // 有初始值 - nums := []int{1, 3, 2, 5, 4} - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 初始化串列 */ - // 無初始值 - let nums1: [Int] = [] - // 有初始值 - var nums = [1, 3, 2, 5, 4] - ``` - -=== "JS" - - ```javascript title="list.js" - /* 初始化串列 */ - // 無初始值 - const nums1 = []; - // 有初始值 - const nums = [1, 3, 2, 5, 4]; - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 初始化串列 */ - // 無初始值 - const nums1: number[] = []; - // 有初始值 - const nums: number[] = [1, 3, 2, 5, 4]; - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 初始化串列 */ - // 無初始值 - List nums1 = []; - // 有初始值 - List nums = [1, 3, 2, 5, 4]; - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 初始化串列 */ - // 無初始值 - let nums1: Vec = Vec::new(); - // 有初始值 - let nums: Vec = vec![1, 3, 2, 5, 4]; - ``` - -=== "C" - - ```c title="list.c" - // C 未提供內建動態陣列 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 初始化串列 */ - // 無初始值 - var nums1 = listOf() - // 有初始值 - var numbers = arrayOf(1, 3, 2, 5, 4) - var nums = numbers.toMutableList() - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 初始化串列 - # 無初始值 - nums1 = [] - # 有初始值 - nums = [1, 3, 2, 5, 4] - ``` +```snippet +init_list +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20%23%20%E7%84%A1%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_list_tutor ### 訪問元素 串列本質上是陣列,因此可以在 $O(1)$ 時間內訪問和更新元素,效率很高。 -=== "Python" - - ```python title="list.py" - # 訪問元素 - num: int = nums[1] # 訪問索引 1 處的元素 - - # 更新元素 - nums[1] = 0 # 將索引 1 處的元素更新為 0 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 訪問元素 */ - int num = nums[1]; // 訪問索引 1 處的元素 - - /* 更新元素 */ - nums[1] = 0; // 將索引 1 處的元素更新為 0 - ``` - -=== "Java" - - ```java title="list.java" - /* 訪問元素 */ - int num = nums.get(1); // 訪問索引 1 處的元素 - - /* 更新元素 */ - nums.set(1, 0); // 將索引 1 處的元素更新為 0 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 訪問元素 */ - int num = nums[1]; // 訪問索引 1 處的元素 - - /* 更新元素 */ - nums[1] = 0; // 將索引 1 處的元素更新為 0 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 訪問元素 */ - num := nums[1] // 訪問索引 1 處的元素 - - /* 更新元素 */ - nums[1] = 0 // 將索引 1 處的元素更新為 0 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 訪問元素 */ - let num = nums[1] // 訪問索引 1 處的元素 - - /* 更新元素 */ - nums[1] = 0 // 將索引 1 處的元素更新為 0 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 訪問元素 */ - const num = nums[1]; // 訪問索引 1 處的元素 - - /* 更新元素 */ - nums[1] = 0; // 將索引 1 處的元素更新為 0 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 訪問元素 */ - const num: number = nums[1]; // 訪問索引 1 處的元素 - - /* 更新元素 */ - nums[1] = 0; // 將索引 1 處的元素更新為 0 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 訪問元素 */ - int num = nums[1]; // 訪問索引 1 處的元素 - - /* 更新元素 */ - nums[1] = 0; // 將索引 1 處的元素更新為 0 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 訪問元素 */ - let num: i32 = nums[1]; // 訪問索引 1 處的元素 - /* 更新元素 */ - nums[1] = 0; // 將索引 1 處的元素更新為 0 - ``` - -=== "C" - - ```c title="list.c" - // C 未提供內建動態陣列 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 訪問元素 */ - val num = nums[1] // 訪問索引 1 處的元素 - /* 更新元素 */ - nums[1] = 0 // 將索引 1 處的元素更新為 0 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 訪問元素 - num = nums[1] # 訪問索引 1 處的元素 - # 更新元素 - nums[1] = 0 # 將索引 1 處的元素更新為 0 - ``` +```snippet +access_element +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E5%85%83%E7%B4%A0%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E8%A8%AA%E5%95%8F%E7%B4%A2%E5%BC%95%201%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%87%E7%B4%A2%E5%BC%95%201%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E7%82%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor access_element_tutor ### 插入與刪除元素 相較於陣列,串列可以自由地新增與刪除元素。在串列尾部新增元素的時間複雜度為 $O(1)$ ,但插入和刪除元素的效率仍與陣列相同,時間複雜度為 $O(n)$ 。 -=== "Python" - - ```python title="list.py" - # 清空串列 - nums.clear() - - # 在尾部新增元素 - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - # 在中間插入元素 - nums.insert(3, 6) # 在索引 3 處插入數字 6 - - # 刪除元素 - nums.pop(3) # 刪除索引 3 處的元素 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 清空串列 */ - nums.clear(); - - /* 在尾部新增元素 */ - nums.push_back(1); - nums.push_back(3); - nums.push_back(2); - nums.push_back(5); - nums.push_back(4); - - /* 在中間插入元素 */ - nums.insert(nums.begin() + 3, 6); // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums.erase(nums.begin() + 3); // 刪除索引 3 處的元素 - ``` - -=== "Java" - - ```java title="list.java" - /* 清空串列 */ - nums.clear(); - - /* 在尾部新增元素 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 在中間插入元素 */ - nums.add(3, 6); // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums.remove(3); // 刪除索引 3 處的元素 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 清空串列 */ - nums.Clear(); - - /* 在尾部新增元素 */ - nums.Add(1); - nums.Add(3); - nums.Add(2); - nums.Add(5); - nums.Add(4); - - /* 在中間插入元素 */ - nums.Insert(3, 6); // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums.RemoveAt(3); // 刪除索引 3 處的元素 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 清空串列 */ - nums = nil - - /* 在尾部新增元素 */ - nums = append(nums, 1) - nums = append(nums, 3) - nums = append(nums, 2) - nums = append(nums, 5) - nums = append(nums, 4) - - /* 在中間插入元素 */ - nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums = append(nums[:3], nums[4:]...) // 刪除索引 3 處的元素 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 清空串列 */ - nums.removeAll() - - /* 在尾部新增元素 */ - nums.append(1) - nums.append(3) - nums.append(2) - nums.append(5) - nums.append(4) - - /* 在中間插入元素 */ - nums.insert(6, at: 3) // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums.remove(at: 3) // 刪除索引 3 處的元素 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 清空串列 */ - nums.length = 0; - - /* 在尾部新增元素 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 在中間插入元素 */ - nums.splice(3, 0, 6); // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums.splice(3, 1); // 刪除索引 3 處的元素 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 清空串列 */ - nums.length = 0; - - /* 在尾部新增元素 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 在中間插入元素 */ - nums.splice(3, 0, 6); // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums.splice(3, 1); // 刪除索引 3 處的元素 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 清空串列 */ - nums.clear(); - - /* 在尾部新增元素 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 在中間插入元素 */ - nums.insert(3, 6); // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums.removeAt(3); // 刪除索引 3 處的元素 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 清空串列 */ - nums.clear(); - - /* 在尾部新增元素 */ - nums.push(1); - nums.push(3); - nums.push(2); - nums.push(5); - nums.push(4); - - /* 在中間插入元素 */ - nums.insert(3, 6); // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums.remove(3); // 刪除索引 3 處的元素 - ``` - -=== "C" - - ```c title="list.c" - // C 未提供內建動態陣列 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 清空串列 */ - nums.clear(); - - /* 在尾部新增元素 */ - nums.add(1); - nums.add(3); - nums.add(2); - nums.add(5); - nums.add(4); - - /* 在中間插入元素 */ - nums.add(3, 6); // 在索引 3 處插入數字 6 - - /* 刪除元素 */ - nums.remove(3); // 刪除索引 3 處的元素 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 清空串列 - nums.clear - - # 在尾部新增元素 - nums << 1 - nums << 3 - nums << 2 - nums << 5 - nums << 4 - - # 在中間插入元素 - nums.insert(3, 6) # 在索引 3 處插入數字 6 - - # 刪除元素 - nums.delete_at(3) # 刪除索引 3 處的元素 - ``` +```snippet +insert_remove_element +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B8%85%E7%A9%BA%E4%B8%B2%E5%88%97%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E5%B0%BE%E9%83%A8%E6%96%B0%E5%A2%9E%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E4%B8%AD%E9%96%93%E6%8F%92%E5%85%A5%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.insert%283%2C%206%29%20%20%23%20%E5%9C%A8%E7%B4%A2%E5%BC%95%203%20%E8%99%95%E6%8F%92%E5%85%A5%E6%95%B8%E5%AD%97%206%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E7%B4%A2%E5%BC%95%203%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_element_tutor ### 走訪串列 與陣列一樣,串列可以根據索引走訪,也可以直接走訪各元素。 -=== "Python" - - ```python title="list.py" - # 透過索引走訪串列 - count = 0 - for i in range(len(nums)): - count += nums[i] - - # 直接走訪串列元素 - for num in nums: - count += num - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 透過索引走訪串列 */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums[i]; - } - - /* 直接走訪串列元素 */ - count = 0; - for (int num : nums) { - count += num; - } - ``` - -=== "Java" - - ```java title="list.java" - /* 透過索引走訪串列 */ - int count = 0; - for (int i = 0; i < nums.size(); i++) { - count += nums.get(i); - } - - /* 直接走訪串列元素 */ - for (int num : nums) { - count += num; - } - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 透過索引走訪串列 */ - int count = 0; - for (int i = 0; i < nums.Count; i++) { - count += nums[i]; - } - - /* 直接走訪串列元素 */ - count = 0; - foreach (int num in nums) { - count += num; - } - ``` - -=== "Go" - - ```go title="list_test.go" - /* 透過索引走訪串列 */ - count := 0 - for i := 0; i < len(nums); i++ { - count += nums[i] - } - - /* 直接走訪串列元素 */ - count = 0 - for _, num := range nums { - count += num - } - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 透過索引走訪串列 */ - var count = 0 - for i in nums.indices { - count += nums[i] - } - - /* 直接走訪串列元素 */ - count = 0 - for num in nums { - count += num - } - ``` - -=== "JS" - - ```javascript title="list.js" - /* 透過索引走訪串列 */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* 直接走訪串列元素 */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 透過索引走訪串列 */ - let count = 0; - for (let i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* 直接走訪串列元素 */ - count = 0; - for (const num of nums) { - count += num; - } - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 透過索引走訪串列 */ - int count = 0; - for (var i = 0; i < nums.length; i++) { - count += nums[i]; - } - - /* 直接走訪串列元素 */ - count = 0; - for (var num in nums) { - count += num; - } - ``` - -=== "Rust" - - ```rust title="list.rs" - // 透過索引走訪串列 - let mut _count = 0; - for i in 0..nums.len() { - _count += nums[i]; - } - - // 直接走訪串列元素 - _count = 0; - for num in &nums { - _count += num; - } - ``` - -=== "C" - - ```c title="list.c" - // C 未提供內建動態陣列 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 透過索引走訪串列 */ - var count = 0 - for (i in nums.indices) { - count += nums[i] - } - - /* 直接走訪串列元素 */ - for (num in nums) { - count += num - } - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 透過索引走訪串列 - count = 0 - for i in 0...nums.length - count += nums[i] - end - - # 直接走訪串列元素 - count = 0 - for num in nums - count += num - end - ``` +```snippet +iterate_list +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%80%8F%E9%81%8E%E7%B4%A2%E5%BC%95%E8%B5%B0%E8%A8%AA%E4%B8%B2%E5%88%97%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%E7%9B%B4%E6%8E%A5%E8%B5%B0%E8%A8%AA%E4%B8%B2%E5%88%97%E5%85%83%E7%B4%A0%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor iterate_list_tutor ### 拼接串列 給定一個新串列 `nums1` ,我們可以將其拼接到原串列的尾部。 -=== "Python" - - ```python title="list.py" - # 拼接兩個串列 - nums1: list[int] = [6, 8, 7, 10, 9] - nums += nums1 # 將串列 nums1 拼接到 nums 之後 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 拼接兩個串列 */ - vector nums1 = { 6, 8, 7, 10, 9 }; - // 將串列 nums1 拼接到 nums 之後 - nums.insert(nums.end(), nums1.begin(), nums1.end()); - ``` - -=== "Java" - - ```java title="list.java" - /* 拼接兩個串列 */ - List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); - nums.addAll(nums1); // 將串列 nums1 拼接到 nums 之後 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 拼接兩個串列 */ - List nums1 = [6, 8, 7, 10, 9]; - nums.AddRange(nums1); // 將串列 nums1 拼接到 nums 之後 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 拼接兩個串列 */ - nums1 := []int{6, 8, 7, 10, 9} - nums = append(nums, nums1...) // 將串列 nums1 拼接到 nums 之後 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 拼接兩個串列 */ - let nums1 = [6, 8, 7, 10, 9] - nums.append(contentsOf: nums1) // 將串列 nums1 拼接到 nums 之後 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 拼接兩個串列 */ - const nums1 = [6, 8, 7, 10, 9]; - nums.push(...nums1); // 將串列 nums1 拼接到 nums 之後 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 拼接兩個串列 */ - const nums1: number[] = [6, 8, 7, 10, 9]; - nums.push(...nums1); // 將串列 nums1 拼接到 nums 之後 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 拼接兩個串列 */ - List nums1 = [6, 8, 7, 10, 9]; - nums.addAll(nums1); // 將串列 nums1 拼接到 nums 之後 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 拼接兩個串列 */ - let nums1: Vec = vec![6, 8, 7, 10, 9]; - nums.extend(nums1); - ``` - -=== "C" - - ```c title="list.c" - // C 未提供內建動態陣列 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 拼接兩個串列 */ - val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() - nums.addAll(nums1) // 將串列 nums1 拼接到 nums 之後 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 拼接兩個串列 - nums1 = [6, 8, 7, 10, 9] - nums += nums1 - ``` +```snippet +concat_list +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8B%BC%E6%8E%A5%E5%85%A9%E5%80%8B%E4%B8%B2%E5%88%97%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%E5%B0%87%E4%B8%B2%E5%88%97%20nums1%20%E6%8B%BC%E6%8E%A5%E5%88%B0%20nums%20%E4%B9%8B%E5%BE%8C&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor concat_list_tutor ### 排序串列 完成串列排序後,我們便可以使用在陣列類別演算法題中經常考查的“二分搜尋”和“雙指標”演算法。 -=== "Python" - - ```python title="list.py" - # 排序串列 - nums.sort() # 排序後,串列元素從小到大排列 - ``` - -=== "C++" - - ```cpp title="list.cpp" - /* 排序串列 */ - sort(nums.begin(), nums.end()); // 排序後,串列元素從小到大排列 - ``` - -=== "Java" - - ```java title="list.java" - /* 排序串列 */ - Collections.sort(nums); // 排序後,串列元素從小到大排列 - ``` - -=== "C#" - - ```csharp title="list.cs" - /* 排序串列 */ - nums.Sort(); // 排序後,串列元素從小到大排列 - ``` - -=== "Go" - - ```go title="list_test.go" - /* 排序串列 */ - sort.Ints(nums) // 排序後,串列元素從小到大排列 - ``` - -=== "Swift" - - ```swift title="list.swift" - /* 排序串列 */ - nums.sort() // 排序後,串列元素從小到大排列 - ``` - -=== "JS" - - ```javascript title="list.js" - /* 排序串列 */ - nums.sort((a, b) => a - b); // 排序後,串列元素從小到大排列 - ``` - -=== "TS" - - ```typescript title="list.ts" - /* 排序串列 */ - nums.sort((a, b) => a - b); // 排序後,串列元素從小到大排列 - ``` - -=== "Dart" - - ```dart title="list.dart" - /* 排序串列 */ - nums.sort(); // 排序後,串列元素從小到大排列 - ``` - -=== "Rust" - - ```rust title="list.rs" - /* 排序串列 */ - nums.sort(); // 排序後,串列元素從小到大排列 - ``` - -=== "C" - - ```c title="list.c" - // C 未提供內建動態陣列 - ``` - -=== "Kotlin" - - ```kotlin title="list.kt" - /* 排序串列 */ - nums.sort() // 排序後,串列元素從小到大排列 - ``` - -=== "Ruby" - - ```ruby title="list.rb" - # 排序串列 - nums = nums.sort { |a, b| a <=> b } # 排序後,串列元素從小到大排列 - ``` +```snippet +sort_list +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8E%92%E5%BA%8F%E4%B8%B2%E5%88%97%0A%20%20%20%20nums.sort%28%29%20%20%23%20%E6%8E%92%E5%BA%8F%E5%BE%8C%EF%BC%8C%E4%B8%B2%E5%88%97%E5%85%83%E7%B4%A0%E5%BE%9E%E5%B0%8F%E5%88%B0%E5%A4%A7%E6%8E%92%E5%88%97&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor sort_list_tutor ## 串列實現 diff --git a/zh-hant/docs/chapter_backtracking/backtracking_algorithm.md b/zh-hant/docs/chapter_backtracking/backtracking_algorithm.md index e35a10e7f..58c1378ba 100644 --- a/zh-hant/docs/chapter_backtracking/backtracking_algorithm.md +++ b/zh-hant/docs/chapter_backtracking/backtracking_algorithm.md @@ -95,339 +95,9 @@ 在以下框架程式碼中,`state` 表示問題的當前狀態,`choices` 表示當前狀態下可以做出的選擇: -=== "Python" - - ```python title="" - def backtrack(state: State, choices: list[choice], res: list[state]): - """回溯演算法框架""" - # 判斷是否為解 - if is_solution(state): - # 記錄解 - record_solution(state, res) - # 不再繼續搜尋 - return - # 走訪所有選擇 - for choice in choices: - # 剪枝:判斷選擇是否合法 - if is_valid(state, choice): - # 嘗試:做出選擇,更新狀態 - make_choice(state, choice) - backtrack(state, choices, res) - # 回退:撤銷選擇,恢復到之前的狀態 - undo_choice(state, choice) - ``` - -=== "C++" - - ```cpp title="" - /* 回溯演算法框架 */ - void backtrack(State *state, vector &choices, vector &res) { - // 判斷是否為解 - if (isSolution(state)) { - // 記錄解 - recordSolution(state, res); - // 不再繼續搜尋 - return; - } - // 走訪所有選擇 - for (Choice choice : choices) { - // 剪枝:判斷選擇是否合法 - if (isValid(state, choice)) { - // 嘗試:做出選擇,更新狀態 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤銷選擇,恢復到之前的狀態 - undoChoice(state, choice); - } - } - } - ``` - -=== "Java" - - ```java title="" - /* 回溯演算法框架 */ - void backtrack(State state, List choices, List res) { - // 判斷是否為解 - if (isSolution(state)) { - // 記錄解 - recordSolution(state, res); - // 不再繼續搜尋 - return; - } - // 走訪所有選擇 - for (Choice choice : choices) { - // 剪枝:判斷選擇是否合法 - if (isValid(state, choice)) { - // 嘗試:做出選擇,更新狀態 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤銷選擇,恢復到之前的狀態 - undoChoice(state, choice); - } - } - } - ``` - -=== "C#" - - ```csharp title="" - /* 回溯演算法框架 */ - void Backtrack(State state, List choices, List res) { - // 判斷是否為解 - if (IsSolution(state)) { - // 記錄解 - RecordSolution(state, res); - // 不再繼續搜尋 - return; - } - // 走訪所有選擇 - foreach (Choice choice in choices) { - // 剪枝:判斷選擇是否合法 - if (IsValid(state, choice)) { - // 嘗試:做出選擇,更新狀態 - MakeChoice(state, choice); - Backtrack(state, choices, res); - // 回退:撤銷選擇,恢復到之前的狀態 - UndoChoice(state, choice); - } - } - } - ``` - -=== "Go" - - ```go title="" - /* 回溯演算法框架 */ - func backtrack(state *State, choices []Choice, res *[]State) { - // 判斷是否為解 - if isSolution(state) { - // 記錄解 - recordSolution(state, res) - // 不再繼續搜尋 - return - } - // 走訪所有選擇 - for _, choice := range choices { - // 剪枝:判斷選擇是否合法 - if isValid(state, choice) { - // 嘗試:做出選擇,更新狀態 - makeChoice(state, choice) - backtrack(state, choices, res) - // 回退:撤銷選擇,恢復到之前的狀態 - undoChoice(state, choice) - } - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 回溯演算法框架 */ - func backtrack(state: inout State, choices: [Choice], res: inout [State]) { - // 判斷是否為解 - if isSolution(state: state) { - // 記錄解 - recordSolution(state: state, res: &res) - // 不再繼續搜尋 - return - } - // 走訪所有選擇 - for choice in choices { - // 剪枝:判斷選擇是否合法 - if isValid(state: state, choice: choice) { - // 嘗試:做出選擇,更新狀態 - makeChoice(state: &state, choice: choice) - backtrack(state: &state, choices: choices, res: &res) - // 回退:撤銷選擇,恢復到之前的狀態 - undoChoice(state: &state, choice: choice) - } - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 回溯演算法框架 */ - function backtrack(state, choices, res) { - // 判斷是否為解 - if (isSolution(state)) { - // 記錄解 - recordSolution(state, res); - // 不再繼續搜尋 - return; - } - // 走訪所有選擇 - for (let choice of choices) { - // 剪枝:判斷選擇是否合法 - if (isValid(state, choice)) { - // 嘗試:做出選擇,更新狀態 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤銷選擇,恢復到之前的狀態 - undoChoice(state, choice); - } - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 回溯演算法框架 */ - function backtrack(state: State, choices: Choice[], res: State[]): void { - // 判斷是否為解 - if (isSolution(state)) { - // 記錄解 - recordSolution(state, res); - // 不再繼續搜尋 - return; - } - // 走訪所有選擇 - for (let choice of choices) { - // 剪枝:判斷選擇是否合法 - if (isValid(state, choice)) { - // 嘗試:做出選擇,更新狀態 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤銷選擇,恢復到之前的狀態 - undoChoice(state, choice); - } - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 回溯演算法框架 */ - void backtrack(State state, List, List res) { - // 判斷是否為解 - if (isSolution(state)) { - // 記錄解 - recordSolution(state, res); - // 不再繼續搜尋 - return; - } - // 走訪所有選擇 - for (Choice choice in choices) { - // 剪枝:判斷選擇是否合法 - if (isValid(state, choice)) { - // 嘗試:做出選擇,更新狀態 - makeChoice(state, choice); - backtrack(state, choices, res); - // 回退:撤銷選擇,恢復到之前的狀態 - undoChoice(state, choice); - } - } - } - ``` - -=== "Rust" - - ```rust title="" - /* 回溯演算法框架 */ - fn backtrack(state: &mut State, choices: &Vec, res: &mut Vec) { - // 判斷是否為解 - if is_solution(state) { - // 記錄解 - record_solution(state, res); - // 不再繼續搜尋 - return; - } - // 走訪所有選擇 - for choice in choices { - // 剪枝:判斷選擇是否合法 - if is_valid(state, choice) { - // 嘗試:做出選擇,更新狀態 - make_choice(state, choice); - backtrack(state, choices, res); - // 回退:撤銷選擇,恢復到之前的狀態 - undo_choice(state, choice); - } - } - } - ``` - -=== "C" - - ```c title="" - /* 回溯演算法框架 */ - void backtrack(State *state, Choice *choices, int numChoices, State *res, int numRes) { - // 判斷是否為解 - if (isSolution(state)) { - // 記錄解 - recordSolution(state, res, numRes); - // 不再繼續搜尋 - return; - } - // 走訪所有選擇 - for (int i = 0; i < numChoices; i++) { - // 剪枝:判斷選擇是否合法 - if (isValid(state, &choices[i])) { - // 嘗試:做出選擇,更新狀態 - makeChoice(state, &choices[i]); - backtrack(state, choices, numChoices, res, numRes); - // 回退:撤銷選擇,恢復到之前的狀態 - undoChoice(state, &choices[i]); - } - } - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 回溯演算法框架 */ - fun backtrack(state: State?, choices: List, res: List?) { - // 判斷是否為解 - if (isSolution(state)) { - // 記錄解 - recordSolution(state, res) - // 不再繼續搜尋 - return - } - // 走訪所有選擇 - for (choice in choices) { - // 剪枝:判斷選擇是否合法 - if (isValid(state, choice)) { - // 嘗試:做出選擇,更新狀態 - makeChoice(state, choice) - backtrack(state, choices, res) - // 回退:撤銷選擇,恢復到之前的狀態 - undoChoice(state, choice) - } - } - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 回溯演算法框架 ### - def backtrack(state, choices, res) - # 判斷是否為解 - if is_solution?(state) - # 記錄解 - record_solution(state, res) - return - end - - # 走訪所有選擇 - for choice in choices - # 剪枝:判斷選擇是否合法 - if is_valid?(state, choice) - # 嘗試:做出選擇,更新狀態 - make_choice(state, choice) - backtrack(state, choices, res) - # 回退:撤銷選擇,恢復到之前的狀態 - undo_choice(state, choice) - end - end - end - ``` +```snippet +backtrack_framework +``` 接下來,我們基於框架程式碼來解決例題三。狀態 `state` 為節點走訪路徑,選擇 `choices` 為當前節點的左子節點和右子節點,結果 `res` 是路徑串列: diff --git a/zh-hant/docs/chapter_computational_complexity/space_complexity.md b/zh-hant/docs/chapter_computational_complexity/space_complexity.md index 5a582ff28..a8b8ba1a1 100755 --- a/zh-hant/docs/chapter_computational_complexity/space_complexity.md +++ b/zh-hant/docs/chapter_computational_complexity/space_complexity.md @@ -24,342 +24,9 @@ 相關程式碼如下: -=== "Python" - - ```python title="" - class Node: - """類別""" - def __init__(self, x: int): - self.val: int = x # 節點值 - self.next: Node | None = None # 指向下一節點的引用 - - def function() -> int: - """函式""" - # 執行某些操作... - return 0 - - def algorithm(n) -> int: # 輸入資料 - A = 0 # 暫存資料(常數,一般用大寫字母表示) - b = 0 # 暫存資料(變數) - node = Node(0) # 暫存資料(物件) - c = function() # 堆疊幀空間(呼叫函式) - return A + b + c # 輸出資料 - ``` - -=== "C++" - - ```cpp title="" - /* 結構體 */ - struct Node { - int val; - Node *next; - Node(int x) : val(x), next(nullptr) {} - }; - - /* 函式 */ - int func() { - // 執行某些操作... - return 0; - } - - int algorithm(int n) { // 輸入資料 - const int a = 0; // 暫存資料(常數) - int b = 0; // 暫存資料(變數) - Node* node = new Node(0); // 暫存資料(物件) - int c = func(); // 堆疊幀空間(呼叫函式) - return a + b + c; // 輸出資料 - } - ``` - -=== "Java" - - ```java title="" - /* 類別 */ - class Node { - int val; - Node next; - Node(int x) { val = x; } - } - - /* 函式 */ - int function() { - // 執行某些操作... - return 0; - } - - int algorithm(int n) { // 輸入資料 - final int a = 0; // 暫存資料(常數) - int b = 0; // 暫存資料(變數) - Node node = new Node(0); // 暫存資料(物件) - int c = function(); // 堆疊幀空間(呼叫函式) - return a + b + c; // 輸出資料 - } - ``` - -=== "C#" - - ```csharp title="" - /* 類別 */ - class Node(int x) { - int val = x; - Node next; - } - - /* 函式 */ - int Function() { - // 執行某些操作... - return 0; - } - - int Algorithm(int n) { // 輸入資料 - const int a = 0; // 暫存資料(常數) - int b = 0; // 暫存資料(變數) - Node node = new(0); // 暫存資料(物件) - int c = Function(); // 堆疊幀空間(呼叫函式) - return a + b + c; // 輸出資料 - } - ``` - -=== "Go" - - ```go title="" - /* 結構體 */ - type node struct { - val int - next *node - } - - /* 建立 node 結構體 */ - func newNode(val int) *node { - return &node{val: val} - } - - /* 函式 */ - func function() int { - // 執行某些操作... - return 0 - } - - func algorithm(n int) int { // 輸入資料 - const a = 0 // 暫存資料(常數) - b := 0 // 暫存資料(變數) - newNode(0) // 暫存資料(物件) - c := function() // 堆疊幀空間(呼叫函式) - return a + b + c // 輸出資料 - } - ``` - -=== "Swift" - - ```swift title="" - /* 類別 */ - class Node { - var val: Int - var next: Node? - - init(x: Int) { - val = x - } - } - - /* 函式 */ - func function() -> Int { - // 執行某些操作... - return 0 - } - - func algorithm(n: Int) -> Int { // 輸入資料 - let a = 0 // 暫存資料(常數) - var b = 0 // 暫存資料(變數) - let node = Node(x: 0) // 暫存資料(物件) - let c = function() // 堆疊幀空間(呼叫函式) - return a + b + c // 輸出資料 - } - ``` - -=== "JS" - - ```javascript title="" - /* 類別 */ - class Node { - val; - next; - constructor(val) { - this.val = val === undefined ? 0 : val; // 節點值 - this.next = null; // 指向下一節點的引用 - } - } - - /* 函式 */ - function constFunc() { - // 執行某些操作 - return 0; - } - - function algorithm(n) { // 輸入資料 - const a = 0; // 暫存資料(常數) - let b = 0; // 暫存資料(變數) - const node = new Node(0); // 暫存資料(物件) - const c = constFunc(); // 堆疊幀空間(呼叫函式) - return a + b + c; // 輸出資料 - } - ``` - -=== "TS" - - ```typescript title="" - /* 類別 */ - class Node { - val: number; - next: Node | null; - constructor(val?: number) { - this.val = val === undefined ? 0 : val; // 節點值 - this.next = null; // 指向下一節點的引用 - } - } - - /* 函式 */ - function constFunc(): number { - // 執行某些操作 - return 0; - } - - function algorithm(n: number): number { // 輸入資料 - const a = 0; // 暫存資料(常數) - let b = 0; // 暫存資料(變數) - const node = new Node(0); // 暫存資料(物件) - const c = constFunc(); // 堆疊幀空間(呼叫函式) - return a + b + c; // 輸出資料 - } - ``` - -=== "Dart" - - ```dart title="" - /* 類別 */ - class Node { - int val; - Node next; - Node(this.val, [this.next]); - } - - /* 函式 */ - int function() { - // 執行某些操作... - return 0; - } - - int algorithm(int n) { // 輸入資料 - const int a = 0; // 暫存資料(常數) - int b = 0; // 暫存資料(變數) - Node node = Node(0); // 暫存資料(物件) - int c = function(); // 堆疊幀空間(呼叫函式) - return a + b + c; // 輸出資料 - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 結構體 */ - struct Node { - val: i32, - next: Option>>, - } - - /* 建立 Node 結構體 */ - impl Node { - fn new(val: i32) -> Self { - Self { val: val, next: None } - } - } - - /* 函式 */ - fn function() -> i32 { - // 執行某些操作... - return 0; - } - - fn algorithm(n: i32) -> i32 { // 輸入資料 - const a: i32 = 0; // 暫存資料(常數) - let mut b = 0; // 暫存資料(變數) - let node = Node::new(0); // 暫存資料(物件) - let c = function(); // 堆疊幀空間(呼叫函式) - return a + b + c; // 輸出資料 - } - ``` - -=== "C" - - ```c title="" - /* 函式 */ - int func() { - // 執行某些操作... - return 0; - } - - int algorithm(int n) { // 輸入資料 - const int a = 0; // 暫存資料(常數) - int b = 0; // 暫存資料(變數) - int c = func(); // 堆疊幀空間(呼叫函式) - return a + b + c; // 輸出資料 - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 類別 */ - class Node(var _val: Int) { - var next: Node? = null - } - - /* 函式 */ - fun function(): Int { - // 執行某些操作... - return 0 - } - - fun algorithm(n: Int): Int { // 輸入資料 - val a = 0 // 暫存資料(常數) - var b = 0 // 暫存資料(變數) - val node = Node(0) // 暫存資料(物件) - val c = function() // 堆疊幀空間(呼叫函式) - return a + b + c // 輸出資料 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 類別 ### - class Node - attr_accessor :val # 節點值 - attr_accessor :next # 指向下一節點的引用 - - def initialize(x) - @val = x - end - end - - ### 函式 ### - def function - # 執行某些操作... - 0 - end - - ### 演算法 ### - def algorithm(n) # 輸入資料 - a = 0 # 暫存資料(常數) - b = 0 # 暫存資料(變數) - node = Node.new(0) # 暫存資料(物件) - c = function # 堆疊幀空間(呼叫函式) - a + b + c # 輸出資料 - end - ``` +```snippet +space_categories +``` ## 推算方法 @@ -372,428 +39,15 @@ 1. **以最差輸入資料為準**:當 $n < 10$ 時,空間複雜度為 $O(1)$ ;但當 $n > 10$ 時,初始化的陣列 `nums` 佔用 $O(n)$ 空間,因此最差空間複雜度為 $O(n)$ 。 2. **以演算法執行中的峰值記憶體為準**:例如,程式在執行最後一行之前,佔用 $O(1)$ 空間;當初始化陣列 `nums` 時,程式佔用 $O(n)$ 空間,因此最差空間複雜度為 $O(n)$ 。 -=== "Python" - - ```python title="" - def algorithm(n: int): - a = 0 # O(1) - b = [0] * 10000 # O(1) - if n > 10: - nums = [0] * n # O(n) - ``` - -=== "C++" - - ```cpp title="" - void algorithm(int n) { - int a = 0; // O(1) - vector b(10000); // O(1) - if (n > 10) - vector nums(n); // O(n) - } - ``` - -=== "Java" - - ```java title="" - void algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) - int[] nums = new int[n]; // O(n) - } - ``` - -=== "C#" - - ```csharp title="" - void Algorithm(int n) { - int a = 0; // O(1) - int[] b = new int[10000]; // O(1) - if (n > 10) { - int[] nums = new int[n]; // O(n) - } - } - ``` - -=== "Go" - - ```go title="" - func algorithm(n int) { - a := 0 // O(1) - b := make([]int, 10000) // O(1) - var nums []int - if n > 10 { - nums := make([]int, n) // O(n) - } - fmt.Println(a, b, nums) - } - ``` - -=== "Swift" - - ```swift title="" - func algorithm(n: Int) { - let a = 0 // O(1) - let b = Array(repeating: 0, count: 10000) // O(1) - if n > 10 { - let nums = Array(repeating: 0, count: n) // O(n) - } - } - ``` - -=== "JS" - - ```javascript title="" - function algorithm(n) { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "TS" - - ```typescript title="" - function algorithm(n: number): void { - const a = 0; // O(1) - const b = new Array(10000); // O(1) - if (n > 10) { - const nums = new Array(n); // O(n) - } - } - ``` - -=== "Dart" - - ```dart title="" - void algorithm(int n) { - int a = 0; // O(1) - List b = List.filled(10000, 0); // O(1) - if (n > 10) { - List nums = List.filled(n, 0); // O(n) - } - } - ``` - -=== "Rust" - - ```rust title="" - fn algorithm(n: i32) { - let a = 0; // O(1) - let b = [0; 10000]; // O(1) - if n > 10 { - let nums = vec![0; n as usize]; // O(n) - } - } - ``` - -=== "C" - - ```c title="" - void algorithm(int n) { - int a = 0; // O(1) - int b[10000]; // O(1) - if (n > 10) - int nums[n] = {0}; // O(n) - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun algorithm(n: Int) { - val a = 0 // O(1) - val b = IntArray(10000) // O(1) - if (n > 10) { - val nums = IntArray(n) // O(n) - } - } - ``` - -=== "Ruby" - - ```ruby title="" - def algorithm(n) - a = 0 # O(1) - b = Array.new(10000) # O(1) - nums = Array.new(n) if n > 10 # O(n) - end - ``` +```snippet +worst_case_space +``` **在遞迴函式中,需要注意統計堆疊幀空間**。觀察以下程式碼: -=== "Python" - - ```python title="" - def function() -> int: - # 執行某些操作 - return 0 - - def loop(n: int): - """迴圈的空間複雜度為 O(1)""" - for _ in range(n): - function() - - def recur(n: int): - """遞迴的空間複雜度為 O(n)""" - if n == 1: - return - return recur(n - 1) - ``` - -=== "C++" - - ```cpp title="" - int func() { - // 執行某些操作 - return 0; - } - /* 迴圈的空間複雜度為 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* 遞迴的空間複雜度為 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Java" - - ```java title="" - int function() { - // 執行某些操作 - return 0; - } - /* 迴圈的空間複雜度為 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* 遞迴的空間複雜度為 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "C#" - - ```csharp title="" - int Function() { - // 執行某些操作 - return 0; - } - /* 迴圈的空間複雜度為 O(1) */ - void Loop(int n) { - for (int i = 0; i < n; i++) { - Function(); - } - } - /* 遞迴的空間複雜度為 O(n) */ - int Recur(int n) { - if (n == 1) return 1; - return Recur(n - 1); - } - ``` - -=== "Go" - - ```go title="" - func function() int { - // 執行某些操作 - return 0 - } - - /* 迴圈的空間複雜度為 O(1) */ - func loop(n int) { - for i := 0; i < n; i++ { - function() - } - } - - /* 遞迴的空間複雜度為 O(n) */ - func recur(n int) { - if n == 1 { - return - } - recur(n - 1) - } - ``` - -=== "Swift" - - ```swift title="" - @discardableResult - func function() -> Int { - // 執行某些操作 - return 0 - } - - /* 迴圈的空間複雜度為 O(1) */ - func loop(n: Int) { - for _ in 0 ..< n { - function() - } - } - - /* 遞迴的空間複雜度為 O(n) */ - func recur(n: Int) { - if n == 1 { - return - } - recur(n: n - 1) - } - ``` - -=== "JS" - - ```javascript title="" - function constFunc() { - // 執行某些操作 - return 0; - } - /* 迴圈的空間複雜度為 O(1) */ - function loop(n) { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* 遞迴的空間複雜度為 O(n) */ - function recur(n) { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "TS" - - ```typescript title="" - function constFunc(): number { - // 執行某些操作 - return 0; - } - /* 迴圈的空間複雜度為 O(1) */ - function loop(n: number): void { - for (let i = 0; i < n; i++) { - constFunc(); - } - } - /* 遞迴的空間複雜度為 O(n) */ - function recur(n: number): void { - if (n === 1) return; - return recur(n - 1); - } - ``` - -=== "Dart" - - ```dart title="" - int function() { - // 執行某些操作 - return 0; - } - /* 迴圈的空間複雜度為 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - function(); - } - } - /* 遞迴的空間複雜度為 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Rust" - - ```rust title="" - fn function() -> i32 { - // 執行某些操作 - return 0; - } - /* 迴圈的空間複雜度為 O(1) */ - fn loop(n: i32) { - for i in 0..n { - function(); - } - } - /* 遞迴的空間複雜度為 O(n) */ - fn recur(n: i32) { - if n == 1 { - return; - } - recur(n - 1); - } - ``` - -=== "C" - - ```c title="" - int func() { - // 執行某些操作 - return 0; - } - /* 迴圈的空間複雜度為 O(1) */ - void loop(int n) { - for (int i = 0; i < n; i++) { - func(); - } - } - /* 遞迴的空間複雜度為 O(n) */ - void recur(int n) { - if (n == 1) return; - recur(n - 1); - } - ``` - -=== "Kotlin" - - ```kotlin title="" - fun function(): Int { - // 執行某些操作 - return 0 - } - /* 迴圈的空間複雜度為 O(1) */ - fun loop(n: Int) { - for (i in 0.. numbers = List.filled(5, 0); - List decimals = List.filled(5, 0.0); - List characters = List.filled(5, 'a'); - List bools = List.filled(5, false); - ``` - -=== "Rust" - - ```rust title="" - // 使用多種基本資料型別來初始化陣列 - let numbers: Vec = vec![0; 5]; - let decimals: Vec = vec![0.0; 5]; - let characters: Vec = vec!['0'; 5]; - let bools: Vec = vec![false; 5]; - ``` - -=== "C" - - ```c title="" - // 使用多種基本資料型別來初始化陣列 - int numbers[10]; - float decimals[10]; - char characters[10]; - bool bools[10]; - ``` - -=== "Kotlin" - - ```kotlin title="" - // 使用多種基本資料型別來初始化陣列 - val numbers = IntArray(5) - val decinals = FloatArray(5) - val characters = CharArray(5) - val bools = BooleanArray(5) - ``` - -=== "Ruby" - - ```ruby title="" - # Ruby 的串列可以自由儲存各種基本資料型別和物件引用 - data = [0, 0.0, 'a', false, ListNode(0)] - ``` +```snippet +basic_type_arrays +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%BE%8C%E7%B9%BC%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%A8%AE%E5%9F%BA%E6%9C%AC%E8%B3%87%E6%96%99%E5%9E%8B%E5%88%A5%E4%BE%86%E5%88%9D%E5%A7%8B%E5%8C%96%E9%99%A3%E5%88%97%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20%2A%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20%2A%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E5%AD%97%E5%85%83%E5%AF%A6%E9%9A%9B%E4%B8%8A%E6%98%AF%E9%95%B7%E5%BA%A6%E7%82%BA%201%20%E7%9A%84%E5%AD%97%E4%B8%B2%0A%20%20%20%20characters%20%3D%20%5B%270%27%5D%20%2A%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20%2A%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E4%B8%B2%E5%88%97%E5%8F%AF%E4%BB%A5%E8%87%AA%E7%94%B1%E5%84%B2%E5%AD%98%E5%90%84%E7%A8%AE%E5%9F%BA%E6%9C%AC%E8%B3%87%E6%96%99%E5%9E%8B%E5%88%A5%E5%92%8C%E7%89%A9%E4%BB%B6%E5%BC%95%E7%94%A8%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20%27a%27%2C%20False%2C%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor basic_type_arrays_tutor diff --git a/zh-hant/docs/chapter_hashing/hash_algorithm.md b/zh-hant/docs/chapter_hashing/hash_algorithm.md index 4a9b25537..fbb429902 100644 --- a/zh-hant/docs/chapter_hashing/hash_algorithm.md +++ b/zh-hant/docs/chapter_hashing/hash_algorithm.md @@ -113,295 +113,13 @@ $$ 請注意,不同程式語言的內建雜湊值計算函式的定義和方法不同。 -=== "Python" - - ```python title="built_in_hash.py" - num = 3 - hash_num = hash(num) - # 整數 3 的雜湊值為 3 - - bol = True - hash_bol = hash(bol) - # 布林量 True 的雜湊值為 1 - - dec = 3.14159 - hash_dec = hash(dec) - # 小數 3.14159 的雜湊值為 326484311674566659 - - str = "Hello 演算法" - hash_str = hash(str) - # 字串“Hello 演算法”的雜湊值為 4617003410720528961 - - tup = (12836, "小哈") - hash_tup = hash(tup) - # 元組 (12836, '小哈') 的雜湊值為 1029005403108185979 - - obj = ListNode(0) - hash_obj = hash(obj) - # 節點物件 的雜湊值為 274267521 - ``` - -=== "C++" - - ```cpp title="built_in_hash.cpp" - int num = 3; - size_t hashNum = hash()(num); - // 整數 3 的雜湊值為 3 - - bool bol = true; - size_t hashBol = hash()(bol); - // 布林量 1 的雜湊值為 1 - - double dec = 3.14159; - size_t hashDec = hash()(dec); - // 小數 3.14159 的雜湊值為 4614256650576692846 - - string str = "Hello 演算法"; - size_t hashStr = hash()(str); - // 字串“Hello 演算法”的雜湊值為 15466937326284535026 - - // 在 C++ 中,內建 std::hash() 僅提供基本資料型別的雜湊值計算 - // 陣列、物件的雜湊值計算需要自行實現 - ``` - -=== "Java" - - ```java title="built_in_hash.java" - int num = 3; - int hashNum = Integer.hashCode(num); - // 整數 3 的雜湊值為 3 - - boolean bol = true; - int hashBol = Boolean.hashCode(bol); - // 布林量 true 的雜湊值為 1231 - - double dec = 3.14159; - int hashDec = Double.hashCode(dec); - // 小數 3.14159 的雜湊值為 -1340954729 - - String str = "Hello 演算法"; - int hashStr = str.hashCode(); - // 字串“Hello 演算法”的雜湊值為 -727081396 - - Object[] arr = { 12836, "小哈" }; - int hashTup = Arrays.hashCode(arr); - // 陣列 [12836, 小哈] 的雜湊值為 1151158 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode(); - // 節點物件 utils.ListNode@7dc5e7b4 的雜湊值為 2110121908 - ``` - -=== "C#" - - ```csharp title="built_in_hash.cs" - int num = 3; - int hashNum = num.GetHashCode(); - // 整數 3 的雜湊值為 3; - - bool bol = true; - int hashBol = bol.GetHashCode(); - // 布林量 true 的雜湊值為 1; - - double dec = 3.14159; - int hashDec = dec.GetHashCode(); - // 小數 3.14159 的雜湊值為 -1340954729; - - string str = "Hello 演算法"; - int hashStr = str.GetHashCode(); - // 字串“Hello 演算法”的雜湊值為 -586107568; - - object[] arr = [12836, "小哈"]; - int hashTup = arr.GetHashCode(); - // 陣列 [12836, 小哈] 的雜湊值為 42931033; - - ListNode obj = new(0); - int hashObj = obj.GetHashCode(); - // 節點物件 0 的雜湊值為 39053774; - ``` - -=== "Go" - - ```go title="built_in_hash.go" - // Go 未提供內建 hash code 函式 - ``` - -=== "Swift" - - ```swift title="built_in_hash.swift" - let num = 3 - let hashNum = num.hashValue - // 整數 3 的雜湊值為 9047044699613009734 - - let bol = true - let hashBol = bol.hashValue - // 布林量 true 的雜湊值為 -4431640247352757451 - - let dec = 3.14159 - let hashDec = dec.hashValue - // 小數 3.14159 的雜湊值為 -2465384235396674631 - - let str = "Hello 演算法" - let hashStr = str.hashValue - // 字串“Hello 演算法”的雜湊值為 -7850626797806988787 - - let arr = [AnyHashable(12836), AnyHashable("小哈")] - let hashTup = arr.hashValue - // 陣列 [AnyHashable(12836), AnyHashable("小哈")] 的雜湊值為 -2308633508154532996 - - let obj = ListNode(x: 0) - let hashObj = obj.hashValue - // 節點物件 utils.ListNode 的雜湊值為 -2434780518035996159 - ``` - -=== "JS" - - ```javascript title="built_in_hash.js" - // JavaScript 未提供內建 hash code 函式 - ``` - -=== "TS" - - ```typescript title="built_in_hash.ts" - // TypeScript 未提供內建 hash code 函式 - ``` - -=== "Dart" - - ```dart title="built_in_hash.dart" - int num = 3; - int hashNum = num.hashCode; - // 整數 3 的雜湊值為 34803 - - bool bol = true; - int hashBol = bol.hashCode; - // 布林值 true 的雜湊值為 1231 - - double dec = 3.14159; - int hashDec = dec.hashCode; - // 小數 3.14159 的雜湊值為 2570631074981783 - - String str = "Hello 演算法"; - int hashStr = str.hashCode; - // 字串“Hello 演算法”的雜湊值為 468167534 - - List arr = [12836, "小哈"]; - int hashArr = arr.hashCode; - // 陣列 [12836, 小哈] 的雜湊值為 976512528 - - ListNode obj = new ListNode(0); - int hashObj = obj.hashCode; - // 節點物件 Instance of 'ListNode' 的雜湊值為 1033450432 - ``` - -=== "Rust" - - ```rust title="built_in_hash.rs" - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - - let num = 3; - let mut num_hasher = DefaultHasher::new(); - num.hash(&mut num_hasher); - let hash_num = num_hasher.finish(); - // 整數 3 的雜湊值為 568126464209439262 - - let bol = true; - let mut bol_hasher = DefaultHasher::new(); - bol.hash(&mut bol_hasher); - let hash_bol = bol_hasher.finish(); - // 布林量 true 的雜湊值為 4952851536318644461 - - let dec: f32 = 3.14159; - let mut dec_hasher = DefaultHasher::new(); - dec.to_bits().hash(&mut dec_hasher); - let hash_dec = dec_hasher.finish(); - // 小數 3.14159 的雜湊值為 2566941990314602357 - - let str = "Hello 演算法"; - let mut str_hasher = DefaultHasher::new(); - str.hash(&mut str_hasher); - let hash_str = str_hasher.finish(); - // 字串“Hello 演算法”的雜湊值為 16092673739211250988 - - let arr = (&12836, &"小哈"); - let mut tup_hasher = DefaultHasher::new(); - arr.hash(&mut tup_hasher); - let hash_tup = tup_hasher.finish(); - // 元組 (12836, "小哈") 的雜湊值為 1885128010422702749 - - let node = ListNode::new(42); - let mut hasher = DefaultHasher::new(); - node.borrow().val.hash(&mut hasher); - let hash = hasher.finish(); - // 節點物件 RefCell { value: ListNode { val: 42, next: None } } 的雜湊值為15387811073369036852 - ``` - -=== "C" - - ```c title="built_in_hash.c" - // C 未提供內建 hash code 函式 - ``` - -=== "Kotlin" - - ```kotlin title="built_in_hash.kt" - val num = 3 - val hashNum = num.hashCode() - // 整數 3 的雜湊值為 3 - - val bol = true - val hashBol = bol.hashCode() - // 布林量 true 的雜湊值為 1231 - - val dec = 3.14159 - val hashDec = dec.hashCode() - // 小數 3.14159 的雜湊值為 -1340954729 - - val str = "Hello 演算法" - val hashStr = str.hashCode() - // 字串“Hello 演算法”的雜湊值為 -727081396 - - val arr = arrayOf(12836, "小哈") - val hashTup = arr.hashCode() - // 陣列 [12836, 小哈] 的雜湊值為 189568618 - - val obj = ListNode(0) - val hashObj = obj.hashCode() - // 節點物件 utils.ListNode@1d81eb93 的雜湊值為 495053715 - ``` - -=== "Ruby" - - ```ruby title="built_in_hash.rb" - num = 3 - hash_num = num.hash - # 整數 3 的雜湊值為 -4385856518450339636 - - bol = true - hash_bol = bol.hash - # 布林量 true 的雜湊值為 -1617938112149317027 - - dec = 3.14159 - hash_dec = dec.hash - # 小數 3.14159 的雜湊值為 -1479186995943067893 - - str = "Hello 演算法" - hash_str = str.hash - # 字串“Hello 演算法”的雜湊值為 -4075943250025831763 - - tup = [12836, '小哈'] - hash_tup = tup.hash - # 元組 (12836, '小哈') 的雜湊值為 1999544809202288822 - - obj = ListNode.new(0) - hash_obj = obj.hash - # 節點物件 # 的雜湊值為 4302940560806366381 - ``` +```snippet +builtin_hash +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%BE%8C%E7%B9%BC%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B8%203%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%E5%B8%83%E6%9E%97%E9%87%8F%20True%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B8%203.14159%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E6%BC%94%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%E5%AD%97%E4%B8%B2%E2%80%9CHello%20%E6%BC%94%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%E5%85%83%E7%B5%84%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E7%89%A9%E4%BB%B6%20%3CListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor builtin_hash_tutor 在許多程式語言中,**只有不可變物件才可作為雜湊表的 `key`** 。假如我們將串列(動態陣列)作為 `key` ,當串列的內容發生變化時,它的雜湊值也隨之改變,我們就無法在雜湊表中查詢到原先的 `value` 了。 diff --git a/zh-hant/docs/chapter_hashing/hash_map.md b/zh-hant/docs/chapter_hashing/hash_map.md index 1c37d0f38..9cfc9015f 100755 --- a/zh-hant/docs/chapter_hashing/hash_map.md +++ b/zh-hant/docs/chapter_hashing/hash_map.md @@ -26,517 +26,23 @@ 雜湊表的常見操作包括:初始化、查詢操作、新增鍵值對和刪除鍵值對等,示例程式碼如下: -=== "Python" - - ```python title="hash_map.py" - # 初始化雜湊表 - hmap: dict = {} - - # 新增操作 - # 在雜湊表中新增鍵值對 (key, value) - hmap[12836] = "小哈" - hmap[15937] = "小囉" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鴨" - - # 查詢操作 - # 向雜湊表中輸入鍵 key ,得到值 value - name: str = hmap[15937] - - # 刪除操作 - # 在雜湊表中刪除鍵值對 (key, value) - hmap.pop(10583) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* 初始化雜湊表 */ - unordered_map map; - - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - map[12836] = "小哈"; - map[15937] = "小囉"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鴨"; - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - string name = map[15937]; - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - map.erase(10583); - ``` - -=== "Java" - - ```java title="hash_map.java" - /* 初始化雜湊表 */ - Map map = new HashMap<>(); - - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - map.put(12836, "小哈"); - map.put(15937, "小囉"); - map.put(16750, "小算"); - map.put(13276, "小法"); - map.put(10583, "小鴨"); - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - String name = map.get(15937); - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - map.remove(10583); - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* 初始化雜湊表 */ - Dictionary map = new() { - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - { 12836, "小哈" }, - { 15937, "小囉" }, - { 16750, "小算" }, - { 13276, "小法" }, - { 10583, "小鴨" } - }; - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - string name = map[15937]; - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - map.Remove(10583); - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* 初始化雜湊表 */ - hmap := make(map[int]string) - - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - hmap[12836] = "小哈" - hmap[15937] = "小囉" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鴨" - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - name := hmap[15937] - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - delete(hmap, 10583) - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* 初始化雜湊表 */ - var map: [Int: String] = [:] - - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - map[12836] = "小哈" - map[15937] = "小囉" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鴨" - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - let name = map[15937]! - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - map.removeValue(forKey: 10583) - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* 初始化雜湊表 */ - const map = new Map(); - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - map.set(12836, '小哈'); - map.set(15937, '小囉'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鴨'); - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - let name = map.get(15937); - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - map.delete(10583); - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* 初始化雜湊表 */ - const map = new Map(); - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - map.set(12836, '小哈'); - map.set(15937, '小囉'); - map.set(16750, '小算'); - map.set(13276, '小法'); - map.set(10583, '小鴨'); - console.info('\n新增完成後,雜湊表為\nKey -> Value'); - console.info(map); - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - let name = map.get(15937); - console.info('\n輸入學號 15937 ,查詢到姓名 ' + name); - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - map.delete(10583); - console.info('\n刪除 10583 後,雜湊表為\nKey -> Value'); - console.info(map); - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* 初始化雜湊表 */ - Map map = {}; - - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - map[12836] = "小哈"; - map[15937] = "小囉"; - map[16750] = "小算"; - map[13276] = "小法"; - map[10583] = "小鴨"; - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - String name = map[15937]; - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - map.remove(10583); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - use std::collections::HashMap; - - /* 初始化雜湊表 */ - let mut map: HashMap = HashMap::new(); - - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - map.insert(12836, "小哈".to_string()); - map.insert(15937, "小囉".to_string()); - map.insert(16750, "小算".to_string()); - map.insert(13279, "小法".to_string()); - map.insert(10583, "小鴨".to_string()); - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - let _name: Option<&String> = map.get(&15937); - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - let _removed_value: Option = map.remove(&10583); - ``` - -=== "C" - - ```c title="hash_map.c" - // C 未提供內建雜湊表 - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* 初始化雜湊表 */ - val map = HashMap() - - /* 新增操作 */ - // 在雜湊表中新增鍵值對 (key, value) - map[12836] = "小哈" - map[15937] = "小囉" - map[16750] = "小算" - map[13276] = "小法" - map[10583] = "小鴨" - - /* 查詢操作 */ - // 向雜湊表中輸入鍵 key ,得到值 value - val name = map[15937] - - /* 刪除操作 */ - // 在雜湊表中刪除鍵值對 (key, value) - map.remove(10583) - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # 初始化雜湊表 - hmap = {} - - # 新增操作 - # 在雜湊表中新增鍵值對 (key, value) - hmap[12836] = "小哈" - hmap[15937] = "小囉" - hmap[16750] = "小算" - hmap[13276] = "小法" - hmap[10583] = "小鴨" - - # 查詢操作 - # 向雜湊表中輸入鍵 key ,得到值 value - name = hmap[15937] - - # 刪除操作 - # 在雜湊表中刪除鍵值對 (key, value) - hmap.delete(10583) - ``` +```snippet +hash_map_operations +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%96%B0%E5%A2%9E%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E6%96%B0%E5%A2%9E%E9%8D%B5%E5%80%BC%E5%B0%8D%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%9B%89%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B4%A8%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%9F%A5%E8%A9%A2%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%90%91%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E8%BC%B8%E5%85%A5%E9%8D%B5%20key%20%EF%BC%8C%E5%BE%97%E5%88%B0%E5%80%BC%20value%0A%20%20%20%20name%20%3D%20hmap%5B15937%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E5%88%AA%E9%99%A4%E9%8D%B5%E5%80%BC%E5%B0%8D%20%28key%2C%20value%29%0A%20%20%20%20hmap.pop%2810583%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_operations_tutor 雜湊表有三種常用的走訪方式:走訪鍵值對、走訪鍵和走訪值。示例程式碼如下: -=== "Python" - - ```python title="hash_map.py" - # 走訪雜湊表 - # 走訪鍵值對 key->value - for key, value in hmap.items(): - print(key, "->", value) - # 單獨走訪鍵 key - for key in hmap.keys(): - print(key) - # 單獨走訪值 value - for value in hmap.values(): - print(value) - ``` - -=== "C++" - - ```cpp title="hash_map.cpp" - /* 走訪雜湊表 */ - // 走訪鍵值對 key->value - for (auto kv: map) { - cout << kv.first << " -> " << kv.second << endl; - } - // 使用迭代器走訪 key->value - for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; - } - ``` - -=== "Java" - - ```java title="hash_map.java" - /* 走訪雜湊表 */ - // 走訪鍵值對 key->value - for (Map.Entry kv: map.entrySet()) { - System.out.println(kv.getKey() + " -> " + kv.getValue()); - } - // 單獨走訪鍵 key - for (int key: map.keySet()) { - System.out.println(key); - } - // 單獨走訪值 value - for (String val: map.values()) { - System.out.println(val); - } - ``` - -=== "C#" - - ```csharp title="hash_map.cs" - /* 走訪雜湊表 */ - // 走訪鍵值對 Key->Value - foreach (var kv in map) { - Console.WriteLine(kv.Key + " -> " + kv.Value); - } - // 單獨走訪鍵 key - foreach (int key in map.Keys) { - Console.WriteLine(key); - } - // 單獨走訪值 value - foreach (string val in map.Values) { - Console.WriteLine(val); - } - ``` - -=== "Go" - - ```go title="hash_map_test.go" - /* 走訪雜湊表 */ - // 走訪鍵值對 key->value - for key, value := range hmap { - fmt.Println(key, "->", value) - } - // 單獨走訪鍵 key - for key := range hmap { - fmt.Println(key) - } - // 單獨走訪值 value - for _, value := range hmap { - fmt.Println(value) - } - ``` - -=== "Swift" - - ```swift title="hash_map.swift" - /* 走訪雜湊表 */ - // 走訪鍵值對 Key->Value - for (key, value) in map { - print("\(key) -> \(value)") - } - // 單獨走訪鍵 Key - for key in map.keys { - print(key) - } - // 單獨走訪值 Value - for value in map.values { - print(value) - } - ``` - -=== "JS" - - ```javascript title="hash_map.js" - /* 走訪雜湊表 */ - console.info('\n走訪鍵值對 Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\n單獨走訪鍵 Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\n單獨走訪值 Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "TS" - - ```typescript title="hash_map.ts" - /* 走訪雜湊表 */ - console.info('\n走訪鍵值對 Key->Value'); - for (const [k, v] of map.entries()) { - console.info(k + ' -> ' + v); - } - console.info('\n單獨走訪鍵 Key'); - for (const k of map.keys()) { - console.info(k); - } - console.info('\n單獨走訪值 Value'); - for (const v of map.values()) { - console.info(v); - } - ``` - -=== "Dart" - - ```dart title="hash_map.dart" - /* 走訪雜湊表 */ - // 走訪鍵值對 Key->Value - map.forEach((key, value) { - print('$key -> $value'); - }); - - // 單獨走訪鍵 Key - map.keys.forEach((key) { - print(key); - }); - - // 單獨走訪值 Value - map.values.forEach((value) { - print(value); - }); - ``` - -=== "Rust" - - ```rust title="hash_map.rs" - /* 走訪雜湊表 */ - // 走訪鍵值對 Key->Value - for (key, value) in &map { - println!("{key} -> {value}"); - } - - // 單獨走訪鍵 Key - for key in map.keys() { - println!("{key}"); - } - - // 單獨走訪值 Value - for value in map.values() { - println!("{value}"); - } - ``` - -=== "C" - - ```c title="hash_map.c" - // C 未提供內建雜湊表 - ``` - -=== "Kotlin" - - ```kotlin title="hash_map.kt" - /* 走訪雜湊表 */ - // 走訪鍵值對 key->value - for ((key, value) in map) { - println("$key -> $value") - } - // 單獨走訪鍵 key - for (key in map.keys) { - println(key) - } - // 單獨走訪值 value - for (_val in map.values) { - println(_val) - } - ``` - -=== "Ruby" - - ```ruby title="hash_map.rb" - # 走訪雜湊表 - # 走訪鍵值對 key->value - hmap.entries.each { |key, value| puts "#{key} -> #{value}" } - - # 單獨走訪鍵 key - hmap.keys.each { |key| puts key } - - # 單獨走訪值 value - hmap.values.each { |val| puts val } - ``` +```snippet +hash_map_traversal +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%96%B0%E5%A2%9E%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E6%96%B0%E5%A2%9E%E9%8D%B5%E5%80%BC%E5%B0%8D%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%9B%89%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B4%A8%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%B5%B0%E8%A8%AA%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20%23%20%E8%B5%B0%E8%A8%AA%E9%8D%B5%E5%80%BC%E5%B0%8D%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%E5%96%AE%E7%8D%A8%E8%B5%B0%E8%A8%AA%E9%8D%B5%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%96%AE%E7%8D%A8%E8%B5%B0%E8%A8%AA%E5%80%BC%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor hash_map_traversal_tutor ## 雜湊表簡單實現 diff --git a/zh-hant/docs/chapter_heap/heap.md b/zh-hant/docs/chapter_heap/heap.md index 11fb08404..a8584f218 100644 --- a/zh-hant/docs/chapter_heap/heap.md +++ b/zh-hant/docs/chapter_heap/heap.md @@ -35,382 +35,13 @@ 類似於排序演算法中的“從小到大排列”和“從大到小排列”,我們可以透過設定一個 `flag` 或修改 `Comparator` 實現“小頂堆積”與“大頂堆積”之間的轉換。程式碼如下所示: -=== "Python" - - ```python title="heap.py" - # 初始化小頂堆積 - min_heap, flag = [], 1 - # 初始化大頂堆積 - max_heap, flag = [], -1 - - # Python 的 heapq 模組預設實現小頂堆積 - # 考慮將“元素取負”後再入堆積,這樣就可以將大小關係顛倒,從而實現大頂堆積 - # 在本示例中,flag = 1 時對應小頂堆積,flag = -1 時對應大頂堆積 - - # 元素入堆積 - heapq.heappush(max_heap, flag * 1) - heapq.heappush(max_heap, flag * 3) - heapq.heappush(max_heap, flag * 2) - heapq.heappush(max_heap, flag * 5) - heapq.heappush(max_heap, flag * 4) - - # 獲取堆積頂元素 - peek: int = flag * max_heap[0] # 5 - - # 堆積頂元素出堆積 - # 出堆積元素會形成一個從大到小的序列 - val = flag * heapq.heappop(max_heap) # 5 - val = flag * heapq.heappop(max_heap) # 4 - val = flag * heapq.heappop(max_heap) # 3 - val = flag * heapq.heappop(max_heap) # 2 - val = flag * heapq.heappop(max_heap) # 1 - - # 獲取堆積大小 - size: int = len(max_heap) - - # 判斷堆積是否為空 - is_empty: bool = not max_heap - - # 輸入串列並建堆積 - min_heap: list[int] = [1, 3, 2, 5, 4] - heapq.heapify(min_heap) - ``` - -=== "C++" - - ```cpp title="heap.cpp" - /* 初始化堆積 */ - // 初始化小頂堆積 - priority_queue, greater> minHeap; - // 初始化大頂堆積 - priority_queue, less> maxHeap; - - /* 元素入堆積 */ - maxHeap.push(1); - maxHeap.push(3); - maxHeap.push(2); - maxHeap.push(5); - maxHeap.push(4); - - /* 獲取堆積頂元素 */ - int peek = maxHeap.top(); // 5 - - /* 堆積頂元素出堆積 */ - // 出堆積元素會形成一個從大到小的序列 - maxHeap.pop(); // 5 - maxHeap.pop(); // 4 - maxHeap.pop(); // 3 - maxHeap.pop(); // 2 - maxHeap.pop(); // 1 - - /* 獲取堆積大小 */ - int size = maxHeap.size(); - - /* 判斷堆積是否為空 */ - bool isEmpty = maxHeap.empty(); - - /* 輸入串列並建堆積 */ - vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); - ``` - -=== "Java" - - ```java title="heap.java" - /* 初始化堆積 */ - // 初始化小頂堆積 - Queue minHeap = new PriorityQueue<>(); - // 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可) - Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); - - /* 元素入堆積 */ - maxHeap.offer(1); - maxHeap.offer(3); - maxHeap.offer(2); - maxHeap.offer(5); - maxHeap.offer(4); - - /* 獲取堆積頂元素 */ - int peek = maxHeap.peek(); // 5 - - /* 堆積頂元素出堆積 */ - // 出堆積元素會形成一個從大到小的序列 - peek = maxHeap.poll(); // 5 - peek = maxHeap.poll(); // 4 - peek = maxHeap.poll(); // 3 - peek = maxHeap.poll(); // 2 - peek = maxHeap.poll(); // 1 - - /* 獲取堆積大小 */ - int size = maxHeap.size(); - - /* 判斷堆積是否為空 */ - boolean isEmpty = maxHeap.isEmpty(); - - /* 輸入串列並建堆積 */ - minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); - ``` - -=== "C#" - - ```csharp title="heap.cs" - /* 初始化堆積 */ - // 初始化小頂堆積 - PriorityQueue minHeap = new(); - // 初始化大頂堆積(使用 lambda 表示式修改 Comparer 即可) - PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); - - /* 元素入堆積 */ - maxHeap.Enqueue(1, 1); - maxHeap.Enqueue(3, 3); - maxHeap.Enqueue(2, 2); - maxHeap.Enqueue(5, 5); - maxHeap.Enqueue(4, 4); - - /* 獲取堆積頂元素 */ - int peek = maxHeap.Peek();//5 - - /* 堆積頂元素出堆積 */ - // 出堆積元素會形成一個從大到小的序列 - peek = maxHeap.Dequeue(); // 5 - peek = maxHeap.Dequeue(); // 4 - peek = maxHeap.Dequeue(); // 3 - peek = maxHeap.Dequeue(); // 2 - peek = maxHeap.Dequeue(); // 1 - - /* 獲取堆積大小 */ - int size = maxHeap.Count; - - /* 判斷堆積是否為空 */ - bool isEmpty = maxHeap.Count == 0; - - /* 輸入串列並建堆積 */ - minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); - ``` - -=== "Go" - - ```go title="heap.go" - // Go 語言中可以透過實現 heap.Interface 來構建整數大頂堆積 - // 實現 heap.Interface 需要同時實現 sort.Interface - type intHeap []any - - // Push heap.Interface 的方法,實現推入元素到堆積 - func (h *intHeap) Push(x any) { - // Push 和 Pop 使用 pointer receiver 作為參數 - // 因為它們不僅會對切片的內容進行調整,還會修改切片的長度。 - *h = append(*h, x.(int)) - } - - // Pop heap.Interface 的方法,實現彈出堆積頂元素 - func (h *intHeap) Pop() any { - // 待出堆積元素存放在最後 - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last - } - - // Len sort.Interface 的方法 - func (h *intHeap) Len() int { - return len(*h) - } - - // Less sort.Interface 的方法 - func (h *intHeap) Less(i, j int) bool { - // 如果實現小頂堆積,則需要調整為小於號 - return (*h)[i].(int) > (*h)[j].(int) - } - - // Swap sort.Interface 的方法 - func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] - } - - // Top 獲取堆積頂元素 - func (h *intHeap) Top() any { - return (*h)[0] - } - - /* Driver Code */ - func TestHeap(t *testing.T) { - /* 初始化堆積 */ - // 初始化大頂堆積 - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* 元素入堆積 */ - // 呼叫 heap.Interface 的方法,來新增元素 - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* 獲取堆積頂元素 */ - top := maxHeap.Top() - fmt.Printf("堆積頂元素為 %d\n", top) - - /* 堆積頂元素出堆積 */ - // 呼叫 heap.Interface 的方法,來移除元素 - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 - - /* 獲取堆積大小 */ - size := len(*maxHeap) - fmt.Printf("堆積元素數量為 %d\n", size) - - /* 判斷堆積是否為空 */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("堆積是否為空 %t\n", isEmpty) - } - ``` - -=== "Swift" - - ```swift title="heap.swift" - /* 初始化堆積 */ - // Swift 的 Heap 型別同時支持最大堆積和最小堆積,且需要引入 swift-collections - var heap = Heap() - - /* 元素入堆積 */ - heap.insert(1) - heap.insert(3) - heap.insert(2) - heap.insert(5) - heap.insert(4) - - /* 獲取堆積頂元素 */ - var peek = heap.max()! - - /* 堆積頂元素出堆積 */ - peek = heap.removeMax() // 5 - peek = heap.removeMax() // 4 - peek = heap.removeMax() // 3 - peek = heap.removeMax() // 2 - peek = heap.removeMax() // 1 - - /* 獲取堆積大小 */ - let size = heap.count - - /* 判斷堆積是否為空 */ - let isEmpty = heap.isEmpty - - /* 輸入串列並建堆積 */ - let heap2 = Heap([1, 3, 2, 5, 4]) - ``` - -=== "JS" - - ```javascript title="heap.js" - // JavaScript 未提供內建 Heap 類別 - ``` - -=== "TS" - - ```typescript title="heap.ts" - // TypeScript 未提供內建 Heap 類別 - ``` - -=== "Dart" - - ```dart title="heap.dart" - // Dart 未提供內建 Heap 類別 - ``` - -=== "Rust" - - ```rust title="heap.rs" - use std::collections::BinaryHeap; - use std::cmp::Reverse; - - /* 初始化堆積 */ - // 初始化小頂堆積 - let mut min_heap = BinaryHeap::>::new(); - // 初始化大頂堆積 - let mut max_heap = BinaryHeap::new(); - - /* 元素入堆積 */ - max_heap.push(1); - max_heap.push(3); - max_heap.push(2); - max_heap.push(5); - max_heap.push(4); - - /* 獲取堆積頂元素 */ - let peek = max_heap.peek().unwrap(); // 5 - - /* 堆積頂元素出堆積 */ - // 出堆積元素會形成一個從大到小的序列 - let peek = max_heap.pop().unwrap(); // 5 - let peek = max_heap.pop().unwrap(); // 4 - let peek = max_heap.pop().unwrap(); // 3 - let peek = max_heap.pop().unwrap(); // 2 - let peek = max_heap.pop().unwrap(); // 1 - - /* 獲取堆積大小 */ - let size = max_heap.len(); - - /* 判斷堆積是否為空 */ - let is_empty = max_heap.is_empty(); - - /* 輸入串列並建堆積 */ - let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); - ``` - -=== "C" - - ```c title="heap.c" - // C 未提供內建 Heap 類別 - ``` - -=== "Kotlin" - - ```kotlin title="heap.kt" - /* 初始化堆積 */ - // 初始化小頂堆積 - var minHeap = PriorityQueue() - // 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可) - val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } - - /* 元素入堆積 */ - maxHeap.offer(1) - maxHeap.offer(3) - maxHeap.offer(2) - maxHeap.offer(5) - maxHeap.offer(4) - - /* 獲取堆積頂元素 */ - var peek = maxHeap.peek() // 5 - - /* 堆積頂元素出堆積 */ - // 出堆積元素會形成一個從大到小的序列 - peek = maxHeap.poll() // 5 - peek = maxHeap.poll() // 4 - peek = maxHeap.poll() // 3 - peek = maxHeap.poll() // 2 - peek = maxHeap.poll() // 1 - - /* 獲取堆積大小 */ - val size = maxHeap.size - - /* 判斷堆積是否為空 */ - val isEmpty = maxHeap.isEmpty() - - /* 輸入串列並建堆積 */ - minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) - ``` - -=== "Ruby" - - ```ruby title="heap.rb" - # Ruby 未提供內建 Heap 類別 - ``` +```snippet +heap_operations +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E7%B5%84%E9%A0%90%E8%A8%AD%E5%AF%A6%E7%8F%BE%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E8%80%83%E6%85%AE%E5%B0%87%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B2%A0%E2%80%9D%E5%BE%8C%E5%86%8D%E5%85%A5%E5%A0%86%E7%A9%8D%EF%BC%8C%E9%80%99%E6%A8%A3%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%87%E5%A4%A7%E5%B0%8F%E9%97%9C%E4%BF%82%E9%A1%9B%E5%80%92%EF%BC%8C%E5%BE%9E%E8%80%8C%E5%AF%A6%E7%8F%BE%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%99%82%E5%B0%8D%E6%87%89%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%EF%BC%8Cflag%20%3D%20-1%20%E6%99%82%E5%B0%8D%E6%87%89%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%E7%A9%8D%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%A9%8D%E9%A0%82%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E7%A9%8D%E9%A0%82%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E7%A9%8D%E5%85%83%E7%B4%A0%E6%9C%83%E5%BD%A2%E6%88%90%E4%B8%80%E5%80%8B%E5%BE%9E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%A9%8D%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E5%A0%86%E7%A9%8D%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BC%B8%E5%85%A5%E4%B8%B2%E5%88%97%E4%B8%A6%E5%BB%BA%E5%A0%86%E7%A9%8D%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor heap_operations_tutor ## 堆積的實現 diff --git a/zh-hant/docs/chapter_preface/suggestions.md b/zh-hant/docs/chapter_preface/suggestions.md index fae2a145f..0ac18e883 100644 --- a/zh-hant/docs/chapter_preface/suggestions.md +++ b/zh-hant/docs/chapter_preface/suggestions.md @@ -13,170 +13,9 @@ - 當涉及程式語言之間不一致的名詞時,本書均以 Python 為準,例如使用 `None` 來表示“空”。 - 本書部分放棄了程式語言的註釋規範,以換取更加緊湊的內容排版。註釋主要分為三種類型:標題註釋、內容註釋、多行註釋。 -=== "Python" - - ```python title="" - """標題註釋,用於標註函式、類別、測試樣例等""" - - # 內容註釋,用於詳解程式碼 - - """ - 多行 - 註釋 - """ - ``` - -=== "C++" - - ```cpp title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "Java" - - ```java title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "C#" - - ```csharp title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "Go" - - ```go title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "Swift" - - ```swift title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "JS" - - ```javascript title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "TS" - - ```typescript title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "Dart" - - ```dart title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "Rust" - - ```rust title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - // 多行 - // 註釋 - ``` - -=== "C" - - ```c title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 標題註釋,用於標註函式、類別、測試樣例等 */ - - // 內容註釋,用於詳解程式碼 - - /** - * 多行 - * 註釋 - */ - ``` - -=== "Ruby" - - ```ruby title="" - ### 標題註釋,用於標註函式、類別、測試樣例等 ### - - # 內容註釋,用於詳解程式碼 - - # 多行 - # 註釋 - ``` +```snippet +comment_style +``` ## 在動畫圖解中高效學習 diff --git a/zh-hant/docs/chapter_stack_and_queue/deque.md b/zh-hant/docs/chapter_stack_and_queue/deque.md index 26451449d..eae2047c9 100644 --- a/zh-hant/docs/chapter_stack_and_queue/deque.md +++ b/zh-hant/docs/chapter_stack_and_queue/deque.md @@ -21,371 +21,13 @@ 同樣地,我們可以直接使用程式語言中已實現的雙向佇列類別: -=== "Python" - - ```python title="deque.py" - from collections import deque - - # 初始化雙向佇列 - deq: deque[int] = deque() - - # 元素入列 - deq.append(2) # 新增至佇列尾 - deq.append(5) - deq.append(4) - deq.appendleft(3) # 新增至佇列首 - deq.appendleft(1) - - # 訪問元素 - front: int = deq[0] # 佇列首元素 - rear: int = deq[-1] # 佇列尾元素 - - # 元素出列 - pop_front: int = deq.popleft() # 佇列首元素出列 - pop_rear: int = deq.pop() # 佇列尾元素出列 - - # 獲取雙向佇列的長度 - size: int = len(deq) - - # 判斷雙向佇列是否為空 - is_empty: bool = len(deq) == 0 - ``` - -=== "C++" - - ```cpp title="deque.cpp" - /* 初始化雙向佇列 */ - deque deque; - - /* 元素入列 */ - deque.push_back(2); // 新增至佇列尾 - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // 新增至佇列首 - deque.push_front(1); - - /* 訪問元素 */ - int front = deque.front(); // 佇列首元素 - int back = deque.back(); // 佇列尾元素 - - /* 元素出列 */ - deque.pop_front(); // 佇列首元素出列 - deque.pop_back(); // 佇列尾元素出列 - - /* 獲取雙向佇列的長度 */ - int size = deque.size(); - - /* 判斷雙向佇列是否為空 */ - bool empty = deque.empty(); - ``` - -=== "Java" - - ```java title="deque.java" - /* 初始化雙向佇列 */ - Deque deque = new LinkedList<>(); - - /* 元素入列 */ - deque.offerLast(2); // 新增至佇列尾 - deque.offerLast(5); - deque.offerLast(4); - deque.offerFirst(3); // 新增至佇列首 - deque.offerFirst(1); - - /* 訪問元素 */ - int peekFirst = deque.peekFirst(); // 佇列首元素 - int peekLast = deque.peekLast(); // 佇列尾元素 - - /* 元素出列 */ - int popFirst = deque.pollFirst(); // 佇列首元素出列 - int popLast = deque.pollLast(); // 佇列尾元素出列 - - /* 獲取雙向佇列的長度 */ - int size = deque.size(); - - /* 判斷雙向佇列是否為空 */ - boolean isEmpty = deque.isEmpty(); - ``` - -=== "C#" - - ```csharp title="deque.cs" - /* 初始化雙向佇列 */ - // 在 C# 中,將鏈結串列 LinkedList 看作雙向佇列來使用 - LinkedList deque = new(); - - /* 元素入列 */ - deque.AddLast(2); // 新增至佇列尾 - deque.AddLast(5); - deque.AddLast(4); - deque.AddFirst(3); // 新增至佇列首 - deque.AddFirst(1); - - /* 訪問元素 */ - int peekFirst = deque.First.Value; // 佇列首元素 - int peekLast = deque.Last.Value; // 佇列尾元素 - - /* 元素出列 */ - deque.RemoveFirst(); // 佇列首元素出列 - deque.RemoveLast(); // 佇列尾元素出列 - - /* 獲取雙向佇列的長度 */ - int size = deque.Count; - - /* 判斷雙向佇列是否為空 */ - bool isEmpty = deque.Count == 0; - ``` - -=== "Go" - - ```go title="deque_test.go" - /* 初始化雙向佇列 */ - // 在 Go 中,將 list 作為雙向佇列使用 - deque := list.New() - - /* 元素入列 */ - deque.PushBack(2) // 新增至佇列尾 - deque.PushBack(5) - deque.PushBack(4) - deque.PushFront(3) // 新增至佇列首 - deque.PushFront(1) - - /* 訪問元素 */ - front := deque.Front() // 佇列首元素 - rear := deque.Back() // 佇列尾元素 - - /* 元素出列 */ - deque.Remove(front) // 佇列首元素出列 - deque.Remove(rear) // 佇列尾元素出列 - - /* 獲取雙向佇列的長度 */ - size := deque.Len() - - /* 判斷雙向佇列是否為空 */ - isEmpty := deque.Len() == 0 - ``` - -=== "Swift" - - ```swift title="deque.swift" - /* 初始化雙向佇列 */ - // Swift 沒有內建的雙向佇列類別,可以把 Array 當作雙向佇列來使用 - var deque: [Int] = [] - - /* 元素入列 */ - deque.append(2) // 新增至佇列尾 - deque.append(5) - deque.append(4) - deque.insert(3, at: 0) // 新增至佇列首 - deque.insert(1, at: 0) - - /* 訪問元素 */ - let peekFirst = deque.first! // 佇列首元素 - let peekLast = deque.last! // 佇列尾元素 - - /* 元素出列 */ - // 使用 Array 模擬時 popFirst 的複雜度為 O(n) - let popFirst = deque.removeFirst() // 佇列首元素出列 - let popLast = deque.removeLast() // 佇列尾元素出列 - - /* 獲取雙向佇列的長度 */ - let size = deque.count - - /* 判斷雙向佇列是否為空 */ - let isEmpty = deque.isEmpty - ``` - -=== "JS" - - ```javascript title="deque.js" - /* 初始化雙向佇列 */ - // JavaScript 沒有內建的雙端佇列,只能把 Array 當作雙端佇列來使用 - const deque = []; - - /* 元素入列 */ - deque.push(2); - deque.push(5); - deque.push(4); - // 請注意,由於是陣列,unshift() 方法的時間複雜度為 O(n) - deque.unshift(3); - deque.unshift(1); - - /* 訪問元素 */ - const peekFirst = deque[0]; - const peekLast = deque[deque.length - 1]; - - /* 元素出列 */ - // 請注意,由於是陣列,shift() 方法的時間複雜度為 O(n) - const popFront = deque.shift(); - const popBack = deque.pop(); - - /* 獲取雙向佇列的長度 */ - const size = deque.length; - - /* 判斷雙向佇列是否為空 */ - const isEmpty = size === 0; - ``` - -=== "TS" - - ```typescript title="deque.ts" - /* 初始化雙向佇列 */ - // TypeScript 沒有內建的雙端佇列,只能把 Array 當作雙端佇列來使用 - const deque: number[] = []; - - /* 元素入列 */ - deque.push(2); - deque.push(5); - deque.push(4); - // 請注意,由於是陣列,unshift() 方法的時間複雜度為 O(n) - deque.unshift(3); - deque.unshift(1); - - /* 訪問元素 */ - const peekFirst: number = deque[0]; - const peekLast: number = deque[deque.length - 1]; - - /* 元素出列 */ - // 請注意,由於是陣列,shift() 方法的時間複雜度為 O(n) - const popFront: number = deque.shift() as number; - const popBack: number = deque.pop() as number; - - /* 獲取雙向佇列的長度 */ - const size: number = deque.length; - - /* 判斷雙向佇列是否為空 */ - const isEmpty: boolean = size === 0; - ``` - -=== "Dart" - - ```dart title="deque.dart" - /* 初始化雙向佇列 */ - // 在 Dart 中,Queue 被定義為雙向佇列 - Queue deque = Queue(); - - /* 元素入列 */ - deque.addLast(2); // 新增至佇列尾 - deque.addLast(5); - deque.addLast(4); - deque.addFirst(3); // 新增至佇列首 - deque.addFirst(1); - - /* 訪問元素 */ - int peekFirst = deque.first; // 佇列首元素 - int peekLast = deque.last; // 佇列尾元素 - - /* 元素出列 */ - int popFirst = deque.removeFirst(); // 佇列首元素出列 - int popLast = deque.removeLast(); // 佇列尾元素出列 - - /* 獲取雙向佇列的長度 */ - int size = deque.length; - - /* 判斷雙向佇列是否為空 */ - bool isEmpty = deque.isEmpty; - ``` - -=== "Rust" - - ```rust title="deque.rs" - /* 初始化雙向佇列 */ - let mut deque: VecDeque = VecDeque::new(); - - /* 元素入列 */ - deque.push_back(2); // 新增至佇列尾 - deque.push_back(5); - deque.push_back(4); - deque.push_front(3); // 新增至佇列首 - deque.push_front(1); - - /* 訪問元素 */ - if let Some(front) = deque.front() { // 佇列首元素 - } - if let Some(rear) = deque.back() { // 佇列尾元素 - } - - /* 元素出列 */ - if let Some(pop_front) = deque.pop_front() { // 佇列首元素出列 - } - if let Some(pop_rear) = deque.pop_back() { // 佇列尾元素出列 - } - - /* 獲取雙向佇列的長度 */ - let size = deque.len(); - - /* 判斷雙向佇列是否為空 */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="deque.c" - // C 未提供內建雙向佇列 - ``` - -=== "Kotlin" - - ```kotlin title="deque.kt" - /* 初始化雙向佇列 */ - val deque = LinkedList() - - /* 元素入列 */ - deque.offerLast(2) // 新增至佇列尾 - deque.offerLast(5) - deque.offerLast(4) - deque.offerFirst(3) // 新增至佇列首 - deque.offerFirst(1) - - /* 訪問元素 */ - val peekFirst = deque.peekFirst() // 佇列首元素 - val peekLast = deque.peekLast() // 佇列尾元素 - - /* 元素出列 */ - val popFirst = deque.pollFirst() // 佇列首元素出列 - val popLast = deque.pollLast() // 佇列尾元素出列 - - /* 獲取雙向佇列的長度 */ - val size = deque.size - - /* 判斷雙向佇列是否為空 */ - val isEmpty = deque.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="deque.rb" - # 初始化雙向佇列 - # Ruby 沒有內直的雙端佇列,只能把 Array 當作雙端佇列來使用 - deque = [] - - # 元素如隊 - deque << 2 - deque << 5 - deque << 4 - # 請注意,由於是陣列,Array#unshift 方法的時間複雜度為 O(n) - deque.unshift(3) - deque.unshift(1) - - # 訪問元素 - peek_first = deque.first - peek_last = deque.last - - # 元素出列 - # 請注意,由於是陣列, Array#shift 方法的時間複雜度為 O(n) - pop_front = deque.shift - pop_back = deque.pop - - # 獲取雙向佇列的長度 - size = deque.length - - # 判斷雙向佇列是否為空 - is_empty = size.zero? - ``` +```snippet +deque_operations +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%88%97%0A%20%20%20%20deq.append%282%29%20%20%23%20%E6%96%B0%E5%A2%9E%E8%87%B3%E4%BD%87%E5%88%97%E5%B0%BE%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20%E6%96%B0%E5%A2%9E%E8%87%B3%E4%BD%87%E5%88%97%E9%A6%96%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22%2C%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%E4%BD%87%E5%88%97%E5%B0%BE%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E5%B0%BE%E5%85%83%E7%B4%A0%20rear%20%3D%22%2C%20rear%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E5%88%97%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%E5%87%BA%E5%88%97%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%A6%96%E5%87%BA%E5%88%97%E5%85%83%E7%B4%A0%20%20pop_front%20%3D%22%2C%20pop_front%29%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%A6%96%E5%87%BA%E5%88%97%E5%BE%8C%20deque%20%3D%22%2C%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20%E4%BD%87%E5%88%97%E5%B0%BE%E5%85%83%E7%B4%A0%E5%87%BA%E5%88%97%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E5%B0%BE%E5%87%BA%E5%88%97%E5%85%83%E7%B4%A0%20%20pop_rear%20%3D%22%2C%20pop_rear%29%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E5%B0%BE%E5%87%BA%E5%88%97%E5%BE%8C%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E7%9A%84%E9%95%B7%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E9%95%B7%E5%BA%A6%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor deque_operations_tutor ## 雙向佇列實現 * diff --git a/zh-hant/docs/chapter_stack_and_queue/queue.md b/zh-hant/docs/chapter_stack_and_queue/queue.md index 990b81969..ae0c7cb47 100755 --- a/zh-hant/docs/chapter_stack_and_queue/queue.md +++ b/zh-hant/docs/chapter_stack_and_queue/queue.md @@ -20,345 +20,13 @@ 我們可以直接使用程式語言中現成的佇列類別: -=== "Python" - - ```python title="queue.py" - from collections import deque - - # 初始化佇列 - # 在 Python 中,我們一般將雙向佇列類別 deque 當作佇列使用 - # 雖然 queue.Queue() 是純正的佇列類別,但不太好用,因此不推薦 - que: deque[int] = deque() - - # 元素入列 - que.append(1) - que.append(3) - que.append(2) - que.append(5) - que.append(4) - - # 訪問佇列首元素 - front: int = que[0] - - # 元素出列 - pop: int = que.popleft() - - # 獲取佇列的長度 - size: int = len(que) - - # 判斷佇列是否為空 - is_empty: bool = len(que) == 0 - ``` - -=== "C++" - - ```cpp title="queue.cpp" - /* 初始化佇列 */ - queue queue; - - /* 元素入列 */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 訪問佇列首元素 */ - int front = queue.front(); - - /* 元素出列 */ - queue.pop(); - - /* 獲取佇列的長度 */ - int size = queue.size(); - - /* 判斷佇列是否為空 */ - bool empty = queue.empty(); - ``` - -=== "Java" - - ```java title="queue.java" - /* 初始化佇列 */ - Queue queue = new LinkedList<>(); - - /* 元素入列 */ - queue.offer(1); - queue.offer(3); - queue.offer(2); - queue.offer(5); - queue.offer(4); - - /* 訪問佇列首元素 */ - int peek = queue.peek(); - - /* 元素出列 */ - int pop = queue.poll(); - - /* 獲取佇列的長度 */ - int size = queue.size(); - - /* 判斷佇列是否為空 */ - boolean isEmpty = queue.isEmpty(); - ``` - -=== "C#" - - ```csharp title="queue.cs" - /* 初始化佇列 */ - Queue queue = new(); - - /* 元素入列 */ - queue.Enqueue(1); - queue.Enqueue(3); - queue.Enqueue(2); - queue.Enqueue(5); - queue.Enqueue(4); - - /* 訪問佇列首元素 */ - int peek = queue.Peek(); - - /* 元素出列 */ - int pop = queue.Dequeue(); - - /* 獲取佇列的長度 */ - int size = queue.Count; - - /* 判斷佇列是否為空 */ - bool isEmpty = queue.Count == 0; - ``` - -=== "Go" - - ```go title="queue_test.go" - /* 初始化佇列 */ - // 在 Go 中,將 list 作為佇列來使用 - queue := list.New() - - /* 元素入列 */ - queue.PushBack(1) - queue.PushBack(3) - queue.PushBack(2) - queue.PushBack(5) - queue.PushBack(4) - - /* 訪問佇列首元素 */ - peek := queue.Front() - - /* 元素出列 */ - pop := queue.Front() - queue.Remove(pop) - - /* 獲取佇列的長度 */ - size := queue.Len() - - /* 判斷佇列是否為空 */ - isEmpty := queue.Len() == 0 - ``` - -=== "Swift" - - ```swift title="queue.swift" - /* 初始化佇列 */ - // Swift 沒有內建的佇列類別,可以把 Array 當作佇列來使用 - var queue: [Int] = [] - - /* 元素入列 */ - queue.append(1) - queue.append(3) - queue.append(2) - queue.append(5) - queue.append(4) - - /* 訪問佇列首元素 */ - let peek = queue.first! - - /* 元素出列 */ - // 由於是陣列,因此 removeFirst 的複雜度為 O(n) - let pop = queue.removeFirst() - - /* 獲取佇列的長度 */ - let size = queue.count - - /* 判斷佇列是否為空 */ - let isEmpty = queue.isEmpty - ``` - -=== "JS" - - ```javascript title="queue.js" - /* 初始化佇列 */ - // JavaScript 沒有內建的佇列,可以把 Array 當作佇列來使用 - const queue = []; - - /* 元素入列 */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 訪問佇列首元素 */ - const peek = queue[0]; - - /* 元素出列 */ - // 底層是陣列,因此 shift() 方法的時間複雜度為 O(n) - const pop = queue.shift(); - - /* 獲取佇列的長度 */ - const size = queue.length; - - /* 判斷佇列是否為空 */ - const empty = queue.length === 0; - ``` - -=== "TS" - - ```typescript title="queue.ts" - /* 初始化佇列 */ - // TypeScript 沒有內建的佇列,可以把 Array 當作佇列來使用 - const queue: number[] = []; - - /* 元素入列 */ - queue.push(1); - queue.push(3); - queue.push(2); - queue.push(5); - queue.push(4); - - /* 訪問佇列首元素 */ - const peek = queue[0]; - - /* 元素出列 */ - // 底層是陣列,因此 shift() 方法的時間複雜度為 O(n) - const pop = queue.shift(); - - /* 獲取佇列的長度 */ - const size = queue.length; - - /* 判斷佇列是否為空 */ - const empty = queue.length === 0; - ``` - -=== "Dart" - - ```dart title="queue.dart" - /* 初始化佇列 */ - // 在 Dart 中,佇列類別 Queue 是雙向佇列,也可作為佇列使用 - Queue queue = Queue(); - - /* 元素入列 */ - queue.add(1); - queue.add(3); - queue.add(2); - queue.add(5); - queue.add(4); - - /* 訪問佇列首元素 */ - int peek = queue.first; - - /* 元素出列 */ - int pop = queue.removeFirst(); - - /* 獲取佇列的長度 */ - int size = queue.length; - - /* 判斷佇列是否為空 */ - bool isEmpty = queue.isEmpty; - ``` - -=== "Rust" - - ```rust title="queue.rs" - /* 初始化雙向佇列 */ - // 在 Rust 中使用雙向佇列作為普通佇列來使用 - let mut deque: VecDeque = VecDeque::new(); - - /* 元素入列 */ - deque.push_back(1); - deque.push_back(3); - deque.push_back(2); - deque.push_back(5); - deque.push_back(4); - - /* 訪問佇列首元素 */ - if let Some(front) = deque.front() { - } - - /* 元素出列 */ - if let Some(pop) = deque.pop_front() { - } - - /* 獲取佇列的長度 */ - let size = deque.len(); - - /* 判斷佇列是否為空 */ - let is_empty = deque.is_empty(); - ``` - -=== "C" - - ```c title="queue.c" - // C 未提供內建佇列 - ``` - -=== "Kotlin" - - ```kotlin title="queue.kt" - /* 初始化佇列 */ - val queue = LinkedList() - - /* 元素入列 */ - queue.offer(1) - queue.offer(3) - queue.offer(2) - queue.offer(5) - queue.offer(4) - - /* 訪問佇列首元素 */ - val peek = queue.peek() - - /* 元素出列 */ - val pop = queue.poll() - - /* 獲取佇列的長度 */ - val size = queue.size - - /* 判斷佇列是否為空 */ - val isEmpty = queue.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="queue.rb" - # 初始化佇列 - # Ruby 內建的佇列(Thread::Queue) 沒有 peek 和走訪方法,可以把 Array 當作佇列來使用 - queue = [] - - # 元素入列 - queue.push(1) - queue.push(3) - queue.push(2) - queue.push(5) - queue.push(4) - - # 訪問佇列元素 - peek = queue.first - - # 元素出列 - # 清注意,由於是陣列,Array#shift 方法時間複雜度為 O(n) - pop = queue.shift - - # 獲取佇列的長度 - size = queue.length - - # 判斷佇列是否為空 - is_empty = queue.empty? - ``` +```snippet +queue_operations +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BD%87%E5%88%97%0A%20%20%20%20%23%20%E5%9C%A8%20Python%20%E4%B8%AD%EF%BC%8C%E6%88%91%E5%80%91%E4%B8%80%E8%88%AC%E5%B0%87%E9%9B%99%E5%90%91%E4%BD%87%E5%88%97%E9%A1%9E%E5%88%A5%20deque%20%E7%9C%8B%E4%BD%9C%E4%BD%87%E5%88%97%E4%BD%BF%E7%94%A8%0A%20%20%20%20%23%20%E9%9B%96%E7%84%B6%20queue.Queue%28%29%20%E6%98%AF%E7%B4%94%E6%AD%A3%E7%9A%84%E4%BD%87%E5%88%97%E9%A1%9E%E5%88%A5%EF%BC%8C%E4%BD%86%E4%B8%8D%E5%A4%AA%E5%A5%BD%E7%94%A8%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%88%97%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22%2C%20front%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E5%88%97%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E5%88%97%E5%85%83%E7%B4%A0%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E5%88%97%E5%BE%8C%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E4%BD%87%E5%88%97%E7%9A%84%E9%95%B7%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E9%95%B7%E5%BA%A6%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E4%BD%87%E5%88%97%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E4%BD%87%E5%88%97%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor queue_operations_tutor ## 佇列實現 diff --git a/zh-hant/docs/chapter_stack_and_queue/stack.md b/zh-hant/docs/chapter_stack_and_queue/stack.md index 3a469369f..97a93e564 100755 --- a/zh-hant/docs/chapter_stack_and_queue/stack.md +++ b/zh-hant/docs/chapter_stack_and_queue/stack.md @@ -22,336 +22,13 @@ 通常情況下,我們可以直接使用程式語言內建的堆疊類別。然而,某些語言可能沒有專門提供堆疊類別,這時我們可以將該語言的“陣列”或“鏈結串列”當作堆疊來使用,並在程式邏輯上忽略與堆疊無關的操作。 -=== "Python" - - ```python title="stack.py" - # 初始化堆疊 - # Python 沒有內建的堆疊類別,可以把 list 當作堆疊來使用 - stack: list[int] = [] - - # 元素入堆疊 - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - # 訪問堆疊頂元素 - peek: int = stack[-1] - - # 元素出堆疊 - pop: int = stack.pop() - - # 獲取堆疊的長度 - size: int = len(stack) - - # 判斷是否為空 - is_empty: bool = len(stack) == 0 - ``` - -=== "C++" - - ```cpp title="stack.cpp" - /* 初始化堆疊 */ - stack stack; - - /* 元素入堆疊 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 訪問堆疊頂元素 */ - int top = stack.top(); - - /* 元素出堆疊 */ - stack.pop(); // 無返回值 - - /* 獲取堆疊的長度 */ - int size = stack.size(); - - /* 判斷是否為空 */ - bool empty = stack.empty(); - ``` - -=== "Java" - - ```java title="stack.java" - /* 初始化堆疊 */ - Stack stack = new Stack<>(); - - /* 元素入堆疊 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 訪問堆疊頂元素 */ - int peek = stack.peek(); - - /* 元素出堆疊 */ - int pop = stack.pop(); - - /* 獲取堆疊的長度 */ - int size = stack.size(); - - /* 判斷是否為空 */ - boolean isEmpty = stack.isEmpty(); - ``` - -=== "C#" - - ```csharp title="stack.cs" - /* 初始化堆疊 */ - Stack stack = new(); - - /* 元素入堆疊 */ - stack.Push(1); - stack.Push(3); - stack.Push(2); - stack.Push(5); - stack.Push(4); - - /* 訪問堆疊頂元素 */ - int peek = stack.Peek(); - - /* 元素出堆疊 */ - int pop = stack.Pop(); - - /* 獲取堆疊的長度 */ - int size = stack.Count; - - /* 判斷是否為空 */ - bool isEmpty = stack.Count == 0; - ``` - -=== "Go" - - ```go title="stack_test.go" - /* 初始化堆疊 */ - // 在 Go 中,推薦將 Slice 當作堆疊來使用 - var stack []int - - /* 元素入堆疊 */ - stack = append(stack, 1) - stack = append(stack, 3) - stack = append(stack, 2) - stack = append(stack, 5) - stack = append(stack, 4) - - /* 訪問堆疊頂元素 */ - peek := stack[len(stack)-1] - - /* 元素出堆疊 */ - pop := stack[len(stack)-1] - stack = stack[:len(stack)-1] - - /* 獲取堆疊的長度 */ - size := len(stack) - - /* 判斷是否為空 */ - isEmpty := len(stack) == 0 - ``` - -=== "Swift" - - ```swift title="stack.swift" - /* 初始化堆疊 */ - // Swift 沒有內建的堆疊類別,可以把 Array 當作堆疊來使用 - var stack: [Int] = [] - - /* 元素入堆疊 */ - stack.append(1) - stack.append(3) - stack.append(2) - stack.append(5) - stack.append(4) - - /* 訪問堆疊頂元素 */ - let peek = stack.last! - - /* 元素出堆疊 */ - let pop = stack.removeLast() - - /* 獲取堆疊的長度 */ - let size = stack.count - - /* 判斷是否為空 */ - let isEmpty = stack.isEmpty - ``` - -=== "JS" - - ```javascript title="stack.js" - /* 初始化堆疊 */ - // JavaScript 沒有內建的堆疊類別,可以把 Array 當作堆疊來使用 - const stack = []; - - /* 元素入堆疊 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 訪問堆疊頂元素 */ - const peek = stack[stack.length-1]; - - /* 元素出堆疊 */ - const pop = stack.pop(); - - /* 獲取堆疊的長度 */ - const size = stack.length; - - /* 判斷是否為空 */ - const is_empty = stack.length === 0; - ``` - -=== "TS" - - ```typescript title="stack.ts" - /* 初始化堆疊 */ - // TypeScript 沒有內建的堆疊類別,可以把 Array 當作堆疊來使用 - const stack: number[] = []; - - /* 元素入堆疊 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 訪問堆疊頂元素 */ - const peek = stack[stack.length - 1]; - - /* 元素出堆疊 */ - const pop = stack.pop(); - - /* 獲取堆疊的長度 */ - const size = stack.length; - - /* 判斷是否為空 */ - const is_empty = stack.length === 0; - ``` - -=== "Dart" - - ```dart title="stack.dart" - /* 初始化堆疊 */ - // Dart 沒有內建的堆疊類別,可以把 List 當作堆疊來使用 - List stack = []; - - /* 元素入堆疊 */ - stack.add(1); - stack.add(3); - stack.add(2); - stack.add(5); - stack.add(4); - - /* 訪問堆疊頂元素 */ - int peek = stack.last; - - /* 元素出堆疊 */ - int pop = stack.removeLast(); - - /* 獲取堆疊的長度 */ - int size = stack.length; - - /* 判斷是否為空 */ - bool isEmpty = stack.isEmpty; - ``` - -=== "Rust" - - ```rust title="stack.rs" - /* 初始化堆疊 */ - // 把 Vec 當作堆疊來使用 - let mut stack: Vec = Vec::new(); - - /* 元素入堆疊 */ - stack.push(1); - stack.push(3); - stack.push(2); - stack.push(5); - stack.push(4); - - /* 訪問堆疊頂元素 */ - let top = stack.last().unwrap(); - - /* 元素出堆疊 */ - let pop = stack.pop().unwrap(); - - /* 獲取堆疊的長度 */ - let size = stack.len(); - - /* 判斷是否為空 */ - let is_empty = stack.is_empty(); - ``` - -=== "C" - - ```c title="stack.c" - // C 未提供內建堆疊 - ``` - -=== "Kotlin" - - ```kotlin title="stack.kt" - /* 初始化堆疊 */ - val stack = Stack() - - /* 元素入堆疊 */ - stack.push(1) - stack.push(3) - stack.push(2) - stack.push(5) - stack.push(4) - - /* 訪問堆疊頂元素 */ - val peek = stack.peek() - - /* 元素出堆疊 */ - val pop = stack.pop() - - /* 獲取堆疊的長度 */ - val size = stack.size - - /* 判斷是否為空 */ - val isEmpty = stack.isEmpty() - ``` - -=== "Ruby" - - ```ruby title="stack.rb" - # 初始化堆疊 - # Ruby 沒有內建的堆疊類別,可以把 Array 當作堆疊來使用 - stack = [] - - # 元素入堆疊 - stack << 1 - stack << 3 - stack << 2 - stack << 5 - stack << 4 - - # 訪問堆疊頂元素 - peek = stack.last - - # 元素出堆疊 - pop = stack.pop - - # 獲取堆疊的長度 - size = stack.length - - # 判斷是否為空 - is_empty = stack.empty? - ``` +```snippet +stack_operations +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A0%86%E7%96%8A%0A%20%20%20%20%23%20Python%20%E6%B2%92%E6%9C%89%E5%85%A7%E5%BB%BA%E7%9A%84%E5%A0%86%E7%96%8A%E9%A1%9E%E5%88%A5%EF%BC%8C%E5%8F%AF%E4%BB%A5%E6%8A%8A%20list%20%E7%95%B6%E4%BD%9C%E5%A0%86%E7%96%8A%E4%BE%86%E4%BD%BF%E7%94%A8%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%E7%96%8A%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22%E5%A0%86%E7%96%8A%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E5%A0%86%E7%96%8A%E9%A0%82%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22%E5%A0%86%E7%96%8A%E9%A0%82%E5%85%83%E7%B4%A0%20peek%20%3D%22%2C%20peek%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%E7%96%8A%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E5%A0%86%E7%96%8A%E5%85%83%E7%B4%A0%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E5%A0%86%E7%96%8A%E5%BE%8C%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%96%8A%E7%9A%84%E9%95%B7%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22%E5%A0%86%E7%96%8A%E7%9A%84%E9%95%B7%E5%BA%A6%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E5%A0%86%E7%96%8A%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor stack_operations_tutor ## 堆疊的實現 diff --git a/zh-hant/docs/chapter_tree/array_representation_of_tree.md b/zh-hant/docs/chapter_tree/array_representation_of_tree.md index e8b0a5830..1ffef38ca 100644 --- a/zh-hant/docs/chapter_tree/array_representation_of_tree.md +++ b/zh-hant/docs/chapter_tree/array_representation_of_tree.md @@ -24,109 +24,9 @@ 為了解決此問題,**我們可以考慮在層序走訪序列中顯式地寫出所有 `None`** 。如下圖所示,這樣處理後,層序走訪序列就可以唯一表示二元樹了。示例程式碼如下: -=== "Python" - - ```python title="" - # 二元樹的陣列表示 - # 使用 None 來表示空位 - tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] - ``` - -=== "C++" - - ```cpp title="" - /* 二元樹的陣列表示 */ - // 使用 int 最大值 INT_MAX 標記空位 - vector tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Java" - - ```java title="" - /* 二元樹的陣列表示 */ - // 使用 int 的包裝類別 Integer ,就可以使用 null 來標記空位 - Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; - ``` - -=== "C#" - - ```csharp title="" - /* 二元樹的陣列表示 */ - // 使用 int? 可空型別 ,就可以使用 null 來標記空位 - int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Go" - - ```go title="" - /* 二元樹的陣列表示 */ - // 使用 any 型別的切片, 就可以使用 nil 來標記空位 - tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15} - ``` - -=== "Swift" - - ```swift title="" - /* 二元樹的陣列表示 */ - // 使用 Int? 可空型別 ,就可以使用 nil 來標記空位 - let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` - -=== "JS" - - ```javascript title="" - /* 二元樹的陣列表示 */ - // 使用 null 來表示空位 - let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "TS" - - ```typescript title="" - /* 二元樹的陣列表示 */ - // 使用 null 來表示空位 - let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Dart" - - ```dart title="" - /* 二元樹的陣列表示 */ - // 使用 int? 可空型別 ,就可以使用 null 來標記空位 - List tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15]; - ``` - -=== "Rust" - - ```rust title="" - /* 二元樹的陣列表示 */ - // 使用 None 來標記空位 - let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)]; - ``` - -=== "C" - - ```c title="" - /* 二元樹的陣列表示 */ - // 使用 int 最大值標記空位,因此要求節點值不能為 INT_MAX - int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15}; - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 二元樹的陣列表示 */ - // 使用 null 來表示空位 - val tree = arrayOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 ) - ``` - -=== "Ruby" - - ```ruby title="" - ### 二元樹的陣列表示 ### - # 使用 nil 來表示空位 - tree = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15] - ``` +```snippet +tree_array_representation +``` ![任意型別二元樹的陣列表示](array_representation_of_tree.assets/array_representation_with_empty.svg) diff --git a/zh-hant/docs/chapter_tree/avl_tree.md b/zh-hant/docs/chapter_tree/avl_tree.md index 91af3eedc..384020680 100644 --- a/zh-hant/docs/chapter_tree/avl_tree.md +++ b/zh-hant/docs/chapter_tree/avl_tree.md @@ -20,213 +20,9 @@ AVL 樹既是二元搜尋樹,也是平衡二元樹,同時滿足這兩類二 由於 AVL 樹的相關操作需要獲取節點高度,因此我們需要為節點類別新增 `height` 變數: -=== "Python" - - ```python title="" - class TreeNode: - """AVL 樹節點類別""" - def __init__(self, val: int): - self.val: int = val # 節點值 - self.height: int = 0 # 節點高度 - self.left: TreeNode | None = None # 左子節點引用 - self.right: TreeNode | None = None # 右子節點引用 - ``` - -=== "C++" - - ```cpp title="" - /* AVL 樹節點類別 */ - struct TreeNode { - int val{}; // 節點值 - int height = 0; // 節點高度 - TreeNode *left{}; // 左子節點 - TreeNode *right{}; // 右子節點 - TreeNode() = default; - explicit TreeNode(int x) : val(x){} - }; - ``` - -=== "Java" - - ```java title="" - /* AVL 樹節點類別 */ - class TreeNode { - public int val; // 節點值 - public int height; // 節點高度 - public TreeNode left; // 左子節點 - public TreeNode right; // 右子節點 - public TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* AVL 樹節點類別 */ - class TreeNode(int? x) { - public int? val = x; // 節點值 - public int height; // 節點高度 - public TreeNode? left; // 左子節點引用 - public TreeNode? right; // 右子節點引用 - } - ``` - -=== "Go" - - ```go title="" - /* AVL 樹節點結構體 */ - type TreeNode struct { - Val int // 節點值 - Height int // 節點高度 - Left *TreeNode // 左子節點引用 - Right *TreeNode // 右子節點引用 - } - ``` - -=== "Swift" - - ```swift title="" - /* AVL 樹節點類別 */ - class TreeNode { - var val: Int // 節點值 - var height: Int // 節點高度 - var left: TreeNode? // 左子節點 - var right: TreeNode? // 右子節點 - - init(x: Int) { - val = x - height = 0 - } - } - ``` - -=== "JS" - - ```javascript title="" - /* AVL 樹節點類別 */ - class TreeNode { - val; // 節點值 - height; //節點高度 - left; // 左子節點指標 - right; // 右子節點指標 - constructor(val, left, right, height) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* AVL 樹節點類別 */ - class TreeNode { - val: number; // 節點值 - height: number; // 節點高度 - left: TreeNode | null; // 左子節點指標 - right: TreeNode | null; // 右子節點指標 - constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; - this.height = height === undefined ? 0 : height; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "Dart" - - ```dart title="" - /* AVL 樹節點類別 */ - class TreeNode { - int val; // 節點值 - int height; // 節點高度 - TreeNode? left; // 左子節點 - TreeNode? right; // 右子節點 - TreeNode(this.val, [this.height = 0, this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* AVL 樹節點結構體 */ - struct TreeNode { - val: i32, // 節點值 - height: i32, // 節點高度 - left: Option>>, // 左子節點 - right: Option>>, // 右子節點 - } - - impl TreeNode { - /* 建構子 */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - height: 0, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* AVL 樹節點結構體 */ - typedef struct TreeNode { - int val; - int height; - struct TreeNode *left; - struct TreeNode *right; - } TreeNode; - - /* 建構子 */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* AVL 樹節點類別 */ - class TreeNode(val _val: Int) { // 節點值 - var height: Int = 0 // 節點高度 - var left: TreeNode? = null // 左子節點 - var right: TreeNode? = null // 右子節點 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### AVL 樹節點類別 ### - class TreeNode - attr_accessor :val # 節點值 - attr_accessor :height # 節點高度 - attr_accessor :left # 左子節點引用 - attr_accessor :right # 右子節點引用 - - def initialize(val) - @val = val - @height = 0 - end - end - ``` +```snippet +avl_tree_node +``` “節點高度”是指從該節點到它的最遠葉節點的距離,即所經過的“邊”的數量。需要特別注意的是,葉節點的高度為 $0$ ,而空節點的高度為 $-1$ 。我們將建立兩個工具函式,分別用於獲取和更新節點的高度: diff --git a/zh-hant/docs/chapter_tree/binary_tree.md b/zh-hant/docs/chapter_tree/binary_tree.md index 2be80c02d..9381de991 100644 --- a/zh-hant/docs/chapter_tree/binary_tree.md +++ b/zh-hant/docs/chapter_tree/binary_tree.md @@ -2,204 +2,9 @@ 二元樹(binary tree)是一種非線性資料結構,代表“祖先”與“後代”之間的派生關係,體現了“一分為二”的分治邏輯。與鏈結串列類似,二元樹的基本單元是節點,每個節點包含值、左子節點引用和右子節點引用。 -=== "Python" - - ```python title="" - class TreeNode: - """二元樹節點類別""" - def __init__(self, val: int): - self.val: int = val # 節點值 - self.left: TreeNode | None = None # 左子節點引用 - self.right: TreeNode | None = None # 右子節點引用 - ``` - -=== "C++" - - ```cpp title="" - /* 二元樹節點結構體 */ - struct TreeNode { - int val; // 節點值 - TreeNode *left; // 左子節點指標 - TreeNode *right; // 右子節點指標 - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - }; - ``` - -=== "Java" - - ```java title="" - /* 二元樹節點類別 */ - class TreeNode { - int val; // 節點值 - TreeNode left; // 左子節點引用 - TreeNode right; // 右子節點引用 - TreeNode(int x) { val = x; } - } - ``` - -=== "C#" - - ```csharp title="" - /* 二元樹節點類別 */ - class TreeNode(int? x) { - public int? val = x; // 節點值 - public TreeNode? left; // 左子節點引用 - public TreeNode? right; // 右子節點引用 - } - ``` - -=== "Go" - - ```go title="" - /* 二元樹節點結構體 */ - type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode - } - /* 建構子 */ - func NewTreeNode(v int) *TreeNode { - return &TreeNode{ - Left: nil, // 左子節點指標 - Right: nil, // 右子節點指標 - Val: v, // 節點值 - } - } - ``` - -=== "Swift" - - ```swift title="" - /* 二元樹節點類別 */ - class TreeNode { - var val: Int // 節點值 - var left: TreeNode? // 左子節點引用 - var right: TreeNode? // 右子節點引用 - - init(x: Int) { - val = x - } - } - ``` - -=== "JS" - - ```javascript title="" - /* 二元樹節點類別 */ - class TreeNode { - val; // 節點值 - left; // 左子節點指標 - right; // 右子節點指標 - constructor(val, left, right) { - this.val = val === undefined ? 0 : val; - this.left = left === undefined ? null : left; - this.right = right === undefined ? null : right; - } - } - ``` - -=== "TS" - - ```typescript title="" - /* 二元樹節點類別 */ - class TreeNode { - val: number; - left: TreeNode | null; - right: TreeNode | null; - - constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { - this.val = val === undefined ? 0 : val; // 節點值 - this.left = left === undefined ? null : left; // 左子節點引用 - this.right = right === undefined ? null : right; // 右子節點引用 - } - } - ``` - -=== "Dart" - - ```dart title="" - /* 二元樹節點類別 */ - class TreeNode { - int val; // 節點值 - TreeNode? left; // 左子節點引用 - TreeNode? right; // 右子節點引用 - TreeNode(this.val, [this.left, this.right]); - } - ``` - -=== "Rust" - - ```rust title="" - use std::rc::Rc; - use std::cell::RefCell; - - /* 二元樹節點結構體 */ - struct TreeNode { - val: i32, // 節點值 - left: Option>>, // 左子節點引用 - right: Option>>, // 右子節點引用 - } - - impl TreeNode { - /* 建構子 */ - fn new(val: i32) -> Rc> { - Rc::new(RefCell::new(Self { - val, - left: None, - right: None - })) - } - } - ``` - -=== "C" - - ```c title="" - /* 二元樹節點結構體 */ - typedef struct TreeNode { - int val; // 節點值 - int height; // 節點高度 - struct TreeNode *left; // 左子節點指標 - struct TreeNode *right; // 右子節點指標 - } TreeNode; - - /* 建構子 */ - TreeNode *newTreeNode(int val) { - TreeNode *node; - - node = (TreeNode *)malloc(sizeof(TreeNode)); - node->val = val; - node->height = 0; - node->left = NULL; - node->right = NULL; - return node; - } - ``` - -=== "Kotlin" - - ```kotlin title="" - /* 二元樹節點類別 */ - class TreeNode(val _val: Int) { // 節點值 - var left: TreeNode? = null // 左子節點引用 - var right: TreeNode? = null // 右子節點引用 - } - ``` - -=== "Ruby" - - ```ruby title="" - ### 二元樹節點類別 ### - class TreeNode - attr_accessor :val # 節點值 - attr_accessor :left # 左子節點引用 - attr_accessor :right # 右子節點引用 - - def initialize(val) - @val = val - end - end - ``` +```snippet +tree_node_class +``` 每個節點都有兩個引用(指標),分別指向左子節點(left-child node)和右子節點(right-child node),該節點被稱為這兩個子節點的父節點(parent node)。當給定一個二元樹的節點時,我們將該節點的左子節點及其以下節點形成的樹稱為該節點的左子樹(left subtree),同理可得右子樹(right subtree)。 @@ -232,226 +37,13 @@ 與鏈結串列類似,首先初始化節點,然後構建引用(指標)。 -=== "Python" - - ```python title="binary_tree.py" - # 初始化二元樹 - # 初始化節點 - n1 = TreeNode(val=1) - n2 = TreeNode(val=2) - n3 = TreeNode(val=3) - n4 = TreeNode(val=4) - n5 = TreeNode(val=5) - # 構建節點之間的引用(指標) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* 初始化二元樹 */ - // 初始化節點 - TreeNode* n1 = new TreeNode(1); - TreeNode* n2 = new TreeNode(2); - TreeNode* n3 = new TreeNode(3); - TreeNode* n4 = new TreeNode(4); - TreeNode* n5 = new TreeNode(5); - // 構建節點之間的引用(指標) - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Java" - - ```java title="binary_tree.java" - // 初始化節點 - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // 構建節點之間的引用(指標) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* 初始化二元樹 */ - // 初始化節點 - TreeNode n1 = new(1); - TreeNode n2 = new(2); - TreeNode n3 = new(3); - TreeNode n4 = new(4); - TreeNode n5 = new(5); - // 構建節點之間的引用(指標) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* 初始化二元樹 */ - // 初始化節點 - n1 := NewTreeNode(1) - n2 := NewTreeNode(2) - n3 := NewTreeNode(3) - n4 := NewTreeNode(4) - n5 := NewTreeNode(5) - // 構建節點之間的引用(指標) - n1.Left = n2 - n1.Right = n3 - n2.Left = n4 - n2.Right = n5 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - // 初始化節點 - let n1 = TreeNode(x: 1) - let n2 = TreeNode(x: 2) - let n3 = TreeNode(x: 3) - let n4 = TreeNode(x: 4) - let n5 = TreeNode(x: 5) - // 構建節點之間的引用(指標) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* 初始化二元樹 */ - // 初始化節點 - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // 構建節點之間的引用(指標) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* 初始化二元樹 */ - // 初始化節點 - let n1 = new TreeNode(1), - n2 = new TreeNode(2), - n3 = new TreeNode(3), - n4 = new TreeNode(4), - n5 = new TreeNode(5); - // 構建節點之間的引用(指標) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* 初始化二元樹 */ - // 初始化節點 - TreeNode n1 = new TreeNode(1); - TreeNode n2 = new TreeNode(2); - TreeNode n3 = new TreeNode(3); - TreeNode n4 = new TreeNode(4); - TreeNode n5 = new TreeNode(5); - // 構建節點之間的引用(指標) - n1.left = n2; - n1.right = n3; - n2.left = n4; - n2.right = n5; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - // 初始化節點 - let n1 = TreeNode::new(1); - let n2 = TreeNode::new(2); - let n3 = TreeNode::new(3); - let n4 = TreeNode::new(4); - let n5 = TreeNode::new(5); - // 構建節點之間的引用(指標) - n1.borrow_mut().left = Some(n2.clone()); - n1.borrow_mut().right = Some(n3); - n2.borrow_mut().left = Some(n4); - n2.borrow_mut().right = Some(n5); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* 初始化二元樹 */ - // 初始化節點 - TreeNode *n1 = newTreeNode(1); - TreeNode *n2 = newTreeNode(2); - TreeNode *n3 = newTreeNode(3); - TreeNode *n4 = newTreeNode(4); - TreeNode *n5 = newTreeNode(5); - // 構建節點之間的引用(指標) - n1->left = n2; - n1->right = n3; - n2->left = n4; - n2->right = n5; - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - // 初始化節點 - val n1 = TreeNode(1) - val n2 = TreeNode(2) - val n3 = TreeNode(3) - val n4 = TreeNode(4) - val n5 = TreeNode(5) - // 構建節點之間的引用(指標) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # 初始化二元樹 - # 初始化節點 - n1 = TreeNode.new(1) - n2 = TreeNode.new(2) - n3 = TreeNode.new(3) - n4 = TreeNode.new(4) - n5 = TreeNode.new(5) - # 構建節點之間的引用(指標) - n1.left = n2 - n1.right = n3 - n2.left = n4 - n2.right = n5 - ``` +```snippet +init_binary_tree +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%85%83%E6%A8%B9%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%85%83%E6%A8%B9%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E7%AF%80%E9%BB%9E%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%A7%8B%E5%BB%BA%E7%AF%80%E9%BB%9E%E4%B9%8B%E9%96%93%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E6%A8%99%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor init_binary_tree_tutor ### 插入與刪除節點 @@ -459,165 +51,13 @@ ![在二元樹中插入與刪除節點](binary_tree.assets/binary_tree_add_remove.svg) -=== "Python" - - ```python title="binary_tree.py" - # 插入與刪除節點 - p = TreeNode(0) - # 在 n1 -> n2 中間插入節點 P - n1.left = p - p.left = n2 - # 刪除節點 P - n1.left = n2 - ``` - -=== "C++" - - ```cpp title="binary_tree.cpp" - /* 插入與刪除節點 */ - TreeNode* P = new TreeNode(0); - // 在 n1 -> n2 中間插入節點 P - n1->left = P; - P->left = n2; - // 刪除節點 P - n1->left = n2; - // 釋放記憶體 - delete P; - ``` - -=== "Java" - - ```java title="binary_tree.java" - TreeNode P = new TreeNode(0); - // 在 n1 -> n2 中間插入節點 P - n1.left = P; - P.left = n2; - // 刪除節點 P - n1.left = n2; - ``` - -=== "C#" - - ```csharp title="binary_tree.cs" - /* 插入與刪除節點 */ - TreeNode P = new(0); - // 在 n1 -> n2 中間插入節點 P - n1.left = P; - P.left = n2; - // 刪除節點 P - n1.left = n2; - ``` - -=== "Go" - - ```go title="binary_tree.go" - /* 插入與刪除節點 */ - // 在 n1 -> n2 中間插入節點 P - p := NewTreeNode(0) - n1.Left = p - p.Left = n2 - // 刪除節點 P - n1.Left = n2 - ``` - -=== "Swift" - - ```swift title="binary_tree.swift" - let P = TreeNode(x: 0) - // 在 n1 -> n2 中間插入節點 P - n1.left = P - P.left = n2 - // 刪除節點 P - n1.left = n2 - ``` - -=== "JS" - - ```javascript title="binary_tree.js" - /* 插入與刪除節點 */ - let P = new TreeNode(0); - // 在 n1 -> n2 中間插入節點 P - n1.left = P; - P.left = n2; - // 刪除節點 P - n1.left = n2; - ``` - -=== "TS" - - ```typescript title="binary_tree.ts" - /* 插入與刪除節點 */ - const P = new TreeNode(0); - // 在 n1 -> n2 中間插入節點 P - n1.left = P; - P.left = n2; - // 刪除節點 P - n1.left = n2; - ``` - -=== "Dart" - - ```dart title="binary_tree.dart" - /* 插入與刪除節點 */ - TreeNode P = new TreeNode(0); - // 在 n1 -> n2 中間插入節點 P - n1.left = P; - P.left = n2; - // 刪除節點 P - n1.left = n2; - ``` - -=== "Rust" - - ```rust title="binary_tree.rs" - let p = TreeNode::new(0); - // 在 n1 -> n2 中間插入節點 P - n1.borrow_mut().left = Some(p.clone()); - p.borrow_mut().left = Some(n2.clone()); - // 刪除節點 p - n1.borrow_mut().left = Some(n2); - ``` - -=== "C" - - ```c title="binary_tree.c" - /* 插入與刪除節點 */ - TreeNode *P = newTreeNode(0); - // 在 n1 -> n2 中間插入節點 P - n1->left = P; - P->left = n2; - // 刪除節點 P - n1->left = n2; - // 釋放記憶體 - free(P); - ``` - -=== "Kotlin" - - ```kotlin title="binary_tree.kt" - val P = TreeNode(0) - // 在 n1 -> n2 中間插入節點 P - n1.left = P - P.left = n2 - // 刪除節點 P - n1.left = n2 - ``` - -=== "Ruby" - - ```ruby title="binary_tree.rb" - # 插入與刪除節點 - _p = TreeNode.new(0) - # 在 n1 -> n2 中間插入節點 _p - n1.left = _p - _p.left = n2 - # 刪除節點 - n1.left = n2 - ``` +```snippet +insert_remove_node +``` ??? pythontutor "視覺化執行" - https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%85%83%E6%A8%B9%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%85%83%E6%A8%B9%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E7%AF%80%E9%BB%9E%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%A7%8B%E5%BB%BA%E7%AF%80%E9%BB%9E%E4%B9%8B%E9%96%93%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E6%A8%99%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E8%88%87%E5%88%AA%E9%99%A4%E7%AF%80%E9%BB%9E%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%96%93%E6%8F%92%E5%85%A5%E7%AF%80%E9%BB%9E%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E7%AF%80%E9%BB%9E%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false + @tutor insert_remove_node_tutor !!! tip