├── .gitignore ├── 数据结构和算法必知必会的 50 个代码实现 ├── go │ ├── .gitkeep │ ├── 05_array │ │ └── .gitkeep │ ├── 06_linkedlist │ │ ├── .gitkeep │ │ ├── palindrome_test.go │ │ ├── singlelinkedlist_test.go │ │ └── palindrome-linked-list.go │ ├── 07_linkedlist │ │ └── .gitkeep │ ├── 29_priority_queue │ │ ├── readme.md │ │ ├── heap_test.go │ │ └── heap.go │ ├── 08_stack │ │ ├── StatckInterface.go │ │ ├── SimpleBrowser_test.go │ │ ├── StackBasedOnLinkedList_test.go │ │ └── StackBasedOnArray_test.go │ ├── 10_recursion │ │ ├── Fibonacci_test.go │ │ ├── Factorial_test.go │ │ ├── RangAll_test.go │ │ ├── Factorial.go │ │ ├── Fibonacci.go │ │ └── RangAll.go │ ├── 12_sorts │ │ ├── MergeSort_test.go │ │ ├── QuickSort_test.go │ │ ├── QuickSort.go │ │ └── MergeSort.go │ ├── 14_sorts │ │ ├── CountingSort_test.go │ │ └── CountingSort.go │ ├── 45_bitmap │ │ ├── bitmap_test.go │ │ └── bitmap.go │ ├── 13_sorts │ │ └── BucketSort_test.go │ ├── 24_tree │ │ └── TreeNode.go │ ├── 11_sorts │ │ └── Sort_test.go │ ├── 32_string │ │ └── string_bf.go │ ├── 09_queue │ │ ├── QueueBasedOnArray_test.go │ │ ├── QueueBasedOnLinkedList_test.go │ │ ├── CircularQueue_test.go │ │ └── QueueBasedOnArray.go │ └── 42_dynamic_programming │ │ └── longest_common_substring.go ├── c-cpp │ ├── .gitkeep │ ├── 05_array │ │ ├── .gitkeep │ │ └── Array_gp.h │ ├── 09_queue │ │ ├── .gitkeep │ │ ├── list_queue │ │ │ └── list_queue.h │ │ └── array_queue │ │ │ └── array_queue.h │ ├── 11_sorts │ │ └── .gitkeep │ ├── 12_sorts │ │ ├── .gitkeep │ │ ├── merge_sort_test.cc │ │ └── quick_sort_test.cc │ ├── 13_sorts │ │ └── .gitkeep │ ├── 14_sorts │ │ ├── .gitkeep │ │ └── analytics_of_std_sort.md │ ├── 15_bsearch │ │ ├── .gitkeep │ │ └── bsearch_test.cc │ ├── 16_bsearch │ │ └── .gitkeep │ ├── 17_skiplist │ │ ├── .gitkeep │ │ ├── SkipList.cpp │ │ └── skiplist_c │ │ │ └── skiplist.h │ ├── 06_linkedlist │ │ ├── .gitkeep │ │ ├── singlelist_gc │ │ │ └── singleList.c │ │ ├── list_isPalindrome │ │ │ ├── LinkList.cpp │ │ │ └── LinkList.h │ │ ├── palindromeList │ │ │ └── ListNode.hpp │ │ └── Dlist │ │ │ └── Dlist.h │ ├── 07_linkedlist │ │ ├── .gitkeep │ │ ├── SingleList.cpp │ │ └── linked_list.h │ ├── 10_recursive │ │ └── .gitkeep │ ├── 18_hashtable │ │ └── .gitkeep │ ├── .gitignore │ ├── 08_stack │ │ ├── linked_list.h │ │ ├── StackBasedOnArray │ │ │ └── StackBasedOnArray.h │ │ ├── linkList │ │ │ └── linklist_stack.h │ │ ├── StackBasedOnLinkedList │ │ │ └── StackBasedOnLinkedList.h │ │ └── arrayStack │ │ │ └── arrayStack.h │ ├── 23_binarytree │ │ └── tree │ │ │ └── list_queue.h │ └── 24_binarysearchtree │ │ └── binarysearchtree.h ├── notes │ ├── .gitkeep │ ├── 12_sorts │ │ └── .gitkeep │ ├── 13_sorts │ │ └── .gitkeep │ ├── 14_sorts │ │ ├── .gitkeep │ │ └── readme.md │ ├── 15_bsearch │ │ ├── .gitkeep │ │ └── readme.md │ ├── 16_bsearch │ │ └── .gitkeep │ ├── 17_skiplist │ │ └── .gitkeep │ ├── 18_hashtable │ │ └── .gitkeep │ ├── 19_hashtable │ │ └── .gitkeep │ ├── 20_hashtable │ │ ├── .gitkeep │ │ └── readme.md │ └── 10_recursion │ │ └── readme.md ├── python │ ├── .gitkeep │ ├── 05_array │ │ └── .gitkeep │ ├── 06_linkedlist │ │ └── .gitkeep │ ├── 07_linkedlist │ │ └── .gitkeep │ ├── 15_bsearch │ │ ├── bsearch.py │ │ └── bsearch_recursion.py │ ├── 45_bitmap │ │ └── bitmap.py │ ├── 28_binary_heap │ │ └── top_k.py │ ├── 14_sorts │ │ └── counting_sort.py │ └── 39_backtracking │ │ └── backtracking.py ├── javascript │ ├── .gitkeep │ ├── 05_array │ │ └── .gitkeep │ ├── 06_linkedlist │ │ └── .gitkeep │ ├── 07_linkedlist │ │ └── .gitkeep │ ├── 15_binary │ │ └── binaryFind.js │ ├── 12_sorts │ │ └── KthNum.js │ └── 45_bitmap │ │ └── bitmap.js ├── object-c │ ├── .gitkeep │ ├── 05_array │ │ ├── .gitkeep │ │ └── MyArray.h │ ├── 06_linkedlist │ │ ├── .gitkeep │ │ ├── ListNode.h │ │ ├── ListNode.m │ │ └── SinglyLinkedList.h │ ├── 07_linkedlist │ │ └── .gitkeep │ ├── 08_stack │ │ ├── stack_practice │ │ │ ├── BalancedParentheses.h │ │ │ ├── ArrayStack.h │ │ │ ├── FourOperation.h │ │ │ └── main.m │ │ ├── LinkedStack.h │ │ ├── ListNode.h │ │ └── ListNode.m │ ├── 33_bm_match │ │ ├── BM.h │ │ └── main.m │ └── 11_Sort │ │ └── Sort.h ├── php │ ├── 05_array │ │ ├── .gitkeep │ │ └── array_test.php │ ├── 08_stack │ │ ├── .gitkeep │ │ └── main.php │ ├── 06_linkedlist │ │ ├── .gitkeep │ │ └── SingleLinkedListNode.php │ ├── 07_linkedlist │ │ └── .gitkeep │ ├── .gitignore │ ├── buildAutoLoad.sh │ ├── composer.json │ ├── 10_heap │ │ ├── topn.php │ │ └── main.php │ ├── 24_tree │ │ ├── main.php │ │ ├── levelOrder.php │ │ └── TreeNode.php │ ├── 09_queue │ │ └── main.php │ ├── README.md │ ├── 13_sort │ │ └── countingSort.php │ └── 12_sort │ │ └── quicksort.php ├── java │ ├── 05_array │ │ └── .gitkeep │ ├── 06_linkedlist │ │ └── .gitkeep │ └── 07_linkedlist │ │ └── .gitkeep ├── scala │ ├── .gitignore │ ├── project │ │ └── build.properties │ ├── src │ │ ├── test │ │ │ └── scala │ │ │ │ ├── ch09_queue │ │ │ │ ├── ArrayQueueTest.scala │ │ │ │ ├── LinkedListQueueTest.scala │ │ │ │ ├── CircularQueueTest.scala │ │ │ │ ├── DynamicArrayQueueTest.scala │ │ │ │ └── DemoQueueTest.scala │ │ │ │ ├── ch39_back_tracking │ │ │ │ ├── EightQueensTest.scala │ │ │ │ ├── BagWeightTest.scala │ │ │ │ └── NQueensTest.scala │ │ │ │ ├── ch06_linkedlist │ │ │ │ └── NodeTest.scala │ │ │ │ ├── ch32_matching │ │ │ │ ├── RabinKarpTest.scala │ │ │ │ └── BruteForceTest.scala │ │ │ │ ├── ch10_recursive │ │ │ │ └── RecursiveDemoTest.scala │ │ │ │ ├── ch12_sorts │ │ │ │ ├── MergeSortTest.scala │ │ │ │ └── QuickSortTest.scala │ │ │ │ ├── ch15_bsearch │ │ │ │ ├── BSearchRecursiveTest.scala │ │ │ │ └── BSearchTest.scala │ │ │ │ ├── ch08_stack │ │ │ │ └── StackDemoTest.scala │ │ │ │ ├── ch20_linked_hash_map │ │ │ │ └── LRUCacheTest.scala │ │ │ │ ├── ch29_heap_solutions │ │ │ │ ├── MiddleNumberKeeperTest.scala │ │ │ │ └── TopKItemsKeeperTest.scala │ │ │ │ └── ch16_bsearch │ │ │ │ └── BSearchTest.scala │ │ └── main │ │ │ └── scala │ │ │ ├── ch09_queue │ │ │ ├── DemoQueue.scala │ │ │ ├── DynamicArrayQueue.scala │ │ │ ├── ArrayQueue.scala │ │ │ ├── CircularQueue.scala │ │ │ └── LinkedListQueue.scala │ │ │ ├── ch15_bsearch │ │ │ └── BSearchRecursive.scala │ │ │ ├── ch08_stack │ │ │ ├── StackDemo.scala │ │ │ └── BrowserDemo.scala │ │ │ ├── ch32_matching │ │ │ └── BruteForce.scala │ │ │ ├── ch10_recursive │ │ │ └── RecursiveDemo.scala │ │ │ ├── ch29_heap_solutions │ │ │ └── TopKItemsKeeper.scala │ │ │ └── ch39_back_tracking │ │ │ └── BagWeight.scala │ └── build.sbt ├── csharp │ ├── 08-stack │ │ └── algo08_stack │ │ │ ├── algo08_stack.csproj │ │ │ └── ArrayStack.cs │ ├── 06-linkedlist │ │ ├── LRU缓存实现思路.txt │ │ └── algo06_linked_list.csproj │ ├── 05-array │ │ └── algo05_array.csproj │ ├── 07-linkedlist │ │ └── _07_linkedlist │ │ │ └── algo07_linkedlist.csproj │ └── Tests │ │ ├── _06_linkedlist_tests │ │ ├── BaseLinkedListTests.cs │ │ └── algo06_linkedlist_tests.csproj │ │ ├── algo08_stack_tests │ │ └── algo08_stack_tests.csproj │ │ ├── _05_array_tests │ │ └── algo05_array_tests.csproj │ │ └── _07_linkedlist_tests │ │ └── algo07_linkedlist_tests.csproj ├── typescript │ ├── 09_queue │ │ └── README.md │ ├── 06_linkedlist │ │ └── List.ts │ └── 14_binarysearch │ │ └── BinarySearch.ts ├── swift │ ├── 08_stack │ │ ├── Stack.swift │ │ ├── Browser.swift │ │ └── BrowserDemo.swift │ ├── 09_queue │ │ └── Queue.swift │ └── 14_sorts │ │ └── CountingSort.swift ├── rust │ ├── 13_sorts │ │ └── sort_string.rs │ ├── 07_linkedlist │ │ ├── middle_of_the_linked_list.rs │ │ ├── reverse_linked_list.rs │ │ ├── linked_list_cycle.rs │ │ ├── util │ │ │ └── linked_list.rs │ │ ├── merge_two_sorted_lists.rs │ │ └── remove_nth_node_from_end_of_list.rs │ ├── 41_dynamic_programming │ │ ├── coin_change.rs │ │ └── min_dis_path.rs │ ├── 40_dynamic_programming │ │ └── triangle.rs │ ├── 15_binary_search │ │ └── sqrtx.rs │ ├── 11_sorts │ │ ├── selection_sort.rs │ │ ├── insertion_sort.rs │ │ └── bubble_sort.rs │ ├── 24_binary_tree │ │ ├── insert_in_binary_tree.rs │ │ └── search_in_binary_tree.rs │ └── 42_dynamic_programming │ │ ├── longest_increasing_subsequence.rs │ │ └── edit_distance.rs ├── .gitignore └── kotlin │ └── 08_stack │ └── StackBasedOnLinkedList.kt ├── 剑指 Offer └── cpp │ ├── 37_SerializeBinaryTrees │ ├── test.txt │ └── SerializeBinaryTrees.cpp │ ├── Utilities │ ├── List.h │ ├── Tree.h │ ├── Array.cpp │ ├── Array.h │ ├── List.cpp │ ├── Tree.cpp │ ├── BinaryTree.cpp │ ├── BinaryTree.h │ ├── StringUtil.cpp │ └── StringUtil.h │ ├── 16_Power │ ├── Power.cpp │ └── 16_Power.vcxproj.filters │ ├── 10_Fibonacci │ ├── Fibonacci.cpp │ └── 10_Fibonacci.vcxproj.filters │ ├── 13_RobotMove │ ├── RobotMove.cpp │ └── 13_RobotMove.vcxproj.filters │ ├── 43_NumberOf1 │ ├── NumberOf1.cpp │ └── 43_NumberOf1.vcxproj.filters │ ├── 09_QueueWithTwoStacks │ ├── Queue.h │ └── QueueWithTwoStacks.cpp │ ├── 30_MinInStack │ ├── MinInStack.cpp │ └── StackWithMin.h │ ├── 34_PathInTree │ ├── PathInTree.cpp │ └── 34_PathInTree.vcxproj.filters │ ├── 49_UglyNumber │ ├── UglyNumber.cpp │ └── 49_UglyNumber.vcxproj.filters │ ├── 53_01_NumberOfK │ ├── NumberOfK.cpp │ └── 53_01_NumberOfK.vcxproj.filters │ ├── 55_01_TreeDepth │ ├── TreeDepth.cpp │ └── 55_01_TreeDepth.vcxproj.filters │ ├── 64_Accumulate │ ├── Accumulate.cpp │ └── 64_Accumulate.vcxproj.filters │ ├── 14_CuttingRope │ ├── CuttingRope.cpp │ └── 14_CuttingRope.vcxproj.filters │ ├── 24_ReverseList │ ├── ReverseList.cpp │ └── 24_ReverseList.vcxproj.filters │ ├── 29_PrintMatrix │ ├── PrintMatrix.cpp │ └── 29_PrintMatrix.vcxproj.filters │ ├── 67_StringToInt │ ├── StringToInt.cpp │ └── 67_StringToInt.vcxproj.filters │ ├── 05_ReplaceSpaces │ └── ReplaceSpaces.cpp │ ├── 21_ReorderArray │ └── ReorderArray.cpp │ ├── 33_SquenceOfBST │ └── SquenceOfBST.cpp │ ├── 35_CopyComplexList │ ├── ComplexList.cpp │ ├── ComplexList.h │ └── CopyComplexList.cpp │ ├── 40_KLeastNumbers │ └── KLeastNumbers.cpp │ ├── 41_StreamMedian │ └── StreamMedian.cpp │ ├── 51_InversePairs │ └── InversePairs.cpp │ ├── 54_KthNodeInBST │ └── KthNodeInBST.cpp │ ├── 63_MaximalProfit │ └── MaximalProfit.cpp │ ├── 65_AddTwoNumbers │ └── AddTwoNumbers.cpp │ ├── 66_ConstuctArray │ └── ConstuctArray.cpp │ ├── 20_NumericStrings │ └── NumericStrings.cpp │ ├── 22_KthNodeFromEnd │ └── KthNodeFromEnd.cpp │ ├── 59_02_QueueWithMax │ └── QueueWithMax.cpp │ ├── 61_ContinousCards │ └── ContinousCards.cpp │ ├── 47_MaxValueOfGifts │ └── MaxValueOfGifts.cpp │ ├── 53_02_MissingNumber │ └── MissingNumber.cpp │ ├── 25_MergeSortedLists │ └── MergeSortedLists.cpp │ ├── 44_DigitsInSequence │ └── DigitsInSequence.cpp │ ├── 60_DicesProbability │ └── DicesProbability.cpp │ ├── 01_AssignmentOperator │ └── AssignmentOperator.cpp │ ├── 03_01_DuplicationInArray │ └── FindDuplication.cpp │ ├── 12_StringPathInMatrix │ └── StringPathInMatrix.cpp │ ├── 15_NumberOf1InBinary │ └── NumberOf1InBinary.cpp │ ├── 18_01_DeleteNodeInList │ └── DeleteNodeInList.cpp │ ├── 26_SubstructureInTree │ └── SubstructureInTree.cpp │ ├── 27_MirrorOfBinaryTree │ └── MirrorOfBinaryTree.cpp │ ├── 31_StackPushPopOrder │ └── StackPushPopOrder.cpp │ ├── 38_StringPermutation │ └── StringPermutation.cpp │ ├── 39_MoreThanHalfNumber │ └── MoreThanHalfNumber.cpp │ ├── 58_02_LeftRotateString │ └── LeftRotateString.cpp │ ├── 62_LastNumberInCircle │ └── LastNumberInCircle.cpp │ ├── 68_CommonParentInTree │ └── CommonParentInTree.cpp │ ├── 07_ConstructBinaryTree │ └── ConstructBinaryTree.cpp │ ├── 23_EntryNodeInListLoop │ └── EntryNodeInListLoop.cpp │ ├── 32_02_PrintTreesInLines │ └── PrintTreesInLines.cpp │ ├── 56_01_NumbersAppearOnce │ └── NumbersAppearOnce.cpp │ ├── 57_01_TwoNumbersWithSum │ └── TwoNumbersWithSum.cpp │ ├── 17_Print1ToMaxOfNDigits │ └── Print1ToMaxOfNDigits.cpp │ ├── 32_03_PrintTreesInZigzag │ └── PrintTreesInZigzag.cpp │ ├── 55_02_BalancedBinaryTree │ └── BalancedBinaryTree.cpp │ ├── 56_02_NumberAppearingOnce │ └── NumberAppearingOnce.cpp │ ├── 59_01_MaxInSlidingWindow │ └── MaxInSlidingWindow.cpp │ ├── 08_NextNodeInBinaryTrees │ └── NextNodeInBinaryTrees.cpp │ ├── 18_02_DeleteDuplicatedNode │ └── DeleteDuplicatedNode.cpp │ ├── 28_SymmetricalBinaryTree │ └── SymmetricalBinaryTree.cpp │ ├── 45_SortArrayForMinNumber │ └── SortArrayForMinNumber.cpp │ ├── 11_MinNumberInRotatedArray │ └── MinNumberInRotatedArray.cpp │ ├── 19_RegularExpressionsMatching │ └── RegularExpressions.cpp │ ├── 36_ConvertBinarySearchTree │ └── ConvertBinarySearchTree.cpp │ ├── 42_GreatestSumOfSubarrays │ └── GreatestSumOfSubarrays.cpp │ ├── 50_01_FirstNotRepeatingChar │ └── FirstNotRepeatingChar.cpp │ ├── 52_FirstCommonNodesInLists │ └── FirstCommonNodesInLists.cpp │ ├── 03_02_DuplicationInArrayNoEdit │ └── FindDuplicationNoEdit.cpp │ ├── 06_PrintListInReversedOrder │ └── PrintListInReversedOrder.cpp │ ├── 50_02_FirstCharacterInStream │ └── FirstCharacterInStream.cpp │ ├── 58_01_ReverseWordsInSentence │ └── ReverseWordsInSentence.cpp │ ├── 32_01_PrintTreeFromTopToBottom │ └── PrintTreeFromTopToBottom.cpp │ ├── 46_TranslateNumbersToStrings │ └── TranslateNumbersToStrings.cpp │ ├── 53_03_IntegerIdenticalToIndex │ └── IntegerIdenticalToIndex.cpp │ ├── 57_02_ContinuousSquenceWithSum │ └── ContinuousSquenceWithSum.cpp │ ├── 48_LongestSubstringWithoutDup │ └── LongestSubstringWithoutDup.cpp │ ├── 04_FindInPartiallySortedMatrix │ └── FindInPartiallySortedMatrix.cpp │ └── 02_Singleton │ └── App.config ├── leetcode ├── num_sum │ └── README.md ├── decode_string │ ├── go │ │ └── main.go │ ├── ts │ │ ├── main.test.js │ │ ├── main.regex.js │ │ └── main.recursion.js │ └── README.md ├── tsconfig.test.json ├── README.md ├── jest.config.js ├── unique_paths │ ├── uniquePaths.js │ └── __test__ │ │ ├── uniquePaths.test.js │ │ ├── btUniquePaths.test.js │ │ └── dpUniquePaths.test.js ├── two_num_II │ └── java │ │ └── .project ├── n_queens │ └── ts │ │ └── __test__ │ │ ├── nQueensBitwise.test.js │ │ └── QueensPosition.test.js ├── jump_game │ └── __test__ │ │ ├── greedyJumpGame.test.js │ │ ├── dpTopDownJumpGame.test.js │ │ ├── dpBottomUpJumpGame.test.js │ │ └── backtrackingJumpGame.test.js ├── recursive_staircase │ ├── __test__ │ │ ├── recursiveStaircaseIT.test.js │ │ ├── recursiveStaircaseBF.test.js │ │ ├── recursiveStaircaseDP.test.js │ │ └── recursiveStaircaseMEM.test.js │ └── recursiveStaircaseBF.js └── knight_tour │ └── __test__ │ └── knightTour.test.js ├── Cracking the Coding Interview └── cpp │ ├── README.md │ ├── Chapter-3-Stacks-and-Queues │ ├── 3.2-Stack-Min │ │ ├── StackNode.cpp │ │ ├── StackNode.h │ │ └── Stack.h │ └── 3.1-Three-in-One │ │ └── FixedMultiStack.h │ ├── .gitignore │ ├── Ch 4. Trees and Graphs │ ├── 4.5_Validate_BST.cpp │ ├── 4.10_Check_Subtree.cpp │ ├── 4.2_Minimal_Tree.cpp │ ├── 4.6_Successor.cpp │ └── 4.4_Check_Balanced.cpp │ ├── Ch 6. Math and Logic Puzzles │ ├── Intro │ │ └── Prime.cpp │ └── 7.The Apocalypse │ │ └── The Apocalypse.cpp │ ├── Ch 17. Hard │ └── Q17_01_Add_Without_Plus │ │ └── addWithoutPlus.cpp │ ├── chapter-8-recursion-and-Dynamic-Programming │ ├── 8-1-Triple-Step.cpp │ ├── 8-11-Coins.cpp │ ├── 8-7-Permutations-without-Dups.cpp │ ├── 8-9-parens.cpp │ ├── 8-8-Permutation-with-dups-alt.cpp │ └── 8-5-Recursive-Multiply.cpp │ ├── Ch 4. Trees and Graphs │ └── C++14 │ │ └── tree.hpp │ ├── Ch 1.Arrays And Strings │ └── 5. One Away │ │ └── 5.One Away.cpp │ └── Ch 7.OOD │ └── 1.Deck Of Cards │ └── BlackJackCrad.cpp └── .github └── ISSUE_TEMPLATE ├── custom.md ├── feature_request.md └── bug_report.md /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | .cache/ -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/python/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/05_array/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/javascript/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/05_array/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/08_stack/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/05_array/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/09_queue/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/11_sorts/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/12_sorts/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/13_sorts/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/14_sorts/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/15_bsearch/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/16_bsearch/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/17_skiplist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/06_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/07_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/java/05_array/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/12_sorts/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/13_sorts/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/14_sorts/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/15_bsearch/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/16_bsearch/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/17_skiplist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/05_array/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/06_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/07_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/python/05_array/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/06_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/07_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/10_recursive/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/18_hashtable/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/java/06_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/java/07_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/javascript/05_array/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/18_hashtable/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/19_hashtable/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/20_hashtable/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/06_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/07_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/python/06_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/python/07_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/javascript/06_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/javascript/07_linkedlist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | vendor 3 | *my* 4 | Queue -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.2.1 2 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/37_SerializeBinaryTrees/test.txt: -------------------------------------------------------------------------------- 1 | 5,$,5,$,5,5,5,5,5,$,$,$,5,$,5,$,$,$,$, -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/buildAutoLoad.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | composer dump-autoload -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/29_priority_queue/readme.md: -------------------------------------------------------------------------------- 1 | 2 | ## TODO 3 | - 该实现方式不能保证 相同优先级的元素在出队列时 和入队列的顺序是一致的 -------------------------------------------------------------------------------- /leetcode/num_sum/README.md: -------------------------------------------------------------------------------- 1 | # 求和问题 2 | 3 | # 链接 4 | 5 | - https://mp.weixin.qq.com/s/5IEY62z-scapftCreyzOhQ 6 | -------------------------------------------------------------------------------- /leetcode/decode_string/go/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Print("AAA") 7 | } 8 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/List.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/List.h -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/Tree.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/Tree.h -------------------------------------------------------------------------------- /剑指 Offer/cpp/16_Power/Power.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/16_Power/Power.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/Array.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/Array.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/Array.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/Array.h -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/List.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/List.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/Tree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/Tree.cpp -------------------------------------------------------------------------------- /leetcode/tsconfig.test.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "module": "commonjs" 5 | } 6 | } -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/BinaryTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/BinaryTree.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/BinaryTree.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/BinaryTree.h -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/StringUtil.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/StringUtil.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/Utilities/StringUtil.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/Utilities/StringUtil.h -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/README.md: -------------------------------------------------------------------------------- 1 | # C++ Solutions to [Cracking The Coding Interview 6th Ed.](http://www.crackingthecodinginterview.com/) -------------------------------------------------------------------------------- /剑指 Offer/cpp/10_Fibonacci/Fibonacci.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/10_Fibonacci/Fibonacci.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/13_RobotMove/RobotMove.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/13_RobotMove/RobotMove.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/43_NumberOf1/NumberOf1.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/43_NumberOf1/NumberOf1.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/09_QueueWithTwoStacks/Queue.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/09_QueueWithTwoStacks/Queue.h -------------------------------------------------------------------------------- /剑指 Offer/cpp/30_MinInStack/MinInStack.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/30_MinInStack/MinInStack.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/30_MinInStack/StackWithMin.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/30_MinInStack/StackWithMin.h -------------------------------------------------------------------------------- /剑指 Offer/cpp/34_PathInTree/PathInTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/34_PathInTree/PathInTree.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/49_UglyNumber/UglyNumber.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/49_UglyNumber/UglyNumber.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/53_01_NumberOfK/NumberOfK.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/53_01_NumberOfK/NumberOfK.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/55_01_TreeDepth/TreeDepth.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/55_01_TreeDepth/TreeDepth.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/64_Accumulate/Accumulate.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/64_Accumulate/Accumulate.cpp -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/.gitignore: -------------------------------------------------------------------------------- 1 | # main files 2 | main.* 3 | 4 | # executives 5 | a.out 6 | 7 | # objective files 8 | *.o 9 | *.obj 10 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/14_CuttingRope/CuttingRope.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/14_CuttingRope/CuttingRope.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/24_ReverseList/ReverseList.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/24_ReverseList/ReverseList.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/29_PrintMatrix/PrintMatrix.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/29_PrintMatrix/PrintMatrix.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/67_StringToInt/StringToInt.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/67_StringToInt/StringToInt.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/05_ReplaceSpaces/ReplaceSpaces.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/05_ReplaceSpaces/ReplaceSpaces.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/21_ReorderArray/ReorderArray.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/21_ReorderArray/ReorderArray.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/33_SquenceOfBST/SquenceOfBST.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/33_SquenceOfBST/SquenceOfBST.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/35_CopyComplexList/ComplexList.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/35_CopyComplexList/ComplexList.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/35_CopyComplexList/ComplexList.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/35_CopyComplexList/ComplexList.h -------------------------------------------------------------------------------- /剑指 Offer/cpp/40_KLeastNumbers/KLeastNumbers.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/40_KLeastNumbers/KLeastNumbers.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/41_StreamMedian/StreamMedian.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/41_StreamMedian/StreamMedian.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/51_InversePairs/InversePairs.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/51_InversePairs/InversePairs.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/54_KthNodeInBST/KthNodeInBST.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/54_KthNodeInBST/KthNodeInBST.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/63_MaximalProfit/MaximalProfit.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/63_MaximalProfit/MaximalProfit.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/65_AddTwoNumbers/AddTwoNumbers.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/65_AddTwoNumbers/AddTwoNumbers.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/66_ConstuctArray/ConstuctArray.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/66_ConstuctArray/ConstuctArray.cpp -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/05_array/Array_gp.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/数据结构和算法必知必会的 50 个代码实现/c-cpp/05_array/Array_gp.h -------------------------------------------------------------------------------- /剑指 Offer/cpp/20_NumericStrings/NumericStrings.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/20_NumericStrings/NumericStrings.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/22_KthNodeFromEnd/KthNodeFromEnd.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/22_KthNodeFromEnd/KthNodeFromEnd.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/59_02_QueueWithMax/QueueWithMax.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/59_02_QueueWithMax/QueueWithMax.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/61_ContinousCards/ContinousCards.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/61_ContinousCards/ContinousCards.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/35_CopyComplexList/CopyComplexList.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/35_CopyComplexList/CopyComplexList.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/47_MaxValueOfGifts/MaxValueOfGifts.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/47_MaxValueOfGifts/MaxValueOfGifts.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/53_02_MissingNumber/MissingNumber.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/53_02_MissingNumber/MissingNumber.cpp -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/17_skiplist/SkipList.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/数据结构和算法必知必会的 50 个代码实现/c-cpp/17_skiplist/SkipList.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/25_MergeSortedLists/MergeSortedLists.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/25_MergeSortedLists/MergeSortedLists.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/44_DigitsInSequence/DigitsInSequence.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/44_DigitsInSequence/DigitsInSequence.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/60_DicesProbability/DicesProbability.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/60_DicesProbability/DicesProbability.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/01_AssignmentOperator/AssignmentOperator.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/01_AssignmentOperator/AssignmentOperator.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/03_01_DuplicationInArray/FindDuplication.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/03_01_DuplicationInArray/FindDuplication.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/09_QueueWithTwoStacks/QueueWithTwoStacks.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/09_QueueWithTwoStacks/QueueWithTwoStacks.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/12_StringPathInMatrix/StringPathInMatrix.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/12_StringPathInMatrix/StringPathInMatrix.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/15_NumberOf1InBinary/NumberOf1InBinary.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/15_NumberOf1InBinary/NumberOf1InBinary.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/18_01_DeleteNodeInList/DeleteNodeInList.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/18_01_DeleteNodeInList/DeleteNodeInList.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/26_SubstructureInTree/SubstructureInTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/26_SubstructureInTree/SubstructureInTree.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/27_MirrorOfBinaryTree/MirrorOfBinaryTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/27_MirrorOfBinaryTree/MirrorOfBinaryTree.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/31_StackPushPopOrder/StackPushPopOrder.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/31_StackPushPopOrder/StackPushPopOrder.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/38_StringPermutation/StringPermutation.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/38_StringPermutation/StringPermutation.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/39_MoreThanHalfNumber/MoreThanHalfNumber.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/39_MoreThanHalfNumber/MoreThanHalfNumber.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/58_02_LeftRotateString/LeftRotateString.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/58_02_LeftRotateString/LeftRotateString.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/62_LastNumberInCircle/LastNumberInCircle.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/62_LastNumberInCircle/LastNumberInCircle.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/68_CommonParentInTree/CommonParentInTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/68_CommonParentInTree/CommonParentInTree.cpp -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/07_linkedlist/SingleList.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/数据结构和算法必知必会的 50 个代码实现/c-cpp/07_linkedlist/SingleList.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/07_ConstructBinaryTree/ConstructBinaryTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/07_ConstructBinaryTree/ConstructBinaryTree.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/23_EntryNodeInListLoop/EntryNodeInListLoop.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/23_EntryNodeInListLoop/EntryNodeInListLoop.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/32_02_PrintTreesInLines/PrintTreesInLines.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/32_02_PrintTreesInLines/PrintTreesInLines.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/56_01_NumbersAppearOnce/NumbersAppearOnce.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/56_01_NumbersAppearOnce/NumbersAppearOnce.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/57_01_TwoNumbersWithSum/TwoNumbersWithSum.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/57_01_TwoNumbersWithSum/TwoNumbersWithSum.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/17_Print1ToMaxOfNDigits/Print1ToMaxOfNDigits.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/17_Print1ToMaxOfNDigits/Print1ToMaxOfNDigits.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/32_03_PrintTreesInZigzag/PrintTreesInZigzag.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/32_03_PrintTreesInZigzag/PrintTreesInZigzag.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/37_SerializeBinaryTrees/SerializeBinaryTrees.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/37_SerializeBinaryTrees/SerializeBinaryTrees.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/55_02_BalancedBinaryTree/BalancedBinaryTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/55_02_BalancedBinaryTree/BalancedBinaryTree.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/56_02_NumberAppearingOnce/NumberAppearingOnce.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/56_02_NumberAppearingOnce/NumberAppearingOnce.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/59_01_MaxInSlidingWindow/MaxInSlidingWindow.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/59_01_MaxInSlidingWindow/MaxInSlidingWindow.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/08_NextNodeInBinaryTrees/NextNodeInBinaryTrees.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/08_NextNodeInBinaryTrees/NextNodeInBinaryTrees.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/18_02_DeleteDuplicatedNode/DeleteDuplicatedNode.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/18_02_DeleteDuplicatedNode/DeleteDuplicatedNode.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/28_SymmetricalBinaryTree/SymmetricalBinaryTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/28_SymmetricalBinaryTree/SymmetricalBinaryTree.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/45_SortArrayForMinNumber/SortArrayForMinNumber.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/45_SortArrayForMinNumber/SortArrayForMinNumber.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/11_MinNumberInRotatedArray/MinNumberInRotatedArray.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/11_MinNumberInRotatedArray/MinNumberInRotatedArray.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/19_RegularExpressionsMatching/RegularExpressions.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/19_RegularExpressionsMatching/RegularExpressions.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/36_ConvertBinarySearchTree/ConvertBinarySearchTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/36_ConvertBinarySearchTree/ConvertBinarySearchTree.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/42_GreatestSumOfSubarrays/GreatestSumOfSubarrays.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/42_GreatestSumOfSubarrays/GreatestSumOfSubarrays.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/50_01_FirstNotRepeatingChar/FirstNotRepeatingChar.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/50_01_FirstNotRepeatingChar/FirstNotRepeatingChar.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/52_FirstCommonNodesInLists/FirstCommonNodesInLists.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/52_FirstCommonNodesInLists/FirstCommonNodesInLists.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/03_02_DuplicationInArrayNoEdit/FindDuplicationNoEdit.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/03_02_DuplicationInArrayNoEdit/FindDuplicationNoEdit.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/06_PrintListInReversedOrder/PrintListInReversedOrder.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/06_PrintListInReversedOrder/PrintListInReversedOrder.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/50_02_FirstCharacterInStream/FirstCharacterInStream.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/50_02_FirstCharacterInStream/FirstCharacterInStream.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/58_01_ReverseWordsInSentence/ReverseWordsInSentence.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/58_01_ReverseWordsInSentence/ReverseWordsInSentence.cpp -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/06_linkedlist/singlelist_gc/singleList.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/数据结构和算法必知必会的 50 个代码实现/c-cpp/06_linkedlist/singlelist_gc/singleList.c -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/32_01_PrintTreeFromTopToBottom/PrintTreeFromTopToBottom.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/32_01_PrintTreeFromTopToBottom/PrintTreeFromTopToBottom.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/46_TranslateNumbersToStrings/TranslateNumbersToStrings.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/46_TranslateNumbersToStrings/TranslateNumbersToStrings.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/53_03_IntegerIdenticalToIndex/IntegerIdenticalToIndex.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/53_03_IntegerIdenticalToIndex/IntegerIdenticalToIndex.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/57_02_ContinuousSquenceWithSum/ContinuousSquenceWithSum.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/57_02_ContinuousSquenceWithSum/ContinuousSquenceWithSum.cpp -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/06_linkedlist/list_isPalindrome/LinkList.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/数据结构和算法必知必会的 50 个代码实现/c-cpp/06_linkedlist/list_isPalindrome/LinkList.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/48_LongestSubstringWithoutDup/LongestSubstringWithoutDup.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/48_LongestSubstringWithoutDup/LongestSubstringWithoutDup.cpp -------------------------------------------------------------------------------- /剑指 Offer/cpp/04_FindInPartiallySortedMatrix/FindInPartiallySortedMatrix.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wx-chevalier/algorithm-examples/master/剑指 Offer/cpp/04_FindInPartiallySortedMatrix/FindInPartiallySortedMatrix.cpp -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch09_queue/ArrayQueueTest.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | class ArrayQueueTest extends DemoQueueTest { 4 | 5 | override def getInstance() = new ArrayQueue[Int](15) 6 | } 7 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/08_stack/StatckInterface.go: -------------------------------------------------------------------------------- 1 | package _8_stack 2 | 3 | type Stack interface { 4 | Push(v interface{}) 5 | Pop() interface{} 6 | IsEmpty() bool 7 | Top() interface{} 8 | Flush() 9 | } 10 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/02_Singleton/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch09_queue/DemoQueue.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | trait DemoQueue[T] { 4 | 5 | var size = 0 6 | 7 | def enqueue(data: T): Unit 8 | 9 | def dequeue(): Option[T] 10 | } 11 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch09_queue/LinkedListQueueTest.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | class LinkedListQueueTest extends DemoQueueTest { 4 | 5 | override def getInstance() = new LinkListQueue[Int] 6 | 7 | } 8 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/08-stack/algo08_stack/algo08_stack.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/06-linkedlist/LRU缓存实现思路.txt: -------------------------------------------------------------------------------- 1 | 实现LRU缓存淘汰算法思路: 2 | 3 | 维护一个有序单链表,越靠近链尾的数据是最早访问的。 4 | 当有一个新的数据被访问时, 5 | 1. 如果数据在缓存中,则将其从原位置删除,然后插入到表头; 6 | 2. 如果数据不在缓存中,有两种情况: 7 | 1) 链表未满,则将数据插入到表头; 8 | 2) 链表已满,则删除尾结点,将新数据插入到表头。 9 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch09_queue/CircularQueueTest.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | class CircularQueueTest extends DemoQueueTest { 4 | 5 | override def getInstance(): DemoQueue[Int] = new CircularQueue[Int](15) 6 | } 7 | -------------------------------------------------------------------------------- /leetcode/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode OJ 题解 2 | 3 | 该项目是[数据结构与算法 https://url.wx-coder.cn/S84SI](https://url.wx-coder.cn/S84SI) 系列文章中讨论的 LeetCode 相关算法题的多语言版本的实现。 4 | 5 | # Motivation & Credits 6 | 7 | - [leetcode-ts](https://github.com/guocaoyi/leetcode-ts) 8 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Chapter-3-Stacks-and-Queues/3.2-Stack-Min/StackNode.cpp: -------------------------------------------------------------------------------- 1 | #include "StackNode.h" 2 | 3 | StackNode::StackNode(int data, StackNode *next) 4 | { 5 | this->data = data; 6 | this->next = next; 7 | minimum = nullptr; 8 | } 9 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/05-array/algo05_array.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | false 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/10_recursion/Fibonacci_test.go: -------------------------------------------------------------------------------- 1 | package Recursion 2 | 3 | import "testing" 4 | 5 | func TestFibs_Fibonacci(t *testing.T) { 6 | fib := NewFibs(10) 7 | for i:=1; i<15; i++{ 8 | fib.Fibonacci(i) 9 | fib.Print(i) 10 | } 11 | } -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/10_recursion/Factorial_test.go: -------------------------------------------------------------------------------- 1 | package Recursion 2 | 3 | import "testing" 4 | 5 | func TestFac_Factorial(t *testing.T) { 6 | fac := NewFactorial(10) 7 | for i:=1; i<15; i++{ 8 | fac.Factorial(i) 9 | fac.Print(i) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/14_sorts/readme.md: -------------------------------------------------------------------------------- 1 | # 排序优化 2 | 3 | ## 如何取舍排序算法? 4 | 5 | * 排序规模小 —— $O(n^2)$ 的算法(通常是插排) 6 | * 排序规模大 —— $O(n\log n)$ 的算法(通常不用归并排序) 7 | 8 | ## 如何优化快速排序? 9 | 10 | 参考:[谈谈内省式排序算法](https://liam.page/2018/08/29/introspective-sort/) 11 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/build.sbt: -------------------------------------------------------------------------------- 1 | lazy val root = (project in file(".")) 2 | .settings( 3 | name := "algo-scala", 4 | version := "1.0", 5 | scalaVersion := "2.12.8", 6 | libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % "test" 7 | ) 8 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/typescript/09_queue/README.md: -------------------------------------------------------------------------------- 1 | ### 队列 2 | 3 | 由于js语言天生就可以使用array数组来实现栈和队列等结构: 4 | ```javascript 5 | // 模拟数组队列 6 | const queue = [] 7 | queue.push(1) // 向数组尾部添加数据 8 | queue.shift() //数组头部去除数据,并返回 9 | ``` 10 | 这里我们使用链表来实现队列结构 11 | 12 | 队列分为无限队列和循环队列 13 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/12_sorts/MergeSort_test.go: -------------------------------------------------------------------------------- 1 | package _2_sorts 2 | 3 | import "testing" 4 | 5 | func TestMergeSort(t *testing.T) { 6 | arr := []int{5, 4} 7 | MergeSort(arr) 8 | t.Log(arr) 9 | 10 | arr = []int{5, 4, 3, 2, 1} 11 | MergeSort(arr) 12 | t.Log(arr) 13 | } 14 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/08_stack/stack_practice/BalancedParentheses.h: -------------------------------------------------------------------------------- 1 | /** 2 | 判断括号是否匹配 {} [] () 3 | 4 | Author: Smallfly 5 | */ 6 | #import 7 | 8 | @interface BalancedParentheses : NSObject 9 | 10 | - (BOOL)checkForParenthessBlanced:(NSString *)express; 11 | 12 | @end 13 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/14_sorts/CountingSort_test.go: -------------------------------------------------------------------------------- 1 | package _4_sorts 2 | 3 | import "testing" 4 | 5 | func TestCountingSort(t *testing.T) { 6 | arr := []int{5, 4} 7 | CountingSort(arr, len(arr)) 8 | t.Log(arr) 9 | 10 | arr = []int{5, 4, 3, 2, 1} 11 | CountingSort(arr, len(arr)) 12 | t.Log(arr) 13 | } 14 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/45_bitmap/bitmap_test.go: -------------------------------------------------------------------------------- 1 | package bitmap 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestBitMap(t *testing.T) { 8 | bitMap := New(80) 9 | for i := 0; i <= 100; i += 10 { 10 | bitMap.Set(uint(i)) 11 | } 12 | for i := 0; i <= 100; i += 10 { 13 | t.Log(bitMap.Get(uint(i))) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/06_linkedlist/palindromeList/ListNode.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: TripleZ 3 | * Date: 2018-10-10 4 | * Brief: ListNode class. 5 | */ 6 | 7 | #ifndef _LISTNODE_HPP_ 8 | #define _LISTNODE_HPP_ 9 | 10 | class ListNode { 11 | public: 12 | int val; 13 | ListNode *next; 14 | }; 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/13_sorts/BucketSort_test.go: -------------------------------------------------------------------------------- 1 | package LinearSort 2 | 3 | import "testing" 4 | 5 | func TestBucketSort(t *testing.T) { 6 | a := []int{1,6,3,5,8,6,4} 7 | BucketSort(a) 8 | t.Log(a) 9 | } 10 | 11 | func TestBucketSortSimple(t *testing.T) { 12 | a := []int{1,6,3,5,8,6,4} 13 | BucketSortSimple(a) 14 | t.Log(a) 15 | } 16 | -------------------------------------------------------------------------------- /leetcode/decode_string/ts/main.test.js: -------------------------------------------------------------------------------- 1 | import { decodeStr } from './main.recursion'; 2 | 3 | describe('测试用例', () => { 4 | it('基准测试', () => { 5 | const s = 'ab2[c]3[d]2[a]'; 6 | expect(decodeStr(s)).toEqual('abccdddaa'); 7 | }); 8 | it('单字符串测试', () => { 9 | const s = '2[leetcode]'; 10 | expect(decodeStr(s)).toEqual('leetcodeleetcode'); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /leetcode/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | coverageDirectory: '/@coverage', 3 | globals: { 4 | 'ts-jest': { 5 | tsConfig: 'tsconfig.test.json' 6 | } 7 | }, 8 | moduleFileExtensions: ['js', 'ts'], 9 | rootDir: './', 10 | testRegex: '/__test__/.+\\.(test|spec)\\.ts$', 11 | transform: { '^.+\\.ts$': 'ts-jest' }, 12 | verbose: true 13 | }; 14 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch39_back_tracking/EightQueensTest.scala: -------------------------------------------------------------------------------- 1 | package ch39_back_tracking 2 | 3 | import org.scalatest.FlatSpec 4 | 5 | class EightQueensTest extends FlatSpec { 6 | 7 | behavior of "EightQueensTest" 8 | 9 | it should "calc8Queues" in { 10 | val eightQueens = new EightQueens() 11 | eightQueens.calc8Queues(0) 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/07-linkedlist/_07_linkedlist/algo07_linkedlist.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/29_priority_queue/heap_test.go: -------------------------------------------------------------------------------- 1 | package pqueue 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_AdjustHeap(t *testing.T) { 10 | list := []Node{Node{0, 0}, Node{1, 1}, Node{2, 2}, Node{3, 3}, Node{4, 1}, Node{6, 6}} 11 | 12 | adjustHeap(list, 1, len(list)-1) 13 | assert.Equal(t, 6, list[1].value) 14 | } 15 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/08_stack/stack_practice/ArrayStack.h: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | 栈实现 4 | 5 | Author: Smallfly 6 | */ 7 | 8 | #import 9 | 10 | @interface Stack : NSObject 11 | 12 | - (id)initWithCapacity:(NSUInteger)count; 13 | 14 | - (BOOL)isEmpty; 15 | - (id)top; 16 | - (NSUInteger)size; 17 | 18 | - (BOOL)push:(id)obj; 19 | - (id)pop; 20 | 21 | @end 22 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/14_sorts/analytics_of_std_sort.md: -------------------------------------------------------------------------------- 1 | # C++ STL 中的 std::sort 分析 2 | 3 | 参见 [Liam Huang 的博客](https://liam.page/)中的 3 篇文章: 4 | 5 | * [谈谈基于比较的排序算法的复杂度下界](https://liam.page/2018/08/28/lower-bound-of-comparation-based-sort-algorithm/) 6 | * [谈谈内省式排序算法](https://liam.page/2018/08/29/introspective-sort/) 7 | * [谈谈 STL 中的 std::sort](https://liam.page/2018/09/18/std-sort-in-STL/) 8 | 9 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/06-linkedlist/algo06_linked_list.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Chapter-3-Stacks-and-Queues/3.2-Stack-Min/StackNode.h: -------------------------------------------------------------------------------- 1 | #ifndef STACKNODE_H 2 | #define STACKNODE_H 3 | 4 | class Stack; 5 | 6 | class StackNode 7 | { 8 | public: 9 | friend class Stack; 10 | StackNode(int data, StackNode *next); 11 | 12 | private: 13 | int data; 14 | StackNode *next; 15 | StackNode *minimum; 16 | }; 17 | 18 | #endif // STACKNODE_H 19 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/24_tree/TreeNode.go: -------------------------------------------------------------------------------- 1 | package _4_tree 2 | 3 | import "fmt" 4 | 5 | type Node struct { 6 | data interface{} 7 | left *Node 8 | right *Node 9 | } 10 | 11 | func NewNode(data interface{}) *Node { 12 | return &Node{data: data} 13 | } 14 | 15 | func (this *Node) String() string { 16 | return fmt.Sprintf("v:%+v, left:%+v, right:%+v", this.data, this.left, this.right) 17 | } 18 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | 19 | # Compiled Static libraries 20 | *.lai 21 | *.la 22 | *.a 23 | *.lib 24 | 25 | # Executables 26 | *.exe 27 | *.out 28 | *.app 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/10_recursion/RangAll_test.go: -------------------------------------------------------------------------------- 1 | package Recursion 2 | 3 | import "testing" 4 | 5 | func TestRangeALL(t *testing.T) { 6 | slice1 := NewRangeArray(4) 7 | for i:=0; i<4; i++{ 8 | slice1.value[i] = i+1 9 | } 10 | slice1.RangeALL(0) 11 | 12 | slice2 := NewRangeArray(3) 13 | slice2.value[0] = "a" 14 | slice2.value[1] = "b" 15 | slice2.value[2] = "c" 16 | slice2.RangeALL(0) 17 | 18 | } 19 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/typescript/06_linkedlist/List.ts: -------------------------------------------------------------------------------- 1 | interface List { 2 | insertToHead(value: T): void 3 | 4 | findByValue(value: T): any 5 | 6 | findByIndex(index: number): any 7 | 8 | insertToIndex(value: T, index: number): void 9 | 10 | remove(value: T): boolean 11 | 12 | insertToHead(value: T): void 13 | 14 | insertToTail(value: T): void 15 | 16 | toString(): string 17 | } 18 | 19 | export default List 20 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/08_stack/LinkedStack.h: -------------------------------------------------------------------------------- 1 | // 2 | // LinkedStack.h 3 | // algo 4 | // 5 | // Created by Wenru Dong on 2018/10/8. 6 | // Copyright © 2018年 Wenru Dong. All rights reserved. 7 | // 8 | // Stack based upon linked list 9 | // 基于链表实现的栈 10 | 11 | #import 12 | 13 | @interface LinkedStack : NSObject 14 | 15 | - (BOOL)isEmpty; 16 | - (void)push:(int)value; 17 | - (int)pop; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/08_stack/stack_practice/FourOperation.h: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | 整型四则运算 4 | 5 | Author: Smallfly 6 | */ 7 | 8 | #import 9 | 10 | @interface FourOperation : NSObject 11 | 12 | + (FourOperation *)shared; 13 | 14 | /** 15 | 整型四则运算 16 | 17 | @param expression 运算表达式,注意操作数和运算符之间要有空格 18 | @return 计算结果 19 | */ 20 | - (NSNumber *)caculateExpression:(NSString *)expression; 21 | 22 | @end 23 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch39_back_tracking/BagWeightTest.scala: -------------------------------------------------------------------------------- 1 | package ch39_back_tracking 2 | 3 | import org.scalatest.FlatSpec 4 | 5 | class BagWeightTest extends FlatSpec { 6 | 7 | behavior of "BagWeightTest" 8 | 9 | it should "calculateMaxWeight" in { 10 | val bagWeight = new BagWeight(5,9) 11 | val maxWeight = bagWeight.calculateMaxWeight(Array(1,2,3,5,6)) 12 | println(maxWeight) 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /leetcode/unique_paths/uniquePaths.js: -------------------------------------------------------------------------------- 1 | import pascalTriangle from '../../math/pascal-triangle/pascalTriangle'; 2 | 3 | /** 4 | * @param {number} width 5 | * @param {number} height 6 | * @return {number} 7 | */ 8 | export default function uniquePaths(width, height) { 9 | const pascalLine = width + height - 2; 10 | const pascalLinePosition = Math.min(width, height) - 1; 11 | 12 | return pascalTriangle(pascalLine)[pascalLinePosition]; 13 | } 14 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/10_recursion/readme.md: -------------------------------------------------------------------------------- 1 | # 递归 2 | 3 | ## 三个条件 4 | 5 | * 可分解为子问题 6 | * 子问题与原问题解法一致,只有规模上的不同 7 | * 有终止条件 8 | 9 | ## 写递归代码 10 | 11 | * 整理出递推公式 12 | * 确定好终止条件 13 | * 「翻译」成代码 14 | 15 | 关键: 16 | 17 | > 只要遇到递归,我们就把它抽象成一个递推公式,不用想一层层的调用关系,不要试图用人脑去分解每一个步骤。 18 | 19 | ## 警惕 20 | 21 | * 堆栈溢出 <- 递归深度过大 22 | * 重复计算 <- 递归过程中的不同分支,重复计算相同子问题 23 | * 保存子问题结果(map/dict) 24 | * 空间复杂度高 <- 递归函数调用带来的消耗 25 | 26 | ## 递归改写非递归 27 | 28 | 本质:人肉模拟函数调用堆栈。 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/08_stack/ListNode.h: -------------------------------------------------------------------------------- 1 | // 2 | // ListNode.h 3 | // algo 4 | // 5 | // Created by Wenru Dong on 2018/10/6. 6 | // Copyright © 2018年 Wenru Dong. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ListNode : NSObject 12 | 13 | @property int value; 14 | @property ListNode *next; 15 | 16 | - (instancetype)initWithValue:(int)value; 17 | + (instancetype)nodeWithValue:(int)value; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/06_linkedlist/ListNode.h: -------------------------------------------------------------------------------- 1 | // 2 | // ListNode.h 3 | // algo 4 | // 5 | // Created by Wenru Dong on 2018/10/6. 6 | // Copyright © 2018年 Wenru Dong. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ListNode : NSObject 12 | 13 | @property int value; 14 | @property ListNode *next; 15 | 16 | - (instancetype)initWithValue:(int)value; 17 | + (instancetype)nodeWithValue:(int)value; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 4. Trees and Graphs/4.5_Validate_BST.cpp: -------------------------------------------------------------------------------- 1 | bool validateBST(TreeNode* root, int min, int max) { 2 | if (root == nullptr) { 3 | return true; 4 | } 5 | if (root->data < min || root->data > max) { 6 | return false; 7 | } 8 | return validateBST(root->left, min, root->data - 1) && validateBST(root->right, root->data + 1, max); 9 | } 10 | 11 | bool validateBST(TreeNode* root) { 12 | return validateBST(root, -2e9, 2e9); 13 | } 14 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 6. Math and Logic Puzzles/Intro/Prime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int i,j,sq; 8 | int min; 9 | for(sq = 2; sq <= 10; sq++) 10 | { 11 | min = (sq-1)*(sq-1); 12 | min = min + (min+1)%2; 13 | for(i = min; i < sq*sq; i+=2) 14 | { 15 | for(j = 3; j <= sq; j+=2) 16 | { 17 | if (i%j == 0) 18 | bad; 19 | } 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/08_stack/linked_list.h: -------------------------------------------------------------------------------- 1 | /** 2 | * C++ 版本单链表结点 3 | * 4 | * Author: Liam Huang (Liam0205) 5 | */ 6 | 7 | #ifndef STACK_LINKED_LIST_H_ 8 | #define STACK_LINKED_LIST_H_ 9 | 10 | #include 11 | 12 | template 13 | struct Node { 14 | using ptr_t = std::shared_ptr>; 15 | T data; 16 | ptr_t next; 17 | 18 | Node(T data_) : data(data_), next(nullptr) {} 19 | Node() : next(nullptr) {} 20 | }; 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /leetcode/unique_paths/__test__/uniquePaths.test.js: -------------------------------------------------------------------------------- 1 | import uniquePaths from '../uniquePaths'; 2 | 3 | describe('uniquePaths', () => { 4 | it('should find the number of unique paths on board', () => { 5 | expect(uniquePaths(3, 2)).toBe(3); 6 | expect(uniquePaths(7, 3)).toBe(28); 7 | expect(uniquePaths(3, 7)).toBe(28); 8 | expect(uniquePaths(10, 10)).toBe(48620); 9 | expect(uniquePaths(100, 1)).toBe(1); 10 | expect(uniquePaths(1, 100)).toBe(1); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 4. Trees and Graphs/4.10_Check_Subtree.cpp: -------------------------------------------------------------------------------- 1 | bool containTree(TreeNode* T1, TreeNode* T2) { 2 | string s1 = "", s2 = ""; 3 | inOrderString(T1, s1); 4 | inOrderString(T2, s2); 5 | return (s1.find(s2) != string::npos); 6 | } 7 | 8 | void inOrderString(TreeNode* root, string s) { 9 | if (root == nullptr) { 10 | s += "X"; 11 | return; 12 | } 13 | s += root->data; 14 | inOrderString(root->left, s); 15 | inOrderString(root->right, s); 16 | } 17 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "algo/php", 3 | "description": "数据结构与算法之美php实现", 4 | "type": "project", 5 | "require": {}, 6 | "autoload": { 7 | "psr-4": { 8 | "Algo_06\\": "06_linkedlist/", 9 | "Algo_07\\": "07_linkedlist/", 10 | "Algo_08\\": "08_stack/", 11 | "Algo_09\\": "09_queue/", 12 | "Algo_24\\": "24_tree/", 13 | "Algo_10\\": "10_heap/" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/12_sorts/QuickSort_test.go: -------------------------------------------------------------------------------- 1 | package _2_sorts 2 | 3 | import ( 4 | "math/rand" 5 | "testing" 6 | ) 7 | 8 | func createRandomArr(length int) []int { 9 | arr := make([]int, length, length) 10 | for i := 0; i < length; i++ { 11 | arr[i] = rand.Intn(100) 12 | } 13 | return arr 14 | } 15 | 16 | func TestQuickSort(t *testing.T) { 17 | arr := []int{5, 4} 18 | QuickSort(arr) 19 | t.Log(arr) 20 | 21 | arr = createRandomArr(100) 22 | QuickSort(arr) 23 | t.Log(arr) 24 | } 25 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch39_back_tracking/NQueensTest.scala: -------------------------------------------------------------------------------- 1 | package ch39_back_tracking 2 | 3 | import org.scalatest.FlatSpec 4 | 5 | class NQueensTest extends FlatSpec { 6 | 7 | behavior of "NQueensTest" 8 | 9 | it should "calc8Queues" in { 10 | val eightQueens = new NQueens(8) 11 | eightQueens.calcNQueues(0) 12 | 13 | } 14 | 15 | it should "calc4Queues" in { 16 | val eightQueens = new NQueens(4) 17 | eightQueens.calcNQueues(0) 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/unique_paths/__test__/btUniquePaths.test.js: -------------------------------------------------------------------------------- 1 | import btUniquePaths from '../btUniquePaths'; 2 | 3 | describe('btUniquePaths', () => { 4 | it('should find the number of unique paths on board', () => { 5 | expect(btUniquePaths(3, 2)).toBe(3); 6 | expect(btUniquePaths(7, 3)).toBe(28); 7 | expect(btUniquePaths(3, 7)).toBe(28); 8 | expect(btUniquePaths(10, 10)).toBe(48620); 9 | expect(btUniquePaths(100, 1)).toBe(1); 10 | expect(btUniquePaths(1, 100)).toBe(1); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /leetcode/unique_paths/__test__/dpUniquePaths.test.js: -------------------------------------------------------------------------------- 1 | import dpUniquePaths from '../dpUniquePaths'; 2 | 3 | describe('dpUniquePaths', () => { 4 | it('should find the number of unique paths on board', () => { 5 | expect(dpUniquePaths(3, 2)).toBe(3); 6 | expect(dpUniquePaths(7, 3)).toBe(28); 7 | expect(dpUniquePaths(3, 7)).toBe(28); 8 | expect(dpUniquePaths(10, 10)).toBe(48620); 9 | expect(dpUniquePaths(100, 1)).toBe(1); 10 | expect(dpUniquePaths(1, 100)).toBe(1); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/33_bm_match/BM.h: -------------------------------------------------------------------------------- 1 | // 2 | // BM.h 3 | // BM-Match 4 | // 5 | // Created by Smallfly on 2018/12/9. 6 | // Copyright © 2018 Smallfly. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | NS_ASSUME_NONNULL_BEGIN 12 | 13 | @interface BM : NSObject 14 | - (instancetype)initWithA:(NSString *)a andB:(NSString *)b; 15 | - (NSInteger)startMatch; 16 | - (void)startMatchCompeletion:(void (^)(NSInteger))completion; 17 | @end 18 | 19 | NS_ASSUME_NONNULL_END 20 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/07_linkedlist/linked_list.h: -------------------------------------------------------------------------------- 1 | /** 2 | * 单链表 3 | * 4 | * Author: Liam Huang (Liam0205) 5 | */ 6 | 7 | #ifndef LINKEDLIST_LINKED_LIST_H_ 8 | #define LINKEDLIST_LINKED_LIST_H_ 9 | 10 | #include 11 | 12 | template 13 | struct Node { 14 | using ptr_t = std::shared_ptr>; 15 | T data; 16 | ptr_t next; 17 | 18 | Node(T data_) : data(data_), next(nullptr) {} 19 | Node() : next(nullptr) {} 20 | }; 21 | 22 | #endif // LINKEDLIST_LINKED_LIST_H_ 23 | -------------------------------------------------------------------------------- /leetcode/two_num_II/java/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | java 4 | Project java created by Buildship. 5 | 6 | 7 | 8 | 9 | org.eclipse.buildship.core.gradleprojectbuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.buildship.core.gradleprojectnature 16 | 17 | 18 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 4. Trees and Graphs/4.2_Minimal_Tree.cpp: -------------------------------------------------------------------------------- 1 | TreeNode* createMinBST(vector arr) { 2 | return createMinBST(arr, 0, arr.length() - 1); 3 | } 4 | 5 | TreeNode* createMinBST(vector arr, int start, int end) { 6 | if (start > end) { 7 | return null; 8 | } 9 | int mid = start + (end - start) / 2; 10 | TreeNode* newNode = new TreeNode(arr[mid]); 11 | newNode.left = createMinBST(arr, start, mid - 1); 12 | newNode.right = createMinBST(arr, mid + 1, end); 13 | return newNode; 14 | } 15 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Chapter-3-Stacks-and-Queues/3.2-Stack-Min/Stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | #include "StackNode.h" 5 | #include 6 | #include 7 | 8 | class Stack 9 | { 10 | public: 11 | Stack(); 12 | virtual ~Stack(); 13 | void push(int item); 14 | void pop(); 15 | int top() const; 16 | int getMinimum() const; 17 | 18 | bool isEmpty() const; 19 | int getSize() const; 20 | 21 | private: 22 | StackNode *head; 23 | int stackSize; 24 | }; 25 | 26 | #endif // STACK_H 27 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/29_priority_queue/heap.go: -------------------------------------------------------------------------------- 1 | package pqueue 2 | 3 | func adjustHeap(src []Node, start, end int) { 4 | if start >= end { 5 | return 6 | } 7 | 8 | // 只需要保证优先级最高的节点在 src[1] 的位置即可 9 | for i := end / 2; i >= start; i-- { 10 | high := i 11 | if src[high].priority < src[2*i].priority { 12 | high = 2 * i 13 | } 14 | if 2*i+1 <= end && src[high].priority < src[2*i+1].priority { 15 | high = 2*i + 1 16 | } 17 | if high == i { 18 | continue 19 | } 20 | src[high], src[i] = src[i], src[high] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/swift/08_stack/Stack.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Jiandan on 2018/10/12. 3 | // Copyright (c) 2018 Jiandan. All rights reserved. 4 | // 5 | 6 | import Foundation 7 | 8 | protocol Stack { 9 | /// 持有的数据类型 10 | associatedtype Element 11 | /// 是否为空 12 | var isEmpty: Bool { get } 13 | /// 队列大小 14 | var size: Int { get } 15 | /// 返回队列头部元素 16 | var peek: Element? { get } 17 | /// 入栈 18 | mutating func push(newElement: Element) -> Bool 19 | /// 出栈 20 | mutating func pop() -> Element? 21 | } 22 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/swift/09_queue/Queue.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Jiandan on 2018/10/11. 3 | // Copyright (c) 2018 Jiandan. All rights reserved. 4 | // 5 | 6 | import Foundation 7 | 8 | protocol Queue { 9 | /// 持有的数据类型 10 | associatedtype Element 11 | /// 是否为空 12 | var isEmpty: Bool { get } 13 | /// 队列大小 14 | var size: Int { get } 15 | /// 返回队列头部元素 16 | var peek: Element? { get } 17 | /// 入队 18 | mutating func enqueue(newElement: Element) -> Bool 19 | /// 出队 20 | mutating func dequeue() -> Element? 21 | } 22 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch06_linkedlist/NodeTest.scala: -------------------------------------------------------------------------------- 1 | package ch06_linkedlist 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | class NodeTest extends FlatSpec with Matchers { 6 | 7 | behavior of "NodeTest" 8 | it should "create node with constructor" in { 9 | val node1 = new Node(1, None) 10 | val node2 = new Node(2, Some(node1)) 11 | val node3 = new Node(2, Some(node2)) 12 | 13 | node1.next should be(None) 14 | node1.next = Some(node3) 15 | node1.next should equal(Some(node3)) 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 4. Trees and Graphs/4.6_Successor.cpp: -------------------------------------------------------------------------------- 1 | TreeNode* mostLeft(TreeNode* root) { 2 | while (root->left != nullptr) { 3 | root = root->left; 4 | } 5 | return root; 6 | } 7 | 8 | TreeNode* findSuccessor(TreeNode* root) { 9 | if (root->right != nullptr) { 10 | return mostLeft(root->right); 11 | } 12 | TreeNode* child = root; 13 | TreeNode* ancestor = root->parent; 14 | while(ancestor != nullptr && ancestor->right == child) { 15 | child = ancestor; 16 | ancestor = child->parent; 17 | } 18 | return ancestor; 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/n_queens/ts/__test__/nQueensBitwise.test.js: -------------------------------------------------------------------------------- 1 | import nQueensBitwise from '../nQueensBitwise'; 2 | 3 | describe('nQueensBitwise', () => { 4 | it('should have solutions for 4 to N queens', () => { 5 | expect(nQueensBitwise(4)).toBe(2); 6 | expect(nQueensBitwise(5)).toBe(10); 7 | expect(nQueensBitwise(6)).toBe(4); 8 | expect(nQueensBitwise(7)).toBe(40); 9 | expect(nQueensBitwise(8)).toBe(92); 10 | expect(nQueensBitwise(9)).toBe(352); 11 | expect(nQueensBitwise(10)).toBe(724); 12 | expect(nQueensBitwise(11)).toBe(2680); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/13_sorts/sort_string.rs: -------------------------------------------------------------------------------- 1 | fn sort_string(s: String) -> Vec> { 2 | let mut bucket: Vec> = vec![vec![]; 3]; 3 | for ch in s.as_bytes() { 4 | if ch as u8 >= 48 && ch as u8 <= 57 { 5 | bucket[0].push(ch); 6 | } else if ch as u8 >= 65 && ch as u8 <= 90 { 7 | bucket[1].push(ch); 8 | } else { 9 | bucket[2].push(ch); 10 | } 11 | } 12 | 13 | bucket 14 | } 15 | fn main() { 16 | let s = "DaFBCA789".to_string(); 17 | println!("{:?}", sort_string(s)); 18 | } 19 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch32_matching/RabinKarpTest.scala: -------------------------------------------------------------------------------- 1 | package ch32_matching 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | import scala.util.Random 6 | 7 | class RabinKarpTest extends FlatSpec with Matchers { 8 | 9 | it should "find firstIndexOf a sub string" in { 10 | val random = Random.alphanumeric 11 | val main = random.take(1000).toArray 12 | val index = Random.nextInt(950) 13 | val sub = random.take(1000).toArray.slice(index, index + 50) 14 | 15 | RabinKarp.firstIndexOf(main, sub) should equal(index) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/08_stack/StackBasedOnArray/StackBasedOnArray.h: -------------------------------------------------------------------------------- 1 | 2 | // 类模板的声明(line 3),类模板实例化后就是模板类 3 | // 类模板声明的写法 template class 类名{} 4 | template class ArrayStack 5 | { 6 | public: 7 | ArrayStack(); 8 | ArrayStack(int count); 9 | ~ArrayStack(); 10 | void push(T data); //入栈 11 | T pop(); //出栈,并删除栈顶元素 12 | T peek(); //返回栈顶元素,不删除栈顶元素,栈顶指针不变 13 | int stackSize(); 14 | int stackMaxSize(); 15 | 16 | private: 17 | int flag; //栈顶标签,指向栈顶 18 | int count ; //栈的容量 19 | T *array; //指针 20 | }; 21 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/08_stack/SimpleBrowser_test.go: -------------------------------------------------------------------------------- 1 | package _8_stack 2 | 3 | import "testing" 4 | 5 | func TestBrowser(t *testing.T) { 6 | b := NewBrowser() 7 | b.PushBack("www.qq.com") 8 | b.PushBack("www.baidu.com") 9 | b.PushBack("www.sina.com") 10 | if b.CanBack() { 11 | b.Back() 12 | } 13 | if b.CanForward() { 14 | b.Forward() 15 | } 16 | if b.CanBack() { 17 | b.Back() 18 | } 19 | if b.CanBack() { 20 | b.Back() 21 | } 22 | if b.CanBack() { 23 | b.Back() 24 | } 25 | b.Open("www.taobao.com") 26 | if b.CanForward() { 27 | b.Forward() 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/10_recursion/Factorial.go: -------------------------------------------------------------------------------- 1 | package Recursion 2 | 3 | // 迭代实现阶乘 4 | type Fac struct { 5 | val map[int]int 6 | } 7 | 8 | func NewFactorial(n int) *Fac { 9 | return &Fac{ 10 | make(map[int]int, n), 11 | } 12 | } 13 | 14 | func (fac *Fac) Factorial(n int) int { 15 | if fac.val[n] != 0{ 16 | return fac.val[n] 17 | } 18 | 19 | if n <= 1{ 20 | fac.val[n] = 1 21 | return 1 22 | }else { 23 | res := n * fac.Factorial(n-1) 24 | fac.val[n] =res 25 | return res 26 | } 27 | } 28 | 29 | func (fac *Fac) Print(n int ) { 30 | println(fac.val[n]) 31 | } 32 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/15_bsearch/readme.md: -------------------------------------------------------------------------------- 1 | # 二分查找(上) 2 | 3 | ## 算法描述 4 | 5 | 二分查找(Binary Search)也叫折半查找,是针对有序数据集合的查找算法。其描述十分简单: 6 | 7 | * 折半取中,判断元素与目标元素的大小关系 8 | * 小于——往前继续折半 9 | * 大于——往后继续折半 10 | * 等于——返回 11 | 12 | 关于它的复杂度分析,参见[谈谈基于比较的排序算法的复杂度下界](https://liam.page/2018/08/28/lower-bound-of-comparation-based-sort-algorithm/)中的相关信息。它的复杂度是 $O(\log n)$。 13 | 14 | ## $O(\log n)$ 的惊人之处 15 | 16 | 在 42 亿个数据中用二分查找一个数据,最多需要比较 32 次。 17 | 18 | ## 适用场景 19 | 20 | * 依赖顺序表结构 21 | * 数据本身必须有序 22 | * 数据量相对比较元素的开销要足够大——不然遍历即可 23 | * 数据量相对内存空间不能太大——不然顺序表装不下 24 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/05_array/MyArray.h: -------------------------------------------------------------------------------- 1 | // 2 | // MyArray.h 3 | // algo 4 | // 5 | // Created by Wenru Dong on 2018/10/3. 6 | // Copyright © 2018年 Wenru Dong. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface MyArray : NSObject 12 | 13 | - (instancetype)initWithCapacity:(NSUInteger)capacity; 14 | - (id)objectAtIndexedSubscript:(NSUInteger)index; 15 | - (void)removeObjectAtIndex:(NSUInteger)index; 16 | - (void)insertObject:(id)anObject atIndex:(NSUInteger)index; 17 | - (void)addObject:(id)anObject; 18 | - (void)printAll; 19 | @end 20 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/11_Sort/Sort.h: -------------------------------------------------------------------------------- 1 | // 2 | // Sort.h 3 | // test1231231 4 | // 5 | // Created by Scarlett Che on 2018/12/12. 6 | // Copyright © 2018 Scarlett Che. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | NS_ASSUME_NONNULL_BEGIN 12 | 13 | @interface Sort : NSObject 14 | // 冒泡排序 15 | + (NSArray *)bubbleSortWithArray:(NSArray *)array; 16 | 17 | // 插入排序 18 | + (NSArray *)insertionSortWithArray:(NSArray *)array; 19 | 20 | // 选择排序 21 | + (NSArray *)selectionSortWithArray:(NSArray *)array; 22 | @end 23 | 24 | NS_ASSUME_NONNULL_END 25 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch09_queue/DynamicArrayQueue.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | import scala.reflect.ClassTag 4 | 5 | class DynamicArrayQueue[T: ClassTag](val capacity: Int) extends ArrayQueue[T](capacity) { 6 | 7 | override def enqueue(data: T): Unit = { 8 | if (tail == capacity) { 9 | //tail is the end of 10 | require(head > 0, "queue is full") 11 | for (i <- Range(head, tail)) { 12 | items(i - head) = items(head) 13 | } 14 | tail = tail - head 15 | head = 0 16 | } 17 | super.enqueue(data) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/10_heap/topn.php: -------------------------------------------------------------------------------- 1 | ".$heap->topn($v).PHP_EOL; 29 | } 30 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/Tests/_06_linkedlist_tests/BaseLinkedListTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using algo06_linked_list; 3 | 4 | namespace algo06_linkedlist_tests 5 | { 6 | public class BaseLinkedListTests 7 | { 8 | protected void PrintLinkedList (SingleLinkedList list) where T : IComparable 9 | { 10 | if (list == null) return; 11 | 12 | var p = list.First; 13 | while (p != null) 14 | { 15 | System.Console.WriteLine (p.Value); 16 | p = p.Next; 17 | } 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/07_linkedlist/middle_of_the_linked_list.rs: -------------------------------------------------------------------------------- 1 | use super::util::linked_list::{ListNode, to_list}; 2 | 3 | pub fn middle_node(head: Option>) -> Option> { 4 | let mut fast_p = &head; 5 | let mut slow_p = &head; 6 | 7 | while fast_p.is_some() && fast_p.as_ref().unwrap().next.is_some() { 8 | slow_p = &slow_p.as_ref().unwrap().next; 9 | fast_p = &fast_p.as_ref().unwrap().next.as_ref().unwrap().next; 10 | } 11 | slow_p.clone() 12 | } 13 | 14 | fn main() { 15 | println!("{:?}", middle_node(to_list(vec![1, 3, 4]))); 16 | } 17 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/14_sorts/CountingSort.go: -------------------------------------------------------------------------------- 1 | package _4_sorts 2 | 3 | import "math" 4 | 5 | func CountingSort(a []int, n int) { 6 | if n <= 1 { 7 | return 8 | } 9 | 10 | var max int = math.MinInt32 11 | for i := range a { 12 | if a[i] > max { 13 | max = a[i] 14 | } 15 | } 16 | 17 | c := make([]int, max+1) 18 | for i := range a { 19 | c[a[i]]++ 20 | } 21 | for i := 1; i <= max; i++ { 22 | c[i] += c[i-1] 23 | } 24 | 25 | r := make([]int, n) 26 | for i := n - 1; i >= 0; i-- { 27 | index := c[a[i]] - 1 28 | r[index] = a[i] 29 | c[a[i]]-- 30 | } 31 | 32 | copy(a, r) 33 | } 34 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/07_linkedlist/reverse_linked_list.rs: -------------------------------------------------------------------------------- 1 | use super::util::linked_list::{ListNode, to_list}; 2 | 3 | pub fn reverse_list(head: Option>) -> Option> { 4 | let mut prev = None; 5 | let mut curr = head; 6 | 7 | while let Some(mut boxed_node) = curr.take() { 8 | let next = boxed_node.next.take(); 9 | boxed_node.next = prev.take(); 10 | 11 | prev = Some(boxed_node); 12 | curr = next; 13 | } 14 | 15 | prev 16 | } 17 | 18 | fn main() { 19 | println!("{:?}", reverse_list(to_list(vec![1, 2, 3, 4, 5]))); 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/decode_string/ts/main.regex.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @file 文件描述 3 | * @description 详细说明 4 | * 5 | * @author 王下邀月熊 <384924552@qq.com> 6 | * 7 | * Created Date: Sun, 2018-07-15 22:18:07 8 | * 9 | * Last Modified: Sun, 2018-07-15 22:22:24 10 | * Last Modified By: 王下邀月熊 <384924552@qq.com> 11 | * 12 | * This code is licensed under the MIT License. 13 | */ 14 | export const decodeString = str => { 15 | return str.replace( 16 | /(\d)\[([a-z]+((\d)\[([a-z]+)\])*)\]/gi, 17 | (matched, $0, $1, $2, $3, $4) => { 18 | $1 = $2 ? $4.repeat(+$3) : $1; 19 | return $0 * $1; 20 | } 21 | ); 22 | }; 23 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/24_tree/main.php: -------------------------------------------------------------------------------- 1 | insert(20); 11 | $tree->insert(30); 12 | $tree->insert(40); 13 | $tree->insert(10); 14 | $tree->insert(21); 15 | $tree->insert(22); 16 | 17 | $tree->preOrder($tree->head); 18 | echo PHP_EOL; 19 | 20 | $tree->inOrder($tree->head); 21 | echo PHP_EOL; 22 | 23 | $tree->postOrder($tree->head); 24 | echo PHP_EOL; 25 | 26 | 27 | print_r($tree->find(30)); 28 | echo PHP_EOL; 29 | 30 | 31 | $tree->delete(30); 32 | $tree->preOrder($tree->head); 33 | echo PHP_EOL; -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch10_recursive/RecursiveDemoTest.scala: -------------------------------------------------------------------------------- 1 | package ch10_recursive 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | class RecursiveDemoTest extends FlatSpec with Matchers { 6 | 7 | behavior of "RecursiveDemoTest" 8 | 9 | it should "calculateStepWays" in { 10 | RecursiveDemo.calculateStepWays(1) should equal(1) 11 | RecursiveDemo.calculateStepWays(2) should equal(2) 12 | RecursiveDemo.calculateStepWays(3) should equal(3) 13 | RecursiveDemo.calculateStepWays(4) should equal(5) 14 | RecursiveDemo.calculateStepWays(5) should equal(8) 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 4. Trees and Graphs/4.4_Check_Balanced.cpp: -------------------------------------------------------------------------------- 1 | int checkHeight(TreeNode* root) { 2 | if (root == nullptr) { 3 | return 0; 4 | } 5 | int leftHeight = checkHeight(root->left); 6 | if (leftHeight == -1) { 7 | return -1; 8 | } 9 | int rightHeight = checkHeight(root->right); 10 | if (rightHeight == -1) { 11 | return -1; 12 | } 13 | 14 | if (abs(leftHeight - rightHeight) > 1) { 15 | return -1; 16 | } 17 | else { 18 | return max(leftHeight, rightHeight) + 1; 19 | } 20 | } 21 | 22 | bool isBalanced(TreeNode* root) { 23 | return (checkHeight == -1); 24 | } 25 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/07_linkedlist/linked_list_cycle.rs: -------------------------------------------------------------------------------- 1 | use super::util::linked_list::{ListNode, to_list}; 2 | 3 | pub fn has_cycle(head: Option>) -> bool { 4 | let mut fast_p = &head; 5 | let mut slow_p = &head; 6 | 7 | while fast_p.is_some() && fast_p.as_ref().unwrap().next.is_some() { 8 | slow_p = &slow_p.as_ref().unwrap().next; 9 | fast_p = &fast_p.as_ref().unwrap().next.as_ref().unwrap().next; 10 | 11 | if slow_p == fast_p { return true; } 12 | } 13 | false 14 | } 15 | 16 | fn main() { 17 | println!("{:?}", has_cycle(to_list(vec![1, 2, 3, 4, 5]))); 18 | } 19 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch09_queue/DynamicArrayQueueTest.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | class DynamicArrayQueueTest extends DemoQueueTest { 4 | 5 | override def getInstance(): DemoQueue[Int] = new DynamicArrayQueue[Int](15) 6 | 7 | it should "copy data when tail reach the end of the queue" in { 8 | val queue = getInstance() 9 | for (i <- Range(0, 15)) { 10 | queue.enqueue(i) 11 | } 12 | queue.size should equal(15) 13 | queue.dequeue().get should equal(0) 14 | 15 | //enqueue another one 16 | queue.enqueue(30) 17 | queue.size should equal(15) 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch32_matching/BruteForceTest.scala: -------------------------------------------------------------------------------- 1 | package ch32_matching 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | import scala.util.Random 6 | 7 | class BruteForceTest extends FlatSpec with Matchers { 8 | 9 | behavior of "BruteForceTest" 10 | 11 | it should "find firstIndexOf a sub string" in { 12 | val random = Random.alphanumeric 13 | val main = random.take(1000).toArray 14 | val index = Random.nextInt(950) 15 | val sub = random.take(1000).toArray.slice(index, index + 50) 16 | 17 | BruteForce.firstIndexOf(main, sub) should equal(index) 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/08_stack/linkList/linklist_stack.h: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | > File Name: linklist_stack.h 3 | > Author: jinshaohui 4 | > Mail: jinshaohui789@163.com 5 | > Time: 18-10-12 6 | > Desc: 7 | ************************************************************************/ 8 | 9 | #ifndef STACK_LINK_LIST_H 10 | #define STACK_LINK_LIST_H 11 | 12 | typedef struct _linkliststack 13 | { 14 | int data; 15 | struct _linkliststack *next; 16 | }linklist_stack; 17 | 18 | 19 | #define stack_is_empty(liststack) (liststack->next == NULL) 20 | 21 | #endif 22 | 23 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/09_queue/main.php: -------------------------------------------------------------------------------- 1 | enqueue(1); 14 | $queue->enqueue(2); 15 | $queue->enqueue(3); 16 | $queue->enqueue(4); 17 | $queue->enqueue(5); 18 | $queue->printSelf(); 19 | var_dump($queue->getLength()); 20 | 21 | $queue->dequeue(); 22 | $queue->printSelf(); 23 | $queue->dequeue(); 24 | $queue->dequeue(); 25 | $queue->dequeue(); 26 | $queue->printSelf(); 27 | 28 | $queue->dequeue(); 29 | $queue->printSelf(); 30 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/33_bm_match/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // BM-Match 4 | // 5 | // Created by Smallfly on 2018/12/9. 6 | // Copyright © 2018 Smallfly. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "BM.h" 11 | 12 | int main(int argc, const char * argv[]) { 13 | @autoreleasepool { 14 | BM *bm = [[BM alloc] initWithA:@"abacadc" andB:@"adc"]; 15 | 16 | [bm startMatchCompeletion:^(NSInteger index) { 17 | NSLog(@"异步查找到下标:%ld\n", index); 18 | }]; 19 | 20 | NSLog(@"同步查找到下标:%ld\n", [bm startMatch]); 21 | } 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/41_dynamic_programming/coin_change.rs: -------------------------------------------------------------------------------- 1 | fn coin_change(coins: Vec, amount: i32) -> i32 { 2 | let mut dp = vec![amount+1; (amount+1) as usize]; 3 | dp[0] = 0; 4 | for i in 1..=amount as usize { 5 | for &coin in coins.iter() { 6 | if i as i32 >= coin { 7 | dp[i] = dp[i].min(dp[i-coin as usize] + 1); 8 | } 9 | } 10 | } 11 | 12 | let last = *dp.last().unwrap(); 13 | if last > amount { -1 } else { last } 14 | } 15 | fn main() { 16 | let coins = vec![1, 3, 5]; 17 | 18 | let m = coin_change(coins, 9); 19 | println!("{}", m); // 3 20 | } 21 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/24_tree/levelOrder.php: -------------------------------------------------------------------------------- 1 | insert(16); 18 | $tree->insert(30); 19 | $tree->insert(12); 20 | $tree->insert(19); 21 | 22 | $tree->insert(10); 23 | $tree->insert(15); 24 | $tree->insert(18); 25 | $tree->insert(21); 26 | $tree->insert(38); 27 | 28 | 29 | $q=$tree->levelOrder([$tree->head]); 30 | 31 | foreach ($q as $n){ 32 | echo $n->data." "; 33 | } 34 | echo PHP_EOL; -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/README.md: -------------------------------------------------------------------------------- 1 | ## 数据结构与算法之美PHP实现 2 | 3 | ### 项目运行 4 | * 依赖composer自动加载,php目录下执行`composer dump-autoload` || `sh buildAutoLoad.sh` 5 | * 项目代码均在mac&php7环境下跑通 6 | 7 | ### 项目实现 8 | #### 06_linkedlist 9 | * 单链表php实现 10 | * 回文判断 11 | 12 | #### 07_linkedlist 13 | * reverse 单链表反转 14 | * checkCircle 链表中环的检测 15 | * mergerSortedList 两个有序的链表合并 16 | * deleteLastKth 删除链表倒数第n个结点 17 | * findMiddleNode 求链表的中间结点 18 | 19 | #### 08_stack 20 | * 链栈实现 21 | 22 | #### 09_stack 23 | * 队列链表实现 24 | #### 10_heap 25 | * main 堆的基本操作,堆排序 26 | * findmiddle 动态数据流求中位数 27 | * topn 动态数据流求top k 28 | #### 24_tree 29 | * main 二叉树的基本操作 前中后序遍历 30 | * levelOrder 二叉树的层级遍历 31 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/11_sorts/Sort_test.go: -------------------------------------------------------------------------------- 1 | package _1_sorts 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestBubbleSort(t *testing.T) { 9 | arr := []int{1,5,9,6,3,7,5,10} 10 | fmt.Println("排序前:",arr) 11 | BubbleSort(arr,len(arr)) 12 | fmt.Println("排序后:",arr) 13 | } 14 | 15 | func TestInsertionSort(t *testing.T) { 16 | arr := []int{1,5,9,6,3,7,5,10} 17 | fmt.Println("排序前:",arr) 18 | InsertionSort(arr,len(arr)) 19 | fmt.Println("排序后:",arr) 20 | } 21 | 22 | func TestSelectionSort(t *testing.T) { 23 | arr := []int{1,5,9,6,3,7,5,10} 24 | fmt.Println("排序前:",arr) 25 | SelectionSort(arr,len(arr)) 26 | fmt.Println("排序后:",arr) 27 | } 28 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/08_stack/ListNode.m: -------------------------------------------------------------------------------- 1 | // 2 | // ListNode.m 3 | // algo 4 | // 5 | // Created by Wenru Dong on 2018/10/6. 6 | // Copyright © 2018年 Wenru Dong. All rights reserved. 7 | // 8 | 9 | #import "ListNode.h" 10 | 11 | @implementation ListNode 12 | 13 | - (instancetype)initWithValue:(int)value { 14 | if (self = [super init]) { 15 | _value = value; 16 | } 17 | return self; 18 | } 19 | 20 | + (instancetype)nodeWithValue:(int)value { 21 | return [[self alloc] initWithValue:value]; 22 | } 23 | 24 | - (NSString*)debugDescription { 25 | return [NSString stringWithFormat:@"%d", _value]; 26 | } 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /leetcode/n_queens/ts/__test__/QueensPosition.test.js: -------------------------------------------------------------------------------- 1 | import QueenPosition from '../QueenPosition'; 2 | 3 | describe('QueenPosition', () => { 4 | it('should store queen position on chessboard', () => { 5 | const position1 = new QueenPosition(0, 0); 6 | const position2 = new QueenPosition(2, 1); 7 | 8 | expect(position2.columnIndex).toBe(1); 9 | expect(position2.rowIndex).toBe(2); 10 | expect(position1.leftDiagonal).toBe(0); 11 | expect(position1.rightDiagonal).toBe(0); 12 | expect(position2.leftDiagonal).toBe(1); 13 | expect(position2.rightDiagonal).toBe(3); 14 | expect(position2.toString()).toBe('2,1'); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/32_string/string_bf.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | //BF search pattern index, return the first match subs start index 8 | func bfSearch(main string, pattern string) int { 9 | 10 | //defensive 11 | if len(main) == 0 || len(pattern) == 0 || len(main) < len(pattern) { 12 | return -1 13 | } 14 | 15 | for i := 0; i <= len(main)-len(pattern); i++ { 16 | subStr := main[i : i+len(pattern)] 17 | if subStr == pattern { 18 | return i 19 | } 20 | } 21 | 22 | return -1 23 | } 24 | 25 | func main() { 26 | 27 | main := "abcd227fac" 28 | pattern := "ac" 29 | fmt.Println(bfSearch(main, pattern)) 30 | } 31 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/06_linkedlist/ListNode.m: -------------------------------------------------------------------------------- 1 | // 2 | // ListNode.m 3 | // algo 4 | // 5 | // Created by Wenru Dong on 2018/10/6. 6 | // Copyright © 2018年 Wenru Dong. All rights reserved. 7 | // 8 | 9 | #import "ListNode.h" 10 | 11 | @implementation ListNode 12 | 13 | - (instancetype)initWithValue:(int)value { 14 | if (self = [super init]) { 15 | _value = value; 16 | } 17 | return self; 18 | } 19 | 20 | + (instancetype)nodeWithValue:(int)value { 21 | return [[self alloc] initWithValue:value]; 22 | } 23 | 24 | - (NSString*)debugDescription { 25 | return [NSString stringWithFormat:@"%d", _value]; 26 | } 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/python/15_bsearch/bsearch.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Wenru 3 | """ 4 | 5 | from typing import List 6 | 7 | def bsearch(nums: List[int], target: int) -> int: 8 | """Binary search of a target in a sorted array 9 | without duplicates. If such a target does not exist, 10 | return -1, othewise, return its index. 11 | """ 12 | low, high = 0, len(nums) - 1 13 | while low <= high: 14 | mid = low + (high - low) // 2 15 | if nums[mid] == target: 16 | return mid 17 | elif nums[mid] < target: 18 | low = mid + 1 19 | else: 20 | high = mid - 1 21 | 22 | return -1 23 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/08_stack/StackBasedOnLinkedList/StackBasedOnLinkedList.h: -------------------------------------------------------------------------------- 1 | // 类模板的声明,关键字 class 也可以更换成 typename 2 | template class LinkedListStack 3 | { 4 | public: 5 | LinkedListStack(); 6 | ~LinkedListStack(); 7 | 8 | void push(const T & data); //入栈 9 | T peek(); //返回栈顶元素,即出栈,不删除栈顶元素 10 | T pop(); //出栈,删除栈顶元素 11 | int size() const; //返回栈的大小 12 | private: 13 | int count; //存放栈的大小,因为是单链表所以这里不规定栈的最大可承载量 14 | struct LinkedNode 15 | { 16 | T data; 17 | LinkedNode * next; 18 | }; 19 | LinkedNode * head; // 单链表的头指针,不带头节点 20 | }; 21 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/24_tree/TreeNode.php: -------------------------------------------------------------------------------- 1 | data = $data; 33 | $this->left = null; 34 | $this->right = null; 35 | } 36 | } -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/python/15_bsearch/bsearch_recursion.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: dreamkong 3 | """ 4 | 5 | from typing import List 6 | 7 | 8 | def bsearch(nums: List[int], target: int) -> int: 9 | return bsearch_internally(nums, 0, len(nums)-1, target) 10 | 11 | 12 | def bsearch_internally(nums: List[int], low: int, high: int, target: int) -> int: 13 | if low > high: 14 | return -1 15 | 16 | mid = low+int((high-low) >> 2) 17 | if nums[mid] == target: 18 | return mid 19 | elif nums[mid] < target: 20 | return bsearch_internally(nums, mid+1, high, target) 21 | else: 22 | return bsearch_internally(nums, low, mid-1, target) 23 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/08_stack/main.php: -------------------------------------------------------------------------------- 1 | pushData(1); 14 | $stack->pushData(2); 15 | $stack->pushData(3); 16 | $stack->pushData(4); 17 | var_dump($stack->getLength()); 18 | $stack->printSelf(); 19 | 20 | $topNode = $stack->top(); 21 | var_dump($topNode->data); 22 | 23 | $stack->pop(); 24 | $stack->printSelf(); 25 | $stack->pop(); 26 | $stack->printSelf(); 27 | 28 | var_dump($stack->getLength()); 29 | 30 | $stack->pop(); 31 | $stack->pop(); 32 | $stack->printSelf(); -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/09_queue/QueueBasedOnArray_test.go: -------------------------------------------------------------------------------- 1 | package _9_queue 2 | 3 | import "testing" 4 | 5 | func TestArrayQueue_EnQueue(t *testing.T) { 6 | q := NewArrayQueue(5) 7 | q.EnQueue(1) 8 | q.EnQueue(2) 9 | q.EnQueue(3) 10 | q.EnQueue(4) 11 | q.EnQueue(5) 12 | q.EnQueue(6) 13 | t.Log(q) 14 | } 15 | 16 | func TestArrayQueue_DeQueue(t *testing.T) { 17 | q := NewArrayQueue(5) 18 | q.EnQueue(1) 19 | q.EnQueue(2) 20 | q.EnQueue(3) 21 | q.EnQueue(4) 22 | q.EnQueue(5) 23 | q.EnQueue(6) 24 | t.Log(q) 25 | q.DeQueue() 26 | t.Log(q) 27 | q.DeQueue() 28 | t.Log(q) 29 | q.DeQueue() 30 | t.Log(q) 31 | q.DeQueue() 32 | t.Log(q) 33 | q.DeQueue() 34 | t.Log(q) 35 | } 36 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/10_heap/main.php: -------------------------------------------------------------------------------- 1 | insert($v); 16 | } 17 | 18 | while(($r=$heap->deleteFirst())!==null){ 19 | echo $r." "; 20 | } 21 | echo PHP_EOL; 22 | 23 | $heap1=new Heap(10); 24 | 25 | foreach ($arr as $v){ 26 | $heap1->insertOnly($v); 27 | } 28 | 29 | 30 | 31 | $heap1->heapAll(); 32 | //堆化后的 33 | print_r($heap1->dataArr); 34 | //堆排序 35 | $heap1->heapSort(); 36 | print_r($heap1->dataArr); 37 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch15_bsearch/BSearchRecursive.scala: -------------------------------------------------------------------------------- 1 | package ch15_bsearch 2 | 3 | object BSearchRecursive { 4 | 5 | def search(items: Array[Int], target: Int): Int = { 6 | _search(items, target, 0, items.length - 1) 7 | } 8 | 9 | private[this] def _search(items: Array[Int], target: Int, low: Int, high: Int): Int = { 10 | if (low > high) { 11 | return -1 12 | } 13 | 14 | val mid = low + (high - low) / 2 15 | if (items(mid) == target) { 16 | mid 17 | } else if (items(mid) > target) { 18 | _search(items, target, low, mid - 1) 19 | } else { 20 | _search(items, target, mid + 1, high) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch12_sorts/MergeSortTest.scala: -------------------------------------------------------------------------------- 1 | package ch12_sorts 2 | 3 | 4 | import org.scalatest.{FlatSpec, Matchers} 5 | 6 | class MergeSortTest extends FlatSpec with Matchers { 7 | behavior of "SortsTest in ch12" 8 | 9 | it should "mergeSort int arrays" in { 10 | var array = Array(4, 5, 6, 3, 2, 1) 11 | array = MergeSort.mergeSort(array) 12 | array.mkString("") should equal("123456") 13 | 14 | array = Array(4) 15 | array = MergeSort.mergeSort(array) 16 | array.mkString("") should equal("4") 17 | 18 | array = Array(4, 2) 19 | array = MergeSort.mergeSort(array) 20 | array.mkString("") should equal("24") 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/10_recursion/Fibonacci.go: -------------------------------------------------------------------------------- 1 | package Recursion 2 | 3 | import "fmt" 4 | 5 | // 递归实现斐波那契数列 6 | type Fibs struct { 7 | val map[int]int // 使用字典存储结果 8 | } 9 | 10 | func NewFibs(n int) *Fibs { 11 | return &Fibs{ 12 | make(map[int]int, n), 13 | } 14 | } 15 | 16 | func (fib *Fibs)Fibonacci(n int) int { 17 | if fib.val[n] != 0{ 18 | return fib.val[n] 19 | } 20 | if n <= 1 { 21 | fib.val[1] = 1 22 | return 1 23 | }else if n ==2{ 24 | fib.val[2] = 1 25 | return 1 26 | } else { 27 | res := fib.Fibonacci(n-1) + fib.Fibonacci(n-2) 28 | fib.val[n] = res 29 | return res 30 | } 31 | } 32 | 33 | func (fib *Fibs)Print(n int) { 34 | fmt.Println(fib.val[n]) 35 | } 36 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 17. Hard/Q17_01_Add_Without_Plus/addWithoutPlus.cpp: -------------------------------------------------------------------------------- 1 | //g++ -std=gnu++11 -o addWithoutPlus addWithoutPlus.cpp 2 | #include 3 | 4 | unsigned sum(unsigned x, unsigned y) { 5 | unsigned xor_result = x ^ y; 6 | unsigned carry = (x & y) << 1; 7 | if ( carry == 0 ) return xor_result; 8 | return sum(xor_result, carry); 9 | } 10 | 11 | int main(){ 12 | std::cout << "The sum of 7 + 8 is: " << sum(7,8) << std::endl; 13 | std::cout << "The sum of 33 + 4 is: " << sum(33,4) << std::endl; 14 | std::cout << "The sum of 11 + 5 is: " << sum(5,11) << std::endl; 15 | std::cout << "The sum of 31 + 7 is: " << sum(31,7) << std::endl; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/09_queue/QueueBasedOnLinkedList_test.go: -------------------------------------------------------------------------------- 1 | package _9_queue 2 | 3 | import "testing" 4 | 5 | func TestListQueue_EnQueue(t *testing.T) { 6 | q := NewLinkedListQueue() 7 | q.EnQueue(1) 8 | q.EnQueue(2) 9 | q.EnQueue(3) 10 | q.EnQueue(4) 11 | q.EnQueue(5) 12 | q.EnQueue(6) 13 | t.Log(q) 14 | } 15 | 16 | func TestListQueue_DeQueue(t *testing.T) { 17 | q := NewLinkedListQueue() 18 | q.EnQueue(1) 19 | q.EnQueue(2) 20 | q.EnQueue(3) 21 | q.EnQueue(4) 22 | q.EnQueue(5) 23 | q.EnQueue(6) 24 | t.Log(q) 25 | q.DeQueue() 26 | t.Log(q) 27 | q.DeQueue() 28 | t.Log(q) 29 | q.DeQueue() 30 | t.Log(q) 31 | q.DeQueue() 32 | t.Log(q) 33 | q.DeQueue() 34 | t.Log(q) 35 | } 36 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/Tests/algo08_stack_tests/algo08_stack_tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/40_dynamic_programming/triangle.rs: -------------------------------------------------------------------------------- 1 | # leetcode [minimum_total](https://leetcode.com/problems/triangle/) 2 | 3 | pub fn minimum_total(mut triangle: Vec>) -> i32 { 4 | if triangle.len() == 0 { return 0; } 5 | 6 | for i in (0..triangle.len() - 1).rev() { 7 | for j in 0..triangle[i].len() { 8 | triangle[i][j] = triangle[i+1][j].min(triangle[i+1][j+1]) + triangle[i][j]; 9 | } 10 | } 11 | triangle[0][0] 12 | } 13 | 14 | fn main() { 15 | let triangle = vec![ 16 | vec![2], 17 | vec![3, 4], 18 | vec![6, 5, 7], 19 | vec![4, 1, 8, 3], 20 | ]; 21 | 22 | println!("{:?}", minimum_total(triangle)); 23 | } 24 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch08_stack/StackDemo.scala: -------------------------------------------------------------------------------- 1 | package ch08_stack 2 | 3 | class Node[T](var data: T, var next: Option[Node[T]]) 4 | 5 | class StackDemo[T] { 6 | 7 | 8 | var headOpt: Option[Node[T]] = None 9 | var size = 0 10 | 11 | def clear(): Unit = { 12 | headOpt = None 13 | size = 0 14 | } 15 | 16 | def push(data: T) = { 17 | val newHead = new Node(data, headOpt) 18 | headOpt = Some(newHead) 19 | size += 1 20 | } 21 | 22 | def pop(): Option[Node[T]] = { 23 | headOpt match { 24 | case None => None 25 | case Some(head) => 26 | headOpt = head.next 27 | size -= 1 28 | Some(head) 29 | 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch09_queue/ArrayQueue.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | import scala.reflect.ClassTag 4 | 5 | class ArrayQueue[T: ClassTag](capacity: Int) extends DemoQueue[T] { 6 | 7 | var items: Array[T] = new Array[T](capacity) 8 | var head = 0 9 | var tail = 0 10 | 11 | override def enqueue(data: T): Unit = { 12 | require(tail < capacity, "queue is full") 13 | items(tail) = data 14 | tail += 1 15 | size += 1 16 | } 17 | 18 | override def dequeue(): Option[T] = { 19 | if (head < tail) { 20 | val result = Some(items(head)) 21 | head += 1 22 | size -= 1 23 | result 24 | } else { 25 | None 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/12_sorts/merge_sort_test.cc: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Liam Huang (Liam0205) on 2018/10/17. 3 | */ 4 | 5 | #include 6 | #include 7 | #include "merge_sort.hpp" 8 | 9 | int main() { 10 | const std::vector test_data{0, -1, 3, 190, -500}; 11 | 12 | std::vector a{test_data}; 13 | merge_sort(a.begin(), a.end()); 14 | for (auto i : a) { 15 | std::cout << i << ' '; 16 | } 17 | std::cout << std::endl; 18 | 19 | std::vector b{test_data}; 20 | inplace_merge_sort(b.begin(), b.end()); 21 | for (auto i : b) { 22 | std::cout << i << ' '; 23 | } 24 | std::cout << std::endl; 25 | 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/Tests/_05_array_tests/algo05_array_tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | false 7 | 8 | 05_array_tests 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/06_linkedlist/palindrome_test.go: -------------------------------------------------------------------------------- 1 | package _6_linkedlist 2 | 3 | import "testing" 4 | 5 | func TestPalindrome1(t *testing.T) { 6 | strs := []string{"heooeh", "hello", "heoeh", "a", ""} 7 | for _, str1 := range strs { 8 | l := NewLinkedList() 9 | for _, c := range str1 { 10 | l.InsertToTail(string(c)) 11 | } 12 | l.Print() 13 | t.Log(isPalindrome1(l)) 14 | } 15 | } 16 | 17 | func TestPalindrome2(t *testing.T) { 18 | strs := []string{"heooeh", "hello", "heoeh", "a", ""} 19 | for _, str1 := range strs { 20 | l := NewLinkedList() 21 | for _, c := range str1 { 22 | l.InsertToTail(string(c)) 23 | } 24 | l.Print() 25 | t.Log(isPalindrome2(l)) 26 | l.Print() 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch15_bsearch/BSearchRecursiveTest.scala: -------------------------------------------------------------------------------- 1 | package ch15_bsearch 2 | 3 | import ch12_sorts.QuickSort 4 | import org.scalatest.{FlatSpec, Matchers} 5 | 6 | import scala.util.Random 7 | 8 | class BSearchRecursiveTest extends FlatSpec with Matchers { 9 | 10 | behavior of "BSearchRecursiveTest" 11 | 12 | it should "search with exist value" in { 13 | val length = 50000 14 | val array = new Array[Int](length) 15 | val rnd = new Random() 16 | for (i <- Range(0, length)) { 17 | array(i) = rnd.nextInt() 18 | } 19 | 20 | val target = array(2698) 21 | 22 | BSearchRecursive.search(QuickSort.quickSort(array), target) should be > -1 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/swift/08_stack/Browser.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Jiandan on 2018/10/12. 3 | // Copyright (c) 2018 Jiandan. All rights reserved. 4 | // 5 | 6 | import Foundation 7 | 8 | struct Page { 9 | /// 存储前进 url 10 | private var forwardArray = [String]() 11 | /// 存储后退 url 12 | private var backArray = [String]() 13 | 14 | var currentURL: String? { return forwardArray.last } 15 | 16 | init(url: String) { 17 | forwardArray.append(url) 18 | } 19 | /// 前进 20 | mutating func goForward(url: String) { 21 | forwardArray.append(url) 22 | } 23 | /// 后退 24 | mutating func goBack() { 25 | backArray.append(forwardArray.popLast()!) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch32_matching/BruteForce.scala: -------------------------------------------------------------------------------- 1 | package ch32_matching 2 | 3 | import scala.util.control.Breaks._ 4 | 5 | object BruteForce { 6 | 7 | def firstIndexOf(main: Array[Char], sub: Array[Char]): Int = { 8 | 9 | require(main != null, "main array required") 10 | require(sub != null, "sub array required") 11 | require(main.length >= sub.length, "sub array should be small than main array") 12 | var result = -1 13 | breakable { 14 | for (i <- 0 until (main.length - sub.length)) { 15 | if (main.slice(i, i + sub.length) sameElements sub) { 16 | result = i 17 | break 18 | } 19 | } 20 | } 21 | result 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/swift/08_stack/BrowserDemo.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Jiandan on 2018/10/12. 3 | // Copyright (c) 2018 Jiandan. All rights reserved. 4 | // 5 | 6 | import Foundation 7 | 8 | struct Page { 9 | /// 存储前进 url 10 | private var forwardArray = [String]() 11 | /// 存储后退 url 12 | private var backArray = [String]() 13 | 14 | var currentURL: String { return forwardArray.last! } 15 | 16 | init(url: String) { 17 | forwardArray.append(url) 18 | } 19 | /// 前进 20 | mutating func goForward(url: String) { 21 | forwardArray.append(url) 22 | } 23 | /// 后退 24 | mutating func goBack() { 25 | backArray.append(forwardArray.popLast()!) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/09_queue/list_queue/list_queue.h: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | > File Name: list_queue.h 3 | > Author: jinshaohui 4 | > Mail: jinshaohui789@163.com 5 | > Time: 18-10-13 6 | > Desc: 7 | ************************************************************************/ 8 | 9 | #ifndef LINK_LIST_QUEUE_H 10 | #define LINK_LIST_QUEUE_H 11 | 12 | typedef struct _list_queue_node 13 | { 14 | int data; 15 | struct _list_queue_node *next; 16 | }queue_node; 17 | 18 | typedef struct _list_queue 19 | { 20 | int num; 21 | queue_node *head; 22 | queue_node *tail; 23 | }list_queue; 24 | 25 | #define list_queue_is_empty(queue) ((queue->num) == 0) 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/09_queue/CircularQueue_test.go: -------------------------------------------------------------------------------- 1 | package _9_queue 2 | 3 | import "testing" 4 | 5 | func TestCircularQueue_EnQueue(t *testing.T) { 6 | q := NewCircularQueue(5) 7 | q.EnQueue(1) 8 | q.EnQueue(2) 9 | q.EnQueue(3) 10 | q.EnQueue(4) 11 | q.EnQueue(5) 12 | q.EnQueue(6) 13 | t.Log(q) 14 | } 15 | 16 | func TestCircularQueue_DeQueue(t *testing.T) { 17 | q := NewCircularQueue(5) 18 | q.EnQueue(1) 19 | q.EnQueue(2) 20 | q.EnQueue(3) 21 | q.EnQueue(4) 22 | q.EnQueue(5) 23 | q.EnQueue(6) 24 | t.Log(q) 25 | t.Log(q.DeQueue()) 26 | t.Log(q) 27 | q.EnQueue(5) 28 | t.Log(q) 29 | q.DeQueue() 30 | t.Log(q) 31 | q.DeQueue() 32 | t.Log(q) 33 | q.DeQueue() 34 | t.Log(q) 35 | q.DeQueue() 36 | t.Log(q) 37 | } 38 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/45_bitmap/bitmap.go: -------------------------------------------------------------------------------- 1 | package bitmap 2 | 3 | // BitMap implement bitmap 4 | type BitMap []byte 5 | 6 | // New create BitMap 7 | func New(length uint) BitMap { 8 | return make([]byte, length/8+1) 9 | } 10 | 11 | // Set set value in bitmap 12 | func (b BitMap) Set(value uint) { 13 | byteIndex := value / 8 14 | if byteIndex >= uint(len(b)) { 15 | return 16 | } 17 | bitIndex := value % 8 18 | []byte(b)[byteIndex] |= 1 << bitIndex 19 | } 20 | 21 | // Get check whether value exist or not 22 | func (b BitMap) Get(value uint) bool { 23 | byteIndex := value / 8 24 | if byteIndex >= uint(len(b)) { 25 | return false 26 | } 27 | bitIndex := value % 8 28 | return []byte(b)[byteIndex]&(1< f32 { 4 | if x == 0 || x == 1 { return x as f32; } 5 | 6 | let mut left = 0f32; 7 | let mut right = x as f32; 8 | let mut res = 0f32; 9 | 10 | while left <= right { 11 | let mid: f32 = (right - left) / 2.0 + left; 12 | 13 | if (right - left).abs() < precision { return mid; } 14 | 15 | if mid > x as f32 / mid { 16 | right = mid; 17 | } else { 18 | left = mid; 19 | } 20 | res = mid 21 | } 22 | 23 | res 24 | } 25 | 26 | fn main() { 27 | println!("{:?}", my_sqrt(8, 0.000001)); 28 | } 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch10_recursive/RecursiveDemo.scala: -------------------------------------------------------------------------------- 1 | package ch10_recursive 2 | 3 | import scala.collection.mutable 4 | 5 | object RecursiveDemo { 6 | 7 | def calculateStepWays(steps: Int): Int = { 8 | //use knownResults to avoid duplicated computing 9 | val knownResults = mutable.HashMap.empty[Int, Int] 10 | steps match { 11 | case 1 => 1 12 | case 2 => 2 13 | case _ => knownResults.get(steps) match { 14 | case Some(result) => result 15 | case None => { 16 | val result = calculateStepWays(steps - 1) + calculateStepWays(steps - 2) 17 | knownResults.put(steps, result) 18 | result 19 | } 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/notes/20_hashtable/readme.md: -------------------------------------------------------------------------------- 1 | # 散列表 2 | 3 | 散列表和链表的组合?为什么呢? 4 | 5 | * 链表:涉及查找的操作慢,不连续存储; 6 | * 顺序表:支持随机访问,连续存储。 7 | 8 | 散列表 + 链表:结合优点、规避缺点。 9 | 10 | ## 结合散列表的 LRU 缓存淘汰算法 11 | 12 | 缓存的操作接口: 13 | 14 | * 向缓存添加数据 15 | * 从缓存删除数据 16 | * 在缓存中查找数据 17 | 18 | 然而——不管是添加还是删除,都涉及到查找数据。因此,单纯的链表效率低下。 19 | 20 | 魔改一把! 21 | 22 | ![](https://static001.geekbang.org/resource/image/ea/6e/eaefd5f4028cc7d4cfbb56b24ce8ae6e.jpg) 23 | 24 | * `prev` 和 `next`:双向链表——LRU 的链表 25 | * `hnext`:单向链表——解决散列冲突的链表 26 | 27 | 操作: 28 | 29 | * 在缓存中查找数据:利用散列表 30 | * 从缓存中删除数据:先利用散列表寻找数据,然后删除——改链表就好了,效率很高 31 | * 向缓存中添加数据:先利用散列表寻找数据,如果找到了,LRU 更新;如果没找到,直接添加在 LRU 链表尾部 32 | 33 | ## Java: LinkedHashMap 34 | 35 | 遍历时,按照访问顺序遍历。实现结构,与上述 LRU 的结构完全相同——只不过它不是缓存,不限制容量大小。 36 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/11_sorts/selection_sort.rs: -------------------------------------------------------------------------------- 1 | /// 选择排序 2 | /// 时间复杂度:O(n2),原地排序算法, 不稳定排序算法 3 | // 选择排序 4 | fn selection_sort(mut nums: Vec) -> Vec { 5 | if nums.is_empty() { return vec![]; } 6 | 7 | for i in 0..nums.len() { 8 | let mut mini_index = i; 9 | // 查找最小 index 10 | for j in i+1..nums.len() { 11 | if nums[j] < nums[mini_index] { 12 | mini_index = j; 13 | } 14 | } 15 | // 交换数据 16 | let tmp = nums[i]; 17 | nums[i] = nums[mini_index]; 18 | nums[mini_index] = tmp; 19 | } 20 | nums 21 | } 22 | 23 | fn main() { 24 | let nums = vec![4, 5, 6, 1, 2, 3]; 25 | println!("{:?}", selection_sort(nums)); 26 | } 27 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/24_binary_tree/insert_in_binary_tree.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/insert-into-a-binary-search-tree/ 2 | use super::util::tree::{TreeNode, to_tree}; 3 | 4 | pub fn insert_into_bst(root: Option>>, val: i32) -> Option>> { 5 | insert(&root, val); 6 | root 7 | } 8 | fn insert(node: &Option>>, val: i32) { 9 | if let Some(n) = node { 10 | let mut n = n.borrow_mut(); 11 | let target = if val > n.val { &mut n.right } else { &mut n.left }; 12 | 13 | if target.is_some() { 14 | return insert(target, val); 15 | } 16 | 17 | *target = Some(Rc::new(RefCell::new(TreeNode::new(val)))); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch09_queue/DemoQueueTest.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | abstract class DemoQueueTest extends FlatSpec with Matchers { 6 | 7 | def getInstance(): DemoQueue[Int] 8 | 9 | behavior of "test" 10 | 11 | it should "dequeue nothing for empty queue" in { 12 | val queue = getInstance() 13 | assert(queue.dequeue().isEmpty) 14 | } 15 | 16 | it should "enqueue/dequeue should be FIFO" in { 17 | val queue = getInstance() 18 | for (i <- Range(0, 10)) { 19 | queue.enqueue(i) 20 | } 21 | 22 | queue.size should equal(10) 23 | 24 | for (i <- Range(0, 10)) { 25 | queue.dequeue().get should equal(i) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/chapter-8-recursion-and-Dynamic-Programming/8-1-Triple-Step.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int countWays(int n , vector v){ 7 | 8 | if (n==0){ 9 | return 1; 10 | } 11 | 12 | int sum = 0; 13 | 14 | for (int i = 0; i < v.size(); ++i) 15 | { 16 | if(n>=v[i]){ 17 | sum = sum + countWays((n-v[i]),v); 18 | } 19 | } 20 | return sum; 21 | } 22 | 23 | int main(int argc, char const *argv[]) 24 | { 25 | 26 | vector v; // vector to store possible step sizes 27 | v.push_back(1); 28 | v.push_back(2); 29 | v.push_back(3); 30 | 31 | int noOfWays = countWays(6,v); 32 | cout< 6 | #include 7 | #include 8 | 9 | #include "quick_sort.hpp" 10 | 11 | void test_quick_sort(std::vector test_data) { 12 | quick_sort(test_data.begin(), test_data.end()); 13 | std::transform(test_data.begin(), test_data.end(), 14 | std::ostream_iterator(std::cout, " "), [](int i){ return i; }); 15 | std::cout << '\n'; 16 | } 17 | 18 | int main() { 19 | test_quick_sort({-3, -1, 1, -2, -3, 0, -3, 100, 1, 1, -100}); 20 | test_quick_sort({1, 1, 1}); 21 | test_quick_sort({1, 0, -1}); 22 | test_quick_sort({1}); 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/Tests/_06_linkedlist_tests/algo06_linkedlist_tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/06_linkedlist/Dlist/Dlist.h: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | > File Name: Dlist.c 3 | > Author: jinshaohui 4 | > Mail: jinshaohui789@163.com 5 | > Time: 18-10-07 6 | > Desc: 7 | ************************************************************************/ 8 | #include 9 | 10 | typedef struct DlistNode //双向链表中每一个节点 11 | { 12 | struct DlistNode *prev; //节点前项指针 13 | struct DlistNode *next; //节点后项指针 14 | int data; //数据 15 | }stDlistNode; 16 | 17 | typedef struct Dlisthead //定义链表总体 18 | { 19 | int size; //链表长度 20 | stDlistNode *head; //头指针 21 | stDlistNode *tail; //尾部指针 22 | }stDlistHead; 23 | 24 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch09_queue/CircularQueue.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | import scala.reflect.ClassTag 4 | 5 | class CircularQueue[T: ClassTag](capacity: Int) extends DemoQueue[T] { 6 | 7 | var items: Array[T] = new Array[T](capacity) 8 | var head = 0 9 | var tail = 0 10 | 11 | 12 | override def enqueue(data: T): Unit = { 13 | require((tail + 1) % capacity != head, "queue is full") 14 | items(tail) = data 15 | tail = (tail + 1) % capacity 16 | size += 1 17 | } 18 | 19 | override def dequeue(): Option[T] = { 20 | if (head == tail) { 21 | None 22 | } else { 23 | size -= 1 24 | val result = Some(items(head)) 25 | head = (head + 1) % capacity 26 | result 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/09_queue/array_queue/array_queue.h: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | > File Name: array_queue.h 3 | > Author: jinshaohui 4 | > Mail: jinshaohui789@163.com 5 | > Time: 18-10-12 6 | > Desc: 7 | ************************************************************************/ 8 | #ifndef ARRAY_QUEUE_H 9 | #define ARRAY_QUEUE_H 10 | 11 | typedef struct _array_queue 12 | { 13 | int size;/*队列的大小*/ 14 | int num; /*当前存储数据的大小*/ 15 | int head;/*队列的头*/ 16 | int tail;/*队列的尾*/ 17 | int *array;/*数据存储区*/ 18 | }array_queue; 19 | 20 | #define array_queue_is_empty(array_queue) (array_queue->num == 0) 21 | #define array_queue_is_full(array_queue) ((array_queue->num) == (array_queue->size)) 22 | 23 | #endif 24 | 25 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/chapter-8-recursion-and-Dynamic-Programming/8-11-Coins.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int ways(int amount, vector denom){ 6 | 7 | if (!amount){ 8 | return 1; 9 | } 10 | 11 | int n = denom.size(); 12 | if(n==1){ 13 | if(amount%denom[0]) 14 | return 0; 15 | else 16 | return 1; 17 | } 18 | int curr = denom[n-1]; 19 | int sum = 0; 20 | denom.pop_back(); 21 | sum += ways(amount,denom); 22 | while(amount>=curr){ 23 | sum += ways(amount-curr,denom); 24 | amount = amount-curr; 25 | } 26 | return sum; 27 | } 28 | 29 | int main(){ 30 | int amount = 8; 31 | vector denom; 32 | denom.push_back(2); 33 | denom.push_back(3); 34 | 35 | cout< 5 | #include 6 | typedef char ElemType; 7 | typedef struct LNode 8 | { 9 | ElemType data; 10 | struct LNode*next; 11 | }LinkList; 12 | 13 | void CreateListHead(LinkList *&L,ElemType a[],int n); 14 | void CreateListTail(LinkList *&L,ElemType a[],int n); 15 | void InitList(LinkList *&L); 16 | void DestroyList(LinkList *&L); 17 | bool ListEmpty(LinkList *L); 18 | int ListLength(LinkList *L); 19 | void ShowList(LinkList *L); 20 | bool GetListElem(LinkList *L,int i,ElemType &e); 21 | int LocateElem(LinkList*L,ElemType e); 22 | bool ListInsert(LinkList *&L,int i,ElemType e); 23 | bool ListDelete(LinkList *&L,int i,ElemType &e); 24 | #endif 25 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/12_sorts/QuickSort.go: -------------------------------------------------------------------------------- 1 | package _2_sorts 2 | 3 | // QuickSort is quicksort methods for golang 4 | func QuickSort(arr []int) { 5 | separateSort(arr, 0, len(arr)-1) 6 | } 7 | 8 | func separateSort(arr []int, start, end int) { 9 | if start >= end { 10 | return 11 | } 12 | i := partition(arr, start, end) 13 | separateSort(arr, start, i-1) 14 | separateSort(arr, i+1, end) 15 | } 16 | 17 | func partition(arr []int, start, end int) int { 18 | // 选取最后一位当对比数字 19 | pivot := arr[end] 20 | 21 | var i = start 22 | for j := start; j < end; j++ { 23 | if arr[j] < pivot { 24 | if !(i == j) { 25 | // 交换位置 26 | arr[i], arr[j] = arr[j], arr[i] 27 | } 28 | i++ 29 | } 30 | } 31 | 32 | arr[i], arr[end] = arr[end], arr[i] 33 | 34 | return i 35 | } 36 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch08_stack/StackDemoTest.scala: -------------------------------------------------------------------------------- 1 | package ch08_stack 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | class StackDemoTest extends FlatSpec with Matchers { 6 | 7 | behavior of "StackDemoTest" 8 | 9 | it should "push/pop should be FILO" in { 10 | val stack = new StackDemo[String] 11 | val num = 100 12 | for (i <- 1 to num) { 13 | stack.push(i.toString) 14 | } 15 | 16 | for (i <- num to 1 by -1) { 17 | stack.pop().get.data should equal(i.toString) 18 | } 19 | } 20 | 21 | it should "pop should also work for empty stack" in { 22 | val stack = new StackDemo[Int] 23 | val num = 100 24 | for (i <- num to 1 by -1) { 25 | assert(stack.pop().isEmpty) 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/08_stack/arrayStack/arrayStack.h: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | > File Name: arrayStack.h 3 | > Author: jinshaohui 4 | > Mail: jinshaohui789@163.com 5 | > Time: 18-10-12 6 | > Desc: 7 | ************************************************************************/ 8 | 9 | #ifndef ARRAY_STACJ_H 10 | #define ARRAY_STACJ_H 11 | 12 | typedef struct _array_stack 13 | { 14 | int size;/*栈的大小*/ 15 | int pos;/*当前存储元素的个数,即栈顶元素下表*/ 16 | int *array;/*数据存储区*/ 17 | }stArrayStack; 18 | 19 | #define arrayStack_size(arrayStack) (arrayStack->size) 20 | #define arrayStack_is_empty(arrayStack) (arrayStack->pos == -1) 21 | #define arrayStack_is_full(arrayStack) (arrayStack->pos == (arrayStack->size-1)) 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/11_sorts/insertion_sort.rs: -------------------------------------------------------------------------------- 1 | /// 插入排序 2 | /// 时间复杂度:O(n2),原地排序算法, 稳定排序算法 3 | // 插入排序 4 | fn insertion_sort(mut nums: Vec) -> Vec { 5 | if nums.is_empty() { return vec![]; } 6 | 7 | for i in 1..nums.len() { 8 | let value = nums[i]; 9 | let mut j = (i - 1) as i32; 10 | // 查找要插入的位置并移动数据 11 | while j >= 0 { 12 | if nums[j as usize] > value { 13 | nums[(j+1) as usize] = nums[j as usize]; 14 | } else { 15 | break; 16 | } 17 | j -= 1; 18 | } 19 | nums[(j+1) as usize] = value; 20 | } 21 | nums 22 | } 23 | 24 | fn main() { 25 | let nums = vec![4, 5, 6, 1, 2, 3]; 26 | println!("{:?}", insert_on_sort(nums)); 27 | } 28 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch20_linked_hash_map/LRUCacheTest.scala: -------------------------------------------------------------------------------- 1 | package ch20_linked_hash_map 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | class LRUCacheTest extends FlatSpec with Matchers { 6 | 7 | behavior of "LRUCacheTest" 8 | 9 | it should "put data and get back" in { 10 | val cache = new LRUCache[Int, Int](2) 11 | cache.put(1, 1) 12 | cache.put(2, 2) 13 | cache.get(1) should equal(Some(1)) // returns 1 14 | cache.put(3, 3) // evicts key 2 15 | cache.get(2) should equal(None) //should not find 16 | cache.put(4, 4) // evicts key 1 17 | cache.get(1) should equal(None) //should not find 18 | cache.get(3) should equal(Some(3)) // returns 3 19 | cache.get(4) should equal(Some(4)) // returns 4 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/chapter-8-recursion-and-Dynamic-Programming/8-7-Permutations-without-Dups.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void findPermutations(string s, string curr,vector& res){ 8 | 9 | int n = s.size(); 10 | if (!n) 11 | { 12 | res.push_back(curr); 13 | return; 14 | } 15 | 16 | for (int i = 0; i < n; ++i) 17 | { 18 | string first = curr+s.substr(i,1); 19 | string rem = s.substr(0,i) + s.substr(i+1,n-i-1); 20 | findPermutations(rem,first,res); 21 | } 22 | } 23 | 24 | int main() 25 | { 26 | string s = "abc"; 27 | string curr =""; 28 | vector res; 29 | findPermutations(s,curr,res); 30 | for (int i = 0; i < res.size(); ++i) 31 | cout< 0) { 22 | queue.dequeue() 23 | queue += item 24 | } 25 | } 26 | 27 | def get(): List[Int] = { 28 | queue.clone().dequeueAll 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch29_heap_solutions/MiddleNumberKeeperTest.scala: -------------------------------------------------------------------------------- 1 | package ch29_heap_solutions 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | class MiddleNumberKeeperTest extends FlatSpec with Matchers { 6 | 7 | behavior of "MiddleNumberKeeperTest" 8 | 9 | it should "get middle of the array" in { 10 | val numKeeper = new MiddleNumberKeeper() 11 | for (i <- Range(0, 10)) { 12 | numKeeper.put(i) 13 | } 14 | 15 | numKeeper.get().get should equal(4) 16 | } 17 | 18 | it should "get 90% position of the array" in { 19 | val numKeeper = new MiddleNumberKeeper(0.9) 20 | for (i <- Range(0, 9)) { 21 | numKeeper.put(i) 22 | } 23 | numKeeper.put(9) 24 | 25 | numKeeper.get().get should equal(8) 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/08_stack/StackBasedOnLinkedList_test.go: -------------------------------------------------------------------------------- 1 | package _8_stack 2 | 3 | import "testing" 4 | 5 | func TestLinkedListStack_Push(t *testing.T) { 6 | s := NewLinkedListStack() 7 | s.Push(1) 8 | s.Push(2) 9 | s.Push(3) 10 | s.Print() 11 | } 12 | 13 | func TestLinkedListStack_Pop(t *testing.T) { 14 | s := NewLinkedListStack() 15 | s.Push(1) 16 | s.Push(2) 17 | s.Push(3) 18 | s.Print() 19 | 20 | t.Log(s.Pop()) 21 | t.Log(s.Pop()) 22 | t.Log(s.Pop()) 23 | t.Log(s.Pop()) 24 | s.Print() 25 | } 26 | 27 | func TestLinkedListStack_Top(t *testing.T) { 28 | s := NewLinkedListStack() 29 | s.Push(1) 30 | s.Push(2) 31 | s.Push(3) 32 | 33 | t.Log(s.Top()) 34 | s.Pop() 35 | t.Log(s.Top()) 36 | s.Pop() 37 | t.Log(s.Top()) 38 | s.Pop() 39 | t.Log(s.Top()) 40 | s.Pop() 41 | } 42 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/42_dynamic_programming/longest_increasing_subsequence.rs: -------------------------------------------------------------------------------- 1 | // leetcode 300 [longest_increasing_subsequence](https://leetcode.com/problems/longest-increasing-subsequence) 2 | fn longest_increasing_subsequence(nums: Vec) -> i32 { 3 | if nums.len() <= 1 { return nums.len() as i32; } 4 | 5 | let mut dp = vec![1; nums.len()]; 6 | let mut max_list = 1; 7 | 8 | for i in 0..nums.len() { 9 | for j in 0..i { 10 | if nums[i] > nums[j] { 11 | dp[i] = dp[i].max(dp[j]+1); 12 | } 13 | } 14 | max_list = max_list.max(dp[i]); 15 | } 16 | max_list 17 | } 18 | fn main() { 19 | let nums = vec![2, 9, 3, 6, 5, 1, 7]; 20 | let m = longest_increasing_subsequence(nums); 21 | println!("{:?}", m); 22 | } 23 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/06_linkedlist/SingleLinkedListNode.php: -------------------------------------------------------------------------------- 1 | data = $data; 42 | $this->next = null; 43 | } 44 | } -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/11_sorts/bubble_sort.rs: -------------------------------------------------------------------------------- 1 | /// 冒泡排序 2 | /// 时间复杂度:O(n2),原地排序算法, 稳定排序算法 3 | // 冒泡排序 4 | fn bubble_sort(mut nums: Vec) -> Vec { 5 | if nums.is_empty() { return vec![]; } 6 | 7 | let n = nums.len(); 8 | for i in 0..n { 9 | // 提前退出标志 10 | let mut swap = false; 11 | for j in 0..n-i-1 { 12 | if nums[j] > nums[j+1] { 13 | // 此次冒泡有数据交换 14 | swap = true; 15 | let tmp = nums[j]; 16 | nums[j] = nums[j+1]; 17 | nums[j+1] = tmp; 18 | } 19 | } 20 | // 若没有数据交换,提前退出 21 | if !swap { break; } 22 | } 23 | nums 24 | } 25 | 26 | fn main() { 27 | let nums = vec![4, 5, 6, 1, 2, 3]; 28 | println!("{:?}", bubble_sort(nums)); 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/jump_game/__test__/greedyJumpGame.test.js: -------------------------------------------------------------------------------- 1 | import greedyJumpGame from '../greedyJumpGame'; 2 | 3 | describe('greedyJumpGame', () => { 4 | it('should solve Jump Game problem in greedy manner', () => { 5 | expect(greedyJumpGame([1, 0])).toBe(true); 6 | expect(greedyJumpGame([100, 0])).toBe(true); 7 | expect(greedyJumpGame([2, 3, 1, 1, 4])).toBe(true); 8 | expect(greedyJumpGame([1, 1, 1, 1, 1])).toBe(true); 9 | expect(greedyJumpGame([1, 1, 1, 10, 1])).toBe(true); 10 | expect(greedyJumpGame([1, 5, 2, 1, 0, 2, 0])).toBe(true); 11 | 12 | expect(greedyJumpGame([1, 0, 1])).toBe(false); 13 | expect(greedyJumpGame([3, 2, 1, 0, 4])).toBe(false); 14 | expect(greedyJumpGame([0, 0, 0, 0, 0])).toBe(false); 15 | expect(greedyJumpGame([5, 4, 3, 2, 1, 0, 0])).toBe(false); 16 | }); 17 | }); 18 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch29_heap_solutions/TopKItemsKeeperTest.scala: -------------------------------------------------------------------------------- 1 | package ch29_heap_solutions 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | import scala.util.Random 6 | 7 | class TopKItemsKeeperTest extends FlatSpec with Matchers { 8 | 9 | behavior of "TopKItemsKeeperTest" 10 | 11 | it should "put and get top K from the keeper" in { 12 | val length = 50 13 | val k = 5 14 | val topKItemsKeeper = new TopKItemsKeeper(k) 15 | val nums = new Array[Int](length) 16 | for (i <- Range(0, length)) { 17 | nums(i) = Random.nextInt 18 | } 19 | 20 | nums.foreach(topKItemsKeeper.put) 21 | val ordering = scala.math.Ordering.Int.reverse 22 | topKItemsKeeper.get().toArray.sorted(ordering) should equal(nums.sorted(ordering).slice(0, k)) 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/javascript/15_binary/binaryFind.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 二分查找 3 | * 4 | * Author: nameczz 5 | */ 6 | // 数组必须有序 不存在重复 7 | const biaryFind = (sortedArr, target) => { 8 | if (sortedArr.length === 0) return -1 9 | let low = 0 10 | let high = sortedArr.length - 1 11 | while (low <= high) { 12 | const mid = Math.floor((low + high) / 2) 13 | if (target === sortedArr[mid]) { 14 | return mid 15 | } else if (target < sortedArr[mid]) { 16 | high = mid - 1 17 | } else { 18 | low = mid + 1 19 | } 20 | } 21 | return -1 22 | } 23 | const arr = [1, 4, 5, 6, 7, 8, 10, 11, 23, 42, 44, 54, 56, 77, 102] 24 | console.log(biaryFind(arr, 44)) 25 | console.log(biaryFind(arr, 1)) 26 | console.log(biaryFind(arr, 102)) 27 | console.log(biaryFind(arr, 1111)) -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/kotlin/08_stack/StackBasedOnLinkedList.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * 基于链表实现的栈。 3 | * 4 | * Author: Zackratos 5 | */ 6 | 7 | class StackBasedOnLinkedList { 8 | 9 | private var top: Node? = null 10 | 11 | fun push(value: Int) { 12 | val newNode = Node(value, null) 13 | // 不管 top 是不是 null,都可以这么写 14 | newNode.next = top 15 | top = newNode 16 | } 17 | 18 | fun pop(): Int { 19 | if (top == null) return -1 20 | val node = top 21 | top = top!!.next 22 | return node!!.data 23 | } 24 | 25 | fun printAll() { 26 | var p = top 27 | while (p != null) { 28 | print("${p.data} ") 29 | p = p.next 30 | } 31 | println() 32 | } 33 | 34 | class Node(var data: Int, var next: Node?) 35 | 36 | } -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/chapter-8-recursion-and-Dynamic-Programming/8-9-parens.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void print_all_parentheses_internal(size_t count, size_t opened, size_t closed, std::string arangement){ 5 | 6 | if(closed > opened){ 7 | return; 8 | } 9 | else if(opened > count){ 10 | return; 11 | } 12 | else if(arangement.size()==2*count){ 13 | std::cout << arangement << std::endl; 14 | } 15 | 16 | print_all_parentheses_internal(count,opened+1,closed, arangement+"("); 17 | print_all_parentheses_internal(count,opened ,closed+1,arangement+")"); 18 | } 19 | 20 | void print_all_parentheses(size_t count){ 21 | print_all_parentheses_internal(count, 0, 0, ""); 22 | } 23 | 24 | int main(int argc, const char* argv[]) { 25 | print_all_parentheses(3); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/typescript/14_binarysearch/BinarySearch.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * 二分查找适合于连续内存的数组查找 3 | * 并且是已经排好序的数组 4 | * 时间复杂度只有log(n) 5 | */ 6 | class BinarySearch { 7 | static bSearch(array: number[], target: number) { 8 | if (!array || array.length === 0) return -1 9 | const length = array.length 10 | let low = 0 11 | let high = length - 1 12 | while (low <= high) { 13 | // 一定是整数,这边的移位运算优先级低于+,-运算符,需要加括号 14 | const mid = low + ((high - low) >> 1) 15 | if (array[mid] === target) { 16 | return mid 17 | } else if (array[mid] > target) { 18 | high = mid - 1 19 | } else { 20 | low = mid + 1 21 | } 22 | } 23 | return -1 24 | } 25 | } 26 | 27 | const testBinarySearch = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 28 | console.log(BinarySearch.bSearch(testBinarySearch, 10)) 29 | -------------------------------------------------------------------------------- /leetcode/recursive_staircase/__test__/recursiveStaircaseIT.test.js: -------------------------------------------------------------------------------- 1 | import recursiveStaircaseIT from '../recursiveStaircaseIT'; 2 | 3 | describe('recursiveStaircaseIT', () => { 4 | it('should calculate number of variants using Iterative solution', () => { 5 | expect(recursiveStaircaseIT(-1)).toBe(0); 6 | expect(recursiveStaircaseIT(0)).toBe(0); 7 | expect(recursiveStaircaseIT(1)).toBe(1); 8 | expect(recursiveStaircaseIT(2)).toBe(2); 9 | expect(recursiveStaircaseIT(3)).toBe(3); 10 | expect(recursiveStaircaseIT(4)).toBe(5); 11 | expect(recursiveStaircaseIT(5)).toBe(8); 12 | expect(recursiveStaircaseIT(6)).toBe(13); 13 | expect(recursiveStaircaseIT(7)).toBe(21); 14 | expect(recursiveStaircaseIT(8)).toBe(34); 15 | expect(recursiveStaircaseIT(9)).toBe(55); 16 | expect(recursiveStaircaseIT(10)).toBe(89); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /leetcode/recursive_staircase/__test__/recursiveStaircaseBF.test.js: -------------------------------------------------------------------------------- 1 | import recursiveStaircaseBF from '../recursiveStaircaseBF'; 2 | 3 | describe('recursiveStaircaseBF', () => { 4 | it('should calculate number of variants using Brute Force solution', () => { 5 | expect(recursiveStaircaseBF(-1)).toBe(0); 6 | expect(recursiveStaircaseBF(0)).toBe(0); 7 | expect(recursiveStaircaseBF(1)).toBe(1); 8 | expect(recursiveStaircaseBF(2)).toBe(2); 9 | expect(recursiveStaircaseBF(3)).toBe(3); 10 | expect(recursiveStaircaseBF(4)).toBe(5); 11 | expect(recursiveStaircaseBF(5)).toBe(8); 12 | expect(recursiveStaircaseBF(6)).toBe(13); 13 | expect(recursiveStaircaseBF(7)).toBe(21); 14 | expect(recursiveStaircaseBF(8)).toBe(34); 15 | expect(recursiveStaircaseBF(9)).toBe(55); 16 | expect(recursiveStaircaseBF(10)).toBe(89); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/08_stack/StackBasedOnArray_test.go: -------------------------------------------------------------------------------- 1 | package _8_stack 2 | 3 | import "testing" 4 | 5 | func TestArrayStack_Push(t *testing.T) { 6 | s := NewArrayStack() 7 | s.Push(1) 8 | s.Push(2) 9 | t.Log(s.Pop()) 10 | s.Push(3) 11 | t.Log(s.Pop()) 12 | t.Log(s.Pop()) 13 | s.Push(4) 14 | t.Log(s.Pop()) 15 | s.Print() 16 | } 17 | 18 | func TestArrayStack_Pop(t *testing.T) { 19 | s := NewArrayStack() 20 | s.Push(1) 21 | s.Push(2) 22 | s.Push(3) 23 | s.Print() 24 | 25 | t.Log(s.Pop()) 26 | t.Log(s.Pop()) 27 | t.Log(s.Pop()) 28 | t.Log(s.Pop()) 29 | s.Print() 30 | } 31 | 32 | func TestArrayStack_Top(t *testing.T) { 33 | s := NewArrayStack() 34 | s.Push(1) 35 | s.Push(2) 36 | s.Push(3) 37 | 38 | t.Log(s.Top()) 39 | s.Pop() 40 | t.Log(s.Top()) 41 | s.Pop() 42 | t.Log(s.Top()) 43 | s.Pop() 44 | t.Log(s.Top()) 45 | s.Pop() 46 | } 47 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch39_back_tracking/BagWeight.scala: -------------------------------------------------------------------------------- 1 | package ch39_back_tracking 2 | 3 | class BagWeight(maxBagItemCount: Int, maxBagWeight: Int) { 4 | 5 | def calculateMaxWeight(items: Array[Int]): Int = { 6 | var maxWeight = 0 7 | 8 | def _calcMaxWeight(itemIndex: Int, currentWeight: Int): Unit = { 9 | if (currentWeight == maxBagWeight || itemIndex == items.length) { 10 | if (currentWeight > maxWeight) { 11 | maxWeight = currentWeight 12 | } 13 | } else { 14 | //check next item 15 | _calcMaxWeight(itemIndex + 1, currentWeight) 16 | if (currentWeight + items(itemIndex) <= maxBagWeight) { 17 | _calcMaxWeight(itemIndex + 1, currentWeight + items(itemIndex)) 18 | } 19 | } 20 | } 21 | 22 | _calcMaxWeight(0, 0) 23 | maxWeight 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/recursive_staircase/__test__/recursiveStaircaseDP.test.js: -------------------------------------------------------------------------------- 1 | import recursiveStaircaseDP from '../recursiveStaircaseDP'; 2 | 3 | describe('recursiveStaircaseDP', () => { 4 | it('should calculate number of variants using Dynamic Programming solution', () => { 5 | expect(recursiveStaircaseDP(-1)).toBe(0); 6 | expect(recursiveStaircaseDP(0)).toBe(0); 7 | expect(recursiveStaircaseDP(1)).toBe(1); 8 | expect(recursiveStaircaseDP(2)).toBe(2); 9 | expect(recursiveStaircaseDP(3)).toBe(3); 10 | expect(recursiveStaircaseDP(4)).toBe(5); 11 | expect(recursiveStaircaseDP(5)).toBe(8); 12 | expect(recursiveStaircaseDP(6)).toBe(13); 13 | expect(recursiveStaircaseDP(7)).toBe(21); 14 | expect(recursiveStaircaseDP(8)).toBe(34); 15 | expect(recursiveStaircaseDP(9)).toBe(55); 16 | expect(recursiveStaircaseDP(10)).toBe(89); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/python/45_bitmap/bitmap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Wenru Dong 3 | """ 4 | 5 | from typing import Optional 6 | 7 | class Bitmap: 8 | def __init__(self, num_bits: int): 9 | self._num_bits = num_bits 10 | self._bytes = bytearray(num_bits // 8 + 1) 11 | 12 | def setbit(self, k: int) -> None: 13 | if k > self._num_bits or k < 1: return 14 | self._bytes[k // 8] |= (1 << k % 8) 15 | 16 | def getbit(self, k: int) -> Optional[bool]: 17 | if k > self._num_bits or k < 1: return 18 | return self._bytes[k // 8] & (1 << k % 8) != 0 19 | 20 | 21 | if __name__ == "__main__": 22 | bitmap = Bitmap(10) 23 | bitmap.setbit(1) 24 | bitmap.setbit(3) 25 | bitmap.setbit(6) 26 | bitmap.setbit(7) 27 | bitmap.setbit(8) 28 | 29 | for i in range(1, 11): 30 | print(bitmap.getbit(i)) -------------------------------------------------------------------------------- /leetcode/decode_string/ts/main.recursion.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @file 文件描述 3 | * @description 详细说明 4 | * 5 | * @author 王下邀月熊 <384924552@qq.com> 6 | * 7 | * Created Date: Sun, 2018-07-15 22:18:26 8 | * 9 | * Last Modified: Sun, 2018-07-15 22:44:31 10 | * Last Modified By: 王下邀月熊 <384924552@qq.com> 11 | * 12 | * This code is licensed under the MIT License. 13 | */ 14 | const reg = /(\d*)\[([a-z]*)\]/i; 15 | 16 | export const decodeStr = str => { 17 | const match = reg.exec(str); 18 | 19 | // 无匹配则返回 20 | if (!match) { 21 | return str; 22 | } 23 | 24 | // 进行字符串匹配生成 25 | let repeatedStr = ''; 26 | const [matchedStr, num, repeatStr] = match; 27 | 28 | Array.from({ 29 | length: parseInt(num, 10) 30 | }).forEach(() => { 31 | repeatedStr += repeatStr; 32 | }); 33 | 34 | // 进行递归提取 35 | return decodeStr(str.replace(matchedStr, repeatedStr)); 36 | }; 37 | -------------------------------------------------------------------------------- /leetcode/jump_game/__test__/dpTopDownJumpGame.test.js: -------------------------------------------------------------------------------- 1 | import dpTopDownJumpGame from '../dpTopDownJumpGame'; 2 | 3 | describe('dpTopDownJumpGame', () => { 4 | it('should solve Jump Game problem in top-down dynamic programming manner', () => { 5 | expect(dpTopDownJumpGame([1, 0])).toBe(true); 6 | expect(dpTopDownJumpGame([100, 0])).toBe(true); 7 | expect(dpTopDownJumpGame([2, 3, 1, 1, 4])).toBe(true); 8 | expect(dpTopDownJumpGame([1, 1, 1, 1, 1])).toBe(true); 9 | expect(dpTopDownJumpGame([1, 1, 1, 10, 1])).toBe(true); 10 | expect(dpTopDownJumpGame([1, 5, 2, 1, 0, 2, 0])).toBe(true); 11 | 12 | expect(dpTopDownJumpGame([1, 0, 1])).toBe(false); 13 | expect(dpTopDownJumpGame([3, 2, 1, 0, 4])).toBe(false); 14 | expect(dpTopDownJumpGame([0, 0, 0, 0, 0])).toBe(false); 15 | expect(dpTopDownJumpGame([5, 4, 3, 2, 1, 0, 0])).toBe(false); 16 | }); 17 | }); 18 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/python/28_binary_heap/top_k.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | 4 | import random 5 | from heap import MinHeap 6 | 7 | 8 | def top_k(nums, k): 9 | """ 10 | 返回数组的前k大元素 11 | :param nums: 12 | :param k: 13 | :return: 14 | """ 15 | if len(nums) <= k: 16 | return nums 17 | 18 | min_h = MinHeap(nums[:k], k) 19 | for i in range(k, len(nums)): 20 | tmp = min_h.get_top() 21 | if nums[i] > tmp: 22 | min_h.remove_top() 23 | min_h.insert(nums[i]) 24 | 25 | return min_h.get_data() 26 | 27 | 28 | if __name__ == '__main__': 29 | nums = [] 30 | k = 3 31 | 32 | for i in range(20): 33 | nums.append(random.randint(1, 100)) 34 | 35 | print('--- nums ---') 36 | print(nums) 37 | 38 | print('--- top {} ---'.format(k)) 39 | print(top_k(nums, k)) 40 | -------------------------------------------------------------------------------- /leetcode/recursive_staircase/__test__/recursiveStaircaseMEM.test.js: -------------------------------------------------------------------------------- 1 | import recursiveStaircaseMEM from '../recursiveStaircaseMEM'; 2 | 3 | describe('recursiveStaircaseMEM', () => { 4 | it('should calculate number of variants using Brute Force with Memoization', () => { 5 | expect(recursiveStaircaseMEM(-1)).toBe(0); 6 | expect(recursiveStaircaseMEM(0)).toBe(0); 7 | expect(recursiveStaircaseMEM(1)).toBe(1); 8 | expect(recursiveStaircaseMEM(2)).toBe(2); 9 | expect(recursiveStaircaseMEM(3)).toBe(3); 10 | expect(recursiveStaircaseMEM(4)).toBe(5); 11 | expect(recursiveStaircaseMEM(5)).toBe(8); 12 | expect(recursiveStaircaseMEM(6)).toBe(13); 13 | expect(recursiveStaircaseMEM(7)).toBe(21); 14 | expect(recursiveStaircaseMEM(8)).toBe(34); 15 | expect(recursiveStaircaseMEM(9)).toBe(55); 16 | expect(recursiveStaircaseMEM(10)).toBe(89); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/23_binarytree/tree/list_queue.h: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | > File Name: list_queue.h 3 | > Author: jinshaohui 4 | > Mail: jinshaohui789@163.com 5 | > Time: 18-10-13 6 | > Desc: 7 | ************************************************************************/ 8 | 9 | #ifndef LINK_LIST_QUEUE_H 10 | #define LINK_LIST_QUEUE_H 11 | 12 | typedef struct _list_queue_node 13 | { 14 | void *data; 15 | struct _list_queue_node *next; 16 | }queue_node; 17 | 18 | typedef struct _list_queue 19 | { 20 | int num; 21 | queue_node *head; 22 | queue_node *tail; 23 | }list_queue; 24 | 25 | #define list_queue_is_empty(queue) ((queue->num) == 0) 26 | list_queue *list_queue_create(); 27 | int list_queue_enqueue(list_queue *queue,void *data); 28 | int list_queue_dequeue(list_queue *queue,void **data); 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/05_array/array_test.php: -------------------------------------------------------------------------------- 1 | insert($i, $i+1); 12 | } 13 | $myArr1->printData(); 14 | 15 | $code = $myArr1->insert(6, 999); 16 | echo "insert at 6: code:{$code}\n"; 17 | $myArr1->printData(); 18 | 19 | list($code, $value) = $myArr1->delete(6); 20 | echo "delete at 6: code:{$code}, value:{$value}\n"; 21 | $myArr1->printData(); 22 | 23 | $code = $myArr1->insert(11, 999); 24 | echo "insert at 11: code:{$code}\n"; 25 | $myArr1->printData(); 26 | 27 | list($code, $value) = $myArr1->delete(0); 28 | echo "delete at 0: code:{$code}, value:{$value}\n"; 29 | $myArr1->printData(); 30 | 31 | list($code, $value) = $myArr1->find(0); 32 | echo "find at 0: code:{$code}, value:{$value}\n"; -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/07_linkedlist/util/linked_list.rs: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | #[derive(PartialEq, Eq, Clone, Debug)] 3 | pub struct ListNode { 4 | pub val: i32, 5 | pub next: Option> 6 | } 7 | 8 | impl ListNode { 9 | #[inline] 10 | fn new(val: i32) -> Self { 11 | ListNode { 12 | next: None, 13 | val 14 | } 15 | } 16 | } 17 | 18 | pub fn to_list(vec: Vec) -> Option> { 19 | let mut current = None; 20 | for &v in vec.iter().rev() { 21 | let mut node = ListNode::new(v); 22 | node.next = current; 23 | current = Some(Box::new(node)); 24 | } 25 | current 26 | } 27 | 28 | #[macro_export] 29 | macro_rules! linked { 30 | ($($e:expr),*) => {to_list(vec![$($e.to_owned()), *])}; 31 | ($($e:expr,)*) => {to_list(vec![$($e.to_owned()), *])}; 32 | } 33 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/swift/14_sorts/CountingSort.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CountingSort.swift 3 | // algo 4 | // 5 | // Created by Wenru Dong on 2018/10/18. 6 | // Copyright © 2018年 Wenru Dong. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | // 假设数组中储存的都是非负整数 12 | public func countingSort(_ a: inout [Int]) { 13 | if a.count <= 1 { return } 14 | 15 | var counts = Array(repeating: 0, count: a.max()! + 1) 16 | for num in a { 17 | counts[num] += 1 18 | } 19 | for i in 1.. { 4 | it('should solve Jump Game problem in bottom-up dynamic programming manner', () => { 5 | expect(dpBottomUpJumpGame([1, 0])).toBe(true); 6 | expect(dpBottomUpJumpGame([100, 0])).toBe(true); 7 | expect(dpBottomUpJumpGame([2, 3, 1, 1, 4])).toBe(true); 8 | expect(dpBottomUpJumpGame([1, 1, 1, 1, 1])).toBe(true); 9 | expect(dpBottomUpJumpGame([1, 1, 1, 10, 1])).toBe(true); 10 | expect(dpBottomUpJumpGame([1, 5, 2, 1, 0, 2, 0])).toBe(true); 11 | 12 | expect(dpBottomUpJumpGame([1, 0, 1])).toBe(false); 13 | expect(dpBottomUpJumpGame([3, 2, 1, 0, 4])).toBe(false); 14 | expect(dpBottomUpJumpGame([0, 0, 0, 0, 0])).toBe(false); 15 | expect(dpBottomUpJumpGame([5, 4, 3, 2, 1, 0, 0])).toBe(false); 16 | }); 17 | }); 18 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/Tests/_07_linkedlist_tests/algo07_linkedlist_tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/08_stack/stack_practice/main.m: -------------------------------------------------------------------------------- 1 | 2 | #import 3 | #import "FourOperation.h" 4 | #import "BalancedParentheses.h" 5 | 6 | int main(int argc, const char * argv[]) { 7 | @autoreleasepool { 8 | // 测试四则运算 9 | NSNumber *a = [[FourOperation shared] caculateExpression:@"10 - 4 / 2 * 3 + 3 - 6 / 2"]; 10 | NSNumber *b = [[FourOperation shared] caculateExpression:@"10 - 3"]; 11 | NSNumber *c = [[FourOperation shared] caculateExpression:@"2 * 3"]; 12 | NSLog(@"FourOperation: %ld\t%ld\t%ld\t", a.integerValue, b.integerValue, c.integerValue); 13 | 14 | // 测试括号匹配 15 | BalancedParentheses *balancedCheck = [BalancedParentheses new]; 16 | BOOL result = [balancedCheck checkForParenthessBlanced:@"([{{{}}}])"]; 17 | NSLog(@"BalancedParentheses: %d", result); 18 | } 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/chapter-8-recursion-and-Dynamic-Programming/8-8-Permutation-with-dups-alt.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void printPerms(string, string = ""); 7 | 8 | int main() 9 | { 10 | printPerms("abbc"); 11 | } 12 | 13 | void printPerms(string remainder, string prefix) 14 | { 15 | long length = remainder.length(); 16 | 17 | if (!length) cout << prefix << endl; 18 | 19 | bool dup[128]; 20 | 21 | memset(dup, false, sizeof(bool) * 128); 22 | 23 | for (int i = 0; i < length; ++i) 24 | { 25 | if (dup[remainder.at(i)]) continue; 26 | 27 | string str1 = i == 0 ? "" : remainder.substr(0,i); 28 | 29 | string str2 = i == length - 1 ? "" : remainder.substr(i+1,length); 30 | 31 | printPerms(str1 + str2, prefix + remainder.at(i)); 32 | 33 | dup[remainder.at(i)] = true; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/jump_game/__test__/backtrackingJumpGame.test.js: -------------------------------------------------------------------------------- 1 | import backtrackingJumpGame from '../backtrackingJumpGame'; 2 | 3 | describe('backtrackingJumpGame', () => { 4 | it('should solve Jump Game problem in backtracking manner', () => { 5 | expect(backtrackingJumpGame([1, 0])).toBe(true); 6 | expect(backtrackingJumpGame([100, 0])).toBe(true); 7 | expect(backtrackingJumpGame([2, 3, 1, 1, 4])).toBe(true); 8 | expect(backtrackingJumpGame([1, 1, 1, 1, 1])).toBe(true); 9 | expect(backtrackingJumpGame([1, 1, 1, 10, 1])).toBe(true); 10 | expect(backtrackingJumpGame([1, 5, 2, 1, 0, 2, 0])).toBe(true); 11 | 12 | expect(backtrackingJumpGame([1, 0, 1])).toBe(false); 13 | expect(backtrackingJumpGame([3, 2, 1, 0, 4])).toBe(false); 14 | expect(backtrackingJumpGame([0, 0, 0, 0, 0])).toBe(false); 15 | expect(backtrackingJumpGame([5, 4, 3, 2, 1, 0, 0])).toBe(false); 16 | }); 17 | }); 18 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/javascript/12_sorts/KthNum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 第k大的数 3 | * @param {array} arr 4 | * @param {number} k 5 | */ 6 | function kthNum(arr, k) { 7 | const len = arr.length; 8 | if (k > len) { 9 | return -1; 10 | } 11 | let p = partition(arr, 0, len - 1); 12 | while (p + 1 !== k) { 13 | if (p + 1 > k) { 14 | p = partition(arr, 0, p - 1); 15 | } else { 16 | p = partition(arr, p + 1, len - 1); 17 | } 18 | } 19 | return arr[p]; 20 | } 21 | 22 | function partition(arr, start, end) { 23 | let i = start; 24 | let pivot = arr[end]; 25 | for (let j = start; j < end; j++) { 26 | if (arr[j] < pivot) { 27 | swap(arr, i, j); 28 | i += 1; 29 | } 30 | } 31 | swap(arr, i, end); 32 | return i; 33 | } 34 | 35 | function swap(arr, i, j) { 36 | if (i === j) return; 37 | let tmp = arr[i]; 38 | arr[i] = arr[j]; 39 | arr[j] = tmp; 40 | } 41 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 4. Trees and Graphs /C++14/tree.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "treenode.hpp" 4 | 5 | template class N = Node> 7 | class Tree 8 | { 9 | public: 10 | using NodePtr = typename N::NodePtr; 11 | 12 | const NodePtr &getRoot() const 13 | { 14 | if (isEmpty()) 15 | throw TreeIsEmptyException(); 16 | return root; 17 | } 18 | 19 | template 20 | void setRoot(U &&node) 21 | { 22 | root = std::forward(node); 23 | } 24 | 25 | bool isEmpty() const 26 | { 27 | return !root; 28 | } 29 | 30 | class TreeIsEmptyException {}; 31 | 32 | protected: 33 | NodePtr root; 34 | }; 35 | 36 | template 37 | using NodePtr = typename Tree::NodePtr; 38 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/chapter-8-recursion-and-Dynamic-Programming/8-5-Recursive-Multiply.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int multiply(int a, int b, vector& dp) 6 | { 7 | int bigger = a < b ? b:a; 8 | int smaller = a > 1; //divide by 2 20 | 21 | int side1 = multiply(s,bigger,dp); 22 | int side2 = 0; 23 | if (smaller%2) 24 | side2 = side1+bigger; 25 | else 26 | side2 = side1; 27 | 28 | dp[smaller] = side2 +side1; 29 | return side1+side2; 30 | } 31 | 32 | int main() 33 | { 34 | int m = 7, n = 6; 35 | int smaller = m>n?n:m; 36 | int bigger = m>n?m:n; 37 | std::vector dp(smaller+1,-1); 38 | cout< None: 8 | solutions = [] 9 | 10 | def backtracking(queens_at_column: List[int], index_sums: List[int], index_diffs: List[int]) -> None: 11 | row = len(queens_at_column) 12 | if row == 8: 13 | solutions.append(queens_at_column) 14 | return 15 | for col in range(8): 16 | if col in queens_at_column or row + col in index_sums or row - col in index_diffs: continue 17 | backtracking(queens_at_column + [col], index_sums + [row + col], index_diffs + [row - col]) 18 | 19 | backtracking([], [], []) 20 | print(*(" " + " ".join("*" * i + "Q" + "*" * (8 - i - 1) + "\n" for i in solution) for solution in solutions), sep="\n") 21 | 22 | 23 | if __name__ == "__main__": 24 | 25 | eight_queens() 26 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 1.Arrays And Strings/5. One Away/5.One Away.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool isOneAway(string s1, string s2){ 6 | string a,b; 7 | a = s1.length() >= s2.length() ? s1 : s2; 8 | b = s1.length() < s2.length() ? s1 : s2; 9 | int len1, len2; 10 | len1 = a.length(); 11 | len2 = b.length(); 12 | if(abs(len1-len2)>1) 13 | return false; 14 | 15 | bool flag = false; 16 | for(int i=0,j=0;i= 11 && faceValue <= 13) 15 | { 16 | return 10; 17 | } 18 | else 19 | { 20 | return faceValue; 21 | } 22 | } 23 | 24 | virtual int minValue() 25 | { 26 | if (isAce()) 27 | { 28 | return 1; 29 | } 30 | else 31 | { 32 | return value(); 33 | } 34 | } 35 | 36 | virtual int maxValue() 37 | { 38 | if (isAce()) 39 | { 40 | return 11; 41 | } 42 | else 43 | { 44 | return value(); 45 | } 46 | } 47 | 48 | virtual bool isAce() 49 | { 50 | return faceValue == 1; 51 | } 52 | 53 | virtual bool isFaceCard() 54 | { 55 | return faceValue >= 11 && faceValue <= 13; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /leetcode/decode_string/README.md: -------------------------------------------------------------------------------- 1 | # 394.Decode String 2 | 3 | ## 题目 4 | 5 | Given an encoded string, return it's decoded string. 6 | 7 | The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. 8 | 9 | You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. 10 | 11 | Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. 12 | 13 | 说明:给定一个编码字符,按编码规则进行解码,输出字符串;编码规则是`count[letter]`,将 letter 的内容 count 次输出,count 是 0 或正整数,letter 是区分大小写的纯字母 14 | 15 | ```js 16 | s = "3[a]2[bc]", return "aaabcbc". 17 | s = "3[a2[c]]", return "accaccacc". 18 | s = "2[abc]3[cd]ef", return "abcabccdcdcdef". 19 | ``` 20 | 21 | ## 分析 22 | 23 | 可以使用正则表达式提取,或者递归提取。 24 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/10_recursion/RangAll.go: -------------------------------------------------------------------------------- 1 | package Recursion 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | // 实现一组数据集合的全排列 7 | type RangeType struct { 8 | value []interface{} 9 | } 10 | 11 | func NewRangeArray(n int) *RangeType { 12 | return &RangeType{ 13 | make([]interface{},n), 14 | } 15 | } 16 | 17 | func (slice *RangeType)RangeALL( start int) { 18 | len := len(slice.value) 19 | if start == len-1{ 20 | // 如果已经是最后位置,直接将数组数据合并输出 21 | fmt.Println(slice.value) 22 | } 23 | 24 | for i:=start; i= end { 14 | return 15 | } 16 | 17 | mid := (start + end) / 2 18 | mergeSort(arr, start, mid) 19 | mergeSort(arr, mid+1, end) 20 | merge(arr, start, mid, end) 21 | } 22 | 23 | func merge(arr []int, start, mid, end int) { 24 | tmpArr := make([]int, end-start+1) 25 | 26 | i := start 27 | j := mid + 1 28 | k := 0 29 | for ; i <= mid && j <= end; k++ { 30 | if arr[i] <= arr[j] { 31 | tmpArr[k] = arr[i] 32 | i++ 33 | } else { 34 | tmpArr[k] = arr[j] 35 | j++ 36 | } 37 | } 38 | 39 | for ; i <= mid; i++ { 40 | tmpArr[k] = arr[i] 41 | k++ 42 | } 43 | for ; j <= end; j++ { 44 | tmpArr[k] = arr[j] 45 | k++ 46 | } 47 | copy(arr[start:end+1], tmpArr) 48 | } 49 | -------------------------------------------------------------------------------- /leetcode/knight_tour/__test__/knightTour.test.js: -------------------------------------------------------------------------------- 1 | import knightTour from '../knightTour'; 2 | 3 | describe('knightTour', () => { 4 | it('should not find solution on 3x3 board', () => { 5 | const moves = knightTour(3); 6 | 7 | expect(moves.length).toBe(0); 8 | }); 9 | 10 | it('should find one solution to do knight tour on 5x5 board', () => { 11 | const moves = knightTour(5); 12 | 13 | expect(moves.length).toBe(25); 14 | 15 | expect(moves).toEqual([ 16 | [0, 0], 17 | [1, 2], 18 | [2, 0], 19 | [0, 1], 20 | [1, 3], 21 | [3, 4], 22 | [2, 2], 23 | [4, 1], 24 | [3, 3], 25 | [1, 4], 26 | [0, 2], 27 | [1, 0], 28 | [3, 1], 29 | [4, 3], 30 | [2, 4], 31 | [0, 3], 32 | [1, 1], 33 | [3, 0], 34 | [4, 2], 35 | [2, 1], 36 | [4, 0], 37 | [3, 2], 38 | [4, 4], 39 | [2, 3], 40 | [0, 4], 41 | ]); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/13_sort/countingSort.php: -------------------------------------------------------------------------------- 1 | $value) { 22 | $countScore[$value]++; 23 | } 24 | 25 | /** 26 | * 顺序求和 27 | */ 28 | for($i=1;$i<=5;$i++) { 29 | $countScore[$i] += $countScore[$i-1]; 30 | } 31 | /** 32 | * 排序 33 | */ 34 | foreach ($score as $key => $value) { 35 | $countScore[$value] --; 36 | $temp[$countScore[$value]] = $value; 37 | } 38 | //copy 39 | for($i=0;$i<$length;$i++) { 40 | $score[$i] = $temp[$i]; 41 | } 42 | return $score; 43 | } -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/07_linkedlist/merge_two_sorted_lists.rs: -------------------------------------------------------------------------------- 1 | use super::util::linked_list::{ListNode, to_list}; 2 | 3 | pub fn merge_two_lists(l1: Option>, l2: Option>) -> Option> { 4 | match (l1, l2) { 5 | (Some(node1), None) => Some(node1), 6 | (None, Some(node2)) => Some(node2), 7 | (Some(mut node1), Some(mut node2)) => { 8 | if node1.val < node2.val { 9 | let n = node1.next.take(); 10 | node1.next = Solution::merge_two_lists(n, Some(node2)); 11 | Some(node1) 12 | } else { 13 | let n = node2.next.take(); 14 | node2.next = Solution::merge_two_lists(Some(node1), n); 15 | Some(node2) 16 | } 17 | }, 18 | _ => None, 19 | } 20 | } 21 | 22 | fn main() { 23 | println!("{:?}", merge_two_lists(to_list(vec![1, 3, 4]), to_list(vec![1, 2, 4]))); 24 | } 25 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/17_skiplist/skiplist_c/skiplist.h: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | > File Name: skiplist.h 3 | > Author: jinshaohui 4 | > Mail: jinshaohui789@163.com 5 | > Time: 18-10-31 6 | > Desc: 7 | ************************************************************************/ 8 | #ifndef __SKIP_LIST_H__ 9 | #define __SKIP_LIST_H__ 10 | 11 | 12 | typedef struct _node 13 | { 14 | int key; /*key是唯一的*/ 15 | int value; /*存储的内容*/ 16 | int max_level; /*当前节点最大层数*/ 17 | struct _node *next[0];/*level层链表结构*/ 18 | }node; 19 | 20 | typedef struct _skiplist 21 | { 22 | int level; 23 | int count; 24 | node *head; 25 | }skiplist; 26 | 27 | /*根据当前结构体元素的地址,获取到结构体首地址*/ 28 | #define offsetof(TYPE,MEMBER) ((size_t) &((TYPE *)0)->MEMBER) 29 | #define container(ptr,type,member) ({\ 30 | const typeof( ((type *)0)->member) *__mptr = (ptr);\ 31 | (type *) ( (char *)__mptr - offsetof(type,member));}) 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/07_linkedlist/remove_nth_node_from_end_of_list.rs: -------------------------------------------------------------------------------- 1 | use super::util::linked_list::{ListNode, to_list}; 2 | 3 | pub fn remove_nth_from_end(head: Option>, n: i32) -> Option> { 4 | let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); 5 | let mut cur = &mut dummy; 6 | let mut length = 0; 7 | 8 | while let Some(_node) = cur.as_mut() { 9 | cur = &mut cur.as_mut().unwrap().next; 10 | if let Some(_inner_node) = cur { length += 1; } 11 | } 12 | 13 | let mut new_cur = dummy.as_mut(); 14 | let idx = length - n; 15 | 16 | for _ in 0..idx { 17 | new_cur = new_cur.unwrap().next.as_mut(); 18 | } 19 | 20 | let next = new_cur.as_mut().unwrap().next.as_mut().unwrap().next.take(); 21 | new_cur.as_mut().unwrap().next = next; 22 | 23 | dummy.unwrap().next 24 | } 25 | 26 | fn main() { 27 | println!("{:?}", remove_nth_from_end(to_list(vec![1, 3, 4]))); 28 | } 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch12_sorts/QuickSortTest.scala: -------------------------------------------------------------------------------- 1 | package ch12_sorts 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | class QuickSortTest extends FlatSpec with Matchers { 6 | 7 | behavior of "QuickSortTest" 8 | 9 | it should "quickSort" in { 10 | var array = Array(4, 5, 6, 3, 2, 1) 11 | array = QuickSort.quickSort(array) 12 | array.mkString("") should equal("123456") 13 | 14 | array = Array(4) 15 | array = QuickSort.quickSort(array) 16 | array.mkString("") should equal("4") 17 | 18 | array = Array(4, 2) 19 | array = QuickSort.quickSort(array) 20 | array.mkString("") should equal("24") 21 | } 22 | 23 | it should "find the Kth element in the array" in { 24 | val array = Array(4, 2, 5, 12, 3) 25 | 26 | QuickSort.findKthElement(array, 3) should equal(4) 27 | QuickSort.findKthElement(array, 5) should equal(12) 28 | QuickSort.findKthElement(array, 1) should equal(2) 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/06_linkedlist/singlelinkedlist_test.go: -------------------------------------------------------------------------------- 1 | package _6_linkedlist 2 | 3 | import "testing" 4 | 5 | func TestInsertToHead(t *testing.T) { 6 | l := NewLinkedList() 7 | for i := 0; i < 10; i++ { 8 | l.InsertToHead(i + 1) 9 | } 10 | l.Print() 11 | } 12 | 13 | func TestInsertToTail(t *testing.T) { 14 | l := NewLinkedList() 15 | for i := 0; i < 10; i++ { 16 | l.InsertToTail(i + 1) 17 | } 18 | l.Print() 19 | } 20 | 21 | func TestFindByIndex(t *testing.T) { 22 | l := NewLinkedList() 23 | for i := 0; i < 10; i++ { 24 | l.InsertToTail(i + 1) 25 | } 26 | t.Log(l.FindByIndex(0)) 27 | t.Log(l.FindByIndex(9)) 28 | t.Log(l.FindByIndex(5)) 29 | t.Log(l.FindByIndex(11)) 30 | } 31 | 32 | func TestDeleteNode(t *testing.T) { 33 | l := NewLinkedList() 34 | for i := 0; i < 3; i++ { 35 | l.InsertToTail(i + 1) 36 | } 37 | l.Print() 38 | 39 | t.Log(l.DeleteNode(l.head.next)) 40 | l.Print() 41 | 42 | t.Log(l.DeleteNode(l.head.next.next)) 43 | l.Print() 44 | } 45 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch08_stack/BrowserDemo.scala: -------------------------------------------------------------------------------- 1 | package ch08_stack 2 | 3 | class BrowserDemo(var currentPageOpt: Option[String], val backStack: StackDemo[String], 4 | val forwardStack: StackDemo[String]) { 5 | 6 | def this() = this(None, new StackDemo[String], new StackDemo[String]) 7 | 8 | def open(page: String) = { 9 | currentPageOpt.foreach(backStack.push) 10 | forwardStack.clear() 11 | currentPageOpt = Some(page) 12 | } 13 | 14 | def canGoBack(): Boolean = backStack.size > 0 15 | 16 | def goBack(): Unit = { 17 | backStack.pop().foreach(page => { 18 | forwardStack.push(currentPageOpt.get) 19 | currentPageOpt = Some(page.data) 20 | }) 21 | } 22 | 23 | def canGoForward(): Boolean = forwardStack.size > 0 24 | 25 | def goForward(): Unit = { 26 | forwardStack.pop().foreach(page => { 27 | backStack.push(currentPageOpt.get) 28 | currentPageOpt = Some(page.data) 29 | }) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/15_bsearch/bsearch_test.cc: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Liam Huang (Liam0205) on 2018/10/24. 3 | */ 4 | 5 | #include 6 | #include 7 | 8 | #include "bsearch.hpp" 9 | 10 | template 11 | void test_bsearch(const VecT& test, T target) { 12 | auto it = bsearch(test.begin(), test.end(), target); 13 | std::cout << std::distance(test.begin(), it) << std::endl; 14 | } 15 | 16 | int main() { 17 | std::vector test{0, 0, 1, 2, 3, 4, 4, 5, 5, 5, 5, 5, 6, 7}; // std::less() 18 | 19 | test_bsearch(test, 8); // 14 20 | test_bsearch(test, -1); // 14 21 | test_bsearch(test, 0); // 0, 1 22 | test_bsearch(test, 4); // 5, 6 23 | test_bsearch(test, 5); // 7, 8, 9, 10, 11 24 | test_bsearch(test, 7); // 13 25 | 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/object-c/06_linkedlist/SinglyLinkedList.h: -------------------------------------------------------------------------------- 1 | // 2 | // SinglyLinkedList.h 3 | // algo 4 | // 5 | // Created by Wenru Dong on 2018/10/6. 6 | // Copyright © 2018年 Wenru Dong. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "ListNode.h" 11 | 12 | @interface SinglyLinkedList : NSObject 13 | 14 | @property ListNode* head; 15 | 16 | - (ListNode*)nodeWithValue:(int)value; 17 | - (ListNode*)nodeAtIndex:(NSUInteger)index; 18 | 19 | - (void)insertNodeWithValue:(int)value; 20 | - (void)insertNode:(nonnull ListNode*)node; 21 | + (void)insertNodeWithValue:(int)value afterNode:(nonnull ListNode*)node; 22 | + (void)insertNode:(nonnull ListNode*)aNode afterNode:(nonnull ListNode*)node; 23 | - (void)insertNodeWithValue:(int)value beforeNode:(nonnull ListNode*)node; 24 | - (void)insertNode:(nonnull ListNode*)aNode beforeNode:(nonnull ListNode*)node; 25 | 26 | - (void)deleteNode:(nonnull ListNode*)node; 27 | - (void)deleteNodesWithValue:(int)value; 28 | 29 | @end 30 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/09_queue/QueueBasedOnArray.go: -------------------------------------------------------------------------------- 1 | package _9_queue 2 | 3 | import "fmt" 4 | 5 | type ArrayQueue struct { 6 | q []interface{} 7 | capacity int 8 | head int 9 | tail int 10 | } 11 | 12 | func NewArrayQueue(n int) *ArrayQueue { 13 | return &ArrayQueue{make([]interface{}, n), n, 0, 0} 14 | } 15 | 16 | func (this *ArrayQueue) EnQueue(v interface{}) bool { 17 | if this.tail == this.capacity { 18 | return false 19 | } 20 | this.q[this.tail] = v 21 | this.tail++ 22 | return true 23 | } 24 | 25 | func (this *ArrayQueue) DeQueue() interface{} { 26 | if this.head == this.tail { 27 | return nil 28 | } 29 | v := this.q[this.head] 30 | this.head++ 31 | return v 32 | } 33 | 34 | func (this *ArrayQueue) String() string { 35 | if this.head == this.tail { 36 | return "empty queue" 37 | } 38 | result := "head" 39 | for i := this.head; i <= this.tail-1; i++ { 40 | result += fmt.Sprintf("<-%+v", this.q[i]) 41 | } 42 | result += "<-tail" 43 | return result 44 | } 45 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/41_dynamic_programming/min_dis_path.rs: -------------------------------------------------------------------------------- 1 | fn min_dis_path(matrix: Vec>) -> i32 { 2 | let m_len = matrix.len(); 3 | if m_len == 0 { return 0; } 4 | 5 | let mut states = vec![vec![0; m_len]; m_len]; 6 | let mut sum = 0; 7 | // 初始化第一行数据 8 | for j in 0..m_len { 9 | sum += matrix[0][j]; 10 | states[0][j] = sum; 11 | } 12 | 13 | sum = 0; 14 | // 初始化第一列数据 15 | for i in 0..m_len { 16 | sum += matrix[i][0]; 17 | states[i][0] = sum; 18 | } 19 | 20 | for i in 1..m_len { 21 | for j in 1..m_len { 22 | states[i][j] = matrix[i][j] + states[i-1][j].min(states[i][j-1]) 23 | } 24 | } 25 | 26 | states[m_len-1][m_len-1] 27 | } 28 | fn main() { 29 | let matrix = vec![ 30 | vec![1, 3, 5, 9], 31 | vec![2, 1, 3, 4], 32 | vec![5, 2, 6, 7], 33 | vec![6, 8, 4, 3], 34 | ]; 35 | 36 | let m = min_dis_path(matrix); 37 | println!("{}", m); 38 | } 39 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/csharp/08-stack/algo08_stack/ArrayStack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace algo08_stack 4 | { 5 | public class ArrayStack 6 | { 7 | private readonly int _capacity; 8 | 9 | private readonly T[] _data; 10 | 11 | private int _top = -1; // 指向栈顶元素,当为-1时表示栈为空 12 | 13 | public ArrayStack(int capacity) 14 | { 15 | _capacity = capacity; 16 | 17 | _data = new T[capacity]; 18 | } 19 | 20 | public int Count => _top + 1; 21 | 22 | public void Push(T val) 23 | { 24 | if (Count == _capacity) throw new InvalidOperationException("Stack full."); 25 | 26 | _top++; 27 | 28 | _data[_top] = val; 29 | } 30 | 31 | public T Pop() 32 | { 33 | if (_top == -1) throw new InvalidOperationException("Stack empty."); 34 | 35 | T val = _data[_top]; 36 | _top--; 37 | 38 | return val; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/42_dynamic_programming/edit_distance.rs: -------------------------------------------------------------------------------- 1 | // leetcode 72 [edit_distance](https://leetcode.com/problems/edit-distance/) 2 | fn edit_distance(word1: &str, word2: &str) -> i32 { 3 | let word1_chars: Vec = word1.chars().collect(); 4 | let word2_chars: Vec = word2.chars().collect(); 5 | let m = word1.len(); 6 | let n = word2.len(); 7 | let mut dp = vec![vec![0; m+1]; n+1]; 8 | 9 | // 初始化第一行 10 | for i in 0..=m { dp[i][0] = i; } 11 | // 初始化第一列 12 | for j in 0..=n { dp[0][j] = j; } 13 | 14 | for i in 1..=m { 15 | for j in 1..=n { 16 | let mut step = 0; 17 | if word1_chars[i-1] != word2_chars[j-1] { step = 1; } 18 | dp[i][j] = (dp[i][j-1] + 1).min(dp[i-1][j] + 1).min(dp[i-1][j-1] + step); 19 | } 20 | } 21 | 22 | dp[m][n] as i32 23 | } 24 | fn main() { 25 | let word1 = "mitcmu"; 26 | let word2 = "mtacnu"; 27 | let m = edit_distance(word1, word2); 28 | println!("{:?}", m); 29 | } 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Ch 6. Math and Logic Puzzles/7.The Apocalypse/The Apocalypse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void std::vector runOneFamily() 6 | { 7 | Random *random = new Random(); 8 | int boys = 0; 9 | int girls = 0; 10 | while (girls == 0) 11 | { 12 | if (random->nextBoolean()) 13 | { 14 | girls += 1; 15 | } 16 | else 17 | { 18 | boys += 1; 19 | } 20 | } 21 | std::vector genders = {girls, boys}; 22 | return genders; 23 | } 24 | 25 | double runNFamilies(int n) 26 | { 27 | int boys = 0; 28 | int girls = 0; 29 | for (int i = 0; i < n; i++) 30 | { 31 | std::vector genders = runOneFamily(); 32 | girls += genders[0]; 33 | boys += genders[1]; 34 | } 35 | return girls / static_cast(boys + girls); 36 | } 37 | 38 | static void main(std::vector &args) 39 | { 40 | double ratio = runNFamilies(10000000); 41 | std::wcout << ratio << std::endl; 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/cpp/Chapter-3-Stacks-and-Queues/3.1-Three-in-One/FixedMultiStack.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class FixedMultiStack 5 | { 6 | public: 7 | //Create 3 stacks, each stack is of size stackCapacity. 8 | FixedMultiStack(int stackCapacity); 9 | virtual ~FixedMultiStack(); 10 | 11 | //Push an element onto stack stackNum, where stackNum is from 0 to 2. 12 | void push(int stackNum, int value); 13 | 14 | //Pop the top element from stack stackNum, where stackNum is from 0 to 2. 15 | void pop(int stackNum); 16 | 17 | //Return the top element on stack stackNum, where stackNum is from 0 to 2. 18 | int top(int stackNum) const; 19 | 20 | bool isEmpty(int stackNum) const; 21 | bool isFull(int stackNum) const; 22 | 23 | private: 24 | int numOfStack = 3; 25 | int stackCapacity; 26 | int *stackArray; 27 | int *stackCapacityUsed; 28 | 29 | //Return the top index of stack stackNum, where stackNum is from 0 to 2. 30 | int indexOfTop(int stackNum) const; 31 | }; 32 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/main/scala/ch09_queue/LinkedListQueue.scala: -------------------------------------------------------------------------------- 1 | package ch09_queue 2 | 3 | class Node[T](var data: T, var next: Option[Node[T]]) 4 | 5 | class LinkListQueue[T]() extends DemoQueue[T] { 6 | 7 | var headOpt: Option[Node[T]] = None 8 | var tailOpt: Option[Node[T]] = None 9 | 10 | override 11 | def enqueue(data: T): Unit = { 12 | val node = new Node(data, None) 13 | size += 1 14 | headOpt match { 15 | case None => headOpt = Some(node) 16 | case Some(_) => 17 | } 18 | tailOpt match { 19 | case None => tailOpt = Some(node) 20 | case Some(tail) => 21 | tail.next = Some(node) 22 | tailOpt = Some(node) 23 | } 24 | } 25 | 26 | override 27 | def dequeue(): Option[T] = { 28 | headOpt.map(head => { 29 | size -= 1 30 | headOpt = head.next 31 | if (headOpt.isEmpty) { 32 | //head is empty reach the end of the queue 33 | tailOpt = None 34 | } 35 | head.data 36 | }) 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/rust/24_binary_tree/search_in_binary_tree.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-in-a-binary-search-tree/ 2 | use super::util::tree::{TreeNode, to_tree}; 3 | 4 | // Iterating method 5 | pub fn search_bst(root: Option>>, val: i32) -> Option>> { 6 | let mut r = root.clone(); 7 | while let Some(node) = r { 8 | if node.borrow().val == val { return Some(node); } 9 | if node.borrow().val > val { 10 | r = node.borrow().left.clone(); 11 | } else { 12 | r = node.borrow().right.clone(); 13 | } 14 | } 15 | None 16 | } 17 | 18 | // Recursive Approach 19 | pub fn search_bst(root: Option>>, val: i32) -> Option>> { 20 | if let Some(n) = &root { 21 | if n.borrow().val > val { return Self::search_bst(n.borrow().left.clone(), val); } 22 | if n.borrow().val < val { return Self::search_bst(n.borrow().right.clone(), val); } 23 | } 24 | root 25 | } 26 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch15_bsearch/BSearchTest.scala: -------------------------------------------------------------------------------- 1 | package ch15_bsearch 2 | 3 | import ch12_sorts.QuickSort 4 | import org.scalatest.{FlatSpec, Matchers} 5 | 6 | import scala.util.Random 7 | 8 | class BSearchTest extends FlatSpec with Matchers { 9 | 10 | behavior of "BSearchTest" 11 | 12 | it should "search with exist value" in { 13 | val length = 50000 14 | val array = new Array[Int](length) 15 | val rnd = new Random() 16 | for (i <- Range(0, length)) { 17 | array(i) = rnd.nextInt() 18 | } 19 | 20 | val target = array(2698) 21 | 22 | BSearch.search(QuickSort.quickSort(array), target) should be > -1 23 | } 24 | 25 | it should "calculate sqrt value -1 " in { 26 | val x = 4 27 | val precision = 0.000001 28 | BSearch.sqrt(x, precision) should equal(2.0) 29 | } 30 | 31 | it should "calculate sqrt value -2 " in { 32 | val x = 0.04 33 | val precision = 0.000001 34 | BSearch.sqrt(x, precision) should equal(0.2 +- precision) 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/go/06_linkedlist/palindrome-linked-list.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * type ListNode struct { 4 | * Val int 5 | * Next *ListNode 6 | * } 7 | */ 8 | func isPalindrome(head *ListNode) bool { 9 | var slow *ListNode = head 10 | var fast *ListNode = head 11 | var prev *ListNode = nil 12 | var temp *ListNode = nil 13 | 14 | if (head == nil || head.Next == nil) { 15 | return true 16 | } 17 | 18 | for (fast != nil && fast.Next !=nil){ 19 | fast = fast.Next.Next 20 | temp = slow.Next 21 | slow.Next = prev 22 | prev = slow 23 | slow = temp 24 | } // 快的先跑完,同时反转了一半链表,剪短 25 | 26 | if fast != nil { 27 | slow = slow.Next // 处理余数,跨过中位数 28 | // prev 增加中 2->1->nil 29 | } 30 | 31 | var l1 *ListNode = prev 32 | var l2 *ListNode = slow 33 | 34 | for (l1 != nil && l2 !=nil && l1.Val == l2.Val){ 35 | l1 = l1.Next 36 | l2 = l2.Next 37 | } 38 | 39 | return (l1 == nil && l2 == nil) 40 | 41 | } 42 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/c-cpp/24_binarysearchtree/binarysearchtree.h: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | > File Name: binarysearchtree.h 3 | > Author: jinshaohui 4 | > Mail: jinshaohui789@163.com 5 | > Time: 18-11-12 6 | > Desc: 7 | ************************************************************************/ 8 | #ifndef __BINARY_SEARCH_TREE__ 9 | #define __BINARY_SEARCH_TREE__ 10 | typedef int mytype; 11 | 12 | typedef struct _bstree_node 13 | { 14 | mytype data; 15 | struct _bstree_node *lchild; 16 | struct _bstree_node *rchild; 17 | }bstree_node; 18 | 19 | typedef struct _bstree 20 | { 21 | int size; 22 | int (*compare)(mytype key1,mytype key2); 23 | int (*destory)(mytype data); 24 | bstree_node *root; 25 | }bstree; 26 | 27 | typedef int (*compare_fuc)(mytype key1,mytype key2); 28 | typedef int (*destory_fuc)(mytype data); 29 | 30 | #define bstree_is_empty(tree) (tree->size == 0) 31 | 32 | bstree *bstree_create(compare_fuc compare,destory_fuc destory); 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/php/12_sort/quicksort.php: -------------------------------------------------------------------------------- 1 | = $r) return; 13 | 14 | $q = partition($a, $l, $r); 15 | quickSortInternally($a, $l, $q-1); 16 | quickSortInternally($a, $q+1, $r); 17 | } 18 | 19 | function partition(&$a, $l, $r): int 20 | { 21 | $pivot = $a[$r]; 22 | $i = $l; 23 | 24 | for ($j = $l; $j < $r; ++$j) { 25 | if ($a[$j] < $pivot) { 26 | [$a[$j], $a[$i]] = [$a[$i], $a[$j]]; 27 | ++$i; 28 | } 29 | } 30 | 31 | [$a[$r], $a[$i]] = [$a[$i], $a[$r]]; 32 | 33 | return $i; 34 | } 35 | 36 | $a1 = [1,4,6,2,3,5,4]; 37 | $a2 = [2, 2, 2, 2]; 38 | $a3 = [4, 3, 2, 1]; 39 | $a4 = [5, -1, 9, 3, 7, 8, 3, -2, 9]; 40 | quickSort($a1); 41 | print_r($a1); 42 | quickSort($a2); 43 | print_r($a2); 44 | quickSort($a3); 45 | print_r($a3); 46 | quickSort($a4); 47 | print_r($a4); -------------------------------------------------------------------------------- /leetcode/recursive_staircase/recursiveStaircaseBF.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Recursive Staircase Problem (Brute Force Solution). 3 | * 4 | * @param {number} stairsNum - Number of stairs to climb on. 5 | * @return {number} - Number of ways to climb a staircase. 6 | */ 7 | export default function recursiveStaircaseBF(stairsNum) { 8 | if (stairsNum <= 0) { 9 | // There is no way to go down - you climb the stairs only upwards. 10 | // Also if you're standing on the ground floor that you don't need to do any further steps. 11 | return 0; 12 | } 13 | 14 | if (stairsNum === 1) { 15 | // There is only one way to go to the first step. 16 | return 1; 17 | } 18 | 19 | if (stairsNum === 2) { 20 | // There are two ways to get to the second steps: (1 + 1) or (2). 21 | return 2; 22 | } 23 | 24 | // Sum up how many steps we need to take after doing one step up with the number of 25 | // steps we need to take after doing two steps up. 26 | return recursiveStaircaseBF(stairsNum - 1) + recursiveStaircaseBF(stairsNum - 2); 27 | } 28 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/16_Power/16_Power.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/javascript/45_bitmap/bitmap.js: -------------------------------------------------------------------------------- 1 | 2 | class BitMap { 3 | constructor(n) { 4 | this.nbits = n; 5 | this.blk = new Array(Math.floor(n / 16) + 1); 6 | this.blk.fill(0); 7 | } 8 | 9 | get(k) { 10 | if( k > this.nbits) return false; 11 | 12 | let byteIndex = Math.floor(k / 16); 13 | let bitIndex = k % 16; 14 | 15 | return !((this.blk[byteIndex] & (1 << bitIndex)) === 0); 16 | } 17 | 18 | set(k) { 19 | if( k > this.nbits) return; 20 | 21 | let byteIndex = Math.floor(k / 16); 22 | let bitIndex = k % 16; 23 | 24 | this.blk[byteIndex] = this.blk[byteIndex] | (1 << bitIndex); 25 | 26 | } 27 | } 28 | 29 | let aBitMap = new BitMap(20); 30 | 31 | aBitMap.set(1); 32 | aBitMap.set(3); 33 | aBitMap.set(5); 34 | aBitMap.set(7); 35 | aBitMap.set(9); 36 | aBitMap.set(11); 37 | aBitMap.set(13); 38 | aBitMap.set(15); 39 | aBitMap.set(17); 40 | aBitMap.set(19); 41 | 42 | for(let i = 0; i < 21; i++) { 43 | console.log(aBitMap.get(i)); 44 | } -------------------------------------------------------------------------------- /剑指 Offer/cpp/10_Fibonacci/10_Fibonacci.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/13_RobotMove/13_RobotMove.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/43_NumberOf1/43_NumberOf1.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /数据结构和算法必知必会的 50 个代码实现/scala/src/test/scala/ch16_bsearch/BSearchTest.scala: -------------------------------------------------------------------------------- 1 | package ch16_bsearch 2 | 3 | import org.scalatest.{FlatSpec, Matchers} 4 | 5 | class BSearchTest extends FlatSpec with Matchers { 6 | 7 | behavior of "BSearchTest" 8 | 9 | it should "findFirstValue" in { 10 | val items = Array(1, 3, 4, 5, 6, 8, 8, 8, 11, 18) 11 | BSearch.findFirstValue(items, 8) should equal(5) 12 | } 13 | 14 | it should "findLastValue" in { 15 | val items = Array(1, 3, 4, 5, 6, 8, 8, 8, 11, 18) 16 | BSearch.findLastValue(items, 8) should equal(7) 17 | } 18 | 19 | it should "findFirstGreaterThan" in { 20 | val items = Array(1, 3, 4, 5, 6, 8, 8, 8, 11, 18) 21 | BSearch.findFirstGreaterThan(items, 2) should equal(1) 22 | BSearch.findFirstGreaterThan(items, 8) should equal(5) 23 | } 24 | 25 | it should "findLastSmallerThan" in { 26 | val items = Array(1, 3, 4, 5, 6, 8, 8, 8, 11, 18) 27 | BSearch.findLastSmallerThan(items, 2) should equal(0) 28 | BSearch.findLastSmallerThan(items, 8) should equal(7) 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/14_CuttingRope/14_CuttingRope.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/24_ReverseList/24_ReverseList.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/29_PrintMatrix/29_PrintMatrix.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/34_PathInTree/34_PathInTree.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/49_UglyNumber/49_UglyNumber.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/53_01_NumberOfK/53_01_NumberOfK.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/55_01_TreeDepth/55_01_TreeDepth.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/64_Accumulate/64_Accumulate.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /剑指 Offer/cpp/67_StringToInt/67_StringToInt.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | --------------------------------------------------------------------------------