├── .gitignore ├── .nojekyll ├── 404.html ├── CNAME ├── Dockerfile ├── NAV.md ├── README.md ├── SUMMARY.md ├── asset ├── back-to-top.css ├── back-to-top.js ├── dark-mode.css ├── dark-mode.js ├── docsify-apachecn-footer.js ├── docsify-baidu-push.js ├── docsify-baidu-stat.js ├── docsify-clicker.js ├── docsify-cnzz.js ├── docsify-copy-code.min.js ├── docsify-quick-page.css ├── docsify-quick-page.js ├── docsify-sidebar-collapse.min.js ├── docsify.min.js ├── edit.css ├── edit.js ├── edit.svg ├── left.svg ├── moon.svg ├── prism-c.min.js ├── prism-cpp.min.js ├── prism-darcula.css ├── prism-java.min.js ├── prism-javascript.min.js ├── prism-kotlin.min.js ├── prism-perl.min.js ├── prism-python.min.js ├── prism-sql.min.js ├── right.svg ├── search.min.js ├── share.css ├── share.js ├── share.svg ├── sidebar.min.css ├── style.css ├── sun.svg ├── up.svg └── vue.css ├── docs ├── jianzhioffer │ └── java │ │ ├── 03_01_DuplicationInArray.md │ │ ├── 03_02_DuplicationInArrayNoEdit.md │ │ ├── 04_FindInPartiallySortedMatrix.md │ │ ├── 05_ReplaceSpaces.md │ │ ├── 06_PrintListInReversedOrder.md │ │ ├── 07_ConstructBinaryTree.md │ │ ├── 08_NextNodeInBinaryTrees.md │ │ ├── 09_01_QueueWithTwoStacks.md │ │ ├── 09_02_StackWithTwoQueues.md │ │ ├── 10_01_Fibonacci.md │ │ ├── 10_02_JumpFloor.md │ │ ├── 10_03_JumpFloorII.md │ │ ├── 10_04_RectCover.md │ │ ├── 11_MinNumberInRotatedArray.md │ │ ├── 12_StringPathInMatrix.md │ │ ├── 13_RobotMove.md │ │ ├── 14_CuttingRope.md │ │ ├── 15_NumberOf1InBinary.md │ │ ├── 16_Power.md │ │ ├── 17_Print1ToMaxOfNDigits.md │ │ ├── 18_01_DeleteNodeInList.md │ │ ├── 18_02_DeleteDuplicatedNode.md │ │ ├── 19_RegularExpressionsMatching.md │ │ ├── 20_NumericStrings.md │ │ ├── 21_ReorderArray.md │ │ ├── 22_KthNodeFromEnd.md │ │ ├── 23_EntryNodeInListLoop.md │ │ ├── 24_ReverseList.md │ │ ├── 25_MergeSortedLists.md │ │ ├── 26_SubstructureInTree.md │ │ ├── 27_MirrorOfBinaryTree.md │ │ ├── 28_SymmetricalBinaryTree.md │ │ ├── 29_PrintMatrix.md │ │ ├── 30_MinInStack.md │ │ ├── 31_StackPushPopOrder.md │ │ ├── 32_01_PrintTreeFromTopToBottom.md │ │ ├── 32_02_PrintTreesInLines.md │ │ ├── 32_03_PrintTreesInZigzag.md │ │ ├── 33_SquenceOfBST.md │ │ ├── 34_PathInTree.md │ │ ├── 35_CopyComplexList.md │ │ ├── 36_ConvertBinarySearchTree.md │ │ ├── 37_SerializeBinaryTrees.md │ │ ├── 38_StringPermutation.md │ │ ├── 39_MoreThanHalfNumber.md │ │ ├── 40_KLeastNumbers.md │ │ ├── 41_StreamMedian.md │ │ ├── 42_GreatestSumOfSubarrays.md │ │ ├── 43_NumberOf1.md │ │ ├── 44_DigitsInSequence.md │ │ ├── 45_SortArrayForMinNumber.md │ │ ├── 46_TranslateNumbersToStrings.md │ │ ├── 47_MaxValueOfGifts.md │ │ ├── 48_LongestSubstringWithoutDup.md │ │ ├── 49_UglyNumber.md │ │ ├── 50_01_FirstNotRepeatingChar.md │ │ ├── 50_02_FristCharacterInStream.md │ │ ├── 52_FirstCommonNodesInLists.md │ │ ├── 53_01_NumberOfK.md │ │ ├── 53_02_MissingNumber.md │ │ ├── 53_03_IntegerIdenticalToIndex.md │ │ ├── 54_KthNodeInBST.md │ │ ├── 55_01_TreeDepth.md │ │ ├── 55_02_BalancedBinaryTree.md │ │ ├── 56_01_NumbersAppearOnce.md │ │ ├── 56_02_NumberAppearingOnce.md │ │ ├── 57_01_TwoNumbersWithSum.md │ │ ├── 57_02_ContinuousSquenceWithSum.md │ │ ├── 58_01_ReverseWordsInSentence.md │ │ ├── 58_02_LeftRotateString.md │ │ ├── 59_01_MaxInSlidingWindow.md │ │ ├── 61_ContinousCards.md │ │ ├── README.md │ │ └── SUMMARY.md ├── leetcode │ ├── cpp │ │ ├── 0001._Two_Sum.md │ │ ├── 0002._Add_Two_Numbers.md │ │ ├── 0003._Longest_Substring_Without_Repeating_Characters.md │ │ ├── 0004._Median_of_Two_Sorted_Arrays.md │ │ ├── 0005._Longest_Palindromic_Substring.md │ │ ├── 0006._ZigZag_Conversion.md │ │ ├── 0007._Reverse_Integer.md │ │ ├── 0008._String_to_Integer_(atoi).md │ │ ├── 0009._Palindrome_Number.md │ │ ├── 0010._Regular_Expression_Matching.md │ │ ├── 0011._Container_With_Most_Water.md │ │ ├── 0012._Integer_to_Roman.md │ │ ├── 0014._Longest_Common_Prefix.md │ │ ├── 0015._3sum.md │ │ ├── 0016._3Sum_Closest.md │ │ ├── 0017._Letter_Combinations_of_a_Phone_Number.md │ │ ├── 0018._4Sum.md │ │ ├── 0019._Remove_Nth_Node_From_End_of_List.md │ │ ├── 0020._Valid_Parentheses.md │ │ ├── 0021._Merge_Two_Sorted_Lists.md │ │ ├── 0022._Generate_Parentheses.md │ │ ├── 0023._Merge_K_Sorted_Lists.md │ │ ├── 0024._Swap_Nodes_in_Pairs.md │ │ ├── 0025._Reverse_Nodes_In_K_Group.md │ │ ├── 0026._Remove_Duplicates_From_Sorted_Array.md │ │ ├── 0027._Remove_Element.md │ │ ├── 0028._Implement_Strstr.md │ │ ├── 0029._Divide_Two_Integers.md │ │ ├── 0030._Substring_With_Concatenation_Of_All_Words.md │ │ ├── 0031._Next_Permutatio.md │ │ ├── 0032._Longest_Valid_Parentheses.md │ │ ├── 0033._Search_in_Rotated_Sorted_Array.md │ │ ├── 0034._Find_First_and_Last_Position_of_Element_in_Sorted_Array.md │ │ ├── 0035._Search_Insert_Position.md │ │ ├── 0036._Valid_Sudoku.md │ │ ├── 0038._Count_and_Say.md │ │ ├── 0039._Combination_Sum.md │ │ ├── 0040._Combination_Sum_II.md │ │ ├── 0041._First_Missing_Positive.md │ │ ├── 0042._Trapping_Rain_Water.md │ │ ├── 0043._Multiply_Strings.md │ │ ├── 0044._Wildcard_Matching.md │ │ ├── 0045._Jump_Game_II.md │ │ ├── 0046._Permutations.md │ │ ├── 0047._Permutations_II.md │ │ ├── 0048._Rotate_Image.md │ │ ├── 0049._Group_Anagrams.md │ │ ├── 0050._powx_n.md │ │ ├── 0051._N-Queens.md │ │ ├── 0052._N-Queens_II.md │ │ ├── 0053._Maximum_Subarray.md │ │ ├── 0054._Spiral_Matrix.md │ │ ├── 0055._Jump_Game.md │ │ ├── 0056._Merge_Intervals.md │ │ ├── 0057._Insert_Interval.md │ │ ├── 0058._Length_of_Last_Word.md │ │ ├── 0059._Spiral_Matrix_II.md │ │ ├── 0060._Permutation_Sequence.md │ │ ├── 0061._Rotate_List.md │ │ ├── 0062._Unique_Paths.md │ │ ├── 0063._Unique_Paths_II.md │ │ ├── 0064._Minimum_Path_Sum.md │ │ ├── 0065._Valid_Number.md │ │ ├── 0066._Plus_One.md │ │ ├── 0068._Text_Justification.md │ │ ├── 0069._Sqr(x).md │ │ ├── 0072._Edit_Distance.md │ │ ├── 0075._Sort_Colors.md │ │ ├── 0076._Minimum_Window_Substring.md │ │ ├── 0077._combinations.md │ │ ├── 0078._subsets.md │ │ ├── 0081._Search_in_Rotated_Sorted_Array_II.md │ │ ├── 0083._Remove_Duplicates_From_Sorted_Lists.md │ │ ├── 0084._Largest_Rectangle_in_Histogram.md │ │ ├── 0085._Maximal_Rectangle.md │ │ ├── 0087._Scramble_String.md │ │ ├── 0088._Merge_Sorted_Array.md │ │ ├── 0090._Subsets_II.md │ │ ├── 0094._binary_tree_inorder_traversal.md │ │ ├── 0096._Unique_Binary_Search_Trees.md │ │ ├── 0097._Interleaving_String.md │ │ ├── 0099._Recover_Binary_Search_Tree.md │ │ ├── 0100._same_tree.md │ │ ├── 0101._Symmetric_Tree.md │ │ ├── 0102._Binary_Tree_Level_Order_Traversal.md │ │ ├── 0104._Maximum_Depth_of_Binary_Tree.md │ │ ├── 0105._Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.md │ │ ├── 0106._Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.md │ │ ├── 0107._Binary_Tree_Level_Order_Traversal_II.md │ │ ├── 0108._Convert_Sorted_Array_to_Binary_Search_Tree.md │ │ ├── 0109._Convert_Sorted_List_to_Binary_Search_Tree.md │ │ ├── 0110._Balanced_Binary_Tree.md │ │ ├── 0111._Minimum_Depth_Of_Binary_Tree.md │ │ ├── 0112._Path_Sum.md │ │ ├── 0114._Flatten_Binary_Tree_to_Linked_List.md │ │ ├── 0115._Distinct_Subsequences.md │ │ ├── 0118._Pascals_Triangle.md │ │ ├── 0119._Pascals_Triangle-II.md │ │ ├── 0120._Triangle.md │ │ ├── 0121._Best_Tim_to_Buy_and_Sell_Stock.md │ │ ├── 0122._Best_Time_to_Buy_and_Sell_Stock_II.md │ │ ├── 0123._Best_Time_to_Buy_and_Sell_Stock_III.md │ │ ├── 0124._Binary_Tree_Maximum_Path_Sum.md │ │ ├── 0127._Word_Ladde.md │ │ ├── 0128._Longest_Consecutive_Sequence.md │ │ ├── 0129._Sum_Root_to_Leaf_Numbers.md │ │ ├── 0131._Palindrome_Partitioning.md │ │ ├── 0136._Single_Numbe.md │ │ ├── 0137._Single_Number_II.md │ │ ├── 0141._Linked_List_Cycle.md │ │ ├── 0142._Linked_List_Cycle_II.md │ │ ├── 0144._Binary_Tree_Preorder_Traversal.md │ │ ├── 0145._Binary_Tree_Postorder_Traversal.md │ │ ├── 0147._Insert_on_Sort_List.md │ │ ├── 0148._Sort_list.md │ │ ├── 0151._Reverse_Words_in_a_String.md │ │ ├── 0153._Find_Minimum_in_Rotated_Sorted_Array.md │ │ ├── 0154._Find_Minimum_in_Rotated_Sorted_Array-II.md │ │ ├── 0160._Intersection_Of_Two_Linked_Lists.md │ │ ├── 0164._Maximum_Gap.md │ │ ├── 0166._Fraction_to_Recurring_Decimal.md │ │ ├── 0167._Two_Sum_II-Input_array_is_sorted.md │ │ ├── 0199._Binary_Tree_Right_Side_View.md │ │ ├── 0216._Combination_Sum_III.md │ │ ├── 0230._Kth_Smallest_Element_in_a_BST.md │ │ ├── 0260._Single_Number_III.md │ │ ├── 0287._Find_the_Duplicate_Number.md │ │ ├── 0326._Power_Of_Three.md │ │ ├── 0328._Odd_Even_Linked_List.md │ │ ├── 0329._Longest_Increasing_Path_in_a_Matrix.md │ │ ├── 0338._Counting_Bits.md │ │ ├── 0413._Arithmetic_Slices.md │ │ ├── 0442._Find_All_Duplicates_in_an_Array.md │ │ ├── 0513._Find_Bottom_Left_Tree_Value.md │ │ ├── 0515._Find_Largest_Value_in_Each_Tree_Row.md │ │ ├── 0540._Single_Element_in_a_Sorted_Array.md │ │ ├── 0581._Shortest_Unsorted_Continuous_Subarray.md │ │ ├── 0629._K_Inverse_Pairs_Array.md │ │ ├── 0632._Smallest_Range.md │ │ ├── 0654._maximum_binary_tree.md │ │ ├── 0668._Kth_Smallest_Number_in_Multiplication_Table.md │ │ ├── 0701._Insert_into_a_Binary_Search_Tree.md │ │ ├── 0715._Range_Module.md │ │ ├── 0719._Find_K-th_Smallest_Pair_Distance.md │ │ ├── 0739._Daily_Temperatures.md │ │ ├── 0797._All_Paths_From_Source_To_Target.md │ │ ├── 0814._Binary_Tree_Pruning.md │ │ ├── 0841._Keys_and_Rooms.md │ │ ├── 0877._Stone_Game.md │ │ ├── 0945._Minimum_Increment_to_Make_Array_Unique.md │ │ ├── 0946._Validate_Stack_Sequences.md │ │ ├── 0947._Most_Stones_Removed_with_Same_Row_or_Column.md │ │ ├── 0948._Bag_of_Tokens.md │ │ ├── 0949._Largest_Time_for_Given_Digits.md │ │ ├── 0950._Reveal_Cards_In_Increasing_Order.md │ │ ├── 0951._Flip_Equivalent_Binary_Trees.md │ │ ├── 0952._Largest_Component_Size_by_Common_Factor.md │ │ ├── README.md │ │ └── SUMMARY.md │ ├── java │ │ ├── 0001._Two_Sum.md │ │ ├── 0002._add_two_numbers.md │ │ ├── 0003._Longest_Substring_Without_Repeating_Characters.md │ │ ├── 0004._Median_of_Two_Sorted_Arrays.md │ │ ├── 0005._Longest_Palindromic_Substring.md │ │ ├── 0006._ZigZag_Conversion.md │ │ ├── 0007._Reverse_Integer.md │ │ ├── 0023._Merge_K_Sorted_Lists.md │ │ ├── 0141._linked_list_cycle.md │ │ ├── 0218._The_Skyline_Problem.md │ │ ├── 0238._product_of_array_except_self.md │ │ ├── 0342._Power_of_Four.md │ │ ├── 0403._Frog_Jump.md │ │ ├── 0757._Set_Intersection_Size_At_Least_Two.md │ │ ├── 0768._Max_Chunks_To_Make_Sorted_II.md │ │ ├── 0780._Reaching_Points.md │ │ ├── 0793._Preimage_Size_of_Factorial_Zeroes_Function.md │ │ ├── 0827._Making_A_Large_Island.md │ │ ├── 0828._Unique_Letter_String.md │ │ ├── 0834._Sum_of_Distances_in_Tree.md │ │ ├── 0843._Guess_the_Word.md │ │ ├── 0847._Shortest_Path_Visiting_All_Nodes.md │ │ ├── 0850._Rectangle_Area_II.md │ │ ├── 0854._K-Similar_Strings.md │ │ ├── 0857._Minimum_Cost_to_Hire_K_Workers.md │ │ ├── 0862._Shortest_Subarray_with_Sum_at_Least_K.md │ │ ├── 0864._Shortest_Path_to_Get_All_Keys.md │ │ ├── 0871._Minimum_Number_of_Refueling_Stops.md │ │ ├── 0878._Nth_Magical_Number.md │ │ ├── 0879._Profitable_Schemes.md │ │ ├── 0882._Reachable_Nodes_In_Subdivided_Graph.md │ │ ├── 0887._Super_Egg_Drop.md │ │ ├── 0891._Sum_of_Subsequence_Widths.md │ │ ├── 0895._Maximum_Frequency_Stack.md │ │ ├── 0899._Orderly_Queue.md │ │ ├── 0902._Numbers_At_Most_N_Given_Digit_Set.md │ │ ├── 0903._Valid_Permutations_for_DI_Sequence.md │ │ ├── 0906._Super_Palindromes.md │ │ ├── 0913._Cat_and_Mouse.md │ │ ├── 0920._Number_of_Music_Playlists.md │ │ ├── README.md │ │ └── SUMMARY.md │ ├── javascript │ │ ├── 0001._Two_Sum.md │ │ ├── 0002._Add_Two_Numbers.md │ │ ├── 0003._Longest_Substring_without_Repeating_Characters.md │ │ ├── 0005._Longest_Palindromic_Substring.md │ │ ├── 0007._Reverse_Integer.md │ │ ├── 0008._String_to_Integer.md │ │ ├── 0009._Palindrome_Number.md │ │ ├── 0011._Container_With_Most_Water.md │ │ ├── 0012._Integer_To_Roman.md │ │ ├── 0013._Roman_To_Integer.md │ │ ├── 0014._Longest_Common_Prefix.md │ │ ├── 0015._Three_Sum.md │ │ ├── 0016._3_Sum_Closest.md │ │ ├── 0017._Letter_Combinations_Of_A_Phone_Number.md │ │ ├── 0019._Remove_Nth_Node_From_End_Of_List.md │ │ ├── 0020._Valid_Parentheses.md │ │ ├── 0021._Merge_Two_Sorted_Lists.md │ │ ├── 0022._Generate_Parentheses.md │ │ ├── 0024._Swap_Nodes_In_Pairs.md │ │ ├── 0027._Remove_Element.md │ │ ├── 0031._Next_Permutation.md │ │ ├── 0035._Search_Insert_Position.md │ │ ├── 0053._Maximum_Subarray.md │ │ ├── 0054._Spiral_Matrix.md │ │ ├── 0055._Jump_Game.md │ │ ├── 0056._Merge_Intervals.md │ │ ├── 0058._Length_of_Last_Word.md │ │ ├── 0061._Rotate_List.md │ │ ├── 0062._Unique_Paths.md │ │ ├── 0064._Minimum_Path_Sum.md │ │ ├── 0066._Plus_One.md │ │ ├── 0067._Add_Binary.md │ │ ├── 0074._Search_a_2D_Matrix.md │ │ ├── 0077._Combinations.md │ │ ├── 0079._Search_Word.md │ │ ├── 0083._Remove_Duplicates_From_Sorted_List.md │ │ ├── 0094._Binary_Tree_Inorder_Traversal.md │ │ ├── 0098._Validate_Binary_Search_Tree.md │ │ ├── 0100._Same_Tree.md │ │ ├── 0101._Symmetric_Tree.md │ │ ├── 0104._Maximum_Depth_of_Binary_Tree.md │ │ ├── 0106._Construct_Binary_Tree_From_Inorder_And_Postorder_Traversal.md │ │ ├── 0120._Triangle.md │ │ ├── 0121._Best_Time_To_Buy_And_Sell_Stock.md │ │ ├── 0141._Linked_List_Cycle.md │ │ ├── 0146._LRU_Cache.md │ │ ├── 0167._Two_Sum_II_-_Input_array_is_sorted.md │ │ ├── 0167._Two_Sum_II_Input_Array_is_Sorted.md │ │ ├── 0171._Excel_Sheet_Column_Number.md │ │ ├── 0179._Largest_Number.md │ │ ├── 0198._House_Robber.md │ │ ├── 0203._Remove_Linked_List_Elements.md │ │ ├── 0206._Reverse_Linked_List.md │ │ ├── 0209._Minimum_Size_Subarray_Sum.md │ │ ├── 0258._Add_Digits.md │ │ ├── 0320._Coin_Change.md │ │ ├── 0347._Top_K_Frequent_Elements.md │ │ ├── 0402._Remove_K_Digits.md │ │ ├── 0406._Queue_Reconstruction_By_Height.md │ │ ├── 0485._Max_Consecutive_Ones.md │ │ ├── 0539._Minimum_Time_Difference.md │ │ ├── 0581._Shortest_Unsorted_Continuous_Subarray.md │ │ ├── 0881._Boats_to_Save_People.md │ │ ├── 0997._Find_The_Town_Judge.md │ │ ├── 1025._Divisor_Game.md │ │ ├── 1130._Minimum_Cost_Tree_From_Leaf_Values.md │ │ ├── 303._Range_Sum_Query_Immutable.md │ │ ├── README.md │ │ ├── SUMMARY.md │ │ └── book.json │ └── python │ │ ├── 001._two_sum.md │ │ ├── 002._add_two_numbers.md │ │ ├── 003._longest_substring_without_repeating_characters.md │ │ ├── 004._median_of_two_sorted_arrays.md │ │ ├── 005._longest_palindromic_substring.md │ │ ├── 006._ZigZag_Conversion.md │ │ ├── 007._Reverse_Integer.md │ │ ├── 008._string_to_integer_(atoi).md │ │ ├── 009._Palindrome_Number.md │ │ ├── 010._regular_expression_matching.md │ │ ├── 011._container_with_most_water.md │ │ ├── 012._Integer_to_Roman.md │ │ ├── 013._Roman_to_Integer.md │ │ ├── 014._longest_common_prefix.md │ │ ├── 015._3sum.md │ │ ├── 016._3sum_closest.md │ │ ├── 017._letter_combinations_of_a_phone_number.md │ │ ├── 018._4sum.md │ │ ├── 019._remove_nth_node_from_end_of_list.md │ │ ├── 020._valid_parentheses.md │ │ ├── 021._merge_two_sorted_lists.md │ │ ├── 022._generate_parentheses.md │ │ ├── 023._merge_k_sorted_lists.md │ │ ├── 024._swap_nodes_in_pairs.md │ │ ├── 026._Remove_Duplicates_from_Sorted_Array.md │ │ ├── 027._Remove_Element.md │ │ ├── 028._implement_strstr.md │ │ ├── 030._Substring_with_Concatenation_of_All_Words.md │ │ ├── 031._next_permutation.md │ │ ├── 032._longest_valid_parentheses.md │ │ ├── 033._search_in_rotated_sorted_array.md │ │ ├── 034._Search_for_a_Range.md │ │ ├── 035._search_insert_position.md │ │ ├── 038._Count_and_Say.md │ │ ├── 039._combination_sum.md │ │ ├── 040._combination_sum_ii.md │ │ ├── 041._First_Missing_Positive.md │ │ ├── 042._trapping_rain_water.md │ │ ├── 043._multiply_strings.md │ │ ├── 044._wildcard_matching.md │ │ ├── 045._Jump_Game_II.md │ │ ├── 046._permutations.md │ │ ├── 047._permutations_ii.md │ │ ├── 048._rotate_image.md │ │ ├── 049._group_anagrams_python.md │ │ ├── 050._pow(x,_n).md │ │ ├── 051._n-queens.md │ │ ├── 052._n-queens_ii.md │ │ ├── 053._maximum_subarray.md │ │ ├── 054._spiral_matrix.md │ │ ├── 055._jump_game.md │ │ ├── 056._Merge_Intervals.md │ │ ├── 058._length_of_last_word.md │ │ ├── 059._spiral_matrix_ii.md │ │ ├── 060._permutation_sequence.md │ │ ├── 061._rotate_list.md │ │ ├── 062._unique_paths.md │ │ ├── 064._minimum_path_sum.md │ │ ├── 065.unique_paths_ii.md │ │ ├── 066._plus_one.md │ │ ├── 067._add_binary.md │ │ ├── 069._sqrt(x).md │ │ ├── 070._Climbing_Stairs.md │ │ ├── 072._edit_distance.md │ │ ├── 073._Set_Matrix_Zeroes.md │ │ ├── 074._search_a_2d_matrix.md │ │ ├── 075._sort_colors.md │ │ ├── 076._Minimum_Window_Substring.md │ │ ├── 077._combinations.md │ │ ├── 078._Subsets.md │ │ ├── 079._word_search.md │ │ ├── 082._remove_duplicates_from_sorted_list_ii.md │ │ ├── 083._remove_duplicates_from_sorted_list.md │ │ ├── 086._partition_list.md │ │ ├── 088._merge_sorted_array.md │ │ ├── 089._gray_code.md │ │ ├── 090._subsets_ii.md │ │ ├── 091._decode_ways.md │ │ ├── 092._reverse_linked_list_ii.md │ │ ├── 093._restore_ip_addresses.md │ │ ├── 094._binary_tree_inorder_traversal.md │ │ ├── 096._unique_binary_search_trees.md │ │ ├── 098._validate_binary_search_tree.md │ │ ├── 100._same_tree.md │ │ ├── 101._symmetric_tree.md │ │ ├── 102._binary_tree_level_order_traversal.md │ │ ├── 103._binary_tree_zigzag_level_order_traversal.md │ │ ├── 104._maximum_depth_of_binary_tree.md │ │ ├── 105._construct_binary_tree_from_preorder_and_inorder_traversal.md │ │ ├── 106._construct_binary_tree_from_inorder_and_postorder_traversal.md │ │ ├── 107._binary_tree_level_order_traversal_ii.md │ │ ├── 108._convert_sorted_array_to_binary_search_tree.md │ │ ├── 109._convert_sorted_list_to_binary_search_tree.md │ │ ├── 110._balanced_binary_tree.md │ │ ├── 111._minimum_depth_of_binary_tree.md │ │ ├── 112._path_sum.md │ │ ├── 113._path_sum_ii.md │ │ ├── 114._flatten_binary_tree_to_linked_list.md │ │ ├── 116._populating_next_right_pointers_in_each_node.md │ │ ├── 117._Populating_Next_Right_Pointers_in_Each_Node_II.md │ │ ├── 118._pascal's_triangle.md │ │ ├── 119._Pascal's_Triangle_II.md │ │ ├── 120._Triangle.md │ │ ├── 121._Best_Time_to_Buy_and_Sell_Stock.md │ │ ├── 124._Binary_Tree_Maximum_Path_Sum.md │ │ ├── 125._valid_palindrome.md │ │ ├── 126._Word_Ladder_II.md │ │ ├── 127._word_ladder.md │ │ ├── 128._Longest_Consecutive_Sequence.md │ │ ├── 129._sum_root_to_leaf_numbers.md │ │ ├── 130._surrounded_regions.md │ │ ├── 131._palindrome_partitioning.md │ │ ├── 133._clone_graph.md │ │ ├── 136._single_number.md │ │ ├── 139._word_break.md │ │ ├── 140._word_break_ii.md │ │ ├── 141._linked_list_cycle.md │ │ ├── 142_Linked_List_Cycle_II.md │ │ ├── 143._reorder_list.md │ │ ├── 144._binary_tree_preorder_traversal.md │ │ ├── 145._binary_tree_postorder_traversal.md │ │ ├── 147._insertion_sort_list.md │ │ ├── 148._sort_list.md │ │ ├── 150._evaluate_reverse_polish_notation.md │ │ ├── 151._reverse_words_in_a_string.md │ │ ├── 152._maximum_product_subarray.md │ │ ├── 153._find_minimum_in_rotated_sorted_array.md │ │ ├── 155._min_stack.md │ │ ├── 157._Read_N_Characters_Given_Read4.md │ │ ├── 158._Read_N_Characters_Given_Read4_II_-_Call_multiple_times.md │ │ ├── 159._Longest_Substring_with_At_Most_Two_Distinct_Characters.md │ │ ├── 160._intersection_of_two_linked_lists.md │ │ ├── 162._find_peak_element.md │ │ ├── 165._compare_version_numbers.md │ │ ├── 166._Fraction_to_Recurring_Decimal.md │ │ ├── 167._two_sum_ii_-_input_array_is_sorted.md │ │ ├── 168._excel_sheet_column_title.md │ │ ├── 169._majority_element.md │ │ ├── 171._excel_sheet_column_number.md │ │ ├── 173._binary_search_tree_iterator.md │ │ ├── 179._Largest_Number.md │ │ ├── 182._duplicate_emails.md │ │ ├── 189._rotate_array.md │ │ ├── 191._number_of_1_bits.md │ │ ├── 198._house_robber.md │ │ ├── 199._binary_tree_right_side_view.md │ │ ├── 200._number_of_islands.md │ │ ├── 203._remove_linked_list_elements.md │ │ ├── 204._count_primes.md │ │ ├── 205._isomorphic_strings.md │ │ ├── 206._reverse_linked_list.md │ │ ├── 207._course_schedule.md │ │ ├── 208._implement_trie_(prefix_tree).md │ │ ├── 210._course_schedule_ii.md │ │ ├── 211._Add_and_Search_Word_-_Data_structure_design.md │ │ ├── 213._house_robber_ii.md │ │ ├── 216._combination_sum_iii.md │ │ ├── 217._contains_duplicate.md │ │ ├── 218._The_Skyline_Problem.md │ │ ├── 219._contains_duplicate_ii.md │ │ ├── 221._maximal_square.md │ │ ├── 222._count_complete_tree_nodes.md │ │ ├── 223._rectangle_area.md │ │ ├── 224._Basic_Calculator.md │ │ ├── 225._implement_stack_using_queues.md │ │ ├── 226._invert_binary_tree.md │ │ ├── 227._basic_calculator_ii.md │ │ ├── 228._summary_ranges.md │ │ ├── 229._majority_element_ii.md │ │ ├── 230._kth_smallest_element_in_a_bst.md │ │ ├── 231._Power_of_Two.md │ │ ├── 232._implement_queue_using_stacks.md │ │ ├── 234._palindrome_linked_list.md │ │ ├── 235._lowest_common_ancestor_of_a_binary_search_tree.md │ │ ├── 236._lowest_common_ancestor_of_a_binary_tree.md │ │ ├── 237._delete_node_in_a_linked_list.md │ │ ├── 238._product_of_array_except_self.md │ │ ├── 240._search_a_2d_matrix_ii.md │ │ ├── 242._valid_anagram.md │ │ ├── 249._Group_Shifted_Strings.md │ │ ├── 252._Meeting_Rooms.md │ │ ├── 255._Verify_Preorder_Sequence_in_Binary_Search_Tree.md │ │ ├── 256._Paint_House.md │ │ ├── 257._binary_tree_paths.md │ │ ├── 258._Add_Digits.md │ │ ├── 261._Graph_Valid_Tree.md │ │ ├── 263._ugly_number.md │ │ ├── 264._ugly_number_ii.md │ │ ├── 265._Paint_House_II.md │ │ ├── 266._Palindrome_Permutation.md │ │ ├── 267._Palindrome_Permutation_II.md │ │ ├── 268._missing_number.md │ │ ├── 270._Closest_Binary_Search_Tree_Value.md │ │ ├── 276._Paint_Fence.md │ │ ├── 277._Find_the_Celebrity.md │ │ ├── 278._First_Bad_Version.md │ │ ├── 279._perfect_squares.md │ │ ├── 280._Wiggle_Sort.md │ │ ├── 283._move_zeroes.md │ │ ├── 285._inorder_successor_in_bst.md │ │ ├── 286._Walls_and_Gates.md │ │ ├── 287._Find_the_Duplicate_Number.md │ │ ├── 289._game_of_life.md │ │ ├── 290._word_pattern.md │ │ ├── 292._nim_game.md │ │ ├── 293._Flip_Game.md │ │ ├── 296._Best_Meeting_Point.md │ │ ├── 298._Binary_Tree_Longest_Consecutive_Sequence.md │ │ ├── 299._bulls_and_cows.md │ │ ├── 300._longest_increasing_subsequence.md │ │ ├── 303._range_sum_query_-_immutable.md │ │ ├── 316._Remove_Duplicate_Letters.md │ │ ├── 319._Bulb_Switcher.md │ │ ├── 322._Coin_Change.md │ │ ├── 323._number_of_connected_components_in_an_undirected_graph.md │ │ ├── 324._Wiggle_Sort_II.md │ │ ├── 326._power_of_three.md │ │ ├── 328._odd_even_linked_list.md │ │ ├── 334._increasing_triplet_subsequence.md │ │ ├── 337._house_robber_iii.md │ │ ├── 338._Counting_Bits.md │ │ ├── 339._Nested_List_Weight_Sum.md │ │ ├── 341._Flatten_Nested_List_Iterator.md │ │ ├── 342._Power_of_Four.md │ │ ├── 344._reverse_string.md │ │ ├── 345._Reverse_Vowels_of_a_String.md │ │ ├── 349._intersection_of_two_arrays.md │ │ ├── 350._intersection_of_two_arrays_ii.md │ │ ├── 353._Design_Snake_Game.md │ │ ├── 361._Bomb_Enemy.md │ │ ├── 364._Nested_List_Weight_Sum_II.md │ │ ├── 366._Find_Leaves_of_Binary_Tree.md │ │ ├── 367._valid_perfect_square.md │ │ ├── 369._Plus_One_Linked_List.md │ │ ├── 371._sum_of_two_integers.md │ │ ├── 374._Guess_Number_Higher_or_Lower.md │ │ ├── 377._combination_sum_iv.md │ │ ├── 378._kth_smallest_element_in_a_sorted_matrix.md │ │ ├── 380._Insert_Delete_GetRandom_O(1).md │ │ ├── 381._Insert_Delete_GetRandom_O(1)_-_Duplicates_allowed.md │ │ ├── 382._linked_list_random_node.md │ │ ├── 383._ransom_note.md │ │ ├── 384._Shuffle_an_Array.md │ │ ├── 386._Lexicographical_Numbers.md │ │ ├── 387._first_unique_character_in_a_string.md │ │ ├── 388._Longest_Absolute_File_Path.md │ │ ├── 389._find_the_difference.md │ │ ├── 392._is_subsequence.md │ │ ├── 394._decode_string.md │ │ ├── 400._Nth_Digit.md │ │ ├── 401._binary_watch.md │ │ ├── 404._sum_of_left_leaves.md │ │ ├── 405._Convert_a_Number_to_Hexadecimal.md │ │ ├── 406._Queue_Reconstruction_by_Height.md │ │ ├── 412._fizz_buzz.md │ │ ├── 413._Arithmetic_Slices.md │ │ ├── 414._third_maximum_number.md │ │ ├── 415._add_strings.md │ │ ├── 416._Partition_Equal_Subset_Sum.md │ │ ├── 421._Maximum_XOR_of_Two_Numbers_in_an_Array.md │ │ ├── 422._Valid_Word_Square.md │ │ ├── 434._number_of_segments_in_a_string.md │ │ ├── 435._Non-overlapping_Intervals.md │ │ ├── 437._path_sum_iii.md │ │ ├── 438._Find_All_Anagrams_in_a_String.md │ │ ├── 439._Ternary_Expression_Parser.md │ │ ├── 441._arranging_coins.md │ │ ├── 448._Find_All_Numbers_Disappeared_in_an_Array.md │ │ ├── 450._Delete_Node_in_a_BST.md │ │ ├── 453._Minimum_Moves_to_Equal_Array_Elements.md │ │ ├── 459._Repeated_Substring_Pattern.md │ │ ├── 461._Hamming_Distance.md │ │ ├── 463._Island_Perimeter.md │ │ ├── 467._Unique_Substrings_in_Wraparound_String.md │ │ ├── 469._Convex_Polygon.md │ │ ├── 476._Number_Complement.md │ │ ├── 477._Total_Hamming_Distance.md │ │ ├── 485._Max_Consecutive_Ones.md │ │ ├── 494._Target_Sum.md │ │ ├── 536._Construct_Binary_Tree_from_String.md │ │ ├── 587._Erect_the_Fence.md │ │ ├── 599._Minimum_Index_Sum_of_Two_Lists.md │ │ ├── 606._Construct_String_from_Binary_Tree.md │ │ ├── 611._Valid_Triangle_Number.md │ │ ├── 646._Maximum_Length_of_Pair_Chain.md │ │ ├── 647._Palindromic_Substrings.md │ │ ├── 657._Judge_Route_Circle.md │ │ ├── 665._Non-decreasing_Array.md │ │ ├── 672._Bulb_Switcher_II.md │ │ ├── 681._Next_Closest_Time.md │ │ ├── 682._Baseball_Game.md │ │ ├── 685._Redundant_Connection_II.md │ │ ├── 687._Longest_Univalue_Path.md │ │ ├── 693._Binary_Number_with_Alternating_Bits.md │ │ ├── 701._Insert_into_a_Binary_Search_Tree.md │ │ ├── 707._Design_Linked_List.md │ │ ├── 740._delete_and_earn.md │ │ ├── 760._Find_Anagram_Mappings.md │ │ ├── 774._Minimize_Max_Distance_to_Gas_Station.md │ │ ├── 777._Swap_Adjacent_in_LR_String.md │ │ ├── 844._Backspace_String_Compare.md │ │ ├── README.md │ │ └── SUMMARY.md └── think-dast-zh │ ├── 0.md │ ├── 1.md │ ├── 10.md │ ├── 11.md │ ├── 12.md │ ├── 13.md │ ├── 14.md │ ├── 15.md │ ├── 16.md │ ├── 17.md │ ├── 2.md │ ├── 3.md │ ├── 4.md │ ├── 5.md │ ├── 6.md │ ├── 7.md │ ├── 8.md │ ├── 9.md │ ├── README.md │ ├── SUMMARY.md │ ├── cover.jpg │ └── img │ ├── 11-1.jpg │ ├── 11-2.jpg │ ├── 12-1.jpg │ ├── 13-1.jpg │ ├── 17-1.jpg │ ├── 17-2.jpg │ ├── 17-3.jpg │ ├── 3-1.jpg │ ├── 4-1.jpg │ ├── 5-1.jpg │ ├── 5-2.jpg │ ├── 5-3.jpg │ ├── 6-1.jpg │ ├── 6-2.jpg │ ├── 6-3.jpg │ ├── 8-1.jpg │ └── qr_alipay.png ├── index.html └── update.sh /.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/.nojekyll -------------------------------------------------------------------------------- /404.html: -------------------------------------------------------------------------------- 1 | --- 2 | permalink: /404.html 3 | --- 4 | 5 | -------------------------------------------------------------------------------- /CNAME: -------------------------------------------------------------------------------- 1 | algo.apachecn.org -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM httpd:2.4 2 | COPY ./ /usr/local/apache2/htdocs/ -------------------------------------------------------------------------------- /asset/back-to-top.css: -------------------------------------------------------------------------------- 1 | #scroll-btn { 2 | position: fixed; 3 | right: 15px; 4 | bottom: 10px; 5 | width: 35px; 6 | height: 35px; 7 | background-repeat: no-repeat; 8 | background-size: cover; 9 | cursor: pointer; 10 | -webkit-user-select: none; 11 | -moz-user-select: none; 12 | -ms-user-select: none; 13 | user-select: none; 14 | background-image: url(up.svg); 15 | background-position-y: -1px; 16 | display: none; 17 | border: 2px solid; 18 | border-radius: 4px; 19 | } -------------------------------------------------------------------------------- /asset/back-to-top.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function() { 2 | var scrollBtn = document.createElement('div') 3 | scrollBtn.id = 'scroll-btn' 4 | document.body.append(scrollBtn) 5 | 6 | window.addEventListener('scroll', function() { 7 | var offset = window.document.documentElement.scrollTop; 8 | scrollBtn.style.display = offset >= 500 ? "block" : "none"; 9 | }) 10 | scrollBtn.addEventListener('click', function(e) { 11 | e.stopPropagation(); 12 | var step = window.scrollY / 15; 13 | var hdl = setInterval(function() { 14 | window.scrollTo(0, window.scrollY - step); 15 | if(window.scrollY <= 0) { 16 | clearInterval(hdl) 17 | } 18 | }, 15) 19 | }) 20 | }) -------------------------------------------------------------------------------- /asset/dark-mode.css: -------------------------------------------------------------------------------- 1 | #dark-mode-btn { 2 | position: fixed; 3 | right: 15px; 4 | top: 100px; 5 | width: 35px; 6 | height: 35px; 7 | background-repeat: no-repeat; 8 | background-size: cover; 9 | cursor: pointer; 10 | -webkit-user-select: none; 11 | -moz-user-select: none; 12 | -ms-user-select: none; 13 | user-select: none; 14 | transition: background-image .15s ease-in-out .15s; 15 | } 16 | 17 | .dark-logo { 18 | background-image: url('sun.svg'); 19 | } 20 | 21 | .light-logo { 22 | background-image: url('moon.svg'); 23 | } -------------------------------------------------------------------------------- /asset/dark-mode.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function() { 2 | var style = document.querySelector('#invert') 3 | if (style == null) { 4 | style = document.createElement('style') 5 | style.id = 'invert' 6 | document.head.append(style) 7 | } 8 | var btn = document.querySelector('#dark-mode-btn') 9 | if (btn == null) { 10 | btn = document.createElement('div') 11 | btn.id = 'dark-mode-btn' 12 | btn.classList.add('light-logo') 13 | document.body.append(btn) 14 | } 15 | 16 | var enableDarkMode = function() { 17 | style.innerText = 'html,img,pre,#dark-mode-btn{filter:invert(100%)}' 18 | btn.classList.remove('light-logo') 19 | btn.classList.add('dark-logo') 20 | localStorage.darkLight = 'dark' 21 | 22 | } 23 | var disableDarkMode = function() { 24 | style.innerText = '' 25 | btn.classList.remove('dark-logo') 26 | btn.classList.add('light-logo') 27 | localStorage.darkLight = 'light' 28 | } 29 | 30 | btn.addEventListener('click', function(){ 31 | var currMode = localStorage.darkLight || 'light' 32 | if (currMode == 'light') 33 | enableDarkMode() 34 | else 35 | disableDarkMode() 36 | }) 37 | 38 | if (localStorage.darkLight == 'dark') 39 | enableDarkMode() 40 | 41 | }) 42 | 43 | -------------------------------------------------------------------------------- /asset/docsify-baidu-push.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | var plugin = function(hook) { 3 | hook.doneEach(function() { 4 | new Image().src = 5 | '//api.share.baidu.com/s.gif?r=' + 6 | encodeURIComponent(document.referrer) + 7 | "&l=" + encodeURIComponent(location.href) 8 | }) 9 | } 10 | var plugins = window.$docsify.plugins || [] 11 | plugins.push(plugin) 12 | window.$docsify.plugins = plugins 13 | })() -------------------------------------------------------------------------------- /asset/docsify-baidu-stat.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | var plugin = function(hook) { 3 | hook.doneEach(function() { 4 | window._hmt = window._hmt || [] 5 | var hm = document.createElement("script") 6 | hm.src = "https://hm.baidu.com/hm.js?" + window.$docsify.bdStatId 7 | document.querySelector("article").appendChild(hm) 8 | }) 9 | } 10 | var plugins = window.$docsify.plugins || [] 11 | plugins.push(plugin) 12 | window.$docsify.plugins = plugins 13 | })() -------------------------------------------------------------------------------- /asset/docsify-cnzz.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | var plugin = function(hook) { 3 | hook.doneEach(function() { 4 | var sc = document.createElement('script') 5 | sc.src = 'https://s5.cnzz.com/z_stat.php?id=' + 6 | window.$docsify.cnzzId + '&online=1&show=line' 7 | document.querySelector('article').appendChild(sc) 8 | }) 9 | } 10 | var plugins = window.$docsify.plugins || [] 11 | plugins.push(plugin) 12 | window.$docsify.plugins = plugins 13 | })() -------------------------------------------------------------------------------- /asset/docsify-quick-page.css: -------------------------------------------------------------------------------- 1 | #prev-page-button { 2 | position:fixed; 3 | top:140px; 4 | width: 35px; 5 | height: 35px; 6 | right: 15px; 7 | background-color: transparent; 8 | background-image: url(left.svg); 9 | background-repeat: no-repeat; 10 | background-size: cover; 11 | border:0; 12 | -webkit-user-select: none; 13 | -moz-user-select: none; 14 | -ms-user-select: none; 15 | user-select: none; 16 | outline:none; 17 | cursor: pointer; 18 | } 19 | 20 | #next-page-button { 21 | position:fixed; 22 | top:180px; 23 | width:35px; 24 | height:35px; 25 | right:15px; 26 | background-color: transparent; 27 | background-image: url(right.svg); 28 | background-repeat: no-repeat; 29 | background-size: cover; 30 | border:0; 31 | -webkit-user-select: none; 32 | -moz-user-select: none; 33 | -ms-user-select: none; 34 | user-select: none; 35 | outline:none; 36 | cursor: pointer; 37 | } -------------------------------------------------------------------------------- /asset/edit.css: -------------------------------------------------------------------------------- 1 | #edit-btn { 2 | position: fixed; 3 | right: 15px; 4 | top: 260px; 5 | width: 35px; 6 | height: 35px; 7 | background-repeat: no-repeat; 8 | background-size: cover; 9 | cursor: pointer; 10 | -webkit-user-select: none; 11 | -moz-user-select: none; 12 | -ms-user-select: none; 13 | user-select: none; 14 | background-image: url(edit.svg); 15 | } -------------------------------------------------------------------------------- /asset/edit.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function() { 2 | var editBtn = document.createElement('div') 3 | editBtn.id = 'edit-btn' 4 | document.body.append(editBtn) 5 | 6 | var repo = window.$docsify.repo 7 | editBtn.addEventListener('click', function() { 8 | if (!repo) return 9 | if (!/https?:\/\//.exec(repo)) 10 | repo = 'https://github.com/' + repo 11 | var url = repo + '/tree/master' + 12 | location.hash.slice(1) + '.md' 13 | window.open(url) 14 | }) 15 | }) -------------------------------------------------------------------------------- /asset/edit.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Edit 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /asset/left.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1210 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /asset/moon.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /asset/right.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1209 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /asset/share.css: -------------------------------------------------------------------------------- 1 | #share-btn { 2 | position: fixed; 3 | right: 15px; 4 | top: 220px; 5 | width: 35px; 6 | height: 35px; 7 | background-repeat: no-repeat; 8 | background-size: cover; 9 | cursor: pointer; 10 | -webkit-user-select: none; 11 | -moz-user-select: none; 12 | -ms-user-select: none; 13 | user-select: none; 14 | background-image: url('share.svg'); 15 | } -------------------------------------------------------------------------------- /asset/sidebar.min.css: -------------------------------------------------------------------------------- 1 | .sidebar-nav li{position:relative;margin:0;cursor:pointer}.sidebar-nav ul:not(.app-sub-sidebar)>li:not(.file)::before{content:'';display:block;position:absolute;top:11px;left:-12px;height:6px;width:6px;border-right:1px solid #505d6b;border-bottom:1px solid #505d6b;transform:rotate(-45deg);transition:transform .1s}.sidebar-nav ul:not(.app-sub-sidebar)>li.open::before{transform:rotate(45deg)}.sidebar-nav ul:not(.app-sub-sidebar)>li.collapse::before{transform:rotate(-45deg)} -------------------------------------------------------------------------------- /asset/sun.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /asset/up.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1211 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /docs/jianzhioffer/java/09_01_QueueWithTwoStacks.md: -------------------------------------------------------------------------------- 1 | ## 用两个栈实现队列 2 | 3 | ### 题目描述 4 | 用两个栈来实现一个队列,完成队列的 `Push` 和 `Pop` 操作。 队列中的元素为 `int` 类型。 5 | 6 | 7 | ### 解法 8 | `Push` 操作,每次都存入 `stack1`; 9 | `Pop` 操作,每次从 `stack2` 取: 10 | - `stack2` 栈不为空时,不能将 `stack1` 元素倒入; 11 | - `stack2` 栈为空时,需要一次将 `stack1` 元素全部倒入。 12 | 13 | ```java 14 | import java.util.Stack; 15 | 16 | /** 17 | * @author bingo 18 | * @since 2018/10/28 19 | */ 20 | 21 | public class Solution { 22 | Stack stack1 = new Stack(); 23 | Stack stack2 = new Stack(); 24 | 25 | public void push(int node) { 26 | stack1.push(node); 27 | } 28 | 29 | public int pop() { 30 | if (stack2.isEmpty()) { 31 | if (stack1.isEmpty()) { 32 | return -1; 33 | } 34 | while (!stack1.isEmpty()) { 35 | stack2.push(stack1.pop()); 36 | } 37 | } 38 | return stack2.pop(); 39 | } 40 | } 41 | ``` 42 | 43 | 44 | ### 测试用例 45 | 1. 往空的队列里添加、删除元素; 46 | 2. 往非空的队列添加、删除元素; 47 | 3. 连续删除元素直至队列为空。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/10_02_JumpFloor.md: -------------------------------------------------------------------------------- 1 | ## 跳台阶 2 | 3 | ### 题目描述 4 | 一只青蛙一次可以跳上`1`级台阶,也可以跳上`2`级。求该青蛙跳上一个`n`级的台阶总共有多少种跳法(先后次序不同算不同的结果)。 5 | 6 | ### 解法 7 | 跳上 `n` 级台阶,可以从 `n-1` 级跳 `1` 级上去,也可以从 `n-2` 级跳 `2` 级上去。所以 8 | ``` 9 | f(n) = f(n-1) + f(n-2) 10 | ``` 11 | 12 | ```java 13 | /** 14 | * @author bingo 15 | * @since 2018/11/23 16 | */ 17 | 18 | public class Solution { 19 | /** 20 | * 青蛙跳台阶 21 | * @param target 跳上的那一级台阶 22 | * @return 多少种跳法 23 | */ 24 | public int JumpFloor(int target) { 25 | if (target < 3) { 26 | return target; 27 | } 28 | int[] res = new int[target + 1]; 29 | res[1] = 1; 30 | res[2] = 2; 31 | for (int i = 3; i <= target; ++i) { 32 | res[i] = res[i - 1] + res[i - 2]; 33 | } 34 | return res[target]; 35 | } 36 | } 37 | ``` 38 | 39 | ### 测试用例 40 | 1. 功能测试(如输入 3、5、10 等); 41 | 2. 边界值测试(如输入 0、1、2); 42 | 3. 性能测试(输入较大的数字,如 40、50、100 等)。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/10_03_JumpFloorII.md: -------------------------------------------------------------------------------- 1 | ## 变态跳台阶 2 | 3 | ### 题目描述 4 | 一只青蛙一次可以跳上`1`级台阶,也可以跳上`2`级……它也可以跳上`n`级。求该青蛙跳上一个`n`级的台阶总共有多少种跳法。 5 | 6 | ### 解法 7 | 跳上 `n-1` 级台阶,可以从 `n-2` 级跳 `1` 级上去,也可以从 `n-3` 级跳 `2` 级上去...也可以从 `0` 级跳上去。那么 8 | ``` 9 | f(n-1) = f(0) + f(1) + ... + f(n-2) ① 10 | ``` 11 | 12 | 跳上 `n` 级台阶,可以从 `n-1` 级跳 `1` 级上去,也可以从 `n-2` 级跳 `2` 级上去...也可以从 `0` 级跳上去。那么 13 | ``` 14 | f(n) = f(0) + f(1) + ... + f(n-2) + f(n-1) ② 15 | 16 | ②-①: 17 | f(n) - f(n-1) = f(n-1) 18 | f(n) = 2f(n-1) 19 | ``` 20 | 21 | 所以 f(n) 是一个等比数列: 22 | ``` 23 | f(n) = 2^(n-1) 24 | ``` 25 | 26 | 27 | ```java 28 | /** 29 | * @author bingo 30 | * @since 2018/11/23 31 | */ 32 | 33 | public class Solution { 34 | /** 35 | * 青蛙跳台阶II 36 | * @param target 跳上的那一级台阶 37 | * @return 多少种跳法 38 | */ 39 | public int JumpFloorII(int target) { 40 | return (int) Math.pow(2, target - 1); 41 | } 42 | } 43 | ``` 44 | 45 | ### 测试用例 46 | 1. 功能测试(如输入 3、5、10 等); 47 | 2. 边界值测试(如输入 0、1、2); 48 | 3. 性能测试(输入较大的数字,如 40、50、100 等)。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/16_Power.md: -------------------------------------------------------------------------------- 1 | ## 数值的整数次方 2 | 3 | ### 题目描述 4 | 给定一个 `double` 类型的浮点数 `base` 和 `int` 类型的整数 `exponent`。求 `base`的 `exponent` 次方。 5 | 6 | ### 解法 7 | 注意判断值数是否小于 0。另外 0 的 0 次方没有意义,也需要考虑一下,看具体题目要求。 8 | 9 | ```java 10 | /** 11 | * @author bingo 12 | * @since 2018/11/20 13 | */ 14 | 15 | public class Solution { 16 | /** 17 | * 计算数值的整数次方 18 | * @param base 底数 19 | * @param exponent 指数 20 | * @return 数值的整数次方 21 | */ 22 | public double Power(double base, int exponent) { 23 | double result = 1.0; 24 | int n = Math.abs(exponent); 25 | for (int i = 0; i < n; ++i) { 26 | result *= base; 27 | } 28 | 29 | return exponent < 0 ? 1.0 / result : result; 30 | } 31 | } 32 | 33 | ``` 34 | 35 | ### 测试用例 36 | 1. 把底数和指数分别设为正数、负数和零。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/42_GreatestSumOfSubarrays.md: -------------------------------------------------------------------------------- 1 | ## 连续子数组的最大和 2 | 3 | ### 题目描述 4 | 输入一个**非空**整型数组,数组里的数可能为正,也可能为负。 5 | 数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。 6 | 7 | 要求时间复杂度为`O(n)`。 8 | 9 | ### 解法 10 | 动态规划法。 11 | 12 | res[i] 表示以第 i 个数字结尾的子数组的最大和,那么求出 `max(res[i])` 即可。 13 | 14 | - `res[i] = array[i]`, if `res[i - 1] < 0` 15 | - `res[i] = res[i - 1] + array[i]`, if `res[i - 1] >= 0` 16 | 17 | ```java 18 | 19 | /** 20 | * @author bingo 21 | * @since 2018/12/7 22 | */ 23 | 24 | public class Solution { 25 | /** 26 | * 求连续子数组的最大和 27 | * 28 | * @param array 数组 29 | * @return 最大和 30 | */ 31 | public int FindGreatestSumOfSubArray(int[] array) { 32 | int n = array.length; 33 | int[] res = new int[n]; 34 | res[0] = array[0]; 35 | int max = res[0]; 36 | for (int i = 1; i < n; ++i) { 37 | res[i] = res[i - 1] > 0 ? res[i - 1] + array[i] : array[i]; 38 | max = Math.max(max, res[i]); 39 | } 40 | return max; 41 | } 42 | } 43 | 44 | 45 | ``` 46 | 47 | ### 测试用例 48 | 1. 功能测试(输入的数组中有正数也有负数;输入的数组中全是正数;输入的数组中全是负数); 49 | 2. 特殊输入测试(表示数组的指针位为空指针)。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/45_SortArrayForMinNumber.md: -------------------------------------------------------------------------------- 1 | ## 把数组排成最小的数 2 | 3 | ### 题目描述 4 | 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 5 | 6 | 例如输入数组 `[3, 32, 321]`,则打印出这3个数字能排成的最小数字`321323`。 7 | 8 | ### 解法 9 | 10 | 11 | ```java 12 | import java.util.Arrays; 13 | 14 | /** 15 | * @author bingo 16 | * @since 2018/12/8 17 | */ 18 | 19 | class Solution { 20 | 21 | /** 22 | * 打印数组元素组成的最小的数字 23 | * 24 | * @param nums 数组 25 | * @return 最小的数字 26 | */ 27 | public String printMinNumber(int[] nums) { 28 | if (nums == null || nums.length == 0) { 29 | return ""; 30 | } 31 | int n = nums.length; 32 | String[] strNums = new String[n]; 33 | for (int i = 0; i < n; ++i) { 34 | strNums[i] = String.valueOf(nums[i]); 35 | } 36 | 37 | Arrays.sort(strNums, (o1, o2) -> (o1 + o2).compareTo(o2 + o1)); 38 | 39 | StringBuilder sb = new StringBuilder(); 40 | for (String str : strNums) { 41 | sb.append(str); 42 | } 43 | return sb.toString(); 44 | } 45 | } 46 | ``` 47 | 48 | ### 测试用例 49 | 1. 功能测试(输入的数组中有多个数字;输入的数组中的数字有重复的数位;输入的数组中只有一个数字); 50 | 2. 特殊输入测试(表示数组的指针为空指针)。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/50_01_FirstNotRepeatingChar.md: -------------------------------------------------------------------------------- 1 | ## 第一个只出现一次的字符 2 | 3 | ### 题目描述 4 | 在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写). 5 | 6 | ### 解法1 7 | 使用HashMap来统计字符出现的次数,因为字符的多少是固定的(大小写字母一共52个),所以可以认为使用HashMap的空间复杂度为O(1)。该解法时间复杂度为O(n)。 8 | 9 | ```java 10 | /** 11 | * @author mcrwayfun 12 | * @version v1.0 13 | * @date Created in 2019/01/24 14 | * @description 15 | */ 16 | public class Solution { 17 | 18 | public int FirstNotRepeatingChar(String str) { 19 | 20 | if (str == null || str.length() == 0) { 21 | return -1; 22 | } 23 | 24 | Map characterMap = new HashMap<>(); 25 | // hashMap is HashTable,search cost O(1) 26 | for (int i = 0; i < str.length(); i++) { 27 | characterMap.put(str.charAt(i), characterMap.getOrDefault(str.charAt(i), 0) + 1); 28 | } 29 | 30 | for (int i = 0; i < str.length(); i++) { 31 | if (characterMap.get(str.charAt(i)) == 1) { 32 | return i; 33 | } 34 | } 35 | 36 | return -1; 37 | } 38 | } 39 | ``` 40 | ### 测试用例 41 | 42 | 1. 功能测试(字符串中仅存在只出现一次的字符;字符串中不存在只出现一次的字符;字符串中所有字符都只出现一次)。 43 | 2. 特殊输入测试(字符串为null)。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/50_02_FristCharacterInStream.md: -------------------------------------------------------------------------------- 1 | ## 字符流中第一个不重复的字符 2 | 3 | ### 题目描述 4 | 5 | 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。如果当前字符流没有存在出现一次的字符,返回#字符。 6 | 7 | 8 | ### 解法1 9 | 与上一道题的思路是一致的。 10 | 11 | ```java 12 | /** 13 | * @author mcrwayfun 14 | * @version v1.0 15 | * @date Created in 2019/01/25 16 | * @description 17 | */ 18 | public class Solution { 19 | 20 | private StringBuilder res = new StringBuilder(); 21 | private Map characterMap = new HashMap<>(); 22 | 23 | // Insert one char from stringstream 24 | public void Insert(char ch) { 25 | res.append(ch); 26 | characterMap.put(ch, characterMap.getOrDefault(ch, 0) + 1); 27 | } 28 | 29 | // return the first appearence once char in current stringstream 30 | public char FirstAppearingOnce() { 31 | 32 | for (char c : res.toString().toCharArray()) { 33 | if (characterMap.get(c) == 1) { 34 | return c; 35 | } 36 | } 37 | 38 | return '#'; 39 | } 40 | } 41 | ``` 42 | ### 测试用例 43 | 44 | 1. 功能测试(读入一个字符;读入多个字符;读入的所有字符都是唯一的;读入的所有字符都是重复出现的)。 45 | 2. 特殊输入测试(读入0个字符)。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/54_KthNodeInBST.md: -------------------------------------------------------------------------------- 1 | ## 二叉搜索树的第k个结点 2 | 3 | ### 题目描述 4 | 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4 5 | 6 | ### 解法 7 | 因为BST的中序遍历得到的是一个升序的列表,所以在进行中序遍历行进行判断即可。所以该算法的时间复杂度为O(logn) 8 | 9 | 10 | ```java 11 | /** 12 | * @author mcrwayfun 13 | * @version 1.0 14 | * @description 15 | * @date Created in 2019/1/28 16 | */ 17 | class Solution { 18 | 19 | private int count = 0; 20 | 21 | public TreeNode KthNode(TreeNode pRoot, int k) { 22 | 23 | if (pRoot == null || k == 0) { 24 | return null; 25 | } 26 | 27 | // 左递归 28 | TreeNode retNode = KthNode(pRoot.left, k); 29 | 30 | if (retNode != null) { 31 | return retNode; 32 | } 33 | 34 | // 符合条件则返回 35 | count++; 36 | if (count == k) { 37 | return pRoot; 38 | } 39 | 40 | // 右递归 41 | retNode = KthNode(pRoot.right, k); 42 | if (retNode != null) { 43 | return retNode; 44 | } 45 | 46 | return null; 47 | } 48 | } 49 | ``` 50 | 51 | ### 测试用例 52 | 1. 功能测试(各种形态不同的二叉搜索树); 53 | 2. 边界值测试(输入k为0、1、二叉搜索树的结点数、二叉搜索树的结点数+1); 54 | 3. 特殊输入测试(指向二叉搜索树的节点的指针为空指针)。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/55_01_TreeDepth.md: -------------------------------------------------------------------------------- 1 | ## 二叉树的深度 2 | 3 | ### 题目描述 4 | 输入一棵二叉树的根结点,求该树的深度。 5 | 6 | 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 7 | 8 | **样例** 9 | ``` 10 | 输入:二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]如下图所示: 11 | 8 12 | / \ 13 | 12 2 14 | / \ 15 | 6 4 16 | 17 | 输出:3 18 | ``` 19 | 20 | ### 解法 21 | 递归即可。 22 | 23 | 24 | ```java 25 | /** 26 | * @author bingo 27 | * @since 2018/12/10 28 | */ 29 | 30 | /** 31 | * Definition for a binary tree node. 32 | * public class TreeNode { 33 | * int val; 34 | * TreeNode left; 35 | * TreeNode right; 36 | * TreeNode(int x) { val = x; } 37 | * } 38 | */ 39 | class Solution { 40 | /** 41 | * 求二叉树的深度 42 | * 43 | * @param root 二叉树根结点 44 | * @return 深度 45 | */ 46 | public int treeDepth(TreeNode root) { 47 | if (root == null) { 48 | return 0; 49 | } 50 | int lDepth = treeDepth(root.left); 51 | int rDepth = treeDepth(root.right); 52 | return 1 + Math.max(lDepth, rDepth); 53 | } 54 | } 55 | ``` 56 | 57 | ### 测试用例 58 | 1. 功能测试(输入普通的二叉树;二叉树中所有节点都没有左/右子树); 59 | 2. 特殊输入测试(二叉树只有一个节点;二叉树的头节点为空指针)。 -------------------------------------------------------------------------------- /docs/jianzhioffer/java/58_01_ReverseWordsInSentence.md: -------------------------------------------------------------------------------- 1 | ## 翻转单词顺序 2 | 3 | ### 题目描述 4 | 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。 5 | 6 | 为简单起见,标点符号和普通字母一样处理。 7 | 8 | 例如输入字符串 `"I am a student."`,则输出 `"student. a am I"`。 9 | 10 | **样例** 11 | ``` 12 | 输入:"I am a student." 13 | 14 | 输出:"student. a am I" 15 | ``` 16 | 17 | ### 解法 18 | 先对字符串按空格切割成数组,再逆序数组后,最后将元素拼接并返回。 19 | 20 | ```java 21 | /** 22 | * @author bingo 23 | * @since 2018/12/12 24 | */ 25 | 26 | class Solution { 27 | /** 28 | * 翻转单词 29 | * 30 | * @param s 字符串 31 | * @return 翻转后的字符串 32 | */ 33 | public String reverseWords(String s) { 34 | if (s == null || s.length() == 0 || s.trim().equals("")) { 35 | return s; 36 | } 37 | 38 | String[] arr = s.split(" "); 39 | int p = 0, q = arr.length - 1; 40 | while (p < q) { 41 | swap(arr, p++, q--); 42 | } 43 | return String.join(" ", arr); 44 | } 45 | private void swap(String[] arr, int p, int q) { 46 | String t = arr[p]; 47 | arr[p] = arr[q]; 48 | arr[q] = t; 49 | } 50 | } 51 | ``` 52 | 53 | ### 测试用例 54 | 1. 功能测试(句子中有多个单词;句子中只有一个单词); 55 | 2. 特殊输入测试(字符串指针为空指针;字符串的内容为空;字符串中只有空格)。 -------------------------------------------------------------------------------- /docs/leetcode/cpp/0007._Reverse_Integer.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0007._Reverse_Integer.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0008._String_to_Integer_(atoi).md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0008._String_to_Integer_(atoi).md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0011._Container_With_Most_Water.md: -------------------------------------------------------------------------------- 1 | # 11. container with most water 2 | 3 | **难度:Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | *https://leetcode.com/problems/container-with-most-water/ 10 | * 11 | > 内容描述 12 | 13 | ``` 14 | Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 15 | 16 | Note: You may not slant the container and n is at least 2. 17 | ``` 18 | 19 | ## 解题方案 20 | 21 | > 思路 22 | ******- 时间复杂度: O(N)******- 空间复杂度: O(1)****** 23 | 24 | 这道题刚开始很容易想到用暴力的方法去解,但是时间复杂度为 O(n^2) 测试之后发现是 TLE,那么我们就要对算法进行优化,这里我们用双指针法,定义两个指针,一个指向头,另一个指向尾部,比较两个指针指向的数的大小,若头部的大,则指向头部的指针向后移动一位,反之,则指向尾部的指针向前移动一位。 25 | 26 | 27 | ```cpp 28 | class Solution { 29 | public: 30 | int maxArea(vector& height) { 31 | int i = 0,j = height.size() - 1,ans = INT_MIN; 32 | while(i < j) 33 | { 34 | int t = min(height[i],height[j]); 35 | ans = max(ans,t * (j - i)); 36 | height[i] < height[j] ? i++ : j--; 37 | } 38 | return ans; 39 | } 40 | }; 41 | ``` 42 | -------------------------------------------------------------------------------- /docs/leetcode/cpp/0012._Integer_to_Roman.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0012._Integer_to_Roman.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0014._Longest_Common_Prefix.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0014._Longest_Common_Prefix.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0017._Letter_Combinations_of_a_Phone_Number.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0017._Letter_Combinations_of_a_Phone_Number.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0019._Remove_Nth_Node_From_End_of_List.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0019._Remove_Nth_Node_From_End_of_List.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0022._Generate_Parentheses.md: -------------------------------------------------------------------------------- 1 | # 22. Generate Parentheses 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/generate-parentheses/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 15 | 16 | 例如,给出 n = 3,生成结果为: 17 | 18 | [ 19 | "((()))", 20 | "(()())", 21 | "(())()", 22 | "()(())", 23 | "()()()" 24 | ] 25 | ``` 26 | 27 | ## 解题方案 28 | > 思路 1 29 | ``` 30 | 回溯法 31 | ``` 32 | 33 | ```cpp 34 | void dfs(int left, int total, string path, vector& ans){ 35 | if(total==0&&left==0){ 36 | ans.push_back(path); 37 | return ; 38 | } 39 | if(left>0) 40 | dfs(left-1, total-1, path+"(", ans); 41 | if(left generateParenthesis(int n) { 45 | vector ans; 46 | string path=""; 47 | dfs(n, n*2, path, ans); 48 | return ans; 49 | } 50 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0024._Swap_Nodes_in_Pairs.md: -------------------------------------------------------------------------------- 1 | # 24. Swap Nodes in Pairs 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/swap-nodes-in-pairs/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 15 | 16 | 示例: 17 | 18 | 给定 1->2->3->4, 你应该返回 2->1->4->3. 19 | 说明: 20 | 21 | 你的算法只能使用常数的额外空间。 22 | 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 23 | ``` 24 | 25 | ## 解题方案 26 | > 思路 1 27 | ``` 28 | 链表反转 29 | ``` 30 | 31 | ```cpp 32 | ListNode* swapPairs(ListNode* head) { 33 | if(head==NULL||head->next==NULL) 34 | return head; 35 | 36 | ListNode* slow=head; 37 | ListNode* fast=head->next; 38 | ListNode* pre=new ListNode(0); 39 | ListNode* ans = pre; 40 | while(slow&&fast){ 41 | slow->next = fast->next; 42 | fast->next = slow; 43 | pre->next = fast; 44 | if(slow->next==NULL||slow->next->next==NULL){ 45 | break; 46 | } 47 | fast = slow->next->next; 48 | pre = slow; 49 | slow = slow->next; 50 | } 51 | return ans->next; 52 | } 53 | ``` 54 | -------------------------------------------------------------------------------- /docs/leetcode/cpp/0025._Reverse_Nodes_In_K_Group.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0025._Reverse_Nodes_In_K_Group.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0026._Remove_Duplicates_From_Sorted_Array.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0026._Remove_Duplicates_From_Sorted_Array.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0027._Remove_Element.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0027._Remove_Element.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0028._Implement_Strstr.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0028._Implement_Strstr.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0029._Divide_Two_Integers.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0029._Divide_Two_Integers.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0032._Longest_Valid_Parentheses.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0032._Longest_Valid_Parentheses.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0034._Find_First_and_Last_Position_of_Element_in_Sorted_Array.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0034._Find_First_and_Last_Position_of_Element_in_Sorted_Array.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0036._Valid_Sudoku.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0036._Valid_Sudoku.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0038._Count_and_Say.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0038._Count_and_Say.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0041._First_Missing_Positive.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0041._First_Missing_Positive.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0042._Trapping_Rain_Water.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0042._Trapping_Rain_Water.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0043._Multiply_Strings.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0043._Multiply_Strings.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0044._Wildcard_Matching.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0044._Wildcard_Matching.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0045._Jump_Game_II.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0045._Jump_Game_II.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0046._Permutations.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0046._Permutations.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0047._Permutations_II.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0047._Permutations_II.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0049._Group_Anagrams.md: -------------------------------------------------------------------------------- 1 | # 49. Group Anagrams 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/group-anagrams/submissions/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 15 | 16 | 示例: 17 | 18 | 输入: ["eat", "tea", "tan", "ate", "nat", "bat"], 19 | 输出: 20 | [ 21 | ["ate","eat","tea"], 22 | ["nat","tan"], 23 | ["bat"] 24 | ] 25 | 说明: 26 | 27 | 所有输入均为小写字母。 28 | 不考虑答案输出的顺序。 29 | ``` 30 | 31 | ## 解题方案 32 | > 思路 1 33 | ``` 34 | 不同的组别字符串元素相同,顺序不同,所以排序后相同 35 | 把排序后相同的元素映射到同一个vector 36 | 所有vector的组合就是结果 37 | ``` 38 | 39 | ```cpp 40 | vector> groupAnagrams(vector& strs) { 41 | vector> ans; 42 | map> maps; 43 | for(int i=0;i难度Easy** 4 | 5 | ## 刷题内容 6 | > 原题连接 7 | 8 | * https://leetcode.com/problems/length-of-last-word/ 9 | 10 | > 内容描述 11 | 12 | ``` 13 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 14 | 15 | If the last word does not exist, return 0. 16 | ``` 17 | 18 | > 思路 19 | ******- 时间复杂度: O(n)*****- 空间复杂度: O(1)****** 20 | 21 | 这题我们只要从字符串的末尾开始向前找到第一个单词即可 22 | ```cpp 23 | class Solution { 24 | public: 25 | int lengthOfLastWord(string s) { 26 | int i = s.length() - 1,length = s.length() - 1; 27 | while((s[i] == ' ') &&(i >= 0)) 28 | { 29 | --i; 30 | --length; 31 | } 32 | while((s[i] != ' ') && (i >= 0)) 33 | --i; 34 | return length- i; 35 | } 36 | }; 37 | ``` 38 | -------------------------------------------------------------------------------- /docs/leetcode/cpp/0059._Spiral_Matrix_II.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0059._Spiral_Matrix_II.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0060._Permutation_Sequence.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0060._Permutation_Sequence.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0061._Rotate_List.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0061._Rotate_List.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0062._Unique_Paths.md: -------------------------------------------------------------------------------- 1 | # 62. Unique Paths 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/unique-paths/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 15 | 16 | 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 17 | 18 | 问总共有多少条不同的路径? 19 | 20 | 21 | 22 | 例如,上图是一个7 x 3 的网格。有多少可能的路径? 23 | 24 | 说明:m 和 n 的值均不超过 100。 25 | 26 | 示例 1: 27 | 28 | 输入: m = 3, n = 2 29 | 输出: 3 30 | 解释: 31 | 从左上角开始,总共有 3 条路径可以到达右下角。 32 | 1. 向右 -> 向右 -> 向下 33 | 2. 向右 -> 向下 -> 向右 34 | 3. 向下 -> 向右 -> 向右 35 | 示例 2: 36 | 37 | 输入: m = 7, n = 3 38 | 输出: 28 39 | ``` 40 | 41 | ## 解题方案 42 | > 思路 1 43 | ``` 44 | 动态规划,走到(i,j)可以从(i-1,j),(i, j-1)两个方向 45 | 最优子结构: 46 | dp[i, j] = dp[i-1, j]+dp[i, j-1] 47 | ``` 48 | 49 | ```cpp 50 | int uniquePaths(int m, int n) { 51 | vector> dp(m, vector(n, 0)); 52 | for(int i=0;i难度: Middle** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/minimum-path-sum/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 15 | 16 | 说明:每次只能向下或者向右移动一步。 17 | 18 | 示例: 19 | 20 | 输入: 21 | [ 22 | [1,3,1], 23 | [1,5,1], 24 | [4,2,1] 25 | ] 26 | 输出: 7 27 | 解释: 因为路径 1→3→1→1→1 的总和最小。 28 | ``` 29 | 30 | ## 解题方案 31 | > 思路 1 32 | ``` 33 | dp: 34 | 1. 首行首列的路径只有一种,累加 35 | 2. 其他都有两种方法,走到i,j的最小路径等于min(sum[i][j-1], sum[i-1][j])+grid[i][j] 36 | ``` 37 | 38 | ```cpp 39 | int minPathSum(vector>& grid) { 40 | int m = grid.size(), n = grid[0].size(); 41 | int dp[m][n]; 42 | dp[0][0] = grid[0][0]; 43 | for (int i = 1; i < m; ++i) dp[i][0] = grid[i][0] + dp[i - 1][0]; 44 | for (int i = 1; i < n; ++i) dp[0][i] = grid[0][i] + dp[0][i - 1]; 45 | for (int i = 1; i < m; ++i) { 46 | for (int j = 1; j < n; ++j) { 47 | dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]); 48 | } 49 | } 50 | return dp[m - 1][n - 1]; 51 | } 52 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0065._Valid_Number.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0065._Valid_Number.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0066._Plus_One.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0066._Plus_One.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0068._Text_Justification.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0068._Text_Justification.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0069._Sqr(x).md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0069._Sqr(x).md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0076._Minimum_Window_Substring.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0076._Minimum_Window_Substring.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0077._combinations.md: -------------------------------------------------------------------------------- 1 | # 77. Combinations 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/combinations/ 10 | 11 | > 内容描述 12 | ``` 13 | 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 14 | 15 | 示例: 16 | 17 | 输入: n = 4, k = 2 18 | 输出: 19 | [ 20 | [2,4], 21 | [3,4], 22 | [2,3], 23 | [1,2], 24 | [1,3], 25 | [1,4], 26 | ] 27 | ``` 28 | 29 | ## 解题方案 30 | > 思路 1 31 | ``` 32 | 回溯寻找所有组合。 33 | ``` 34 | 35 | ```cpp 36 | void dfs(int k, int index, int n, vector& path, vector>& ans){ 37 | if(k==0){ 38 | ans.push_back(path); 39 | return ; 40 | } 41 | for(int i=index;i<=n;i++){ 42 | path.push_back(i); 43 | dfs(k-1, i+1, n, path, ans); 44 | path.pop_back(); 45 | } 46 | } 47 | vector> combine(int n, int k) { 48 | vector> ans; 49 | vector path; 50 | dfs(k, 1, n, path, ans); 51 | return ans; 52 | } 53 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0078._subsets.md: -------------------------------------------------------------------------------- 1 | # 78. Subsets 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/subsets/ 10 | 11 | > 内容描述 12 | ``` 13 | 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 14 | 15 | 说明:解集不能包含重复的子集。 16 | 17 | 示例: 18 | 19 | 输入: nums = [1,2,3] 20 | 输出: 21 | [ 22 | [3], 23 | [1], 24 | [2], 25 | [1,2,3], 26 | [1,3], 27 | [2,3], 28 | [1,2], 29 | [] 30 | ] 31 | ``` 32 | 33 | ## 解题方案 34 | > 思路 1 35 | ``` 36 | 每个元素有两种选择,选与不选,可以使用K位二进制数组表示K个元素的选与不选。 37 | ``` 38 | 39 | ```cpp 40 | vector> subsets(vector& nums) { 41 | vector> ans; 42 | for(int i=0;i tmp; 44 | int index = 0; 45 | int j=i; 46 | while(j){ 47 | if(j%2==1) 48 | tmp.push_back(nums[index]); 49 | index++; 50 | j/=2; 51 | } 52 | ans.push_back(tmp); 53 | } 54 | return ans; 55 | } 56 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0081._Search_in_Rotated_Sorted_Array_II.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0081._Search_in_Rotated_Sorted_Array_II.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0083._Remove_Duplicates_From_Sorted_Lists.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0083._Remove_Duplicates_From_Sorted_Lists.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0085._Maximal_Rectangle.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0085._Maximal_Rectangle.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0087._Scramble_String.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0087._Scramble_String.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0088._Merge_Sorted_Array.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0088._Merge_Sorted_Array.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0090._Subsets_II.md: -------------------------------------------------------------------------------- 1 | # 90. Subsets II 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/subsets-ii/submissions/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 15 | 16 | 说明:解集不能包含重复的子集。 17 | 18 | 示例: 19 | 20 | 输入: [1,2,2] 21 | 输出: 22 | [ 23 | [2], 24 | [1], 25 | [1,2,2], 26 | [2,2], 27 | [1,2], 28 | [] 29 | ] 30 | ``` 31 | 32 | ## 解题方案 33 | > 思路 1 34 | ``` 35 | 回溯搜索 36 | ``` 37 | 38 | ```cpp 39 | void dfs(vector nums, int index, vector subset, vector>& ans){ 40 | ans.push_back(subset); 41 | if(index == nums.size()){ 42 | return ; 43 | } 44 | for(int i=index;iindex) 46 | continue; 47 | subset.push_back(nums[i]); 48 | dfs(nums, i+1, subset, ans); 49 | subset.pop_back(); 50 | } 51 | } 52 | vector> subsetsWithDup(vector& nums) { 53 | vector> ans; 54 | vector subset; 55 | sort(nums.begin(), nums.end()); 56 | dfs(nums, 0, subset, ans); 57 | return ans; 58 | } 59 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0094._binary_tree_inorder_traversal.md: -------------------------------------------------------------------------------- 1 | # 94. Binary Tree Inorder Traversal 2 | **难度: Medium** 3 | 4 | ## 刷题内容 5 | > 原题连接 6 | 7 | * https://leetcode-cn.com/problems/binary-tree-inorder-traversal/ 8 | 9 | > 内容描述 10 | ``` 11 | 给定一个二叉树,返回它的中序 遍历。 12 | 13 | 示例: 14 | 15 | 输入: [1,null,2,3] 16 | 1 17 | \ 18 | 2 19 | / 20 | 3 21 | 22 | 输出: [1,3,2] 23 | 24 | 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 25 | ``` 26 | 27 | ## 解题方案 28 | > 思路 1 29 | ``` 30 | 递归。 31 | ``` 32 | 33 | ```cpp 34 | void dfs(TreeNode* root, vector& ans){ 35 | if(root==NULL) 36 | return ; 37 | dfs(root->left, ans); 38 | ans.push_back(root->val); 39 | dfs(root->right, ans); 40 | } 41 | vector inorderTraversal(TreeNode* root) { 42 | vector ans; 43 | dfs(root, ans); 44 | return ans; 45 | } 46 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0096._Unique_Binary_Search_Trees.md: -------------------------------------------------------------------------------- 1 | # 96. Unique Binary Search Trees 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/unique-binary-search-trees/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 15 | 16 | 示例: 17 | 18 | 输入: 3 19 | 输出: 5 20 | 解释: 21 | 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 22 | 23 | 1 3 3 2 1 24 | \ / / / \ \ 25 | 3 2 1 1 3 2 26 | / / \ \ 27 | 2 1 2 3 28 | ``` 29 | 30 | ## 解题方案 31 | > 思路 1 32 | ``` 33 | 假设有n个节点,左右子树有(0,n-1)(1,n-2)...(n-1, 0)等情况 34 | 子结构: 35 | dp[i] = dp[0]*dp[i-1]+...+dp[i-1]*dp[0] 36 | ``` 37 | 38 | ```cpp 39 | int numTrees(int n) { 40 | vector dp(n+1, 0); 41 | dp[0]=1; 42 | dp[1]=1; 43 | for(int i=2;i<=n;i++){ 44 | for(int j=0;j难度: Easy** 3 | ## 刷题内容 4 | > 原题连接 5 | * https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/ 6 | > 内容描述 7 | ``` 8 | Given a binary tree, find its minimum depth. 9 | 10 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 11 | 12 | Note: A leaf is a node with no children. 13 | ``` 14 | ## 解题方案 15 | > 思路 1 16 | ``` 17 | 遍历树,找出最小深度的分支 18 | ``` 19 | ```cpp 20 | void dfs(TreeNode* root, int depth, int& ans){ 21 | if(root == NULL) 22 | return ; 23 | if(root->left==NULL && root->right==NULL){ 24 | if(depthleft, depth+1, ans); 29 | dfs(root->right, depth+1, ans); 30 | } 31 | int minDepth(TreeNode* root) { 32 | int ans = 10000; 33 | if(root==NULL) 34 | return 0; 35 | dfs(root, 1, ans); 36 | return ans; 37 | } 38 | 39 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0112._Path_Sum.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0112._Path_Sum.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0114._Flatten_Binary_Tree_to_Linked_List.md: -------------------------------------------------------------------------------- 1 | # 114. Flatten Binary Tree to Linked List 2 | 3 | **难度: Middle** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个二叉树,原地将它展开为链表。 15 | 16 | 例如,给定二叉树 17 | 18 | 1 19 | / \ 20 | 2 5 21 | / \ \ 22 | 3 4 6 23 | 将其展开为: 24 | 25 | 1 26 | \ 27 | 2 28 | \ 29 | 3 30 | \ 31 | 4 32 | \ 33 | 5 34 | \ 35 | 6 36 | ``` 37 | 38 | ## 解题方案 39 | > 思路 1 40 | ``` 41 | 后续遍历二叉树 42 | ``` 43 | 44 | ```cpp 45 | void dfs(TreeNode* root){ 46 | if(root==NULL) 47 | return ; 48 | dfs(root->left); 49 | dfs(root->right); 50 | TreeNode* tmp=root->right; 51 | root->right=root->left; 52 | root->left=NULL; 53 | while(root->right) 54 | root=root->right; 55 | root->right = tmp; 56 | } 57 | void flatten(TreeNode* root) { 58 | dfs(root); 59 | } 60 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0115._Distinct_Subsequences.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0115._Distinct_Subsequences.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0119._Pascals_Triangle-II.md: -------------------------------------------------------------------------------- 1 | ## 119. Pascal's Triangle II 2 | 3 | 难度:Easy 4 | 5 | ## 内容 6 | 7 | 题目链接:https://leetcode.com/problems/pascals-triangle-ii 8 | 9 | Given a non-negative index *k* where *k* ≤ 33, return the *k*th index row of the Pascal's triangle. 10 | 11 | Note that the row index starts from 0. 12 | 13 | ![img](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) 14 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 15 | 16 | **Example:** 17 | 18 | ``` 19 | Input: 3 20 | Output: [1,3,3,1] 21 | ``` 22 | 23 | **Follow up:** 24 | 25 | Could you optimize your algorithm to use only *O*(*k*) extra space? 26 | 27 | ## 思路 28 | 29 | 思路和[上一题](118._Pascals_Triangle.md)一样,只不过这里不需要存每一行的数据。 30 | 31 | 注意:和上一题相比,这里的 `rowIndex + 1 = numRows` 32 | 33 | ## 代码 34 | 35 | ``` 36 | class Solution { 37 | public: 38 | vector getRow(int rowIndex) { 39 | vector res(rowIndex+1, 0); 40 | res[0] = 1; 41 | for (auto i = 0; i <= rowIndex; ++i) 42 | for (auto j = i; j > 0; --j) 43 | res[j] += res[j-1]; 44 | return res; 45 | } 46 | }; 47 | ``` 48 | 49 | 来源:https://github.com/xiaqunfeng/leetcode -------------------------------------------------------------------------------- /docs/leetcode/cpp/0120._Triangle.md: -------------------------------------------------------------------------------- 1 | # 120. Triangle 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/triangle/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 15 | 16 | 例如,给定三角形: 17 | 18 | [ 19 | [2], 20 | [3,4], 21 | [6,5,7], 22 | [4,1,8,3] 23 | ] 24 | 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 25 | ``` 26 | 27 | ## 解题方案 28 | > 思路 1 29 | ``` 30 | dfs超时 31 | 采用dp,自底向上更新每个数,每个数加上向下路径的最小和,更新到第一层既为第一层向下路径的最小和。 32 | ``` 33 | 34 | ```cpp 35 | 36 | int minimumTotal(vector>& triangle) { 37 | for (int i = triangle.size() - 2; i >= 0; i--) 38 | for (int j = 0; j < triangle[i].size(); j++) 39 | triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); 40 | return triangle[0][0]; 41 | } 42 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0121._Best_Tim_to_Buy_and_Sell_Stock.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0121._Best_Tim_to_Buy_and_Sell_Stock.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0122._Best_Time_to_Buy_and_Sell_Stock_II.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0122._Best_Time_to_Buy_and_Sell_Stock_II.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0123._Best_Time_to_Buy_and_Sell_Stock_III.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0123._Best_Time_to_Buy_and_Sell_Stock_III.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0124._Binary_Tree_Maximum_Path_Sum.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0124._Binary_Tree_Maximum_Path_Sum.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0127._Word_Ladde.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0127._Word_Ladde.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0141._Linked_List_Cycle.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0141._Linked_List_Cycle.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0144._Binary_Tree_Preorder_Traversal.md: -------------------------------------------------------------------------------- 1 | # 144. Binary Tree Preorder Traversal 2 | 3 | **难度: Middle** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/binary-tree-preorder-traversal/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个二叉树,返回它的 前序 遍历。 15 | 16 | 示例: 17 | 18 | 输入: [1,null,2,3] 19 | 1 20 | \ 21 | 2 22 | / 23 | 3 24 | 25 | 输出: [1,2,3] 26 | 27 | ``` 28 | 29 | ## 解题方案 30 | > 思路 1 31 | ``` 32 | 递归 33 | ``` 34 | 35 | ```cpp 36 | void dfs(TreeNode* root, vector &ans){ 37 | if(root==NULL) 38 | return ; 39 | ans.push_back(root->val); 40 | dfs(root->left, ans); 41 | dfs(root->right, ans); 42 | } 43 | vector preorderTraversal(TreeNode* root) { 44 | vector ans; 45 | dfs(root, ans); 46 | return ans; 47 | } 48 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0145._Binary_Tree_Postorder_Traversal.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0145._Binary_Tree_Postorder_Traversal.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0147._Insert_on_Sort_List.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0147._Insert_on_Sort_List.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0148._Sort_list.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0148._Sort_list.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0151._Reverse_Words_in_a_String.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0151._Reverse_Words_in_a_String.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0160._Intersection_Of_Two_Linked_Lists.md: -------------------------------------------------------------------------------- 1 | # 160 intersection_of_Two_Linked_Lists 2 | **难度: Easy** 3 | ## 刷题内容 4 | >原题连接 5 | * https://leetcode-cn.com/problems/intersection-of-two-linked-lists/ 6 | >内容描述 7 | ``` 8 | Write a program to find the node at which the intersection of two singly linked lists begins. 9 | ``` 10 | 11 | ## 解题方案 12 | > 思路 1 13 | ``` 14 | 1. 求长度差 15 | 2. 长的链表先走掉长的部分 16 | 3. 一起走,相遇即为交点 17 | ``` 18 | ```cpp 19 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 20 | int lena=0; 21 | int lenb=0; 22 | ListNode *a = headA; 23 | ListNode *b = headB; 24 | while(a){ 25 | lena++; 26 | a=a->next; 27 | } 28 | while(b){ 29 | lenb++; 30 | b=b->next; 31 | } 32 | if(a!=b) 33 | return NULL; 34 | int sub=abs(lena-lenb); 35 | if(lena>lenb){ 36 | while(sub--) 37 | headA=headA->next; 38 | }else 39 | while(sub--) 40 | headB=headB->next; 41 | while(headA!=headB){ 42 | headA = headA->next; 43 | headB = headB->next; 44 | } 45 | return headA; 46 | } 47 | ``` 48 | 49 | -------------------------------------------------------------------------------- /docs/leetcode/cpp/0164._Maximum_Gap.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0164._Maximum_Gap.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0166._Fraction_to_Recurring_Decimal.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0166._Fraction_to_Recurring_Decimal.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0199._Binary_Tree_Right_Side_View.md: -------------------------------------------------------------------------------- 1 | # 199. Binary Tree Right Side View 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/binary-tree-right-side-view/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。 15 | 16 | 示例: 17 | 18 | 输入: [1,2,3,null,5,null,4] 19 | 输出: [1, 3, 4] 20 | 解释: 21 | 22 | 1 <--- 23 | / \ 24 | 2 3 <--- 25 | \ \ 26 | 5 4 <--- 27 | ``` 28 | 29 | ## 解题方案 30 | > 思路 1 31 | ``` 32 | 二叉树层次遍历 33 | ``` 34 | 35 | ```cpp 36 | vector rightSideView(TreeNode* root) { 37 | vector ans; 38 | if(root==NULL) 39 | return ans; 40 | vector stack; 41 | stack.push_back(root); 42 | 43 | while(!stack.empty()){ 44 | vector tmp; 45 | TreeNode* node; 46 | for(int i=0;ileft) 49 | tmp.push_back(node->left); 50 | if(node->right) 51 | tmp.push_back(node->right); 52 | } 53 | ans.push_back(node->val); 54 | stack = tmp; 55 | } 56 | return ans; 57 | } 58 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0216._Combination_Sum_III.md: -------------------------------------------------------------------------------- 1 | # 216. Combination Sum III 2 | 3 | **难度: Middle** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/combination-sum-iii/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。 15 | 16 | 说明: 17 | 18 | 所有数字都是正整数。 19 | 解集不能包含重复的组合。 20 | 示例 1: 21 | 22 | 输入: k = 3, n = 7 23 | 输出: [[1,2,4]] 24 | 示例 2: 25 | 26 | 输入: k = 3, n = 9 27 | 输出: [[1,2,6], [1,3,5], [2,3,4]] 28 | ``` 29 | 30 | ## 解题方案 31 | > 思路 1 32 | ``` 33 | 回溯 34 | ``` 35 | 36 | ```cpp 37 | void dfs(int n, int k, int index, vector& path, vector>& ans){ 38 | if(n<0||k<0) 39 | return; 40 | if(n==0&&k==0){ 41 | ans.push_back(path); 42 | return ; 43 | } 44 | for(int i=index;i<=9;i++){ 45 | path.push_back(i); 46 | dfs(n-i, k-1, i+1, path, ans); 47 | path.pop_back(); 48 | } 49 | } 50 | vector> combinationSum3(int k, int n) { 51 | vector> ans; 52 | vector path; 53 | dfs(n, k, 1, path, ans); 54 | return ans; 55 | } 56 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0230._Kth_Smallest_Element_in_a_BST.md: -------------------------------------------------------------------------------- 1 | # 230. Kth Smallest Element in a BST 2 | 3 | **难度: Middle** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。 15 | 16 | 说明: 17 | 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。 18 | 19 | 示例 1: 20 | 21 | 输入: root = [3,1,4,null,2], k = 1 22 | 3 23 | / \ 24 | 1 4 25 | \ 26 | 2 27 | 输出: 1 28 | 示例 2: 29 | 30 | 输入: root = [5,3,6,2,4,null,null,1], k = 3 31 | 5 32 | / \ 33 | 3 6 34 | / \ 35 | 2 4 36 | / 37 | 1 38 | 输出: 3 39 | 进阶: 40 | 如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数? 41 | ``` 42 | 43 | ## 解题方案 44 | > 思路 1 45 | ``` 46 | 遍历树后排序 47 | ``` 48 | ``` 49 | ```cpp 50 | void dfs(TreeNode* root, vector& nums){ 51 | if(root==NULL) 52 | return ; 53 | nums.push_back(root->val); 54 | dfs(root->left, nums); 55 | dfs(root->right, nums); 56 | } 57 | int kthSmallest(TreeNode* root, int k) { 58 | vector nums; 59 | dfs(root, nums); 60 | sort(nums.begin(), nums.end()); 61 | return nums[k-1]; 62 | } 63 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0260._Single_Number_III.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/leetcode/cpp/0260._Single_Number_III.md -------------------------------------------------------------------------------- /docs/leetcode/cpp/0287._Find_the_Duplicate_Number.md: -------------------------------------------------------------------------------- 1 | # 287. Find the Duplicate Number 2 | 3 | **难度: Middle** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/find-the-duplicate-number/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。 15 | 16 | 示例 1: 17 | 18 | 输入: [1,3,4,2,2] 19 | 输出: 2 20 | 示例 2: 21 | 22 | 输入: [3,1,3,4,2] 23 | 输出: 3 24 | 说明: 25 | 26 | 不能更改原数组(假设数组是只读的)。 27 | 只能使用额外的 O(1) 的空间。 28 | 时间复杂度小于 O(n2) 。 29 | 数组中只有一个重复的数字,但它可能不止重复出现一次。 30 | ``` 31 | 32 | ## 解题方案 33 | > 思路 1 34 | ``` 35 | 采用下标取反标记,假设下标数字为负,则为ans 36 | ``` 37 | 38 | ```cpp 39 | int findDuplicate(vector& nums) { 40 | for(int i=0;i难度: Easy** 3 | ## 刷题内容 4 | > 原题连接 5 | * https://leetcode-cn.com/problems/power-of-three/ 6 | > 内容描述 7 | ``` 8 | Given an integer, write a function to determine if it is a power of three. 9 | 10 | ###example 11 | 1. Input: 27 -> Output: true 12 | 13 | 2. Input: 0 -> Output: false 14 | 15 | 3. Input: 9 -> Output: true 16 | 17 | 4. Input: 45 -> Output: false 18 | ``` 19 | ### 题解方案 20 | ``` 21 | 只要是3的幂次,一定能够被3的最大次方整除 22 | ``` 23 | ### coding 24 | ```cpp 25 | bool isPowerOfThree(int n) { 26 | return n > 0 and 1162261467 % n ==0; 27 | } 28 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0328._Odd_Even_Linked_List.md: -------------------------------------------------------------------------------- 1 | # 328. Odd Even Linked List 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/odd-even-linked-list/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 15 | 16 | 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。 17 | 18 | 示例 1: 19 | 20 | 输入: 1->2->3->4->5->NULL 21 | 输出: 1->3->5->2->4->NULL 22 | 示例 2: 23 | 24 | 输入: 2->1->3->5->6->4->7->NULL 25 | 输出: 2->3->6->7->1->5->4->NULL 26 | ``` 27 | 28 | ## 解题方案 29 | > 思路 1 30 | ``` 31 | 如题 32 | ``` 33 | 34 | ```cpp 35 | ListNode* oddEvenList(ListNode* head) { 36 | if(head==NULL || head->next==NULL) 37 | return head; 38 | ListNode* link = head->next; 39 | ListNode* slow=head; 40 | ListNode* fast=head->next; 41 | while(fast&&fast->next){ 42 | slow->next = fast->next; 43 | fast->next = fast->next->next; 44 | slow=slow->next; 45 | fast=fast->next; 46 | } 47 | cout<val<next = link; 49 | return head; 50 | } 51 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0338._Counting_Bits.md: -------------------------------------------------------------------------------- 1 | # 338. Counting Bits 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | > 原题连接 7 | 8 | * https://leetcode-cn.com/problems/counting-bits/ 9 | > 内容描述 10 | ``` 11 | 给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。 12 | 13 | 示例 1: 14 | 15 | 输入: 2 16 | 输出: [0,1,1] 17 | 示例 2: 18 | 19 | 输入: 5 20 | 输出: [0,1,1,2,1,2] 21 | 进阶: 22 | 23 | 给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗? 24 | 要求算法的空间复杂度为O(n)。 25 | 你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。 26 | ``` 27 | 28 | ## 解题方案 29 | > 思路 1 30 | ``` 31 | 第i个数的二进制中数含1的个数等于等于第(i&i-1)个数中二进制数中1的个数加1 32 | ``` 33 | 34 | ```cpp 35 | vector countBits(int num) { 36 | vector res(num+1,0); 37 | for(int i=1;i<=num;i++){ 38 | res[i]=res[i&(i-1)]+1; 39 | } 40 | return res; 41 | } 42 | 43 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0442._Find_All_Duplicates_in_an_Array.md: -------------------------------------------------------------------------------- 1 | # 442. Find All Duplicates in an Array 2 | 3 | **难度: Middle** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。 15 | 16 | 找到所有出现两次的元素。 17 | 18 | 你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗? 19 | 20 | 示例: 21 | 22 | 输入: 23 | [4,3,2,7,8,2,3,1] 24 | 25 | 输出: 26 | [2,3] 27 | ``` 28 | 29 | ## 解题方案 30 | > 思路 1 31 | ``` 32 | 数值在1-n之间,可以对相应数值-1的下标位置取反,如果出现两次,就为正值,否则为负。 33 | ``` 34 | 35 | ```cpp 36 | vector findDuplicates(vector& nums) { 37 | vector ans; 38 | for(int i=0;i难度: Middle** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/find-bottom-left-tree-value/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个二叉树,在树的最后一行找到最左边的值。 15 | 16 | 示例 1: 17 | 18 | 输入: 19 | 20 | 2 21 | / \ 22 | 1 3 23 | 24 | 输出: 25 | 1 26 | 27 | 28 | 示例 2: 29 | 30 | 输入: 31 | 32 | 1 33 | / \ 34 | 2 3 35 | / / \ 36 | 4 5 6 37 | / 38 | 7 39 | 40 | 输出: 41 | 7 42 | 43 | 44 | 注意: 您可以假设树(即给定的根节点)不为 NULL。 45 | ``` 46 | 47 | ## 解题方案 48 | > 思路 1 49 | ``` 50 | 从左到右层次遍历二叉树 51 | ``` 52 | 53 | ```cpp 54 | int findBottomLeftValue(TreeNode* root) { 55 | vector que; 56 | que.push_back(root); 57 | while(que.size()>0){ 58 | vector tmp; 59 | int len = que.size(); 60 | for(int i=0;ileft) 62 | tmp.push_back(que[i]->left); 63 | if(que[i]->right) 64 | tmp.push_back(que[i]->right); 65 | } 66 | if(tmp.size()==0) 67 | break; 68 | que = tmp; 69 | } 70 | return que[0]->val; 71 | } 72 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0540._Single_Element_in_a_Sorted_Array.md: -------------------------------------------------------------------------------- 1 | # 540. Single Element in a Sorted Array 2 | 3 | **难度: Middle** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/single-element-in-a-sorted-array/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 给定一个只包含整数的有序数组,每个元素都会出现两次,唯有一个数只会出现一次,找出这个数。 15 | 16 | 示例 1: 17 | 18 | 输入: [1,1,2,3,3,4,4,8,8] 19 | 输出: 2 20 | 示例 2: 21 | 22 | 输入: [3,3,7,7,10,11,11] 23 | 输出: 10 24 | 注意: 您的方案应该在 O(log n)时间复杂度和 O(1)空间复杂度中运行。 25 | ``` 26 | 27 | ## 解题方案 28 | > 思路 1 29 | ``` 30 | 时间复杂度选择二分 31 | 32 | ``` 33 | 34 | ```cpp 35 | int singleNonDuplicate(vector& nums) { 36 | int start=0, end=nums.size()/2; 37 | while(start难度: Easy** 4 | 5 | ## 刷题内容 6 | > 原题连接 7 | * https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/ 8 | > 内容描述 9 | ``` 10 | 给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。 11 | 12 | 你找到的子数组应是最短的,请输出它的长度。 13 | 14 | 示例 1: 15 | 16 | 输入: [2, 6, 4, 8, 10, 9, 15] 17 | 输出: 5 18 | 解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。 19 | ``` 20 | 21 | ## 解题方案 22 | > 思路 1 23 | ``` 24 | 1. 拷贝数组,排序 25 | 2. 计算两个数组不同的起始位置和末端位置 26 | 3. 计算差值 27 | ``` 28 | 29 | ```cpp 30 | int findUnsortedSubarray(vector& nums) { 31 | vector tmp(nums.begin(), nums.end()); 32 | sort(tmp.begin(), tmp.end()); 33 | int start=-1, end=-1; 34 | for(int i=0;i=0;i--){ 41 | if(tmp[i]!=nums[i]){ 42 | end = i; 43 | break; 44 | } 45 | } 46 | if(start==-1&&end==-1) 47 | return 0; 48 | return end-start+1; 49 | } 50 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0654._maximum_binary_tree.md: -------------------------------------------------------------------------------- 1 | # 654. Maximum Binary Tree 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | > 原题连接 7 | * https://leetcode-cn.com/problems/maximum-binary-tree/ 8 | > 内容描述 9 | ``` 10 | 给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下: 11 | 12 | 二叉树的根是数组中的最大元素。 13 | 左子树是通过数组中最大值左边部分构造出的最大二叉树。 14 | 右子树是通过数组中最大值右边部分构造出的最大二叉树。 15 | 通过给定的数组构建最大二叉树,并且输出这个树的根节点。 16 | 17 | Example 1: 18 | 19 | 输入: [3,2,1,6,0,5] 20 | 输入: 返回下面这棵树的根节点: 21 | 22 | 6 23 | / \ 24 | 3 5 25 | \ / 26 | 2 0 27 | \ 28 | 1 29 | ``` 30 | 31 | ## 解题方案 32 | > 思路 1 33 | ``` 34 | 深搜构建二叉树 35 | ``` 36 | 37 | ```cpp 38 | TreeNode* dfs(vector& nums, int start, int end){ 39 | int root_val = 0, max=INT_MIN; 40 | if(start==end) 41 | return NULL; 42 | for(int i=start;ileft = dfs(nums, start, root_val); 50 | root->right = dfs(nums, root_val+1, end); 51 | return root; 52 | } 53 | TreeNode* constructMaximumBinaryTree(vector& nums) { 54 | return dfs(nums, 0, nums.size()); 55 | } 56 | 57 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0739._Daily_Temperatures.md: -------------------------------------------------------------------------------- 1 | # 739. Daily Temperatures 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/daily-temperatures/ 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。 15 | 16 | 例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。 17 | 18 | 提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的都是 [30, 100] 范围内的整数。 19 | ``` 20 | 21 | ## 解题方案 22 | > 思路 1 23 | ``` 24 | 暴力超时。 25 | 采用递减栈思维,用栈存下表 26 | 当前值小于栈顶值,入栈 27 | 否则出站,出栈index的结果为当前处理下表和出栈下标的差值。 28 | ``` 29 | 30 | ```cpp 31 | vector dailyTemperatures(vector& temperatures) { 32 | if(temperatures.size()==0) 33 | return temperatures; 34 | vector ans(temperatures.size(), 0); 35 | stack index; 36 | for(int i=0;itemperatures[index.top()]){ 39 | int tmp = index.top(); 40 | index.pop(); 41 | ans[tmp]=i-tmp; 42 | } 43 | index.push(i); 44 | } 45 | return ans; 46 | } 47 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0814._Binary_Tree_Pruning.md: -------------------------------------------------------------------------------- 1 | # 814. Binary Tree Pruning 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | > 原题连接 7 | * https://leetcode-cn.com/problems/binary-tree-pruning/ 8 | > 内容描述 9 | ``` 10 | 给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。 11 | 12 | 返回移除了所有不包含 1 的子树的原二叉树。 13 | 14 | ( 节点 X 的子树为 X 本身,以及所有 X 的后代。) 15 | 16 | 示例1: 17 | 输入: [1,null,0,0,1] 18 | 输出: [1,null,0,null,1] 19 | ``` 20 | 21 | ## 解题方案 22 | > 思路 1 23 | ``` 24 | 遍历二叉树,切除左右子树中无1的子树。 25 | ``` 26 | 27 | ```cpp 28 | bool dfs(TreeNode* root){ 29 | if(root==NULL) 30 | return false; 31 | bool left = dfs(root->left); 32 | bool right = dfs(root->right); 33 | if(left==false) 34 | root->left=NULL; 35 | if(right==false) 36 | root->right=NULL; 37 | return root->val==1||left||right; 38 | } 39 | TreeNode* pruneTree(TreeNode* root) { 40 | dfs(root); 41 | return root; 42 | } 43 | ``` -------------------------------------------------------------------------------- /docs/leetcode/cpp/0945._Minimum_Increment_to_Make_Array_Unique.md: -------------------------------------------------------------------------------- 1 | ### 945. Minimum Increment to Make Array Unique 2 | 3 | 题目: 4 | https://leetcode.com/problems/minimum-increment-to-make-array-unique/ 5 | 6 | 难度: 7 | Medium 8 | 9 | 题意: 10 | 11 | 1. 给定一个数组 12 | 2. 每次操作,数组中的元素只能+1 13 | 3. 求最少多少次操作,数组中所有元素都不相同 14 | 15 | 思路: 16 | 17 | - 注意看题意,数组中的元素只能+1,所以数组需要先排序,从小到大,因为小的数处理好,大的数不管怎么+1都不会冲突 18 | - 从小到大循环,需要操作的只可能是跟前一个相同的,或者比前一个小(因为前一个也有可能跟前前一个相同),因此我们跟前面一个比较,如果比前面一个大,那么啥事都没,如果跟前一个相同,或者比前一个小,那么我们就把他加到比前面一个数大1即可 19 | 20 | 解法: 21 | 22 | ```c++ 23 | class Solution { 24 | public: 25 | int minIncrementForUnique(vector& A) { 26 | sort(A.begin(), A.end()); 27 | int ret = 0; 28 | for (int i= 1;i < A.size();i++) { 29 | if (A[i] <= A[i - 1]) { 30 | ret += A[i - 1] - A[i] + 1; 31 | A[i] = A[i - 1] + 1; 32 | } 33 | } 34 | return ret; 35 | } 36 | }; 37 | ``` 38 | 39 | -------------------------------------------------------------------------------- /docs/leetcode/cpp/0946._Validate_Stack_Sequences.md: -------------------------------------------------------------------------------- 1 | ### 946. Validate Stack Sequences 2 | 3 | 题目: 4 | https://leetcode.com/problems/validate-stack-sequences/ 5 | 6 | 难度: 7 | Medium 8 | 9 | 题意: 10 | 11 | 1. 两个数组 12 | 2. 问入栈顺序为pushed数组,是否可能出栈顺序为popped数组 13 | 14 | 思路: 15 | 16 | - 模拟即可。我们把新建一个栈,按照pushed数组的顺序一个一个丢进去,并且,检查popped数组前面的数组,如果可以弹出就弹出。到最后判断栈是否为空即可 17 | 18 | 解法: 19 | 20 | ```c++ 21 | class Solution { 22 | public: 23 | int stack[1010]; 24 | bool validateStackSequences(vector& pushed, vector& popped) { 25 | int n = 0, j = 0; 26 | for (int i = 0;i < pushed.size();i++) { 27 | stack[n++] = pushed[i]; 28 | while (n > 0 && stack[n - 1] == popped[j]) { 29 | n--; 30 | j++; 31 | } 32 | } 33 | if (n == 0) { 34 | return true; 35 | } else { 36 | return false; 37 | } 38 | } 39 | }; 40 | ``` 41 | 42 | -------------------------------------------------------------------------------- /docs/leetcode/cpp/README.md: -------------------------------------------------------------------------------- 1 | # Leetcode C++ 题解 2 | -------------------------------------------------------------------------------- /docs/leetcode/java/0001._Two_Sum.md: -------------------------------------------------------------------------------- 1 | # 1. Two Sum 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/two-sum 10 | 11 | > 内容描述 12 | 13 | ``` 14 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 15 | 16 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 17 | 18 | Example: 19 | 20 | Given nums = [2, 7, 11, 15], target = 9, 21 | 22 | Because nums[0] + nums[1] = 2 + 7 = 9, 23 | return [0, 1]. 24 | ``` 25 | 26 | ## 解题方案 27 | 28 | > 思路 1 29 | ******- 时间复杂度: O(N)******- 空间复杂度: O(N)****** 30 | 31 | 32 | ```java 33 | class Solution { 34 | public int[] twoSum(int[] nums, int target) { 35 | Map lookup = new HashMap<>(); 36 | int[] res = new int[2]; 37 | for (int i = 0; i < nums.length; i++) { 38 | if (lookup.containsKey(target - nums[i])) { 39 | res = new int[] { lookup.get(target - nums[i]), i }; 40 | break; 41 | } else { 42 | lookup.put(nums[i], i); 43 | } 44 | } 45 | return res; 46 | } 47 | } 48 | ``` 49 | -------------------------------------------------------------------------------- /docs/leetcode/java/0007._Reverse_Integer.md: -------------------------------------------------------------------------------- 1 | # 5. Reverse Integer 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/reverse-integer 10 | 11 | > 内容描述 12 | 13 | ``` 14 | Given a 32-bit signed integer, reverse digits of an integer. 15 | 16 | Example 1: 17 | 18 | Input: 123 19 | Output: 321 20 | 21 | Example 2: 22 | 23 | Input: -123 24 | Output: -321 25 | 26 | Example 3: 27 | 28 | Input: 120 29 | Output: 21 30 | 31 | 32 | ``` 33 | 34 | ## 解题方案 35 | 36 | > 思路 1 37 | ******- 时间复杂度: O(n)******- 空间复杂度: O(1)****** 38 | 39 | 将整数翻转,翻转后是否溢出了, beats 95.35% 40 | 41 | ```java 42 | class Solution { 43 | public int reverse(int x) { 44 | // 使用一个long型变量来保存 45 | long index = 0; 46 | while (x != 0){ 47 | index = index * 10 + x %10; 48 | x = x / 10; 49 | } 50 | int result = (int) index; 51 | if(result != index){ 52 | return 0; 53 | } 54 | return (int)index; 55 | } 56 | } 57 | ``` 58 | -------------------------------------------------------------------------------- /docs/leetcode/java/0141._linked_list_cycle.md: -------------------------------------------------------------------------------- 1 | # 141. Linked List Cycle 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/linked-list-cycle 10 | 11 | > 内容描述 12 | 13 | ``` 14 | Given a linked list, determine if it has a cycle in it. 15 | 16 | Follow up: 17 | Can you solve it without using extra space? 18 | ``` 19 | 20 | ## 解题方案 21 | 22 | 23 | > 思路 1 24 | ******- 时间复杂度: O(N)******- 空间复杂度: O(1)****** 25 | 26 | 27 | 快慢指针 28 | 29 | 30 | 31 | ```java 32 | java 33 | public class Solution { 34 | public boolean hasCycle(ListNode head) { 35 | if (head == null){ 36 | return false; 37 | } 38 | ListNode fast = head; 39 | ListNode slow = head; 40 | while (fast != null && slow != null && fast.next != null){ 41 | fast = fast.next.next; 42 | slow = slow.next; 43 | if (slow == fast){ 44 | return true; 45 | } 46 | } 47 | return false; 48 | } 49 | } 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /docs/leetcode/java/0342._Power_of_Four.md: -------------------------------------------------------------------------------- 1 | # 342. Power of Four 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/power-of-four 10 | 11 | > 内容描述 12 | 13 | ``` 14 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 15 | 16 | Example 1: 17 | 18 | Input: 16 19 | Output: true 20 | Example 2: 21 | 22 | Input: 5 23 | Output: false 24 | Follow up: Could you solve it without loops/recursion? 25 | ``` 26 | 27 | ## 解题方案 28 | 29 | > 思路 1 30 | ******- 时间复杂度: O(1)******- 空间复杂度: O(1)****** 31 | 32 | recursive 33 | 34 | ```java 35 | class Solution { 36 | public boolean isPowerOfFour(int num) { 37 | if (num <= 0) 38 | return false; 39 | if (num == 1) 40 | return true; 41 | if (num % 4 == 0) 42 | return isPowerOfFour(num/4); 43 | return false; 44 | } 45 | } 46 | ``` 47 | -------------------------------------------------------------------------------- /docs/leetcode/java/0768._Max_Chunks_To_Make_Sorted_II.md: -------------------------------------------------------------------------------- 1 | ### 768. Max Chunks To Make Sorted II 2 | 3 | 4 | 5 | 题目: 6 | https://leetcode.com/problems/max-chunks-to-make-sorted-ii/ 7 | 8 | 难度: 9 | Hard 10 | 11 | 题意: 12 | 13 | 1. 给定一个数组,求最多能够将数组分成多少段,使得每段排序之后连接起来,是一个有序数组 14 | 15 | 思路: 16 | 17 | - 显而易见,数据能否分的条件是,分出来的左边数组的最大值不大于比右边数组的最小值 18 | - 只需要扫描一下,先把最大值和最小值数组预处理出来,然后遍历就可以得出结果 19 | 20 | 解法: 21 | 22 | ```java 23 | class Solution { 24 | public int maxChunksToSorted(int[] arr) { 25 | int[] min = new int[arr.length]; 26 | int[] max = new int[arr.length]; 27 | max[0] = arr[0]; 28 | for (int i = 1;i < arr.length;i++) { 29 | max[i] = Math.max(arr[i], max[i - 1]); 30 | } 31 | min[arr.length - 1] = arr[arr.length - 1]; 32 | for (int i = arr.length - 2;i >= 0;i--) { 33 | min[i] = Math.min(arr[i], min[i + 1]); 34 | } 35 | int ret = 1; 36 | for (int i = 0;i + 1 < arr.length;i++) { 37 | if (max[i] <= min[i + 1]) { 38 | ret++; 39 | } 40 | } 41 | return ret; 42 | } 43 | } 44 | ``` 45 | 46 | -------------------------------------------------------------------------------- /docs/leetcode/java/README.md: -------------------------------------------------------------------------------- 1 | # Leetcode Java 题解 -------------------------------------------------------------------------------- /docs/leetcode/javascript/0053._Maximum_Subarray.md: -------------------------------------------------------------------------------- 1 | # 053. Maximum Subarray 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | [https://leetcode-cn.com/problems/maximum-subarray/](https://leetcode-cn.com/problems/maximum-subarray/) 10 | 11 | > 内容描述 12 | 13 | 给定一个整数数组 `nums` ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 14 | 15 | #### 示例: 16 | 17 | 输入: [-2,1,-3,4,-1,2,1,-5,4], 18 | 输出: 6 19 | 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 20 | 21 | #### 进阶: 22 | 23 | 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 24 | 25 | ## 解题方案 26 | 27 | > 思路 28 | ******- 时间复杂度: O(N)******- 空间复杂度: O(2N)****** 29 | 30 | 31 | 解法DP 32 | 33 | ```javascript 34 | /** 35 | * @param {number[]} nums 36 | * @return {number} 37 | */ 38 | var maxSubArray = function(nums) { 39 | if(nums.length === 1) { 40 | return nums[0] 41 | } 42 | let sum = nums[0] 43 | let dp = nums[0] 44 | for (let i = 1; i < nums.length; i++) { 45 | dp = Math.max(dp + nums[i], nums[i]) 46 | sum = Math.max(sum, dp) 47 | } 48 | return sum; 49 | }; 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /docs/leetcode/javascript/0058._Length_of_Last_Word.md: -------------------------------------------------------------------------------- 1 | # 58. Length of Last Word 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/length-of-last-word 10 | 11 | > 内容描述 12 | 13 | ``` 14 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 15 | 16 | If the last word does not exist, return 0. 17 | 18 | Note: A word is defined as a character sequence consists of non-space characters only. 19 | 20 | Example: 21 | 22 | Input: "Hello World" 23 | 24 | Output: 5 25 | ``` 26 | 27 | ## 解题方案 28 | 29 | > 思路 1 30 | ******- 时间复杂度: O(N)******- 空间复杂度: O(N)****** 31 | 32 | * 将数组以空格分割,找到最后一个字符串输出长度 33 | * 注意以空格结尾以及输入空字符串 34 | 35 | 代码: 36 | 37 | ```javascript 38 | /** 39 | * @param {string} s 40 | * @return {number} 41 | */ 42 | var lengthOfLastWord = function(s) { 43 | var temp = s.split(' ').filter(function (value) { 44 | return value!=''; 45 | }); 46 | return temp.length>0?temp.pop().length:0; 47 | }; 48 | ``` 49 | 50 | -------------------------------------------------------------------------------- /docs/leetcode/javascript/0104._Maximum_Depth_of_Binary_Tree.md: -------------------------------------------------------------------------------- 1 | # 104. Maximum Depth of Binary Tree 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/maximum-depth-of-binary-tree 10 | 11 | > 内容描述 12 | 13 | ``` 14 | Given a binary tree, find its maximum depth. 15 | 16 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 17 | 18 | Note: A leaf is a node with no children. 19 | 20 | Example: 21 | 22 | Given binary tree [3,9,20,null,null,15,7], 23 | 24 | 3 25 | / \ 26 | 9 20 27 | / \ 28 | 15 7 29 | return its depth = 3. 30 | ``` 31 | 32 | ## 解题方案 33 | 34 | > 思路 1 35 | ******- 时间复杂度: O(log2 N)******- 空间复杂度: O(N)****** 36 | 37 | * 这道题使用递归进行解决,因为对于树的每一个儿子的处理方法是一致的。 38 | * 将左儿子和右儿子中最大的数进行返回再加上当前的深度1即可解决。 39 | 40 | 代码: 41 | 42 | ```javascript 43 | var maxDepth = function(root) { 44 | if(root===null||root === undefined) 45 | return 0; 46 | return Math.max(maxDepth(root.left),maxDepth(root.right))+1; 47 | }; 48 | ``` 49 | 50 | -------------------------------------------------------------------------------- /docs/leetcode/javascript/0106._Construct_Binary_Tree_From_Inorder_And_Postorder_Traversal.md: -------------------------------------------------------------------------------- 1 | # 106. Construct Binary Tree From Inorder And Postorder Traversal 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ 10 | 11 | > 内容描述 12 | 13 | 根据一棵树的中序遍历与后序遍历构造二叉树。 14 | 15 | 注意: 16 | 你可以假设树中没有重复的元素。 17 | 18 | 例如,给出 19 | 20 | 中序遍历 inorder = [9,3,15,20,7] 21 | 后序遍历 postorder = [9,15,7,20,3] 22 | 返回如下的二叉树: 23 | 24 | 3 25 | / \ 26 | 9 20 27 | / \ 28 | 15 7 29 | 30 | 31 | ## 解题方案 32 | 33 | > 思路 1 34 | ******- 时间复杂度: O(N)******- 空间复杂度: O(N)****** 35 | 36 | * 37 | 38 | 代码: 39 | 40 | ```javascript 41 | var buildTree = function(inorder, postorder) { 42 | if (!inorder.length || !postorder.length) { 43 | return null 44 | } 45 | let rootVal = postorder[postorder.length - 1] 46 | let root = new TreeNode(rootVal) 47 | let k = inorder.indexOf(rootVal) 48 | root.left = buildTree(inorder.slice(0, k), postorder.slice(0, k)) 49 | root.right = buildTree(inorder.slice(k+1), postorder.slice(k, postorder.length - 1)) 50 | return root 51 | }; 52 | 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /docs/leetcode/javascript/0171._Excel_Sheet_Column_Number.md: -------------------------------------------------------------------------------- 1 | # 0171. Excel Sheet Column Number 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/excel-sheet-column-number/ 10 | 11 | > 内容描述 12 | 13 | 给定一个Excel表格中的列名称,返回其相应的列序号。 14 | 15 | 例如, 16 | 17 | A -> 1 18 | B -> 2 19 | C -> 3 20 | ... 21 | Z -> 26 22 | AA -> 27 23 | AB -> 28 24 | ... 25 | 26 | 示例 1: 27 | 28 | 输入: "A" 29 | 输出: 1 30 | 31 | 示例 2: 32 | 33 | 输入: "AB" 34 | 输出: 28 35 | 36 | 示例 3: 37 | 38 | 输入: "ZY" 39 | 输出: 701 40 | 41 | 42 | ## 解题方案 43 | 44 | > 思路 1 45 | ******- 时间复杂度: O(N)******- 空间复杂度: O(1)****** 46 | 47 | 利用parseInt可以按照进制来解析的特性,可以将英文字母轻松转换成数字 48 | 49 | 代码: 50 | 51 | ```javascript 52 | /** 53 | * @param {string} s 54 | * @return {number} 55 | */ 56 | var titleToNumber = function(s) { 57 | if (!s) { 58 | return 0 59 | } 60 | let list = s.split('') 61 | list = list.map((alpha, index) => (parseInt(alpha, 36) - 9) * Math.pow(26, list.length - index - 1)) 62 | return list.reduce((acc, cur) => (acc + cur), 0) 63 | } 64 | ``` 65 | -------------------------------------------------------------------------------- /docs/leetcode/javascript/0179._Largest_Number.md: -------------------------------------------------------------------------------- 1 | # 0179. Largest Number 2 | 3 | **难度: Medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode-cn.com/problems/largest-number/ 10 | 11 | > 内容描述 12 | 13 | 给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。 14 | 15 | 示例 1: 16 | 17 | 输入: [10,2] 18 | 输出: 210 19 | 示例 2: 20 | 21 | 输入: [3,30,34,5,9] 22 | 输出: 9534330 23 | 24 | 说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。 25 | 26 | ## 解题方案 27 | 28 | > 思路 1 29 | ******- 时间复杂度: O(N)******- 空间复杂度: O(1)****** 30 | 31 | 排序时,计算两个数字谁在前面组成的数字比较大即可 32 | 33 | 代码: 34 | 35 | ```javascript 36 | /** 37 | * @param {number[]} nums 38 | * @return {string} 39 | */ 40 | var largestNumber = function(nums) { 41 | if (nums.every(n => !n)) { 42 | return '0' 43 | } 44 | return nums.sort((a, b) => { 45 | return Number('' + b + a) - Number('' + a + b) 46 | }).join('') 47 | }; 48 | ``` 49 | -------------------------------------------------------------------------------- /docs/leetcode/javascript/0406._Queue_Reconstruction_By_Height.md: -------------------------------------------------------------------------------- 1 | # 406. Queue Reconstruction By Height 2 | 3 | **难度: medium** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * [https://leetcode-cn.com/problems/queue-reconstruction-by-height/](https://leetcode-cn.com/problems/queue-reconstruction-by-height/) 10 | 11 | > 内容描述 12 | 13 | 假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。 14 | 15 | **注意:** 16 | 总人数少于1100人。 17 | 18 | **示例 1:** 19 | 20 | ``` 21 | 输入: 22 | [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 23 | 24 | 输出: 25 | [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] 26 | ``` 27 | 28 | 29 | ## 解题方案 30 | 31 | > 思路 1 32 | ******- 时间复杂度: O(N²)******- 空间复杂度: O(N)****** 33 | 34 | 贪心算法 35 | **思路** 36 | 个子矮的人的位置不会影响到其他人,他的位置不会影响到其他人。 37 | 38 | **操作步骤** 39 | 1. 对人群排序,由高到低,身高相同再由低到高 40 | 2. 建立一个空队列 41 | 3. 对排序后的人群进行遍历,将当前遍历的人 按照他的索引(n)插入到队列第n的位置 42 | 43 | 代码: 44 | 45 | ```javascript 46 | var reconstructQueue = function(people) { 47 | people.sort((a, b) => ((b[0] - a[0]) || (a[1] - b[1]))); 48 | let queue = []; 49 | people.forEach(person => { 50 | queue.splice([person[1]], 0, person); 51 | }) 52 | return queue 53 | }; 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /docs/leetcode/javascript/0485._Max_Consecutive_Ones.md: -------------------------------------------------------------------------------- 1 | # 485. Max Consecutive Ones 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/max-consecutive-ones 10 | 11 | > 内容描述 12 | 13 | ``` 14 | Given a binary array, find the maximum number of consecutive 1s in this array. 15 | 16 | Example 1: 17 | Input: [1,1,0,1,1,1] 18 | Output: 3 19 | Explanation: The first two digits or the last three digits are consecutive 1s. 20 | The maximum number of consecutive 1s is 3. 21 | Note: 22 | 23 | The input array will only contain 0 and 1. 24 | The length of input array is a positive integer and will not exceed 10,000 25 | 26 | ``` 27 | 28 | ## 解题方案 29 | 30 | > 思路 1 31 | ******- 时间复杂度: O(N)******- 空间复杂度: O(N)****** 32 | 33 | * 使用temp保存每个0之间的差值 34 | * 找出最大的差值即可 35 | 36 | 代码: 37 | 38 | ```javascript 39 | /** 40 | * @param {number[]} nums 41 | * @return {number} 42 | */ 43 | var findMaxConsecutiveOnes = function(nums) { 44 | var max = 0,temp = 0; 45 | for(var i =0;i难度: Esay** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | [https://leetcode-cn.com/problems/divisor-game/](https://leetcode-cn.com/problems/divisor-game/) 10 | 11 | > 内容描述 12 | 13 | 爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。 14 | 15 | 最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作: 16 | 17 | 选出任一 x,满足 `0 < x < N` 且 `N % x == 0` 。 18 | 用` N - x` 替换黑板上的数字` N `。 19 | 如果玩家无法执行这些操作,就会输掉游戏。 20 | 21 | 只有在爱丽丝在游戏中取得胜利时才返回 `True`,否则返回 `False`。假设两个玩家都以最佳状态参与游戏。 22 | 23 | #### 示例1: 24 | 25 | 输入:2 26 | 输出:true 27 | 解释:爱丽丝选择 1,鲍勃无法进行操作。 28 | 29 | 30 | #### 示例2: 31 | 32 | 输入:3 33 | 输出:false 34 | 解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。 35 | 36 | 37 | ## 解题方案 38 | 39 | > 思路 40 | ******- 时间复杂度: O(1)******- 空间复杂度: O(1)****** 41 | 42 | 43 | ```javascript 44 | /** 45 | * @param {number} N 46 | * @return {boolean} 47 | */ 48 | var divisorGame = function(N) { 49 | return N % 2 === 0; 50 | }; 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /docs/leetcode/javascript/README.md: -------------------------------------------------------------------------------- 1 | # Leetcode JavaScript 题解 2 | 3 | > 看左侧栏,开始你的表演! 4 | -------------------------------------------------------------------------------- /docs/leetcode/python/008._string_to_integer_(atoi).md: -------------------------------------------------------------------------------- 1 | ### 8. String to Integer (atoi) 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | Medium 9 | 10 | 11 | 需要考虑比较多的边界条件&特殊情况 12 | 1. 首先输入可能会有空格,所以先去掉空格 13 | 2. 去掉空格后要考虑空字符串情况 14 | 3. 字符串首位可能会有正负号,要考虑 15 | 4. 开始转换成数字,题目说只要遇到非数字就可以break了 16 | 5. 结果太大或者太小超过```int```限制就要返回特定数字 ```2147483647``` 或者 ```-2147483648``` 17 | 6. 根据之前的正负号结果返回对应数值 18 | 19 | 20 | ```python 21 | class Solution(object): 22 | def myAtoi(self, str): 23 | """ 24 | :type str: str 25 | :rtype: int 26 | """ 27 | str = str.strip() 28 | strNum = 0 29 | if len(str) == 0: 30 | return strNum 31 | 32 | positive = True 33 | if str[0] == '+' or str[0] == '-': 34 | if str[0] == '-': 35 | positive = False 36 | str = str[1:] 37 | 38 | for char in str: 39 | if char >='0' and char <='9': 40 | strNum = strNum * 10 + ord(char) - ord('0') 41 | if char < '0' or char > '9': 42 | break 43 | 44 | if strNum > 2147483647: 45 | if positive == False: 46 | return -2147483648 47 | else: 48 | return 2147483647 49 | if not positive: 50 | strNum = 0 - strNum 51 | return strNum 52 | 53 | ``` 54 | -------------------------------------------------------------------------------- /docs/leetcode/python/019._remove_nth_node_from_end_of_list.md: -------------------------------------------------------------------------------- 1 | ### 19. Remove Nth Node From End of List 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: Medium 9 | 10 | 11 | AC击败了95.80%的Python用户,技巧 dummy head 和双指针。 12 | 13 | 切记最后要返回```dummy.next```而不是```head```,因为有这样一种情况,删掉节点后```linked list```空了,那返回```head```的话结果显然不同。如: 14 | 输入链表为```[1]```, ```n = 1```, 应该返回```None```而不是```[1]``` 15 | 16 | ```python 17 | class Solution(object): 18 | def removeNthFromEnd(self, head, n): 19 | """ 20 | :type head: ListNode 21 | :type n: int 22 | :rtype: ListNode 23 | """ 24 | dummy = ListNode(-1) 25 | dummy.next = head 26 | p, q = dummy, dummy 27 | 28 | for i in range(n): 29 | q = q.next 30 | 31 | while q.next: 32 | p = p.next 33 | q = q.next 34 | 35 | p.next = p.next.next 36 | return dummy.next 37 | 38 | ``` 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /docs/leetcode/python/021._merge_two_sorted_lists.md: -------------------------------------------------------------------------------- 1 | ### 21. Merge Two Sorted Lists 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: Easy 9 | 10 | 11 | 同样适用dummy head 12 | 13 | ```python 14 | class Solution(object): 15 | def mergeTwoLists(self, l1, l2): 16 | """ 17 | :type l1: ListNode 18 | :type l2: ListNode 19 | :rtype: ListNode 20 | """ 21 | if l1 == None: 22 | return l2 23 | if l2 == None: 24 | return l1 25 | 26 | dummy = ListNode(-1) 27 | cur = dummy 28 | 29 | while l1 and l2: 30 | if l1.val < l2.val: 31 | cur.next = l1 32 | l1 = l1.next 33 | else: 34 | cur.next = l2 35 | l2 = l2.next 36 | cur = cur.next 37 | 38 | if l1: 39 | cur.next = l1 40 | else: 41 | cur.next = l2 42 | return dummy.next 43 | 44 | ``` 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/leetcode/python/023._merge_k_sorted_lists.md: -------------------------------------------------------------------------------- 1 | ### 23. Merge k Sorted Lists 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Hard 11 | 12 | 思路: 13 | 14 | 看到思路有heap,similar question有ugly number|| -> 这个是用heapq来解决的 15 | 16 | 那么就用heap吧? heapsort 17 | 18 | 最简单的做法是只要每个list里面还有node,就把他们扔到minheap里面去,然后再把minheap pop,一个一个node连起来,听起来时间复杂度和空间复杂度都蛮高的。 19 | 直接merge必然是不好的,因为没有利用有序这个点,应该做的是每次取来一个,然后再把应该的下一个放入 20 | 21 | 写到这里瞬间明白和ugly number ii像的点了,甚至感觉跟find in sorted matrix ii也像 22 | 23 | ```python 24 | class Solution(object): 25 | def mergeKLists(self, lists): 26 | """ 27 | :type lists: List[ListNode] 28 | :rtype: ListNode 29 | """ 30 | import heapq 31 | h = [] 32 | for lst_head in lists: 33 | if lst_head: 34 | heapq.heappush(h, (lst_head.val, lst_head)) 35 | cur = ListNode(-1) 36 | dummy = cur 37 | while h: 38 | smallest_node = heapq.heappop(h)[1] 39 | cur.next = smallest_node 40 | cur = cur.next 41 | if smallest_node.next: 42 | heapq.heappush(h, (smallest_node.next.val, smallest_node.next)) 43 | return dummy.next 44 | ``` 45 | 46 | 当然还像merge two sorted list 47 | -------------------------------------------------------------------------------- /docs/leetcode/python/027._Remove_Element.md: -------------------------------------------------------------------------------- 1 | ### 27. Remove Element 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/remove-element 10 | * https://leetcode-cn.com/problems/remove-element/ 11 | 12 | > 内容描述 13 | 14 | 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。 15 | 16 | 不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。 17 | 18 | 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。 19 | 20 | 21 | 示例 1: 22 | 23 | ``` 24 | 给定 nums = [3,2,2,3], val = 3, 25 | 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。 26 | 你不需要考虑数组中超出新长度后面的元素。 27 | ``` 28 | 29 | 示例 2: 30 | 31 | ``` 32 | 给定 nums = [0,1,2,2,3,0,4,2], val = 2, 33 | 函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。 34 | 注意这五个元素可为任意顺序。 35 | 你不需要考虑数组中超出新长度后面的元素。 36 | ``` 37 | 38 | ## 解题方案 39 | 40 | > 思路 1 41 | 42 | 瞬秒 43 | 44 | ```python 45 | class Solution(object): 46 | def removeElement(self, nums, val): 47 | """ 48 | :type nums: List[int] 49 | :type val: int 50 | :rtype: int 51 | """ 52 | while val in nums: 53 | nums.remove(val) 54 | return len(nums) 55 | ``` 56 | -------------------------------------------------------------------------------- /docs/leetcode/python/028._implement_strstr.md: -------------------------------------------------------------------------------- 1 | ### 28. Implement strStr() 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 一行解法如何? 14 | ```python 15 | class Solution(object): 16 | def strStr(self, haystack, needle): 17 | """ 18 | :type haystack: str 19 | :type needle: str 20 | :rtype: int 21 | """ 22 | return haystack.find(needle) 23 | ``` 24 | 25 | 26 | 这个题目其实可以引来一大类,那就是关于string的算法,但是此处先用暴力算法来AC,然后再来细读/品味别的string相关算法吧。 27 | 28 | 虽然是暴力算法,但是也不容易写对啊 29 | ```python 30 | class Solution(object): 31 | def strStr(self, haystack, needle): 32 | """ 33 | :type haystack: str 34 | :type needle: str 35 | :rtype: int 36 | """ 37 | if not needle: 38 | return 0 39 | for i in xrange(len(haystack) - len(needle) + 1): 40 | if haystack[i] == needle[0]: 41 | j = 1 42 | while j < len(needle) and haystack[i+j] == needle[j]: 43 | j += 1 44 | if j == len(needle): 45 | return i 46 | return -1 47 | ``` 48 | -------------------------------------------------------------------------------- /docs/leetcode/python/040._combination_sum_ii.md: -------------------------------------------------------------------------------- 1 | ### 40. Combination Sum II 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Medium 11 | 12 | 13 | Combination Sum 已经AC,做了minor change. 14 | - 现在不需要```set```化```candidates```了 15 | - 但是递归的时候```index```要从```i+1```开始了 16 | - 要判断```combo not in res```才```append```到```res```中去 17 | 18 | ```python 19 | class Solution(object): 20 | def combinationSum2(self, candidates, target): 21 | """ 22 | :type candidates: List[int] 23 | :type target: int 24 | :rtype: List[List[int]] 25 | """ 26 | def dfs(remain, combo, index): 27 | if remain == 0 and combo not in res: 28 | res.append(combo) 29 | return 30 | for i in range(index, len(candidates)): 31 | if candidates[i] > remain: 32 | break 33 | dfs(remain - candidates[i], combo + [candidates[i]], i+1) 34 | candidates.sort() 35 | res = [] 36 | dfs(target, [], 0) 37 | return res 38 | 39 | ``` 40 | -------------------------------------------------------------------------------- /docs/leetcode/python/044._wildcard_matching.md: -------------------------------------------------------------------------------- 1 | ###44. Wildcard Matching 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Hard 10 | 11 | 12 | 13 | 做完Regular Expression Matching来做的这道题,按照DP思路run一下是超时,感觉是开心的,至少暂时没有报错了,有待优化,应该在dp的同时在贪心一下么。 14 | 15 | 16 | 17 | 超时代码 18 | ``` 19 | class Solution(object): 20 | def isMatch(self, s, p): 21 | """ 22 | :type s: str 23 | :type p: str 24 | :rtype: bool 25 | """ 26 | m, n = len(s), len(p) 27 | dp = [ [0 for i in xrange(n+1)] for j in xrange(m+1)] 28 | 29 | dp[0][0] = 1 30 | 31 | # init the first line 32 | for i in xrange(1,n+1): 33 | if p[i-1] == '*': 34 | dp[0][i] = dp[0][i-1] 35 | 36 | for i in xrange(1,m+1): 37 | for j in xrange(1,n+1): 38 | if p[j-1] == s[i-1] or p[j-1] == '?': 39 | dp[i][j] = dp[i-1][j-1] 40 | elif p[j-1] == '*': 41 | dp[i][j] = dp[i][j-1] or dp[i-1][j] 42 | 43 | return dp[m][n] == 1 44 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/045._Jump_Game_II.md: -------------------------------------------------------------------------------- 1 | ### 45. Jump Game II 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 思路 13 | 14 | greedy solution, the current jump is ```[i, cur_end]```, and the ```cur_farthest``` is the farthest point 15 | that all of point in ```[i, cur_end]``` can reach, whenever ```cur_farthest``` is larger than the last point' index, 16 | return current ```jump+1```; whenever ```i``` reaches ```cur_end```, update ```cur_end``` to ```current cur_farthest```. 17 | - Time: O(log(n)) 18 | - Space: O(1) 19 | 20 | ```python 21 | class Solution(object): 22 | def jump(self, nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: int 26 | """ 27 | # Note You can assume that you can always reach the last index. 28 | cur_end, cur_farthest, step, n = 0, 0, 0, len(nums) 29 | for i in range(n-1): 30 | cur_farthest = max(cur_farthest, i + nums[i]) 31 | if cur_farthest >= n - 1: 32 | step += 1 33 | break 34 | if i == cur_end: 35 | cur_end = cur_farthest 36 | step += 1 37 | return step 38 | 39 | 40 | 41 | ``` 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/leetcode/python/047._permutations_ii.md: -------------------------------------------------------------------------------- 1 | ### 47. Permutations II 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Medium 10 | 11 | 跟第46题一样,就是最后append的时候不一样,只有没有结果里面没有的才加入 12 | 13 | 14 | ```python 15 | class Solution(object): 16 | def permuteUnique(self, nums): 17 | """ 18 | :type nums: List[int] 19 | :rtype: List[List[int]] 20 | """ 21 | if len(nums) == 0: 22 | return [] 23 | if len(nums) == 1: 24 | return [nums] 25 | res = [] 26 | for i in range(len(nums)): 27 | prefix = nums[i] 28 | rest = nums[:i] + nums[i+1:] 29 | for j in self.permuteUnique(rest): 30 | if [prefix]+j not in res: 31 | res.append([prefix]+j) 32 | return res 33 | ``` 34 | 35 | 36 | -------------------------------------------------------------------------------- /docs/leetcode/python/049._group_anagrams_python.md: -------------------------------------------------------------------------------- 1 | ### 49. Group Anagrams python 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度 : Medium 8 | 9 | python大法好 10 | 11 | 12 | ```python 13 | class Solution(object): 14 | def groupAnagrams(self, strs): 15 | """ 16 | :type strs: List[str] 17 | :rtype: List[List[str]] 18 | """ 19 | mapx = {} 20 | for i in strs: 21 | x = ''.join(sorted(list(i))) 22 | if x in mapx: 23 | mapx[x].append(i) 24 | else: 25 | mapx[x] = [i] 26 | return mapx.values() 27 | 28 | ``` 29 | -------------------------------------------------------------------------------- /docs/leetcode/python/050._pow(x,_n).md: -------------------------------------------------------------------------------- 1 | ### 50. Pow(x, n) 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Medium 10 | 11 | 12 | Recursive 13 | 14 | ```python 15 | class Solution(object): 16 | def myPow(self, x, n): 17 | """ 18 | :type x: float 19 | :type n: int 20 | :rtype: float 21 | """ 22 | if n == 0: 23 | return 1 24 | if n < 0: 25 | return 1 / self.myPow(x, -n) 26 | if n % 2 == 0: 27 | return self.myPow(x*x, n/2) 28 | else: 29 | return x * self.myPow(x*x, n/2) 30 | 31 | ``` 32 | iterative 33 | 34 | 35 | ```python 36 | class Solution: 37 | def myPow(self, x, n): 38 | if n < 0: 39 | x = 1 / x 40 | n = -n 41 | pow = 1 42 | while n: 43 | if n & 1: 44 | pow *= x 45 | x *= x 46 | n >>= 1 47 | return pow 48 | ``` 49 | -------------------------------------------------------------------------------- /docs/leetcode/python/055._jump_game.md: -------------------------------------------------------------------------------- 1 | ### 55. Jump Game 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Medium 10 | 11 | 12 | 问题出现在一旦有0,而且这个0是不可跨过的那么无解,无法达到 13 | 14 | 15 | 看了hint,根本不用这个数组,直接用一个数来记录可达最远距离,非常巧妙 16 | 17 | 18 | ```python 19 | class Solution(object): 20 | def canJump(self, nums): 21 | """ 22 | :type nums: List[int] 23 | :rtype: bool 24 | """ 25 | if not nums: 26 | return True 27 | if len(nums) == 1: 28 | return True 29 | n = len(nums) 30 | idx, reach = 0, 0 31 | while idx < n-1 and idx <= reach: # idx <= reach是为了处理nums[idx] == 0的情况,若idx>reach说明已经失败了 32 | reach = max(reach, idx+nums[idx]) 33 | idx += 1 34 | return reach >= n-1 35 | ``` 36 | 37 | idx记录当前loop位置,reach记录当前可到位置 38 | 39 | 注意这里的while循环的条件是 `idx < n-1 and idx <= reach`,之所以加上 `idx <= reach` 是因为如果```idx > reach```说明```idx```层不可达,其实也可以直接terminate. 40 | -------------------------------------------------------------------------------- /docs/leetcode/python/056._Merge_Intervals.md: -------------------------------------------------------------------------------- 1 | ### 56. Merge Intervals 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Medium 10 | 11 | 12 | Just go through the intervals sorted by start coordinate and 13 | either combine the current interval with the previous one if they overlap, or add it to the output by itself if they don’t. 14 | 15 | ```python 16 | class Solution(object): 17 | def merge(self, intervals): 18 | """ 19 | :type intervals: List[Interval] 20 | :rtype: List[Interval] 21 | """ 22 | res = [] 23 | for i in sorted(intervals, key = lambda i: i.start): 24 | if res and i.start <= res[-1].end: 25 | res[-1].end = max(i.end, res[-1].end) 26 | else: 27 | res.append(i) 28 | return res 29 | ``` 30 | 31 | 32 | -------------------------------------------------------------------------------- /docs/leetcode/python/058._length_of_last_word.md: -------------------------------------------------------------------------------- 1 | ### 58. Length of Last Word 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度 : Easy 8 | 9 | 我的解法: 10 | 11 | ```python 12 | class Solution(object): 13 | def lengthOfLastWord(self, s): 14 | """ 15 | :type s: str 16 | :rtype: int 17 | """ 18 | s = s[::-1].strip() 19 | return s.find(' ') if s.find(' ') != -1 else len(s) 20 | ``` 21 | 作弊式做法 22 | 23 | ```python 24 | class Solution(object): 25 | def lengthOfLastWord(self, s): 26 | """ 27 | :type s: str 28 | :rtype: int 29 | """ 30 | lst = s.split() 31 | if len(lst) >= 1: 32 | return len(lst[-1]) 33 | return 0 34 | ``` 35 | split()方法最低可以分0组,split(' ')最低可以分1组 36 | ```python 37 | 一行解法: 38 | class Solution(object): 39 | def lengthOfLastWord(self, s): 40 | """ 41 | :type s: str 42 | :rtype: int 43 | """ 44 | return len(s.strip().split(" ")[-1]) 45 | ``` 46 | -------------------------------------------------------------------------------- /docs/leetcode/python/061._rotate_list.md: -------------------------------------------------------------------------------- 1 | 2 | ###61. Rotate List 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | 11 | Medium 12 | 13 | - k可能比list的size大,需要做一个取余准备 14 | - 计算list size的同时把tail也记录下来,方便之后把tail的next指向原本的head 15 | - 利用之前的到末端的kth node 16 | 17 | 18 | AC 代码 19 | 20 | ``` 21 | class Solution(object): 22 | def rotateRight(self, head, k): 23 | if head == None or k == 0 : 24 | return head 25 | 26 | cur = head 27 | size = 1 28 | while cur.next: 29 | size += 1 30 | cur = cur.next 31 | 32 | tail = cur 33 | 34 | k = k % size 35 | 36 | p = self.findKth(head,k) 37 | 38 | tail.next = head 39 | head = p.next 40 | p.next = None 41 | return head 42 | 43 | def findKth(self,head, k): 44 | dummy = ListNode(-1) 45 | dummy.next = head 46 | p = dummy 47 | q = dummy 48 | 49 | for i in range(k): 50 | q = q.next 51 | 52 | while q.next: 53 | p = p.next 54 | q = q.next 55 | return p 56 | ``` 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/leetcode/python/067._add_binary.md: -------------------------------------------------------------------------------- 1 | ###67. Add Binary 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度 : Easy 8 | 9 | 10 | 几种case: 11 | 12 | - a or b 为空,最简单 13 | - 唯一的问题是如果有进位的处理,进位的处理就是先让其中的一个数和```‘1’```做```addBinary```处理 ,然后再用```addBinary``` 14 | 15 | ```python 16 | class Solution(object): 17 | def addBinary(self, a, b): 18 | """ 19 | :type a: str 20 | :type b: str 21 | :rtype: str 22 | """ 23 | if (a == '' or b == ''): 24 | return a + b 25 | elif a[-1] == '0' and b[-1] == '0': 26 | return self.addBinary(a[:-1], b[:-1]) + '0' 27 | elif a[-1] == '1' and b[-1] == '1': 28 | return self.addBinary(a[:-1], self.addBinary(b[:-1],'1')) + '0' 29 | else: 30 | return self.addBinary(a[:-1], b[:-1]) + '1' 31 | ``` 32 | -------------------------------------------------------------------------------- /docs/leetcode/python/073._Set_Matrix_Zeroes.md: -------------------------------------------------------------------------------- 1 | ### 73. Set Matrix Zeroes 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 10 | 难度 : Medium 11 | 12 | 13 | 14 | 思路: 15 | 16 | Naive AC代码,一看类似那个 game of life,不用extra space,不用O(mn),应该就是用状态转移机了(?),所以还是先naive AC把: 17 | 18 | ```python 19 | class Solution(object): 20 | def setZeroes(self, matrix): 21 | """ 22 | :type matrix: List[List[int]] 23 | :rtype: void Do not return anything, modify matrix in-place instead. 24 | """ 25 | def setZero(i,j): 26 | for m in range(col): 27 | matrix[i][m] = 0 28 | for n in range(row): 29 | matrix[n][j] = 0 30 | 31 | row = len(matrix) 32 | col = len(matrix[0]) if row else 0 33 | new_matrix = [matrix[i][:] for i in range(row)] 34 | 35 | for i in range(row): 36 | for j in range(col): 37 | if new_matrix[i][j] == 0: 38 | setZero(i,j) 39 | ``` 40 | 41 | 42 | 43 | `正确思路`: 44 | 45 | 一边遍历,一边将相应的行和列置为0是行不通的,会影响后面元素的遍历判断,所以要记录下哪些行和哪些列是要置为0的。为了节约空间,在原矩阵中借两条边,如果该行或者列要置为0,则把左边或者上边的相应位置置为0。如果左边和上边本来就有0,那么需要额外标记一下,最后把左边或者右边也全部置为0. 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/leetcode/python/082._remove_duplicates_from_sorted_list_ii.md: -------------------------------------------------------------------------------- 1 | ###82. Remove Duplicates from Sorted List II 2 | 3 | 4 | 题目: 5 | 6 | 7 | 8 | 9 | 难度: 10 | 11 | Medium 12 | 13 | 14 | 木有space 和 time的限制,第一想法,用dictionary存一下每个nodes的个数,这样只要看到它是大于1的,就删删删。 15 | 16 | 虽然是笨办法。但是也可以AC 17 | 18 | ``` 19 | class Solution(object): 20 | def deleteDuplicates(self, head): 21 | """ 22 | :type head: ListNode 23 | :rtype: ListNode 24 | """ 25 | dummy = ListNode(-1) 26 | dummy.next = head 27 | 28 | cur = dummy.next 29 | nodeNumber = {} 30 | while cur: 31 | if cur.val in nodeNumber: 32 | nodeNumber[cur.val] += 1 33 | else: 34 | nodeNumber[cur.val] = 1 35 | cur = cur.next 36 | 37 | cur = dummy 38 | while cur.next: 39 | if nodeNumber[cur.next.val] > 1: 40 | cur.next = cur.next.next 41 | else: 42 | cur = cur.next 43 | return dummy.next 44 | ``` 45 | 46 | 47 | 谷歌一下,更省时间的方法是用一个prev 和 cur 指针,然后用一个bool来记录是否duplicate,这样loop一次即可解决问题。 48 | 49 | to be 写出来 -------------------------------------------------------------------------------- /docs/leetcode/python/083._remove_duplicates_from_sorted_list.md: -------------------------------------------------------------------------------- 1 | ### 83. Remove Duplicates from Sorted List 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | dummy 大法 13 | 14 | ```python 15 | class Solution(object): 16 | def deleteDuplicates(self, head): 17 | """ 18 | :type head: ListNode 19 | :rtype: ListNode 20 | """ 21 | dummy = head 22 | while head: 23 | while head.next and head.next.val == head.val: 24 | head.next = head.next.next # skip duplicated node 25 | head = head.next # not duplicate of current node, move to next node 26 | return dummy 27 | 28 | ``` 29 | -------------------------------------------------------------------------------- /docs/leetcode/python/086._partition_list.md: -------------------------------------------------------------------------------- 1 | ###86. Partition List 2 | 3 | 4 | 题目: 5 | 6 | 7 | 8 | 难度 : Medium 9 | 10 | 11 | 思路一: 12 | 13 | 14 | 最简单的思路就是两个dummy head,然后一个指向 小于的node,一个指向大于的node 15 | 16 | 17 | 思路二: 18 | 19 | 不走寻常路了,使用两个指针,一个指向小于的尾巴,一个一直往后走,指向大于,然后交换node 20 | 21 | 完成比完美更重要啊,其实可以先试试用简单方法,因为我用我的不走寻常路画了比较久的图,写起来也稍显没那么美观,还在交换node的部分卡了一会 22 | 23 | 24 | 25 | ``` 26 | class Solution(object): 27 | def partition(self, head, x): 28 | """ 29 | :type head: ListNode 30 | :type x: int 31 | :rtype: ListNode 32 | """ 33 | dummy = ListNode(-1) 34 | dummy.next = head 35 | 36 | p1 = p2 = dummy 37 | 38 | while p1.next and p1.next.val < x: 39 | p1 = p1.next 40 | 41 | p2 = p1.next 42 | 43 | while p2: 44 | while p2.next and p2.next.val >= x: 45 | p2 = p2.next 46 | 47 | if p2.next == None: 48 | break 49 | node = p2.next 50 | p2.next = node.next 51 | node.next = p1.next 52 | p1.next = node 53 | p1 = p1.next 54 | 55 | return dummy.next 56 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/100._same_tree.md: -------------------------------------------------------------------------------- 1 | ### 100. Same Tree 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 太简单了,递归一行! 14 | 15 | 16 | ```python 17 | # Definition for a binary tree node. 18 | # class TreeNode(object): 19 | # def __init__(self, x): 20 | # self.val = x 21 | # self.left = None 22 | # self.right = None 23 | 24 | class Solution(object): 25 | def isSameTree(self, p, q): 26 | """ 27 | :type p: TreeNode 28 | :type q: TreeNode 29 | :rtype: bool 30 | """ 31 | return p.val == q.val and all(map(self.isSameTree, (p.left, p.right), (q.left, q.right))) if p and q else p is q 32 | ``` 33 | 34 | ```python 35 | class Solution(object): 36 | def isSameTree(self, p, q): 37 | """ 38 | :type p: TreeNode 39 | :type q: TreeNode 40 | :rtype: bool 41 | """ 42 | if (not p and q) or (p and not q): 43 | return False 44 | if not p and not q: 45 | return True 46 | if p.val == q.val: 47 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 48 | return False 49 | ``` 50 | -------------------------------------------------------------------------------- /docs/leetcode/python/101._symmetric_tree.md: -------------------------------------------------------------------------------- 1 | ### 101. Symmetric Tree 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 两棵树symmetric, 有几种可能: 14 | 15 | - 均为none ,symmetric 16 | - 左孩子,右孩子都不存在,并且值相等, symmetric 17 | - 右子树 和 另一棵树的左子树相等,左子树 和另一颗树的右子树相等 🌲 18 | 19 | 20 | ```python 21 | class Solution(object): 22 | def isSymmetric(self, root): 23 | """ 24 | :type root: TreeNode 25 | :rtype: bool 26 | """ 27 | if not root: 28 | return True 29 | return self.symmetric(root.left, root.right) 30 | 31 | def symmetric(self, l1, l2): 32 | if not l1 or not l2: 33 | if not l1 and not l2: 34 | return True 35 | else: 36 | return False 37 | if l1.val == l2.val: 38 | return self.symmetric(l1.left, l2.right) and self.symmetric(l1.right, l2.left) 39 | else: 40 | return False 41 | ``` 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/leetcode/python/103._binary_tree_zigzag_level_order_traversal.md: -------------------------------------------------------------------------------- 1 | ### 103. Binary Tree Zigzag Level Order Traversal 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Medium 11 | 12 | 13 | 14 | ```python 15 | class Solution(object): 16 | def zigzagLevelOrder(self, root): 17 | """ 18 | :type root: TreeNode 19 | :rtype: List[List[int]] 20 | """ 21 | if not root: 22 | return [] 23 | res, cur_level, level_count = [], [root], 0 24 | while cur_level: 25 | next_level, tmp_res = [], [] 26 | for node in cur_level: 27 | tmp_res.append(node.val) 28 | if node.left: 29 | next_level.append(node.left) 30 | if node.right: 31 | next_level.append(node.right) 32 | if level_count % 2 == 0: 33 | res.append(tmp_res) 34 | else: 35 | tmp_res.reverse() 36 | res.append(tmp_res) 37 | level_count += 1 38 | cur_level = next_level 39 | 40 | return res 41 | ``` 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/leetcode/python/104._maximum_depth_of_binary_tree.md: -------------------------------------------------------------------------------- 1 | ### 104. Maximum Depth of Binary Tree 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 简单题,但是这道题跟[leetcode111](https://github.com/Lisanaaa/thinking_in_lc/blob/master/111._minimum_depth_of_binary_tree.md)不一样,这道题没有特殊情况,所以一行就够了 13 | 14 | 15 | ```python 16 | class Solution(object): 17 | def maxDepth(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: int 21 | """ 22 | return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0 23 | ``` 24 | -------------------------------------------------------------------------------- /docs/leetcode/python/107._binary_tree_level_order_traversal_ii.md: -------------------------------------------------------------------------------- 1 | ###107. Binary Tree Level Order Traversal II 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 用102 的算法作弊 14 | 15 | 16 | ``` 17 | # Definition for a binary tree node. 18 | # class TreeNode(object): 19 | # def __init__(self, x): 20 | # self.val = x 21 | # self.left = None 22 | # self.right = None 23 | 24 | class Solution(object): 25 | def levelOrderBottom(self, root): 26 | """ 27 | :type root: TreeNode 28 | :rtype: List[List[int]] 29 | """ 30 | res = [] 31 | 32 | if root == None: return [] 33 | 34 | curLevel = [root] 35 | while curLevel: 36 | nextLevel = [] 37 | tmpRes = [] 38 | for node in curLevel: 39 | tmpRes.append(node.val) 40 | if node.left: nextLevel.append(node.left) 41 | if node.right: nextLevel.append(node.right) 42 | res.append(tmpRes) 43 | curLevel = nextLevel 44 | res.reverse() 45 | return res 46 | ``` 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/leetcode/python/108._convert_sorted_array_to_binary_search_tree.md: -------------------------------------------------------------------------------- 1 | ### 108. Convert Sorted Array to Binary Search Tree 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | Medium 9 | 10 | 11 | 思路: 12 | 13 | 递归 14 | 15 | - nums为空,return None 16 | - nums非空,nums[n/2]为中间元素,根结点,nums[:mid]为左子树, nums[mid+1:]为右子树 17 | 18 | 19 | ```python 20 | class Solution(object): 21 | def sortedArrayToBST(self, nums): 22 | """ 23 | :type nums: List[int] 24 | :rtype: TreeNode 25 | """ 26 | if not nums: 27 | return None 28 | if nums: 29 | mid = len(nums) / 2 30 | root = TreeNode(nums[mid]) 31 | root.left = self.sortedArrayToBST(nums[:mid]) 32 | root.right = self.sortedArrayToBST(nums[mid+1:]) 33 | return root 34 | ``` 35 | -------------------------------------------------------------------------------- /docs/leetcode/python/109._convert_sorted_list_to_binary_search_tree.md: -------------------------------------------------------------------------------- 1 | ### 109. Convert Sorted List to Binary Search Tree 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | 11 | Medium 12 | 13 | 思路: 14 | 15 | 跟第 108 题一样 16 | 17 | ```python 18 | class Solution(object): 19 | def sortedListToBST(self, head): 20 | """ 21 | :type head: ListNode 22 | :rtype: TreeNode 23 | """ 24 | def sortedArrayToBST(nums): 25 | if not nums: 26 | return None 27 | if nums: 28 | mid = len(nums) / 2 29 | root = TreeNode(nums[mid]) 30 | root.left = sortedArrayToBST(nums[:mid]) 31 | root.right = sortedArrayToBST(nums[mid+1:]) 32 | return root 33 | if not head: 34 | return None 35 | else: 36 | lst = [] 37 | while head: 38 | lst.append(head.val) 39 | head = head.next 40 | return sortedArrayToBST(lst) 41 | ``` 42 | -------------------------------------------------------------------------------- /docs/leetcode/python/112._path_sum.md: -------------------------------------------------------------------------------- 1 | ### 112. Path Sum 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 递归 13 | 14 | ```python 15 | class Solution(object): 16 | def hasPathSum(self, root, sum): 17 | """ 18 | :type root: TreeNode 19 | :type sum: int 20 | :rtype: bool 21 | """ 22 | if not root: 23 | return False 24 | if root.left or root.right: 25 | return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val) 26 | else: 27 | return root.val == sum 28 | ``` 29 | -------------------------------------------------------------------------------- /docs/leetcode/python/113._path_sum_ii.md: -------------------------------------------------------------------------------- 1 | ### 113. Path Sum II 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 9 | tag : DFS 10 | 11 | 12 | 难度 : Medium 13 | 14 | 15 | 注意宁愿写几次curList + [root.val] 也不要直接传一个list进去,因为list pass by reference的亏已经吃过了 16 | 17 | ```python 18 | class Solution(object): 19 | def pathSum(self, root, sum): 20 | """ 21 | :type root: TreeNode 22 | :type sum: int 23 | :rtype: List[List[int]] 24 | """ 25 | res = [] 26 | self.auxPathSum(root, sum, [], res) 27 | return res 28 | def auxPathSum(self, root, sum, cur_list, cur_lists): 29 | if not root: 30 | return 31 | sum -= root.val 32 | if sum == 0 and not root.left and not root.right: 33 | cur_lists.append(cur_list + [root.val]) 34 | return 35 | if root.left: 36 | self.auxPathSum(root.left, sum, cur_list + [root.val], cur_lists) 37 | if root.right: 38 | self.auxPathSum(root.right, sum, cur_list + [root.val], cur_lists) 39 | ``` 40 | 41 | -------------------------------------------------------------------------------- /docs/leetcode/python/119._Pascal's_Triangle_II.md: -------------------------------------------------------------------------------- 1 | ### 119. Pascal's Triangle II 2 | 3 | 题目: 4 | 5 | 6 | 难度 : Easy 7 | 8 | 9 | 10 | 思路: 11 | 12 | 太简单了,注意一点算数就好 13 | 14 | 15 | ```python 16 | class Solution(object): 17 | def getRow(self, rowIndex): 18 | """ 19 | :type rowIndex: int 20 | :rtype: List[int] 21 | """ 22 | if rowIndex == 0: 23 | return [1] 24 | res = [1] 25 | for i in range(1, rowIndex+1): 26 | tmp = [1] 27 | for j in range(1, i): 28 | tmp.append(res[j-1]+res[j]) 29 | tmp.append(1) 30 | res = tmp 31 | return res 32 | ``` 33 | -------------------------------------------------------------------------------- /docs/leetcode/python/125._valid_palindrome.md: -------------------------------------------------------------------------------- 1 | ### 125. Valid Palindrome 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 13 | 就是比较reversed string 和原本的是否相等. 14 | 15 | 16 | ```python 17 | class Solution(object): 18 | def isPalindrome(self,s): 19 | """ 20 | :type s: str 21 | :rtype: bool 22 | """ 23 | 24 | new=[] 25 | s = s.lower() 26 | 27 | for i in s: 28 | if '0'<=i<='9' or 'a'<=i<='z': 29 | new.append(i) 30 | 31 | return new == new[::-1] 32 | ``` 33 | 34 | 或者用正则,详见[re.sub()用法](http://blog.csdn.net/geekleee/article/details/75309433) 35 | 瞬间```beats 97.71%``` 36 | ```python 37 | class Solution(object): 38 | def isPalindrome(self, s): 39 | """ 40 | :type s: str 41 | :rtype: bool 42 | """ 43 | newString = re.sub("[^0-9a-zA-Z]+", "", s) 44 | return newString.lower() == newString.lower()[::-1] 45 | ``` 46 | 47 | -------------------------------------------------------------------------------- /docs/leetcode/python/129._sum_root_to_leaf_numbers.md: -------------------------------------------------------------------------------- 1 | ###129. Sum Root to Leaf Numbers 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Medium 10 | 11 | 其实递归不难想到,不过我自己做错在细节方面 12 | 13 | 如果只有单支,每朝下走一层,代表的数字都增加10, 10* 原本的 + 新节点的数字,最终也是用这个来解 14 | 15 | ``` 16 | class Solution(object): 17 | def sumNumbers(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: int 21 | """ 22 | return self.calSum(root,0) 23 | 24 | 25 | def calSum(self,root,curSum): 26 | if root == None: 27 | return 0 28 | else: 29 | curSum = curSum * 10 + root.val 30 | if root.left == None and root.right == None: 31 | return curSum 32 | else: 33 | return self.calSum(root.left, curSum) + self.calSum(root.right, curSum) 34 | 35 | 36 | 37 | ``` 38 | -------------------------------------------------------------------------------- /docs/leetcode/python/131._palindrome_partitioning.md: -------------------------------------------------------------------------------- 1 | ###131. Palindrome Partitioning 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | Medium 9 | 10 | 知道一定是用递归做,但是在怎么拆的部分疑惑了,然后看了hint 11 | 12 | key部分长这样,拆法是类似于combination,然后这个len(s) == 0是确保能被拆为palindrome,因为这样剩下的string才是空的 13 | 14 | 15 | 这个recursion tree是这样的,感觉时间复杂度是O(n!),因为每次树都branch n个分支 16 | 17 | ``` 18 | 19 | class Solution(object): 20 | def partition(self, s): 21 | """ 22 | :type s: str 23 | :rtype: List[List[str]] 24 | """ 25 | self.res = [] 26 | self.dfs(s,[]) 27 | return self.res 28 | 29 | 30 | def dfs(self, s, stringList): 31 | if len(s) == 0: 32 | self.res.append(stringList) 33 | for i in range(1,len(s)+1): 34 | if self.isPalindrome(s[:i]): 35 | self.dfs(s[i:],stringList + [s[:i]]) 36 | 37 | def isPalindrome(self, s): 38 | if len(s) <= 1: 39 | return True 40 | return s[0] == s[-1] and self.isPalindrome(s[1:-1]) 41 | 42 | a = Solution() 43 | print a.partition("aab") 44 | 45 | # [['a', 'a', 'b'], ['aa', 'b']] 46 | ``` 47 | 48 | 输出是每次必定从单个char的list开始,然后单个char 配 palindrome word,然后palindrome word再来配char... -------------------------------------------------------------------------------- /docs/leetcode/python/136._single_number.md: -------------------------------------------------------------------------------- 1 | ### 136. Single Number 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | 11 | Easy 12 | 13 | 14 | 思路: 15 | 16 | 位运算,终于要take it了 17 | 18 | 非常常见的一道算法题,将所有数字进行异或操作即可。对于异或操作明确以下三点: 19 | 20 | - 一个整数与自己异或的结果是0 21 | - 一个整数与0异或的结果是自己 22 | - 异或操作满足交换律,即a^b=b^a 23 | 24 | Python的位操作: 25 | 26 | 27 | 神奇的解法: 28 | 29 | 30 | ```python 31 | class Solution(object): 32 | def singleNumber(self, nums): 33 | """ 34 | :type nums: List[int] 35 | :rtype: int 36 | """ 37 | res = nums[0] 38 | for i in nums[1:]: 39 | res ^= i 40 | return res 41 | ``` 42 | 43 | -------------------------------------------------------------------------------- /docs/leetcode/python/151._reverse_words_in_a_string.md: -------------------------------------------------------------------------------- 1 | ### 151. Reverse Words in a String 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | Medium 9 | 10 | 太简单了 11 | 12 | ```python 13 | class Solution(object): 14 | def reverseWords(self, s): 15 | """ 16 | :type s: str 17 | :rtype: str 18 | """ 19 | tmp = s.split() 20 | res = " ".join(tmp[::-1]) 21 | return res 22 | 23 | ``` 24 | 25 | ```python 26 | class Solution(object): 27 | def reverseWords(self, s): 28 | """ 29 | :type s: str 30 | :rtype: str 31 | """ 32 | tmp = s.split() 33 | tmp.reverse() 34 | res = " ".join(tmp) 35 | return res 36 | 37 | ``` 38 | -------------------------------------------------------------------------------- /docs/leetcode/python/152._maximum_product_subarray.md: -------------------------------------------------------------------------------- 1 | ###152. Maximum Product Subarray 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Medium 11 | 12 | 思路: 13 | 14 | 粗一看, 一股浓烈的DP气息飘来,想要套用53题的思路和方程。但是这个跟sum是不一样的,因为乘积可以正负正负的跳,这样的动归方程肯定是不对的 15 | 16 | dp[i] = max(dp[i-1] * a[i],a[i]) 17 | 18 | 举个例子 : [-2,3,-4] 19 | 20 | 21 | 用O(N^2)超时,厉害啊! 22 | 23 | 想,可不可以记录+的和-的,记录两个dp数组,我哭了,真的是这样做的 24 | 25 | 最大值可能来源于最小值 -> 哲学般的句子 26 | 27 | ``` 28 | class Solution(object): 29 | def maxProduct(self, nums): 30 | """ 31 | :type nums: List[int] 32 | :rtype: int 33 | """ 34 | n = len(nums) 35 | maxdp = [ nums[0] for i in range(n)] 36 | mindp = [ nums[0] for i in range(n)] 37 | 38 | 39 | for i in range(1,n): 40 | maxdp[i] = max(mindp[i-1]*nums[i], maxdp[i-1]*nums[i],nums[i]) 41 | mindp[i] = min(maxdp[i-1]*nums[i], mindp[i-1]*nums[i],nums[i]) 42 | 43 | return max(maxdp) 44 | ``` 45 | -------------------------------------------------------------------------------- /docs/leetcode/python/159._Longest_Substring_with_At_Most_Two_Distinct_Characters.md: -------------------------------------------------------------------------------- 1 | ### 159. Longest Substring with At Most Two Distinct Characters 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度 : Hard 8 | 9 | 10 | 11 | ```python 12 | class Solution(object): 13 | def lengthOfLongestSubstringTwoDistinct(self, s): 14 | """ 15 | :type s: str 16 | :rtype: int 17 | """ 18 | maps = {} 19 | begin, end, counter, length = 0, 0, 0, 0 20 | while end < len(s): 21 | maps[s[end]] = maps.get(s[end], 0) + 1 22 | if maps[s[end]] == 1: 23 | counter += 1 24 |            end += 1   # end 永远指向下一个待处理的字符 25 |            while counter > 2: 26 | maps[s[begin]] -= 1 27 | if maps[s[begin]] == 0: 28 | counter -= 1 29 | begin += 1 30 |            length = max(length, end - begin) # 因此这里是```end - begin```而不是```end - begin + 1``` 31 |        return length 32 | ``` 33 | -------------------------------------------------------------------------------- /docs/leetcode/python/165._compare_version_numbers.md: -------------------------------------------------------------------------------- 1 | ###165. Compare Version Numbers 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 其实我并不觉得这个很简单 13 | 14 | 因为可能两个的位数不一样,首端或者尾端需要补0,同时我还考虑过可能有出现多个'.'的状况 15 | 16 | 17 | 18 | ``` 19 | class Solution(object): 20 | def compareVersion(self, version1, version2): 21 | """ 22 | :type version1: str 23 | :type version2: str 24 | :rtype: int 25 | """ 26 | v1 = version1.split('.') 27 | v2 = version2.split('.') 28 | v1 = [int(x) for x in v1] 29 | v2 = [int(x) for x in v2] 30 | 31 | len1 = len(v1) 32 | len2 = len(v2) 33 | lenMax = max(len1, len2) 34 | for x in range(lenMax): 35 | v1Token = 0 36 | if x < len1: 37 | v1Token = v1[x] 38 | v2Token = 0 39 | if x < len2: 40 | v2Token = v2[x] 41 | if v1Token > v2Token: 42 | return 1 43 | elif v1Token < v2Token: 44 | return -1 45 | return 0 46 | 47 | ``` 48 | -------------------------------------------------------------------------------- /docs/leetcode/python/167._two_sum_ii_-_input_array_is_sorted.md: -------------------------------------------------------------------------------- 1 | ### 167. Two Sum II - Input array is sorted 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Medium 11 | 12 | 13 | 思路: 14 | 15 | 16 | 双指针 17 | 18 | ```python 19 | class Solution(object): 20 | def twoSum(self, numbers, target): 21 | """ 22 | :type numbers: List[int] 23 | :type target: int 24 | :rtype: List[int] 25 | """ 26 | l, r = 0, len(numbers) - 1 27 | while l < r: 28 | if numbers[l] + numbers[r] == target: 29 | return [l+1, r+1] 30 | elif numbers[l] + numbers[r] > target: 31 | r -= 1 32 | else: 33 | l += 1 34 | 35 | ``` 36 | -------------------------------------------------------------------------------- /docs/leetcode/python/168._excel_sheet_column_title.md: -------------------------------------------------------------------------------- 1 | ###168. Excel Sheet Column Title 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 依旧26进制的反击,不过这个反击我做的没之前那个好,看了hint 13 | 14 | ``` 15 | class Solution(object): 16 | def convertToTitle(self, n): 17 | """ 18 | :type n: int 19 | :rtype: str 20 | """ 21 | ans = '' 22 | while n : 23 | ans = chr(ord('A') + (n - 1) % 26) + ans 24 | n = (n - 1) // 26 25 | return ans 26 | 27 | ``` 28 | 29 | -------------------------------------------------------------------------------- /docs/leetcode/python/171._excel_sheet_column_number.md: -------------------------------------------------------------------------------- 1 | ###171. Excel Sheet Column Number 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 26进制的反击 14 | 15 | ``` 16 | class Solution(object): 17 | def titleToNumber(self, s): 18 | """ 19 | :type s: str 20 | :rtype: int 21 | """ 22 | maps = {} 23 | for i in range(65,91): 24 | maps[chr(i)] = i - 64 25 | 26 | lst = list(s) 27 | lst.reverse() 28 | num = 0 29 | for idx,item in enumerate(lst): 30 | num += maps[item] * (26 ** idx) 31 | return num 32 | 33 | ``` 34 | 35 | -------------------------------------------------------------------------------- /docs/leetcode/python/182._duplicate_emails.md: -------------------------------------------------------------------------------- 1 | # 182. duplicate-emails 查找重复的电子邮箱 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/duplicate-emails 10 | * https://leetcode-cn.com/problems/duplicate-emails 11 | 12 | > 内容描述 13 | 14 | ``` 15 | 编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。 16 | 17 | 示例: 18 | +----+---------+ 19 | | Id | Email | 20 | +----+---------+ 21 | | 1 | a@b.com | 22 | | 2 | c@d.com | 23 | | 3 | a@b.com | 24 | +----+---------+ 25 | 26 | 根据以上输入,你的查询应返回以下结果: 27 | +---------+ 28 | | Email | 29 | +---------+ 30 | | a@b.com | 31 | +---------+ 32 | 33 | 说明:所有电子邮箱都是小写字母。 34 | ``` 35 | 36 | ## 解题方案 37 | 38 | > 思路 1 39 | 40 | ```sql 41 | select Email 42 | from Person 43 | group by Email 44 | having count(1)>1 45 | ``` 46 | 或者 47 | ```sql 48 | select Email from Person group by Email having count(Email) > 1 49 | ``` 50 | -------------------------------------------------------------------------------- /docs/leetcode/python/189._rotate_array.md: -------------------------------------------------------------------------------- 1 | ###189. Rotate Array 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度 : Easy 8 | 9 | 首先,要知道一点,```k```如果大于```nums```的长度了,那么其实进行 ```k % len(nums)``` 次就行了 10 | 11 | 其次,要注意```k 为0```的情况 12 | 13 | ```python 14 | class Solution(object): 15 | def rotate(self, nums, k): 16 | """ 17 | :type nums: List[int] 18 | :type k: int 19 | :rtype: void Do not return anything, modify nums in-place instead. 20 | """ 21 | k = k % len(nums) 22 | if k != 0: 23 | tmp = nums[-k:] 24 | for j in range(len(nums)-1, k-1, -1): 25 | nums[j] = nums[j-k] 26 | nums[:k] = tmp 27 | ``` 28 | 29 | 30 | 还有作弊大法,贼🐂批 31 | 32 | ```python 33 | class Solution(object): 34 | def rotate(self, nums, k): 35 | """ 36 | :type nums: List[int] 37 | :type k: int 38 | :rtype: void Do not return anything, modify nums in-place instead. 39 | """ 40 | k %= len(nums) 41 | nums[:] = nums[-k:] + nums[:-k] 42 | ``` 43 | -------------------------------------------------------------------------------- /docs/leetcode/python/191._number_of_1_bits.md: -------------------------------------------------------------------------------- 1 | ### 191. Number of 1 Bits 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 转成二进制,数1的个数 14 | 15 | ```python 16 | class Solution(object): 17 | def hammingWeight(self, n): 18 | """ 19 | :type n: int 20 | :rtype: int 21 | """ 22 | return bin(n).count('1') 23 | ``` 24 | 25 | 26 | 27 | 有wikipedia的题目 [Hamming Weight]((https://zh.wikipedia.org/wiki/汉明重量)) 28 | 29 | 30 | 31 | 用wikipedia的解法: 32 | 33 | 原理是在于每次使用x & x-1 总会把低位的数字给置0 34 | 35 | 比如 3 = 011 2 = 010 3 & 2 = 010 cnt =1 36 | 37 | ​ 2 = 010 1 = 001 2 & 1 = 000 cnt = 2 38 | 39 | 比如 9 = 1001 8 = 1000 9&8 = 1000 cnt =1 40 | 41 | ​ 8 = 1000 7 = 0111 8&7 = 0000 cnt = 2 42 | 43 | > 减1操作将最右边的符号从0变到1,从1变到0,与操作将会移除最右端的1。如果最初X有N个1,那么经过N次这样的迭代运算,X将减到0。下面的算法就是根据这个原理实现的。 44 | 45 | 所以关键点是每次都会把最右边的1变成0. 46 | 47 | 48 | 49 | AC代码 50 | 51 | 52 | 53 | ```python 54 | class Solution(object): 55 | def hammingWeight(self, n): 56 | """ 57 | :type n: int 58 | :rtype: int 59 | """ 60 | cnt = 0 61 | while n != 0: 62 | n &= n - 1 63 | cnt += 1 64 | return cnt 65 | ``` 66 | 67 | -------------------------------------------------------------------------------- /docs/leetcode/python/198._house_robber.md: -------------------------------------------------------------------------------- 1 | 2 | ### 198. House Robber 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | 11 | Easy 12 | 13 | 14 | 状态转移方程: 15 | 16 | dp[i] = max(dp[i-1], dp[i-2] + nums[i]) 17 | 18 | 19 | AC 代码 20 | 21 | ```python 22 | class Solution(object): 23 | def rob(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: int 27 | """ 28 | n = len(nums) 29 | if n == 0 : return 0 30 | elif n == 1 : return nums[0] 31 | elif n == 2 : return max(nums[0], nums[1]) 32 | else: 33 | dp = [0 for i in range(n)] 34 | dp[0] = nums[0] 35 | dp[1] = max(nums[0],nums[1]) 36 | for i in range(2,n): 37 | dp[i] = max( dp[i-1], dp[i-2] + nums[i]) 38 | return dp[n-1] 39 | ``` 40 | 41 | ```python 42 | class Solution(object): 43 | def rob(self, nums): 44 | """ 45 | :type nums: List[int] 46 | :rtype: int 47 | """ 48 | last, now = 0, 0 49 | for i in nums: last, now = now, max(last + i, now) 50 | return now 51 | ``` 52 | 53 | 54 | -------------------------------------------------------------------------------- /docs/leetcode/python/199._binary_tree_right_side_view.md: -------------------------------------------------------------------------------- 1 | ###199. Binary Tree Right Side View 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Medium 11 | 12 | 13 | 还是在玩第102题,level order traversal. 14 | 15 | ``` 16 | class Solution(object): 17 | def rightSideView(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: List[int] 21 | """ 22 | if root == None: return [] 23 | 24 | res = [] 25 | curLevel = [root] 26 | while curLevel: 27 | nextLevel = [] 28 | tmpRes = [] 29 | for node in curLevel: 30 | tmpRes.append(node.val) 31 | if node.left: nextLevel.append(node.left) 32 | if node.right: nextLevel.append(node.right) 33 | res.append(tmpRes[-1]) 34 | curLevel = nextLevel 35 | return res 36 | ``` 37 | 38 | -------------------------------------------------------------------------------- /docs/leetcode/python/203._remove_linked_list_elements.md: -------------------------------------------------------------------------------- 1 | ###203. Remove Linked List Elements 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | AC代码如下: 13 | 14 | 15 | 16 | ``` 17 | class Solution(object): 18 | def removeElements(self, head, val): 19 | """ 20 | :type head: ListNode 21 | :type val: int 22 | :rtype: ListNode 23 | """ 24 | dummy = ListNode(-1) 25 | dummy.next = head 26 | 27 | cur = dummy 28 | 29 | while cur.next: 30 | if cur.next.val == val: 31 | cur.next = cur.next.next 32 | else: 33 | cur = cur.next 34 | 35 | return dummy.next 36 | 37 | 38 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/204._count_primes.md: -------------------------------------------------------------------------------- 1 | ###204. Count Primes 2 | 3 | 4 | 题目: 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 14 | 这个题的hint是已经把算法喂到嘴边了 15 | 16 | 17 | 18 | 19 | ``` 20 | Input: an integer n > 1 21 | 22 | Let A be an array of Boolean values, indexed by integers 2 to n, 23 | initially all set to true. 24 | 25 | for i = 2, 3, 4, ..., not exceeding √n: 26 | if A[i] is true: 27 | for j = i^2, i^2+i, i^2+2*i, i^2+3i, ..., not exceeding n : 28 | A[j] := false 29 | 30 | Output: all i such that A[i] is true. 31 | ``` 32 | 33 | 34 | 35 | python算法 36 | 37 | 38 | ``` 39 | class Solution(object): 40 | def countPrimes(self, n): 41 | """ 42 | :type n: int 43 | :rtype: int 44 | """ 45 | isPrime = [1 for i in range(n)] 46 | 47 | i = 2 48 | while i * i < n: 49 | if isPrime[i]: 50 | j = i * i 51 | while j < n : 52 | isPrime[j] = 0 53 | j += i 54 | i += 1 55 | 56 | return sum(isPrime[2:]) 57 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/205._isomorphic_strings.md: -------------------------------------------------------------------------------- 1 | ###205. Isomorphic Strings 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度 : Easy 8 | 9 | 10 | AC之法,用dictionary,因为限制,所以确保s 和 t 是isomorphic 同时 t 和 s 是 11 | 12 | 13 | ``` 14 | class Solution(object): 15 | def isIsomorphic(self, s, t): 16 | """ 17 | :type s: str 18 | :type t: str 19 | :rtype: bool 20 | """ 21 | return self.iso(s,t) and self.iso(t,s) 22 | 23 | def iso(self,s, t): 24 | """ 25 | :type s: str 26 | :type t: str 27 | :rtype: bool 28 | """ 29 | mapx = {} 30 | for i in range(len(s)): 31 | if s[i] not in mapx: 32 | mapx[s[i]] = t[i] 33 | elif s[i] in mapx: 34 | if t[i] != mapx[s[i]]: 35 | return False 36 | return True 37 | 38 | 39 | ``` 40 | -------------------------------------------------------------------------------- /docs/leetcode/python/216._combination_sum_iii.md: -------------------------------------------------------------------------------- 1 | ###216. Combination Sum III 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Medium 11 | 12 | 继续Combination Sum 系列 13 | 14 | 15 | ``` 16 | class Solution(object): 17 | def combinationSum3(self, k, n): 18 | """ 19 | :type k: int 20 | :type n: int 21 | :rtype: List[List[int]] 22 | """ 23 | candidates = [1,2,3,4,5,6,7,8,9] 24 | self.res = [] 25 | self.combSum(candidates, n, [], k) 26 | return self.res 27 | 28 | 29 | def combSum(self,candidates, target, valueList, k): 30 | if target == 0 and k == 0: 31 | self.res.append(valueList) 32 | length = len(candidates) 33 | if length == 0 or k < 0 : 34 | return 35 | for i in range(length): 36 | if candidates[i] > target: 37 | return 38 | self.combSum(candidates[i+1:], target - candidates[i], valueList + [candidates[i]], k-1) 39 | 40 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/223._rectangle_area.md: -------------------------------------------------------------------------------- 1 | # 223. Rectangle Area 2 | **难度: 中等** 3 | 4 | ## 刷题内容 5 | 6 | > 原题连接 7 | 8 | * https://leetcode.com/problems/rectangle-area 9 | 10 | > 内容描述 11 | 12 | ``` 13 | Find the total area covered by two rectilinear rectangles in a 2D plane. 14 | 15 | Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 16 | 17 | Rectangle Area 18 | 19 | Example: 20 | 21 | Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 22 | Output: 45 23 | Note: 24 | 25 | Assume that the total area is never beyond the maximum possible value of int. 26 | ``` 27 | 28 | ## 解题方案 29 | 30 | > 思路 1 31 | 32 | sb题没什么好说的 33 | 34 | ```python 35 | class Solution(object): 36 | def computeArea(self, A, B, C, D, E, F, G, H): 37 | """ 38 | :type A: int 39 | :type B: int 40 | :type C: int 41 | :type D: int 42 | :type E: int 43 | :type F: int 44 | :type G: int 45 | :type H: int 46 | :rtype: int 47 | """ 48 | return (C - A) * (D - B) + (H - F) * (G - E) - max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0) 49 | ``` 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/leetcode/python/225._implement_stack_using_queues.md: -------------------------------------------------------------------------------- 1 | ###225. Implement Stack using Queues 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 又到了作弊神预言Python的强项 14 | 15 | 16 | ``` 17 | class Stack(object): 18 | def __init__(self): 19 | """ 20 | initialize your data structure here. 21 | """ 22 | self.lst = [] 23 | 24 | 25 | def push(self, x): 26 | """ 27 | :type x: int 28 | :rtype: nothing 29 | """ 30 | self.lst.append(x) 31 | 32 | 33 | def pop(self): 34 | """ 35 | :rtype: nothing 36 | """ 37 | self.lst.remove(self.lst[-1]) 38 | 39 | 40 | def top(self): 41 | """ 42 | :rtype: int 43 | """ 44 | return self.lst[-1] 45 | 46 | def empty(self): 47 | """ 48 | :rtype: bool 49 | """ 50 | return self.lst == [] 51 | 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /docs/leetcode/python/226._invert_binary_tree.md: -------------------------------------------------------------------------------- 1 | ### 226. Invert Binary Tree 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 典型的递归题 12 | 13 | 14 | ```python 15 | class Solution(object): 16 | def invertTree(self, root): 17 | """ 18 | :type root: TreeNode 19 | :rtype: TreeNode 20 | """ 21 | if not root: 22 | return None 23 | self.invertTree(root.left) 24 | self.invertTree(root.right) 25 | root.left, root.right = root.right, root.left 26 | return root 27 | ``` 28 | 29 | -------------------------------------------------------------------------------- /docs/leetcode/python/232._implement_queue_using_stacks.md: -------------------------------------------------------------------------------- 1 | ###232. Implement Queue using Stacks 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | Easy 9 | 10 | 这个题没有乖乖听话,不过因为当年做过用两个stack来模拟queue 11 | 12 | 然后不得不说,我Python大法实在太厉害了 13 | 14 | 这功能强大的,我简直要啧啧啧 15 | 16 | ``` 17 | class Queue(object): 18 | def __init__(self): 19 | """ 20 | initialize your data structure here. 21 | """ 22 | self.lst = [] 23 | 24 | 25 | def push(self, x): 26 | """ 27 | :type x: int 28 | :rtype: nothing 29 | """ 30 | self.lst.append(x) 31 | 32 | 33 | def pop(self): 34 | """ 35 | :rtype: nothing 36 | """ 37 | del self.lst[0] 38 | 39 | def peek(self): 40 | """ 41 | :rtype: int 42 | """ 43 | return self.lst[0] 44 | 45 | 46 | def empty(self): 47 | """ 48 | :rtype: bool 49 | """ 50 | return self.lst == [] 51 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/235._lowest_common_ancestor_of_a_binary_search_tree.md: -------------------------------------------------------------------------------- 1 | ###235. Lowest Common Ancestor of a Binary Search Tree 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度 : Easy 8 | 9 | - 两个node,一个大于root,一个小于root,那么必定root两边,共同的ancestor是root,同时再考虑同为空的状况 10 | - 两个node,都比node小,到左边去寻找,那么先找到那个必定是common ancestor 11 | - 两个node,都比node大,类似.... 12 | 13 | 14 | AC解法 15 | 16 | ``` 17 | class Solution(object): 18 | def lowestCommonAncestor(self, root, p, q): 19 | """ 20 | :type root: TreeNode 21 | :type p: TreeNode 22 | :type q: TreeNode 23 | :rtype: TreeNode 24 | """ 25 | if root == None or root == p or root == q: 26 | return root 27 | elif p.val < root.val < q.val or q.val < root.val < p.val : 28 | return root 29 | elif p.val < root.val and q.val < root.val: 30 | return self.lowestCommonAncestor(root.left,p,q) 31 | else: 32 | return self.lowestCommonAncestor(root.right,p,q) 33 | ``` 34 | -------------------------------------------------------------------------------- /docs/leetcode/python/252._Meeting_Rooms.md: -------------------------------------------------------------------------------- 1 | ### 252. Meeting Rooms 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 10 | 难度 : Easy 11 | 12 | 13 | 14 | 思路: 15 | 16 | 学了一下如何根据attribute 来sort object `intervals.sort(key = lambda interval : interval.start)` 17 | 18 | 19 | 20 | AC 代码 21 | 22 | ``` 23 | # Definition for an interval. 24 | # class Interval(object): 25 | # def __init__(self, s=0, e=0): 26 | # self.start = s 27 | # self.end = e 28 | 29 | class Solution(object): 30 | def canAttendMeetings(self, intervals): 31 | """ 32 | :type intervals: List[Interval] 33 | :rtype: bool 34 | """ 35 | n = len(intervals) 36 | if n < 2 : return True 37 | intervals.sort(key = lambda interval : interval.start) 38 | for i in range(1,n): 39 | if intervals[i].start < intervals[i-1].end: 40 | return False 41 | return True 42 | ``` 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/leetcode/python/256._Paint_House.md: -------------------------------------------------------------------------------- 1 | ### 256. Paint House 2 | 3 | 题目: 4 | 5 | 6 | 难度: 7 | Medium 8 | 9 | 10 | 11 | 其实这个题目有实际意义诶,至少我的故乡?在要申请啥东西的时候就把街上的房子全刷了。 12 | 13 | 然后这个是相邻的房子不同色。 14 | 15 | 16 | 17 | 其实我觉得paint fense更难一点 18 | 19 | 20 | 21 | 思路: 22 | 23 | 数组 dp\[x][3] 代表第x个房子paint r/g/b的值 24 | 25 | 26 | 27 | AC代码 28 | 29 | ``` 30 | class Solution(object): 31 | def minCost(self, costs): 32 | """ 33 | :type costs: List[List[int]] 34 | :rtype: int 35 | """ 36 | m = len(costs) 37 | if m == 0 : return 0 38 | elif m == 1 : return min(costs[0][0], costs[0][1],costs[0][2]) 39 | else: 40 | n = 3 if m else 0 41 | dp = [[0 for i in range(3)] for j in range(m)] 42 | 43 | dp[0] = costs[0] 44 | 45 | 46 | for i in range(1,m): 47 | dp[i][0] = min(dp[i-1][1],dp[i-1][2]) + costs[i][0] 48 | dp[i][1] = min(dp[i-1][0],dp[i-1][2]) + costs[i][1] 49 | dp[i][2] = min(dp[i-1][0],dp[i-1][1]) + costs[i][2] 50 | return min(dp[m-1][0], dp[m-1][1], dp[m-1][2]) 51 | 52 | ``` 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/leetcode/python/258._Add_Digits.md: -------------------------------------------------------------------------------- 1 | ### 258. Add Digits 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 思路 13 | 14 | 这就简单的一p了。。 15 | 16 | 17 | ```python 18 | class Solution(object): 19 | def addDigits(self, num): 20 | """ 21 | :type num: int 22 | :rtype: int 23 | """ 24 | while num / 10 >= 1: 25 | tmp = 0 26 | while num / 10 >= 1: 27 | tmp += num % 10 28 | num /= 10 29 | tmp += num % 10 30 | num = tmp 31 | return num 32 | ``` 33 | 34 | 35 | -------------------------------------------------------------------------------- /docs/leetcode/python/263._ugly_number.md: -------------------------------------------------------------------------------- 1 | ###263. Ugly Number 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Easy 11 | 12 | 13 | 思路: 14 | 15 | 因为其prime factors 只包括 2, 3, 5,所以比如如果能被2 整除, n = n / 2, 直到不能被2整除,然后同样对3,5检验,如果最终结果为1,那么就是ugly number,否则不过关 16 | 17 | 18 | 注意一下边界条件,当num为0的时候,return一下False 19 | 20 | ``` 21 | class Solution(object): 22 | def isUgly(self, num): 23 | """ 24 | :type num: int 25 | :rtype: bool 26 | """ 27 | if num == 0 : return False 28 | while num % 2 == 0: 29 | num = num / 2 30 | while num % 3 == 0: 31 | num = num / 3 32 | while num % 5 == 0: 33 | num = num / 5 34 | if num == 1: 35 | return True 36 | return False 37 | ``` 38 | 39 | -------------------------------------------------------------------------------- /docs/leetcode/python/265._Paint_House_II.md: -------------------------------------------------------------------------------- 1 | ### 265. Paint House II 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 难度: 9 | 10 | Hard 11 | 12 | 13 | 14 | 思路: 15 | 16 | 感觉不像hard 题,知道为啥hard了,因为can you solve it in O(nk) runtime 17 | 18 | 数组 dp\[x][k] 代表第x个房子paint 0..k的值 19 | 20 | 21 | 22 | 用paint house 1 改的AC代码: 23 | 24 | 不过这个时间复杂度是O(nkk)吧 25 | 26 | 27 | 28 | ``` 29 | class Solution(object): 30 | def minCostII(self, costs): 31 | """ 32 | :type costs: List[List[int]] 33 | :rtype: int 34 | """ 35 | n = len(costs) 36 | if n == 0 : return 0 37 | elif n == 1 : return min (costs[0]) 38 | else: 39 | k = len(costs[0]) if n else 0 40 | dp = [[0 for i in range(k)] for j in range(n)] 41 | 42 | dp[0] = costs[0] 43 | 44 | for i in range(1,n): 45 | for j in range(0,k): 46 | minVal = float('inf') 47 | for m in range(0,k): 48 | if m != j and dp[i-1][m] < minVal: 49 | minVal = dp[i-1][m] 50 | dp[i][j] = minVal + costs[i][j] 51 | 52 | return min(dp[-1]) 53 | ``` 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/leetcode/python/266._Palindrome_Permutation.md: -------------------------------------------------------------------------------- 1 | ### 266. Palindrome Permutation 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 难度 : Easy 9 | 10 | 11 | 12 | 思路: 13 | 14 | hint 已经提示的很明显。数单字个数来处理 15 | 16 | 17 | 18 | AC代码 19 | 20 | 21 | 22 | ``` 23 | class Solution(object): 24 | def canPermutePalindrome(self, s): 25 | """ 26 | :type s: str 27 | :rtype: bool 28 | """ 29 | lookup = {} 30 | 31 | for char in s: 32 | lookup[char] = lookup.get(char,0) + 1 33 | 34 | res = 0 35 | 36 | for char, cnt in lookup.items(): 37 | if cnt % 2 == 0 : 38 | continue 39 | else: 40 | res += 1 41 | 42 | return res < 2 43 | ``` 44 | 45 | ​ 46 | 47 | -------------------------------------------------------------------------------- /docs/leetcode/python/268._missing_number.md: -------------------------------------------------------------------------------- 1 | ### 268. Missing Number 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Medium 10 | 11 | 12 | 13 | 等差数列前n项和减去数组之和,一行瞬秒 14 | ```(注意题目input从0开始取值)``` 15 | 16 | 17 | ```python 18 | class Solution(object): 19 | def missingNumber(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: int 23 | """ 24 | return len(nums) * (len(nums) + 1) / 2 - sum(nums) 25 | ``` 26 | 27 | 28 | 29 | 第二种解法是位运算:位运算(异或运算) 30 | 31 | 32 | 33 | ```python 34 | class Solution(object): 35 | def missingNumber(self, nums): 36 | """ 37 | :type nums: List[int] 38 | :rtype: int 39 | """ 40 | res = n = len(nums) 41 | for i in range(n): 42 | res ^= i 43 | res ^= nums[i] 44 | return res 45 | ``` 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /docs/leetcode/python/277._Find_the_Celebrity.md: -------------------------------------------------------------------------------- 1 | ### 277. Find the Celebrity 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 10 | 难度 : Medium 11 | 12 | 13 | 14 | 思路: 15 | 16 | 算法考试考过 17 | 18 | celebrity 是 每个人都知道他,而他不认识任何别的人。 19 | 20 | 21 | 22 | 如果用图来看,那就每个别的人都有箭头指向c,而c没有任何出去的箭头。 23 | 24 | O(N^2)的代码还是还是很容易想到的 25 | 26 | 但是我们可以有提升,那么就是可以check `knows(a,b)`,如果 a knows b,那么可以排除a是celebrity,否则可以排除b是celebrity. 27 | 28 | 最后还要确认一遍是否这个是真的celebrity 29 | 30 | 31 | 32 | AC代码 33 | 34 | ``` 35 | # The knows API is already defined for you. 36 | # @param a, person a 37 | # @param b, person b 38 | # @return a boolean, whether a knows b 39 | # def knows(a, b): 40 | 41 | class Solution(object): 42 | def findCelebrity(self, n): 43 | """ 44 | :type n: int 45 | :rtype: int 46 | """ 47 | if n == 0: 48 | return -1 49 | c = 0 50 | for i in xrange(1,n): 51 | if not knows(i, c): 52 | c = i 53 | for i in range(n): 54 | if c != i: 55 | if not knows(i,c) or knows(c,i): 56 | return -1 57 | return c 58 | 59 | 60 | ``` 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/leetcode/python/278._First_Bad_Version.md: -------------------------------------------------------------------------------- 1 | ### 278. First Bad Version 2 | 3 | 4 | 5 | 6 | 7 | 题目: 8 | 9 | 10 | 11 | 12 | 难度 : Easy 13 | 14 | 15 | 16 | 思路: 17 | 18 | 根据 search for a range 改的 19 | 20 | 21 | 22 | ```python 23 | class Solution(object): 24 | def firstBadVersion(self, n): 25 | """ 26 | :type n: int 27 | :rtype: int 28 | """ 29 | l, r = 0, n - 1 30 | while l <= r: 31 | mid = l + ((r - l) >> 2) 32 | if not isBadVersion(mid): 33 | l = mid + 1 34 | else: 35 | r = mid - 1 36 | return l 37 | ``` 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /docs/leetcode/python/290._word_pattern.md: -------------------------------------------------------------------------------- 1 | ###290. Word Pattern 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度 : Easy 8 | 9 | 4.pattern = "abba", str = "dog dog dog dog" should return false. 10 | 11 | 因为这个的限制,所以中间加了一个loop用来查询是否这个a对应的已经出现过了。 12 | 13 | 不过其实也可以用两个dictionary来处理,可以O(n^3) -> O(n^2) 14 | 15 | 16 | ``` 17 | class Solution(object): 18 | def wordPattern(self, pattern, str): 19 | """ 20 | :type pattern: str 21 | :type str: str 22 | :rtype: bool 23 | """ 24 | strList = str.split(' ') 25 | if len(pattern) != len(strList): 26 | return False 27 | lookup = {} 28 | for i in range(len(strList)): 29 | if pattern[i] not in lookup: 30 | for key in lookup: 31 | if lookup[key] == strList[i]: 32 | return False 33 | lookup[pattern[i]] = strList[i] 34 | elif lookup[pattern[i]] != strList[i]: 35 | return False 36 | 37 | return True 38 | 39 | ``` 40 | 41 | 42 | 另外看到一段非常简短代码,使用了map函数,有待学习 43 | -------------------------------------------------------------------------------- /docs/leetcode/python/292._nim_game.md: -------------------------------------------------------------------------------- 1 | ### 292. Nim Game 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 对于总是优先开始的那方 14 | 15 | 16 | - 有一到三块,总是赢 17 | - 有四块,总是输 18 | - 有五块,总是赢 19 | 20 | 所以如果自己想赢,总是要迫使对方拿之后,给自己遗留5块,或者三块以及以下。 21 | 22 | - 如果是六块: 23 | - 拿一块,对方五块,对方赢 24 | - 拿两块,对方余下四块,我方赢 25 | - 拿三块,余三块,对方赢 26 | 27 | - 七块: 28 | - 拿三块,余四块,迫使对方输,总是赢 29 | 30 | 本打算用递归来看,因为对方也可以重复使用这个函数,但是会超时,所以就看了一下hint 31 | 32 | 33 | - n <= 3 能赢 √ 34 | - n == 4 总输 35 | - n = 5,6,7 总赢 36 | - n == 8, 先手如何选,总可以转成5,6,7 对方总会赢 37 | 38 | 39 | 所以 n % 4 == 0 时候,先手必输 40 | 41 | 简直是啊,有些游戏就是这样来必赢的啊,没想到你是这样的题目 42 | 43 | 44 | 45 | ``` 46 | class Solution(object): 47 | def canWinNim(self, n): 48 | """ 49 | :type n: int 50 | :rtype: bool 51 | """ 52 | return n % 4 != 0 53 | ``` 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/leetcode/python/293._Flip_Game.md: -------------------------------------------------------------------------------- 1 | ### 293. Flip Game 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 思路 13 | 14 | 15 | 16 | 17 | ```python 18 | class Solution(object): 19 | def generatePossibleNextMoves(self, s): 20 | """ 21 | :type s: str 22 | :rtype: List[str] 23 | """ 24 | res = [] 25 | if not s or len(s) <= 1: 26 | return res 27 | for i in range(len(s)-1): 28 | if s[i] == '+' and s[i+1] == '+': 29 | res.append(s[:i]+'--'+s[i+2:]) 30 | return res 31 | ``` 32 | 33 | 这里要注意一个点:s[i+2:] 虽然i+2取不到,但是s[i+2:]就是一个空字符串。 34 | 35 | -------------------------------------------------------------------------------- /docs/leetcode/python/300._longest_increasing_subsequence.md: -------------------------------------------------------------------------------- 1 | ### 300. Longest Increasing Subsequence 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | Medium 9 | 10 | 11 | 思路: 12 | 13 | 典型DP 14 | 15 | 递推关系式: 16 | 17 | 对于以num[i]结束的longest increasing subsequence的长度 18 | 19 | dp[i] = dp[j] + 1 if num[i] > num[j] else 1 20 | 21 | 最后loop一圈,求出最长的 22 | 23 | AC 代码 24 | 25 | ```python 26 | class Solution(object): 27 | def lengthOfLIS(self, nums): 28 | """ 29 | :type nums: List[int] 30 | :rtype: int 31 | """ 32 | if not nums: 33 | return 0 34 | dp = [1 for i in range(len(nums))] 35 | for i in range(1, len(nums)): 36 | for j in range(i): 37 | if nums[i] > nums[j]: 38 | dp[i] = max(dp[j]+1, dp[i]) 39 | return max(dp) 40 | ``` 41 | 42 | -------------------------------------------------------------------------------- /docs/leetcode/python/303._range_sum_query_-_immutable.md: -------------------------------------------------------------------------------- 1 | ###303. Range Sum Query - Immutable 2 | 3 | 题目: 4 | 5 | 6 | 7 | tag : DP 8 | 难度 : Easy 9 | 10 | 11 | 12 | ``` 13 | sum(i, j) = nums[i] j = i 14 | sum(i,j) = sum[i,j-1] + nums[j] j > i 15 | 16 | ``` 17 | 18 | Python代码 19 | 20 | ``` 21 | 22 | class NumArray(object): 23 | def __init__(self, nums): 24 | """ 25 | initialize your data structure here. 26 | :type nums: List[int] 27 | """ 28 | self.sums = nums 29 | for i in range(1, len(self.sums)): 30 | self.sums[i] = self.sums[i-1] + self.sums[i] 31 | 32 | 33 | 34 | 35 | def sumRange(self, i, j): 36 | """ 37 | sum of elements nums[i..j], inclusive. 38 | :type i: int 39 | :type j: int 40 | :rtype: int 41 | """ 42 | if i == 0 : 43 | return self.sums[j] 44 | else : 45 | return self.sums[j] - self.sums[i-1] 46 | 47 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/322._Coin_Change.md: -------------------------------------------------------------------------------- 1 | ### 322. Coin Change 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 难度: 9 | 10 | Medium 11 | 12 | DP入门 13 | 14 | 递推方程式: dp[i] = min(dp[i-vj]+1), vj 是硬币的面额 15 | 16 | 伪码: 17 | 18 | ``` 19 | Set Min[i] equal to Infinity for all of i 20 | Min[0]=0 21 | 22 | For i = 1 to S 23 | For j = 0 to N - 1 24 | If (Vj<=i AND Min[i-Vj]+1 7 | 8 | 9 | 难度: 10 | Medium 11 | 12 | 思路: 13 | 14 | 首先这道题和[Wiggle Sort](https://github.com/Lisanaaa/thinking_in_lc/blob/master/280._Wiggle_Sort.md)要求不一样,不能有等于, 15 | 所以如果碰到一串```‘1,1,1,1,1,1’```,当调换顺序时候还是不会满足。 16 | 17 | 因此我们用新方法,首先将原数组排序,然后大的那一半数字降序插在奇数```index```上,小的那一半数字降序插在偶数```index```上 18 | 19 | 20 | ```python 21 | class Solution(object): 22 | def wiggleSort(self, nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: void Do not return anything, modify nums in-place instead. 26 | """ 27 | nums.sort() 28 | half = len(nums[::2]) 29 | nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1] 30 | ``` 31 | 32 | 33 | ### Follow up 34 | O(n) time, O(1) space 35 | 36 | 思路: 37 | 首先想到的是将我们上面的排序方法用堆排序实现即可,建堆O(n),调整堆O(lgN) 38 | 39 | 40 | ```python 41 | 42 | ``` 43 | -------------------------------------------------------------------------------- /docs/leetcode/python/326._power_of_three.md: -------------------------------------------------------------------------------- 1 | ### 326. Power of Three 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 9 | 难度 : Easy 10 | 11 | 12 | 直接就上的递归 13 | 14 | ```python 15 | class Solution(object): 16 | def isPowerOfThree(self,n): 17 | """ 18 | :type n: int 19 | :rtype: bool 20 | """ 21 | if n <= 0: 22 | return False 23 | if n == 1: 24 | return True 25 | if n % 3 == 0: 26 | return self.isPowerOfThree(n/3) 27 | return False 28 | 29 | ``` 30 | 31 | 有一个follow up,可否不用 loop/recursion 32 | 33 | 看到了取巧的办法,因为是Given an integer,是有范围的(<2147483648),存在能输入的最大的3的幂次,即 3^19=1162261467。 34 | 35 | 只用检查是否能被这个数整除 36 | 37 | 38 | ```python 39 | class Solution(object): 40 | def isPowerOfThree(self, n): 41 | """ 42 | :type n: int 43 | :rtype: bool 44 | """ 45 | return n > 0 and pow(3, 19) % n == 0 46 | 47 | ``` 48 | 49 | -------------------------------------------------------------------------------- /docs/leetcode/python/337._house_robber_iii.md: -------------------------------------------------------------------------------- 1 | ###337. House Robber III 2 | 3 | 4 | 题目: 5 | 6 | 7 | 8 | 难度: 9 | Medium 10 | 11 | 思路: 12 | 13 | 参考 14 | 15 | 16 | 这个解法好像有点厉害 17 | 18 | 从root开始抢起来,最大能抢到的两个可能: 抢root和不抢root 19 | 20 | - rob_root = max(rob_L + rob_R , no_rob_L + no_nob_R + root.val) 21 | - no_rob_root = rob_L + rob_R 22 | 23 | 24 | 这个递归写起来就很厉害了 25 | 26 | 27 | ``` 28 | class Solution(object): 29 | def rob(self, root): 30 | """ 31 | :type root: TreeNode 32 | :rtype: int 33 | """ 34 | def dfs(root): 35 | if not root: return 0, 0 36 | rob_L, no_rob_L = dfs(root.left) 37 | rob_R, no_rob_R = dfs(root.right) 38 | return max(no_rob_R + no_rob_L + root.val , rob_L + rob_R), rob_L + rob_R 39 | 40 | return dfs(root)[0] 41 | 42 | ``` 43 | 44 | 对于每个node,我们return的是从这个node能抢到的最大值,以及不抢它能获得的最大值,这个递归简直我服 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/leetcode/python/338._Counting_Bits.md: -------------------------------------------------------------------------------- 1 | ### 338. Counting Bits 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | Medium 9 | 10 | 11 | 12 | **O(n\*sizeof(integer))** 算法,其实就是把count of 1 bit拿来用: 13 | 14 | ``` 15 | class Solution(object): 16 | def countBits(self, num): 17 | """ 18 | :type num: int 19 | :rtype: List[int] 20 | """ 21 | def hammingWeight(n): 22 | cnt = 0 23 | while n != 0: 24 | n &= n -1 25 | cnt += 1 26 | return cnt 27 | 28 | res = [] 29 | for i in range(num+1): 30 | res.append(hammingWeight(i)) 31 | return res 32 | 33 | ``` 34 | 35 | 36 | 37 | DP算法 - to be done 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /docs/leetcode/python/341._Flatten_Nested_List_Iterator.md: -------------------------------------------------------------------------------- 1 | ### 341. Flatten Nested List Iterator 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 10 | 难度: 11 | Medium 12 | 13 | 14 | 15 | ```python 16 | class NestedIterator(object): 17 | 18 | def __init__(self, nestedList): 19 | """ 20 | Initialize your data structure here. 21 | :type nestedList: List[NestedInteger] 22 | """ 23 | def dfs(nestedList): 24 | for item in nestedList: 25 | if item.isInteger(): 26 | self.stack.append(item.getInteger()) 27 | else: 28 | dfs(item.getList()) 29 | self.stack = [] 30 | dfs(nestedList) 31 | 32 | 33 | def next(self): 34 | """ 35 | :rtype: int 36 | """ 37 | if self.hasNext(): 38 | return self.stack.pop(0) 39 | 40 | 41 | def hasNext(self): 42 | """ 43 | :rtype: bool 44 | """ 45 | return self.stack != [] 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /docs/leetcode/python/342._Power_of_Four.md: -------------------------------------------------------------------------------- 1 | ### 342. Power of Four 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 10 | 难度 : Easy 11 | 12 | 继续照抄power of three 13 | 14 | ```python 15 | class Solution(object): 16 | def isPowerOfFour(self, num): 17 | """ 18 | :type num: int 19 | :rtype: bool 20 | """ 21 | if num <= 0 : 22 | return False 23 | if num == 1: 24 | return True 25 | if num % 4 == 0: 26 | return self.isPowerOfFour(num/4) 27 | return False 28 | 29 | ``` 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /docs/leetcode/python/344._reverse_string.md: -------------------------------------------------------------------------------- 1 | ### 344. Reverse String 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Easy 11 | 12 | 思路: 13 | 14 | 不要脸的python AC code: 15 | 16 | 17 | ```python 18 | class Solution(object): 19 | def reverseString(self, s): 20 | """ 21 | :type s: str 22 | :rtype: str 23 | """ 24 | return s[::-1] 25 | ``` 26 | 27 | 因为python不支持item assignment 28 | 29 | 所以如果非要用two pointer来做的话,那么会是这样 30 | 31 | ```python 32 | class Solution(object): 33 | def reverseString(self, s): 34 | """ 35 | :type s: str 36 | :rtype: str 37 | """ 38 | lst = list(s) 39 | n = len(lst) 40 | start, end = 0, n - 1 41 | 42 | while start < end: 43 | lst[end], lst[start] = lst[start],lst[end] 44 | start += 1 45 | end -= 1 46 | return ''.join(lst) 47 | ``` 48 | -------------------------------------------------------------------------------- /docs/leetcode/python/345._Reverse_Vowels_of_a_String.md: -------------------------------------------------------------------------------- 1 | ### 345. Reverse Vowels of a String 2 | 3 | 4 | 题目: 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 14 | 思路 15 | 16 | 字符串不可变,所以用list代替,最后join 17 | 18 | 19 | 20 | ```python 21 | class Solution(object): 22 | def reverseVowels(self, s): 23 | """ 24 | :type s: str 25 | :rtype: str 26 | """ 27 | vowels = 'aeiou' 28 | string = list(s) 29 | i, j = 0, len(s) -1 30 | while i <= j: 31 | if string[i].lower() not in vowels: 32 | i += 1 33 | elif string[j].lower() not in vowels: 34 | j -= 1 35 | else: 36 | string[i], string[j] = string[j], string[i] 37 | i += 1 38 | j -= 1 39 | return ''.join(string) 40 | ``` 41 | 42 | 正则版本 43 | 44 | ```python 45 | class Solution(object): 46 | def reverseVowels(self, s): 47 | """ 48 | :type s: str 49 | :rtype: str 50 | """ 51 | vowels = re.findall('(?i)[aeiou]', s) 52 | return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s) 53 | ``` 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /docs/leetcode/python/349._intersection_of_two_arrays.md: -------------------------------------------------------------------------------- 1 | ### 349. Intersection of Two Arrays 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 13 | Python一句话作弊 14 | 15 | ```python 16 | class Solution(object): 17 | def intersection(self, nums1, nums2): 18 | """ 19 | :type nums1: List[int] 20 | :type nums2: List[int] 21 | :rtype: List[int] 22 | """ 23 | return list(set(nums1).intersection(nums2)) 24 | ``` 25 | 26 | -------------------------------------------------------------------------------- /docs/leetcode/python/364._Nested_List_Weight_Sum_II.md: -------------------------------------------------------------------------------- 1 | ### 364. Nested List Weight Sum II 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 难度: 9 | Medium 10 | 11 | 思路: 12 | 13 | 14 | 15 | 跟 Nested List Weight Sum I 的区别是这个是从不是数depth,是数层的高度: 16 | 17 | 18 | 19 | 比较naive的AC代码: 20 | 21 | ``` 22 | class Solution(object): 23 | def depthSumInverse(self, nestedList): 24 | """ 25 | :type nestedList: List[NestedInteger] 26 | :rtype: int 27 | """ 28 | def level(nestedList,height): 29 | self.level = max(height, self.level) 30 | for item in nestedList: 31 | if not item.isInteger(): 32 | level(item.getList(), height + 1) 33 | 34 | def dfs(nestedList, height): 35 | for item in nestedList: 36 | if item.isInteger(): 37 | self.res += item.getInteger() * height 38 | else: 39 | dfs(item.getList(),height - 1) 40 | 41 | self.level = 1 42 | self.res = 0 43 | level(nestedList,1) 44 | dfs(nestedList, self.level) 45 | return self.res 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /docs/leetcode/python/367._valid_perfect_square.md: -------------------------------------------------------------------------------- 1 | ###367. Valid Perfect Square 2 | 3 | 题目: 4 | 5 | 6 | 7 | 8 | 难度: 9 | 10 | Medium 11 | 12 | 13 | 直接用循环做也可以AC 14 | 15 | 16 | ``` 17 | class Solution(object): 18 | def isPerfectSquare(self, num): 19 | """ 20 | :type num: int 21 | :rtype: bool 22 | """ 23 | if num == 1 or num == 4 : return True 24 | for i in xrange(num//2): 25 | if i*i == num: 26 | return True 27 | elif i*i > num: 28 | return False 29 | return False 30 | 31 | ``` 32 | 33 | 然后发现有传说中的牛顿法 34 | 35 | 有待阅读,然后还有二分法 36 | 37 | ``` 38 | r = x 39 | while r*r > x: 40 | r = (r + x/r) / 2 41 | return r*r == x 42 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/369._Plus_One_Linked_List.md: -------------------------------------------------------------------------------- 1 | ### 369.Plus One Linked List 2 | 3 | 题目: 4 | 5 | 6 | 难度 : Medium 7 | 8 | 9 | 10 | 类似题目: plus one,plus one 用递归和循环写了,对于linked list,因为most significant digit在首位,递归写起来不方便,用循环尝试,然后代码并没有实质上的区别。 11 | 12 | 13 | 14 | ``` 15 | class Solution(object): 16 | def plusOne(self, head): 17 | """ 18 | :type head: ListNode 19 | :rtype: ListNode 20 | """ 21 | lst = [] 22 | cur = head 23 | 24 | while cur: 25 | lst.append(cur) 26 | cur = cur.next 27 | 28 | carry = 1 29 | for i in range(len(lst)-1,-1,-1): 30 | lst[i].val += carry 31 | if lst[i].val < 10: 32 | carry = 0 33 | break 34 | else: 35 | lst[i].val -= 10 36 | 37 | if carry == 1: 38 | node = ListNode(1) 39 | node.next = head 40 | return node 41 | else: 42 | return head 43 | ``` 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /docs/leetcode/python/374._Guess_Number_Higher_or_Lower.md: -------------------------------------------------------------------------------- 1 | ### 374. Guess Number Higher or Lower 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 思路 13 | 14 | 二分 15 | 16 | ```python 17 | class Solution(object): 18 | def guessNumber(self, n): 19 | """ 20 | :type n: int 21 | :rtype: int 22 | """ 23 | l, r = 1, n 24 | while l <= r: 25 | mid = l + ((r - l) >> 2) 26 | if guess(mid) == 1: 27 | l = mid + 1 28 | elif guess(mid) == -1: 29 | r = mid - 1 30 | else: 31 | return mid 32 | ``` 33 | 34 | 35 | -------------------------------------------------------------------------------- /docs/leetcode/python/387._first_unique_character_in_a_string.md: -------------------------------------------------------------------------------- 1 | ### 387. First Unique Character in a String 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | Easy 9 | 10 | 11 | 12 | 思路一: 13 | 14 | Python作弊法 15 | 16 | 用Python的Counter模块 17 | 18 | 可以参考 19 | 20 | 21 | 22 | 23 | ```python 24 | class Solution(object): 25 | def firstUniqChar(self, s): 26 | """ 27 | :type s: str 28 | :rtype: int 29 | """ 30 | d = collections.Counter(s) 31 | for x,c in enumerate(s): 32 | if d[c] == 1: 33 | return x 34 | return -1 35 | ``` 36 | 37 | 38 | 思路二: 39 | 40 | 利用问题的特性,因为只有可能是小写字母,所以可以用一个长度为26的array, 先数一遍char的数量,然后enumerate从左往右又来 41 | 42 | ```python 43 | class Solution(object): 44 | def firstUniqChar(self, s): 45 | """ 46 | :type s: str 47 | :rtype: int 48 | """ 49 | cnt = [0 for i in range(26)] 50 | for char in s: 51 | cnt[ord(char) - ord('a')] += 1 52 | 53 | for idx, char in enumerate(s): 54 | if cnt[ord(char) - ord('a')] == 1: 55 | return idx 56 | return -1 57 | 58 | ``` 59 | -------------------------------------------------------------------------------- /docs/leetcode/python/389._find_the_difference.md: -------------------------------------------------------------------------------- 1 | 2 | ### 389. Find the Difference 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | 11 | Easy 12 | 13 | 用个字典来记录,把s加进去,把t减掉,最后剩下那个要么个数为1,要么个数为-1 14 | 15 | ```python 16 | class Solution(object): 17 | def findTheDifference(self, s, t): 18 | """ 19 | :type s: str 20 | :type t: str 21 | :rtype: str 22 | """ 23 | res = {} 24 | for i in s: 25 | res[i] = res.get(i, 0) + 1 26 | for j in t: 27 | res[j] = res.get(j, 0) - 1 28 | for key in res: 29 | if abs(res[key]) == 1: # 这里用 abs 是因为新增加的那个字母在 s 中可能未出现过 30 | return key 31 | ``` 32 | 还有一个简单的方法 33 | ```python 34 | class Solution(object): 35 | def findTheDifference(self, s, t): 36 | """ 37 | :type s: str 38 | :type t: str 39 | :rtype: str 40 | """ 41 | from collections import Counter 42 | return list((Counter(t) - Counter(s)).keys()).pop() 43 | ``` 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/leetcode/python/400._Nth_Digit.md: -------------------------------------------------------------------------------- 1 | ### 400. Nth Digit 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 思路: 13 | 14 | 这道简单题我服, tag是math,找规律 15 | 16 | ``` 17 | 1- 9 : 9 → 只占1位 9 18 | 10 - 99: 90 → 两位 90 * 2 19 | 100 - 999: 900 → 三位 900 * 3 20 | 1000 - 9999: 9000 → 四位 9000 * 4 21 | ``` 22 | 23 | 24 | 25 | AC代码来之不易,是参考别人的,这里的`for i in range(9)`, 其实无论`range`多少都可以吧 26 | 27 | 28 | 29 | ``` 30 | class Solution(object): 31 | def findNthDigit(self, n): 32 | """ 33 | :type n: int 34 | :rtype: int 35 | """ 36 | for i in range(9): 37 | d = 9 * 10 ** i 38 | if n <= d * (i+1): break 39 | n -= d *(i+1) 40 | n -= 1 41 | 42 | return int(str(10**i + n / (i+1))[n % (i+1)]) 43 | ``` 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /docs/leetcode/python/404._sum_of_left_leaves.md: -------------------------------------------------------------------------------- 1 | ###404. Sum of Left Leaves 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Easy 11 | 12 | 13 | 思路: 14 | 15 | 16 | 典型递归,检查root的左孩子是不是node,是的话加上它的值,不是的话递归去求它的孩子们的,对于右边,递归的求sum of left leaves 17 | 18 | 19 | 20 | ``` 21 | class Solution(object): 22 | def sumOfLeftLeaves(self, root): 23 | """ 24 | :type root: TreeNode 25 | :rtype: int 26 | """ 27 | def isLeaf(node): 28 | if node == None: 29 | return False 30 | if node.left == None and node.right == None: 31 | return True 32 | return False 33 | 34 | res = 0 35 | 36 | if root: 37 | if isLeaf(root.left): 38 | res += root.left.val 39 | else: 40 | res += self.sumOfLeftLeaves(root.left) 41 | if root.right: 42 | res += self.sumOfLeftLeaves(root.right) 43 | 44 | return res 45 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/414._third_maximum_number.md: -------------------------------------------------------------------------------- 1 | ###414. Third Maximum Number 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 思路: 13 | 14 | 用三个变量来记录,max, secondmax, thirdmax, 15 | 16 | - 遇到比max还大的就更新,当前max降级为secondmax,当前secondmax降级为thirdmax 17 | - 遇到比max小但是比secondmax大的也这样做降级处理 18 | - 更thirdmax 19 | 20 | 21 | AC代码 22 | 23 | 24 | ``` 25 | class Solution(object): 26 | def thirdMax(self, nums): 27 | """ 28 | :type nums: List[int] 29 | :rtype: int 30 | """ 31 | m, sm, tm = float('-inf'), float('-inf'), float('-inf') 32 | 33 | for num in nums: 34 | if num > m: 35 | tm = sm 36 | sm = m 37 | m = num 38 | elif num < m and num > sm: 39 | tm = sm 40 | sm = num 41 | elif num < m and num < sm and num > tm: 42 | tm = num 43 | 44 | return tm if tm != float('-inf') else m 45 | ``` 46 | 47 | -------------------------------------------------------------------------------- /docs/leetcode/python/415._add_strings.md: -------------------------------------------------------------------------------- 1 | # 415. Add Strings 2 | 3 | **难度: Easy** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/add-strings 10 | 11 | > 内容描述 12 | 13 | ``` 14 | 15 | Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. 16 | 17 | Note: 18 | 19 | The length of both num1 and num2 is < 5100. 20 | Both num1 and num2 contains only digits 0-9. 21 | Both num1 and num2 does not contain any leading zero. 22 | You must not use any built-in BigInteger library or convert the inputs to integer directly. 23 | ``` 24 | 25 | ## 解题方案 26 | 27 | > 思路 1 28 | 29 | 题目说不能直接将input转换为int,那我就一次只转换一位,真tm简单! 30 | 31 | ```python 32 | class Solution(object): 33 | def addStrings(self, num1, num2): 34 | """ 35 | :type num1: str 36 | :type num2: str 37 | :rtype: str 38 | """ 39 | def str2int(num): 40 | res = 0 41 | for i in range(len(num)-1, -1, -1): 42 | res += int(num[i]) * pow(10, len(num)-1-i) 43 | return res 44 | return str(str2int(num1) + str2int(num2)) 45 | ``` 46 | -------------------------------------------------------------------------------- /docs/leetcode/python/422._Valid_Word_Square.md: -------------------------------------------------------------------------------- 1 | ### 422. Valid Word Square 2 | 3 | 4 | 5 | 6 | 7 | 题目: 8 | 9 | 10 | 11 | 12 | 难度 : Easy 13 | 14 | 15 | 16 | 思路: 17 | 18 | 就是对比一个矩阵内 xy == yx? 19 | 20 | try /except 真是好用 21 | 22 | AC代码 23 | 24 | 25 | 26 | ``` 27 | class Solution(object): 28 | def validWordSquare(self, words): 29 | """ 30 | :type words: List[str] 31 | :rtype: bool 32 | """ 33 | n = len(words) 34 | for i in xrange(n): 35 | m = len(words[i]) 36 | for j in xrange(m): 37 | try: 38 | if words[i][j] != words[j][i]: 39 | return False 40 | except: 41 | return False 42 | return True 43 | ``` 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/leetcode/python/434._number_of_segments_in_a_string.md: -------------------------------------------------------------------------------- 1 | ### 434. Number of Segments in a String 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 作弊神器Python 13 | 14 | 15 | ```python 16 | class Solution(object): 17 | def countSegments(self, s): 18 | """ 19 | :type s: str 20 | :rtype: int 21 | """ 22 | return len(s.split()) 23 | ``` 24 | 25 | 不过对于比如C++这种语言来说,应该是O(N),扫一圈应该也能得到正确答案 26 | 27 | 总之拿Python做string的题目就是作弊啊 28 | -------------------------------------------------------------------------------- /docs/leetcode/python/437._path_sum_iii.md: -------------------------------------------------------------------------------- 1 | ### 437. Path Sum III 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Easy 11 | 12 | 思路: 13 | 14 | 15 | 16 | 17 | ```python 18 | class Solution(object): 19 | def pathSum(self, root, sum): 20 | """ 21 | :type root: TreeNode 22 | :type sum: int 23 | :rtype: int 24 | """ 25 | if not root: 26 | return 0 27 | res = self.auxPathSum(root, sum) 28 | res += self.pathSum(root.left, sum) 29 | res += self.pathSum(root.right, sum) 30 | return res 31 | def auxPathSum(self, root, sum): 32 | if not root: 33 | return 0 34 | if sum == root.val: 35 |            # 因为可能有负值, 所以sum为0也会有解, 必须加上 36 |            return 1 + self.auxPathSum(root.left, 0) + self.auxPathSum(root.right, 0) 37 | else: 38 | return self.auxPathSum(root.left, sum - root.val) + self.auxPathSum(root.right, sum - root.val) 39 | ``` 40 | -------------------------------------------------------------------------------- /docs/leetcode/python/441._arranging_coins.md: -------------------------------------------------------------------------------- 1 | ###441. Arranging Coins 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | Easy 9 | 10 | 11 | 可以直接O(1),公式: 12 | 13 | i(i+1)/2 = n 14 | 15 | 解i 16 | 17 | i = ( sqrt(8*n+1) -1 )/ 2 18 | 19 | 20 | ``` 21 | import math 22 | class Solution(object): 23 | def arrangeCoins(self, n): 24 | """ 25 | :type n: int 26 | :rtype: int 27 | """ 28 | return int((math.sqrt( 8 * n + 1) - 1 )/ 2 ) 29 | ``` -------------------------------------------------------------------------------- /docs/leetcode/python/448._Find_All_Numbers_Disappeared_in_an_Array.md: -------------------------------------------------------------------------------- 1 | ### 448. Find All Numbers Disappeared in an Array 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 13 | 14 | 15 | ```python 16 | class Solution(object): 17 | def findDisappearedNumbers(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: List[int] 21 | """ 22 | return list(set(range(1, len(nums)+1)) - set(nums)) 23 | ``` 24 | 25 | 26 | -------------------------------------------------------------------------------- /docs/leetcode/python/459._Repeated_Substring_Pattern.md: -------------------------------------------------------------------------------- 1 | ### 459. Repeated Substring Pattern 2 | 3 | 4 | 题目: 5 | 6 | 7 | 8 | 难度: 9 | 10 | Easy 11 | 12 | 13 | 思路 14 | 15 | - 如果存在这样的子串,那么子串的第一个字符和最后一个字符肯定跟父字符串```s```的相同。 16 | - 因此构建一个新字符串```s*2```(两个父字符串相加),去掉首尾字符 17 | - 如果此时能在其中找到```s```,说明存在这样的子串 18 | 19 | 20 | 21 | 22 | ```python 23 | class Solution(object): 24 | def repeatedSubstringPattern(self, s): 25 | """ 26 | :type s: str 27 | :rtype: bool 28 | """ 29 | return (s*2)[1:-1].find(s) != -1 30 | ``` 31 | 32 | -------------------------------------------------------------------------------- /docs/leetcode/python/461._Hamming_Distance.md: -------------------------------------------------------------------------------- 1 | ### 461. Hamming Distance 2 | 3 | 4 | 5 | 题目: 6 | For binary strings *a* and *b* the Hamming distance is equal to the number of ones ([Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight)) in *a* [XOR](https://en.wikipedia.org/wiki/Exclusive_or) *b*. 27 | > 28 | > 29 | 30 | 31 | 32 | 一行无敌 33 | ```python 34 | class Solution(object): 35 | def hammingDistance(self, x, y): 36 | """ 37 | :type x: int 38 | :type y: int 39 | :rtype: int 40 | """ 41 | return bin(x^y).count('1') 42 | ``` 43 | AC代码 44 | 45 | ```python 46 | class Solution(object): 47 | def hammingDistance(self, x, y): 48 | """ 49 | :type x: int 50 | :type y: int 51 | :rtype: int 52 | """ 53 | dist = 0 54 | val = x ^ y 55 | 56 | while val: 57 | dist += 1 58 | val &= val - 1 59 | 60 | return dist 61 | ``` 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /docs/leetcode/python/463._Island_Perimeter.md: -------------------------------------------------------------------------------- 1 | ### 463. Island Perimeter 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Easy 11 | 12 | 思路: 13 | 14 | 15 | 16 | 17 | ```python 18 | class Solution(object): 19 | def islandPerimeter(self, grid): 20 | """ 21 | :type grid: List[List[int]] 22 | :rtype: int 23 | """ 24 | # 每一个陆地单元格的周长为4,当两单元格上下或者左右相邻时,令周长减2 25 | h = len(grid) 26 | w = len(grid[0]) if h else 0 27 | ans = 0 28 | for x in range(h): 29 | for y in range(w): 30 | if grid[x][y] == 1: 31 | ans += 4 32 | # 因为x+1还在后面,所以不需要考虑,即只需要考虑左边和上边,因为循环已经出现过该点了 33 | if x > 0 and grid[x - 1][y]: 34 | ans -= 2 35 | if y > 0 and grid[x][y - 1]: 36 | ans -= 2 37 | return ans 38 | ``` 39 | -------------------------------------------------------------------------------- /docs/leetcode/python/476._Number_Complement.md: -------------------------------------------------------------------------------- 1 | ### 476. Number Complement 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Easy 11 | 12 | 13 | 14 | 15 | 16 | ```python 17 | class Solution(object): 18 | def findComplement(self, num): 19 | """ 20 | :type num: int 21 | :rtype: int 22 | """ 23 | i = 1 << (len(bin(num)) -2) # 因为bin函数转化成的格式是‘0bXXXX’,头两个‘0b’要减掉去 24 | return (i - 1) ^ num 25 | # return (i - 1) - num # 这样也可以 26 | ``` 27 | 28 | 29 | -------------------------------------------------------------------------------- /docs/leetcode/python/485._Max_Consecutive_Ones.md: -------------------------------------------------------------------------------- 1 | ### 485. Max Consecutive Ones 2 | 3 | 4 | 5 | 题目: 6 | 7 | 8 | 9 | 难度: 10 | Easy 11 | 12 | 思路: 13 | 14 | 15 | 一行无敌 16 | ```python 17 | class Solution(object): 18 | def findMaxConsecutiveOnes(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: int 22 | """ 23 | return len(max(''.join(map(str, nums)).split('0'))) 24 | ``` 25 | 26 | ```python 27 | class Solution(object): 28 | def findMaxConsecutiveOnes(self, nums): 29 | """ 30 | :type nums: List[int] 31 | :rtype: int 32 | """ 33 | res, count = [], 0 34 | for x in nums: 35 | count = 0 if x == 0 else count + 1 36 | res.append(count) 37 | return max(res) 38 | ``` 39 | 40 | 41 | -------------------------------------------------------------------------------- /docs/leetcode/python/657._Judge_Route_Circle.md: -------------------------------------------------------------------------------- 1 | ### 657. Judge Route Circle 2 | 题目: 3 | 4 | 5 | 6 | 难度: 7 | 8 | Easy 9 | 10 | 11 | 12 | 13 | ```python 14 | class Solution(object): 15 | def judgeCircle(self, moves): 16 | """ 17 | :type moves: str 18 | :rtype: bool 19 | """ 20 | return moves.count('D') == moves.count('U') and moves.count('R') == moves.count('L') 21 | ``` 22 | 23 | 24 | -------------------------------------------------------------------------------- /docs/leetcode/python/665._Non-decreasing_Array.md: -------------------------------------------------------------------------------- 1 | ### 665. Non-decreasing Array 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 思路 13 | 14 | 从index=1的元素依次检查,只要不符合规则则让count+1,如果count>1则肯定不符合返回False 15 | 但是我们在发现nums[i]小于nums[i-1]的时候,我们就必须要对原数组作出改变了,来让它的后面index部分尽可能满足条件 16 | 下面就是两种情况: 17 | - 2,4,2,6 18 | 19 | 如果是这种情况,当index=2时,不满足条件,但是i=0的元素是小于i=2处元素的,我们需要改变的是i-1处的元素,也就是将4改变成i=2处元素即2,最终变成2,2,2,6 20 | 21 | - 3,4,2,6 22 | 23 | 这种情况如果我们将4变成2那么仍然是不满足条件的,此时我们需要将2变成4,即将i处元素变为i-1处元素 24 | 25 | 在每一次不符合条件的时候我们都检查一下count,如果count大于1的话我们就返回False,否则最终就返回True 26 | 27 | ```python 28 | class Solution(object): 29 | def checkPossibility(self, nums): 30 | """ 31 | :type nums: List[int] 32 | :rtype: bool 33 | """ 34 | count = 0 35 | for i in range(1,len(nums)): 36 | if nums[i] < nums[i-1]: 37 | count += 1 38 | if count > 1: 39 | return False 40 | if i - 2 < 0 or nums[i-2] <= nums[i]: 41 | nums[i-1] = nums[i] 42 | else: 43 | nums[i] = nums[i-1] 44 | return True 45 | ``` 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/leetcode/python/681._Next_Closest_Time.md: -------------------------------------------------------------------------------- 1 | ### 681. Next Closest Time 2 | 3 | 4 | 题目: 5 | 6 | 7 | 8 | 难度: 9 | 10 | Medium 11 | 12 | 13 | 14 | 思路 15 | 16 | 题目说输入一个时间,format是HH:MM, 然后输出接下来最近的一个时间,且这个时间的数字必须要在输入的时间中可以找到,所以我们用```h```, ```m``` 17 | 分别代表输入时间的小时数和分钟数,然后可以计算出输入时间的总分钟数```curr```,在未来的一天之内,我们一分钟一分钟往下面试,第一个满足的就直接 18 | 作为结果就行了. 19 | 20 | 21 | 22 | 23 | ```python 24 | class Solution(object): 25 | def nextClosestTime(self, time): 26 | """ 27 | :type time: str 28 | :rtype: str 29 | """ 30 | h, m = time.split(":") 31 |        curr = int(h) * 60 + int(m) # 这里要注意h可能会是0开头的,如输入的时间为01:22,所以需要int(h)和int(m) 32 |        result = None 33 | for i in xrange(curr+1, curr+1441): 34 | t = i % 1440 35 | h, m = t // 60, t % 60 36 | result = "%02d:%02d" % (h, m) 37 | if set(result) <= set(time): 38 | break 39 | return result 40 | ``` 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /docs/leetcode/python/682._Baseball_Game.md: -------------------------------------------------------------------------------- 1 | ### 682. Baseball Game 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 思路 13 | 14 | points用来存放每一次的分数,最后求和。 15 | 16 | 17 | ```python 18 | class Solution(object): 19 | def calPoints(self, ops): 20 | """ 21 | :type ops: List[str] 22 | :rtype: int 23 | """ 24 | points = [] 25 | for i in ops: 26 | if i == 'C': 27 | points.pop() 28 | elif i == 'D': 29 | points.append(2 * points[-1]) 30 | elif i == '+': 31 | points.append(points[-1] + points[-2]) 32 | else: 33 | points.append(int(i)) 34 | return sum(points) 35 | ``` 36 | 37 | 38 | -------------------------------------------------------------------------------- /docs/leetcode/python/693._Binary_Number_with_Alternating_Bits.md: -------------------------------------------------------------------------------- 1 | # 693. Binary Number with Alternating Bits 交替位二进制数 2 | 3 | **难度: 中等** 4 | 5 | ## 刷题内容 6 | 7 | > 原题连接 8 | 9 | * https://leetcode.com/problems/binary-number-with-alternating-bits 10 | * https://leetcode-cn.com/problems/binary-number-with-alternating-bits 11 | 12 | > 内容描述 13 | 14 | ``` 15 | 给定一个正整数,检查他是否为交替位二进制数:换句话说,就是他的二进制数相邻的两个位数永不相等。 16 | 17 | 示例 1: 18 | 19 | 输入: 5 20 | 输出: True 21 | 解释: 22 | 5的二进制数是: 101 23 | 示例 2: 24 | 25 | 输入: 7 26 | 输出: False 27 | 解释: 28 | 7的二进制数是: 111 29 | 示例 3: 30 | 31 | 输入: 11 32 | 输出: False 33 | 解释: 34 | 11的二进制数是: 1011 35 | 示例 4: 36 | 37 | 输入: 10 38 | 输出: True 39 | 解释: 40 | 10的二进制数是: 1010 41 | ``` 42 | 43 | ## 解题方案 44 | 45 | > 思路 1 46 | 47 | 太简单了,可以一行秒,但是太难看了,还是多写几行吧 48 | 49 | 调用bin函数转换成二进制以后再转换成字符串,注意二进制前面2为是‘0b’,要记得去掉 50 | 51 | ```python 52 | class Solution(object): 53 | def hasAlternatingBits(self, n): 54 | """ 55 | :type n: int 56 | :rtype: bool 57 | """ 58 | tmp = str(bin(n))[2:] 59 | res = [tmp[i] != tmp[i-1] for i in range(1, len(tmp))] 60 | return all(res) 61 | ``` 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/leetcode/python/740._delete_and_earn.md: -------------------------------------------------------------------------------- 1 | ### 740. Delete and Earn 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Medium 10 | 11 | 12 | 13 | 14 | ```python 15 | class Solution(object): 16 | def deleteAndEarn(self, nums): 17 | """ 18 | :type nums: List[int] 19 | :rtype: int 20 | """ 21 | dp = [0] * 10001 22 | for num in nums: 23 | dp[num] += num 24 | for i in range(2, 10001): 25 | dp[i] = max(dp[i]+dp[i-2], dp[i-1]) 26 | return dp[-1] 27 | ``` 28 | 29 | 30 | -------------------------------------------------------------------------------- /docs/leetcode/python/760._Find_Anagram_Mappings.md: -------------------------------------------------------------------------------- 1 | ### 760. Find Anagram Mappings 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 13 | 14 | 15 | ```python 16 | class Solution(object): 17 | def anagramMappings(self, A, B): 18 | """ 19 | :type A: List[int] 20 | :type B: List[int] 21 | :rtype: List[int] 22 | """ 23 | if not A: 24 | return [] 25 | res = [] 26 | for i in A: 27 | res.append(B.index(i)) 28 | return res 29 | ``` 30 | 31 | 32 | -------------------------------------------------------------------------------- /docs/leetcode/python/844._Backspace_String_Compare.md: -------------------------------------------------------------------------------- 1 | ### 844. Backspace String Compare 2 | 3 | 题目: 4 | 5 | 6 | 7 | 难度: 8 | 9 | Easy 10 | 11 | 12 | 思路 13 | 14 | 就看一下两个字符串变化完之后是不是相等就行了, 15 | - 时间复杂度:O(n) 16 | - 空间复杂度:O(n) 17 | 18 | 19 | ```python 20 | class Solution(object): 21 | def backspaceCompare(self, S, T): 22 | """ 23 | :type S: str 24 | :type T: str 25 | :rtype: bool 26 | """ 27 | def afterChange(s): 28 | res = '' 29 | for i in s: 30 | if i == '#': 31 | res = '' if len(res) == 0 else res[:-1] 32 | else: 33 | res += i 34 | return res 35 | return afterChange(S) == afterChange(T) 36 | ``` 37 | 38 | 39 | -------------------------------------------------------------------------------- /docs/leetcode/python/README.md: -------------------------------------------------------------------------------- 1 | # Leetcode Python 题解 2 | 3 | > 看左侧栏,开始你的表演! 4 | -------------------------------------------------------------------------------- /docs/think-dast-zh/SUMMARY.md: -------------------------------------------------------------------------------- 1 | + [数据结构思维中文版](README.md) 2 | + [前言](0.md) 3 | + [第一章 接口](1.md) 4 | + [第二章 算法分析](2.md) 5 | + [第三章 `ArrayList`](3.md) 6 | + [第四章 `LinkedList`](4.md) 7 | + [第五章 双链表](5.md) 8 | + [第六章 树的遍历](6.md) 9 | + [第七章 到达哲学](7.md) 10 | + [第八章 索引器](8.md) 11 | + [第九章 `Map`接口](9.md) 12 | + [第十章 哈希](10.md) 13 | + [第十一章 `HashMap`](11.md) 14 | + [第十二章 `TreeMap`](12.md) 15 | + [第十三章 二叉搜索树](13.md) 16 | + [第十四章 持久化](14.md) 17 | + [第十五章 爬取维基百科](15.md) 18 | + [第十六章 布尔搜索](16.md) 19 | + [第十七章 排序](17.md) -------------------------------------------------------------------------------- /docs/think-dast-zh/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/cover.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/11-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/11-1.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/11-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/11-2.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/12-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/12-1.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/13-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/13-1.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/17-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/17-1.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/17-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/17-2.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/17-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/17-3.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/3-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/3-1.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/4-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/4-1.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/5-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/5-1.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/5-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/5-2.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/5-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/5-3.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/6-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/6-1.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/6-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/6-2.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/6-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/6-3.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/8-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/8-1.jpg -------------------------------------------------------------------------------- /docs/think-dast-zh/img/qr_alipay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/apachecn-algo-zh/ca52c3b386331be95ac1f1313dcf0d484cf89c04/docs/think-dast-zh/img/qr_alipay.png -------------------------------------------------------------------------------- /update.sh: -------------------------------------------------------------------------------- 1 | git add -A 2 | git commit -am "$(date "+%Y-%m-%d %H:%M:%S")" 3 | git push --------------------------------------------------------------------------------