├── .gitignore ├── README.md ├── code ├── 1.Two_Sum │ ├── two-sum.java │ └── two-sum.js ├── 100.Same_Tree │ └── same-tree.java ├── 101.Symmetric_Tree │ └── symmetric-tree.java ├── 102.Binary_Tree_Level_Order_Traversal │ └── binary-tree-level-order-traversal.java ├── 103.Binary_Tree_Zigzag_Level_Order_Traversal │ └── binary-tree-zigzag-level-order-traversal.java ├── 104.Maximum_Depth_of_Binary_Tree │ └── maximum-depth-of-binary-tree.java ├── 107.Binary_Tree_Level_Order_Traversal_II │ └── binary-tree-level-order-traversal-ii.java ├── 108.Convert_Sorted_Array_to_Binary_Search_Tree │ └── convert-sorted-array-to-binary-search-tree.java ├── 109.Convert_Sorted_List_to_Binary_Search_Tree │ └── convert-sorted-list-to-binary-search-tree.java ├── 11.Container_With_Most_Water │ └── container-with-most-water.java ├── 110.Balanced_Binary_Tree │ └── balanced-binary-tree.java ├── 111.Minimum_Depth_of_Binary_Tree │ └── minimum-depth-of-binary-tree.java ├── 112.Path_Sum │ └── path-sum.java ├── 113.Path_Sum_II │ └── path-sum-ii.java ├── 116.Populating_Next_Right_Pointers_in_Each_Node │ └── populating-next-right-pointers-in-each-node.java ├── 118.Pascal's_Triangle │ └── pascals-triangle.java ├── 119.Pascal's_Triangle_II │ └── pascals-triangle-ii.java ├── 121.Best_Time_to_Buy_and_Sell_Stock │ └── best-time-to-buy-and-sell-stock.java ├── 122.Best_Time_to_Buy_and_Sell_Stock_II │ └── best-time-to-buy-and-sell-stock-ii.java ├── 129.Sum_Root_to_Leaf_Numbers │ └── sum-root-to-leaf-numbers.java ├── 133.Clone_Graph │ └── clone-graph.java ├── 135.Candy │ └── candy.java ├── 136.Single_Number │ └── single-number.js ├── 137.Single_Number_II │ └── single-number-ii.java ├── 138.Copy_List_with_Random_Pointer │ └── copy-list-with-random-pointer.java ├── 139.Word_Break │ └── word-break.java ├── 14.Longest_Common_Prefix │ └── longest-common-prefix.java ├── 141.Linked_List_Cycle │ └── linked-list-cycle.java ├── 142.Linked_List_Cycle_II │ └── linked-list-cycle-ii.java ├── 143.Reorder_List │ └── reorder-list.java ├── 144.Binary_Tree_Preorder_Traversal │ └── binary-tree-preorder-traversal.java ├── 15.3Sum │ └── 3sum.java ├── 151.Reverse_Words_in_a_String │ └── reverse-words-in-a-string.java ├── 152.Maximum_Product_Subarray │ └── maximum-product-subarray.java ├── 153.Find_Minimum_in_Rotated_Sorted_Array │ └── find-minimum-in-rotated-sorted-array.java ├── 155.Min_Stack │ └── min-stack.java ├── 160.Intersection_of_Two_Linked_Lists │ └── intersection-of-two-linked-lists.java ├── 162.Find_Peak_Element │ └── find-peak-element.java ├── 165.Compare_Version_Numbers │ └── compare-version-numbers.java ├── 167.Two_Sum_II_-_Input_array_is_sorted │ └── two-sum-ii-input-array-is-sorted.java ├── 169.Majority_Element │ └── majority-element.java ├── 17.Letter_Combinations_of_a_Phone_Number │ └── letter-combinations-of-a-phone-number.java ├── 172.Factorial_Trailing_Zeroes │ └── factorial-trailing-zeroes.java ├── 173.Binary_Search_Tree_Iterator │ └── binary-search-tree-iterator.java ├── 179.Largest_Number │ └── largest-number.java ├── 181.Employees_Earning_More_Than_Their_Managers │ └── employees-earning-more-than-their-managers.sql ├── 183.Customers_Who_Never_Order │ └── customers-who-never-order.sql ├── 187.Repeated_DNA_Sequences │ └── repeated-dna-sequences.java ├── 189.Rotate_Array │ └── rotate-array.java ├── 19.Remove_Nth_Node_From_End_of_List │ └── remove-nth-node-from-end-of-list.java ├── 191.Number_of_1_Bits │ └── number-of-1-bits.java ├── 198.House_Robber │ └── house-robber.java ├── 199.Binary_Tree_Right_Side_View │ └── binary-tree-right-side-view.java ├── 2.Add_Two_Numbers │ └── add-two-numbers.java ├── 20.Valid_Parentheses │ └── valid-parentheses.java ├── 200.Number_of_Islands │ └── number-of-islands.java ├── 202.Happy_Number │ └── happy-number.java ├── 203.Remove_Linked_List_Elements │ └── remove-linked-list-elements.java ├── 205.Isomorphic_Strings │ └── isomorphic-strings.java ├── 206.Reverse_Linked_List │ └── reverse-linked-list.java ├── 207.Course_Schedule │ └── course-schedule.java ├── 209.Minimum_Size_Subarray_Sum │ └── minimum-size-subarray-sum.java ├── 21.Merge_Two_Sorted_Lists │ └── merge-two-sorted-lists.java ├── 215.Kth_Largest_Element_in_an_Array │ └── kth-largest-element-in-an-array.java ├── 217.Contains_Duplicate │ └── missing-number.java ├── 219.Contains_Duplicate_II │ └── contains-duplicate-ii.java ├── 223.Rectangle_Area │ └── rectangle-area.java ├── 225.Implement_Stack_using_Queues │ └── implement-stack-using-queues.java ├── 226.Invert_Binary_Tree │ └── invert-binary-tree.java ├── 230.Kth_Smallest_Element_in_a_BST │ └── kth-smallest-element-in-a-bst.java ├── 231.Power_of_Two │ └── power-of-two.java ├── 232.Implement_Queue_using_Stacks │ └── implement-queue-using-stacks.java ├── 234.Palindrome_Linked_List │ └── palindrome-linked-list.java ├── 237.Delete_Node_in_a_Linked_List │ └── delete-node-in-a-linked-list.java ├── 238.Product_of_Array_Except_Self │ └── product-of-array-except-self.java ├── 24.Swap_Nodes_in_Pairs │ ├── swap-nodes-in-pairs.java │ └── swap-nodes-in-pairs.js ├── 242.Valid_Anagram │ └── valid-anagram.java ├── 257.Binary_Tree_Paths │ └── binary-tree-paths.java ├── 258.Add_Digits │ └── add-digits.java ├── 26.Remove_Duplicates_from_Sorted_Array │ └── remove-duplicates-from-sorted-array.js ├── 260.Single_Number_III │ └── single-number-iii.java ├── 263.Ugly_Number │ └── ugly-number.java ├── 264.Ugly_Number_II │ └── ugly-number-ii.java ├── 268.Missing_Number │ ├── missing-number.java │ └── missing-number.js ├── 27.Remove_Element │ └── remove-element.js ├── 274.H-Index │ └── h-index.java ├── 275.H-Index_II │ └── h-index-ii.java ├── 278.First_Bad_Version │ └── first-bad-version.java ├── 279.Perfect_Squares │ └── perfect-squares.java ├── 28.Implement_strStr() │ └── implement-strstr.js ├── 283.Move_Zeroes │ └── move-zeroes.js ├── 287.Find_the_Duplicate_Number │ └── find-the-duplicate-number.java ├── 290.Word_Pattern │ └── word-pattern.java ├── 292.Nim_Game │ └── nim-game.java ├── 3.Longest_Substring_Without_Repeating_Characters │ └── longest-substring-without-repeating-characters.java ├── 300.Longest_Increasing_Subsequence │ └── longest-increasing-subsequence.java ├── 303.Range_Sum_Query-Immutable │ └── range-sum-query-immutable.java ├── 31.Next_Permutation │ └── next-permutation.java ├── 319.Bulb_Switcher │ └── bulb-switcher.java ├── 32.Longest_Valid_Parentheses │ └── longest-valid-parentheses.java ├── 326.Power_of_Three │ └── power-of-three.java ├── 328.Odd_Even_Linked_List │ └── odd-even-linked-list.java ├── 33.Search_in_Rotated_Sorted_Array │ └── search-in-rotated-sorted-array.java ├── 34.Search_for_a_Range │ └── search-for-a-range.java ├── 342.Power_of_Four │ └── power-of-four.java ├── 343.Integer_Break │ └── integer-break.java ├── 344.Reverse_String │ └── reverse-string.java ├── 345.Reverse_Vowels_of_a_String │ └── reverse-vowels-of-a-string.java ├── 347.Top_K_Frequent_Elements │ └── top-k-frequent-elements.java ├── 349.Intersection_of_Two_Arrays │ └── intersection-of-two-arrays.java ├── 35.Search_Insert_Position │ ├── search-insert-position.java │ └── search-insert-position.js ├── 350.Intersection_of_Two_Arrays_II │ └── intersection-of-two-arrays-ii.java ├── 36.Valid_Sudoku │ └── valid-sudoku.java ├── 367.Valid_Perfect_Square │ └── valid-perfect-square.java ├── 374.Guess_Number_Higher_or_Lower │ └── guess-number-higher-or-lower.java ├── 375.Guess_Number_Higher_or_Lower_II │ └── guess-number-higher-or-lower-ii.java ├── 378.Kth_Smallest_Element_in_a_Sorted_Matrix │ └── kth-smallest-element-in-a-sorted-matrix.java ├── 38.Count_and_Say │ └── count-and-say.java ├── 382.Linked_List_Random_Node │ └── linked-list-random-node.java ├── 383.Ransom_Note │ └── ransom-note.java ├── 384.Shuffle_an_Array │ └── shuffle-an-array.java ├── 387.First_Unique_Character_in_a_String │ └── first-unique-character-in-a-string.java ├── 389.Find_the_Difference │ └── find-the-difference.java ├── 392.Is_Subsequence │ └── is-subsequence.java ├── 398.Random_Pick_Index │ └── random-pick-index.java ├── 400.Nth_Digit │ └── nth-digit.java ├── 404.Sum_of_Left_Leaves │ └── sum-of-left-leaves.java ├── 409.Longest_Palindrome │ └── longest-palindrome.java ├── 412.Fizz_Buzz │ └── fizz-buzz.java ├── 413.Arithmetic_Slices │ └── arithmetic-slices.java ├── 414.Third_Maximum_Number │ └── single-element-in-a-sorted-array.java ├── 415.Add_Strings │ └── add-strings.java ├── 419.Battleships_in_a_Board │ └── battleships-in-a-board.java ├── 429.N-ary_Tree_Level_Order_Traversal │ └── n-ary-tree-level-order-traversal.java ├── 434.Number_of_Segments_in_a_String │ └── number-of-segments-in-a-string.js ├── 438.Find_All_Anagrams_in_a_String │ └── find-all-anagrams-in-a-string.java ├── 441.Arranging_Coins │ └── arranging-coins.js ├── 442.Find_All_Duplicates_in_an_Array │ ├── find-all-duplicates-in-an-array.java │ └── find-all-duplicates-in-an-array.py ├── 443.String_Compression │ └── string-compression.java ├── 448.Find_All_Numbers_Disappeared_in_an_Array │ └── find-all-numbers-disappeared-in-an-array.java ├── 451.Sort_Characters_By_Frequency │ └── sort-characters-by-frequency.java ├── 453.Minimum_Moves_to_Equal_Array_Elements │ └── minimum-moves-to-equal-array-elements.java ├── 455.Assign_Cookies │ └── assign-cookies.java ├── 459.Repeated_Substring_Pattern │ └── repeated-substring-pattern.java ├── 46.Permutations │ └── permutations.java ├── 461.Hamming_Distance │ └── hamming-distance.java ├── 462.Minimum_Moves_to_Equal_Array_Elements_II │ └── minimum-moves-to-equal-array-elements-ii.java ├── 463.Island_Perimeter │ └── island-perimeter.java ├── 476.Number_Complement │ └── number-complement.java ├── 482.License_Key_Formatting │ └── license-key-formatting.java ├── 485.Max_Consecutive_Ones │ └── max-consecutive-ones.java ├── 492.Construct_the_Rectangle │ └── construct-the-rectangle:description.java ├── 495.Teemo_Attacking │ └── teemo-attacking.java ├── 496.Next_Greater_Element_I │ └── next-greater-element-i.java ├── 50.Pow(x,n) │ └── powx-n.java ├── 500.Keyboard_Row │ └── keyboard-row.java ├── 501.Find_Mode_in_Binary_Search_Tree │ └── find-mode-in-binary-search-tree.java ├── 503.Next_Greater_Element_II │ └── next-greater-element-ii.java ├── 506.Relative_Ranks │ └── relative-ranks.java ├── 507.Perfect_Number │ └── perfect-number.java ├── 508.Most_Frequent_Subtree_Sum │ └── most-frequent-subtree-sum.java ├── 513.Find_Bottom_Left_Tree_Value │ └── find-bottom-left-tree-value.java ├── 515.Find_Largest_Value_in_Each_Tree_Row │ └── find-largest-value-in-each-tree-row.java ├── 520.Detect_Capital │ └── detect-capital.js ├── 521.Longest_Uncommon_Subsequence_I │ └── longest-uncommon-subsequence-i.java ├── 525.Contiguous_Array │ └── contiguous-array.java ├── 53.Maximum_Subarray │ └── maximum-subarray.java ├── 530.Minimum_Absolute_Difference_in_BST │ └── minimum-absolute-difference-in-bst.java ├── 532.K-diff_Pairs_in_an_Array │ └── k-diff-pairs-in-an-array.java ├── 537.Complex_Number_Multiplication │ └── complex-number-multiplication.java ├── 538.Convert_BST_to_Greater_Tree │ └── convert-bst-to-greater-tree.java ├── 539.Minimum_Time_Difference │ └── minimum-time-difference.java ├── 54.Spiral_Matrix │ └── spiral-matrix.java ├── 540.Single_Element_in_a_Sorted_Array │ └── single-element-in-a-sorted-array.java ├── 541.Reverse_String_II │ └── reverse-string-ii.java ├── 543.Diameter_of_Binary_Tree │ └── diameter-of-binary-tree.java ├── 547.Friend_Circles │ └── friend-circles.java ├── 551.Student_Attendance_Record_I │ └── student-attendance-record-i.java ├── 553.Optimal_Division │ └── optimal-division.java ├── 554.Brick_Wall │ └── brick-wall.java ├── 557.Reverse_Words_in_a_String_III │ └── reverse-words-in-a-string-iii.java ├── 561.Array_Partition_I │ └── array-partition-i.java ├── 563.Binary_Tree_Tilt │ └── binary-tree-tilt.java ├── 566.Reshape_the_Matrix │ └── reshape-the-matrix.java ├── 572.Subtree_of_Another_Tree │ └── subtree-of-another-tree.java ├── 575.Distribute_Candies │ └── distribute-candies.java ├── 58.Length_of_Last_Word │ └── length-of-last-word.js ├── 581.Shortest_Unsorted_Continuous_Subarray │ └── shortest-unsorted-continuous-subarray.java ├── 589.N-ary_Tree_Preorder_Traversal │ └── n-ary-tree-preorder-traversal.java ├── 590.N-ary_Tree_Postorder_Traversal │ └── n-ary-tree-postorder-traversal.java ├── 594.Longest_Harmonious_Subsequence │ └── longest-harmonious-subsequence.java ├── 595.Big_Countries │ └── big-countries.sql ├── 596.Classes_More_Than_5_Students │ └── classes-more-than-5-students.sql ├── 598.Range_Addition_II │ └── range-addition-ii.java ├── 599.Minimum_Index_Sum_of_Two_Lists │ └── minimum-index-sum-of-two-lists.java ├── 6.ZigZag_Conversion │ └── zigzag-conversion.java ├── 605.Can_Place_Flowers │ └── word-pattern.java ├── 606.Construct_String_from_Binary_Tree │ └── construct-string-from-binary-tree.java ├── 61.Rotate_List │ └── rotate-list.java ├── 617.Merge_Two_Binary_Trees │ └── merge-two-binary-trees.java ├── 62.Unique_Paths │ └── unique-paths.java ├── 620.Not_Boring_Movies │ └── not-boring-movies.sql ├── 623.Add_One_Row_to_Tree │ └── add-one-row-to-tree.java ├── 628.Maximum_Product_of_Three_Numbers │ └── maximum-product-of-three-numbers.java ├── 633.Sum_of_Square_Numbers │ └── sum-of-square-numbers.java ├── 637.Average_of_Levels_in_Binary_Tree │ └── average-of-levels-in-binary-tree.java ├── 643.Maximum_Average_Subarray_I │ └── maximum-average-subarray-i.java ├── 645.Set_Mismatch │ └── set-mismatch.java ├── 646.Maximum_Length_of_Pair_Chain │ └── maximum-length-of-pair-chain.java ├── 647.Palindromic_Substrings │ └── palindromic-substrings.java ├── 653.Two_Sum_IV-Input_is_a_BST │ └── two-sum-iv-input-is-a-bst.java ├── 654.Maximum_Binary_Tree │ └── maximum-binary-tree.java ├── 657.Judge_Route_Circle │ └── judge-route-circle.js ├── 66.Plus_One │ └── plus-one.java ├── 661.Image_Smoother │ └── image-smoother.java ├── 662.Maximum_Width_of_Binary_Tree │ └── maximum-width-of-binary-tree.java ├── 665.Non-decreasing_Array │ └── non-decreasing-array.java ├── 669.Trim_a_Binary_Search_Tree │ └── trim-a-binary-search-tree.java ├── 67.Add_Binary │ └── add-binary.java ├── 671.Second_Minimum_Node_In_a_Binary_Tree │ └── second-minimum-node-in-a-binary-tree.java ├── 672.Bulb_Switcher_II │ └── bulb-switcher-ii.java ├── 674.Longest_Continuous_Increasing_Subsequence │ └── longest-continuous-increasing-subsequence.java ├── 676.Implement_Magic_Dictionary │ └── implement-magic-dictionary.java ├── 677.Map_Sum_Pairs │ └── map-sum-pairs.java ├── 680.Valid_Palindrome_II │ └── valid-palindrome-ii.java ├── 684.Redundant_Connection │ └── redundant-connection.java ├── 686.Repeated_String_Match │ └── repeated-string-match.java ├── 687.Longest_Univalue_Path │ └── longest-univalue-path.java ├── 69.Sqrt(x) │ └── sqrtx.java ├── 690.Employee_Importance │ └── employee-importance.java ├── 693.Binary_Number_with_Alternating_Bits │ └── binary-number-with-alternating-bits.java ├── 695.Max_Area_of_Island │ └── max-area-of-island.java ├── 697.Degree_of_an_Array │ └── degree-of-an-array.java ├── 7.Reverse_Integer │ └── reverse-integer.py ├── 70.Climbing_Stairs │ └── climbing-stairs.java ├── 700.Search_in_a_Binary_Search_Tree │ └── search-in-a-binary-search-tree.java ├── 701.Insert_into_a_Binary_Search_Tree │ └── insert-into-a-binary-search-tree.java ├── 704.Binary_Search │ └── binary-search.java ├── 709.To_Lower_Case │ └── to-lower-case.java ├── 717.1-bit_and_2-bit_Characters │ └── 1-bit-and-2-bit-characters.java ├── 720.Longest_Word_in_Dictionary │ └── longest-word-in-dictionary.java ├── 724.Find_Pivot_Index │ └── find-pivot-index.java ├── 725.Split_Linked_List_in_Parts │ └── split-linked-list-in-parts.java ├── 728.Self_Dividing_Numbers │ └── self-dividing-numbers.java ├── 733.Flood_Fill │ └── flood-fill.java ├── 734.Sentence_Similarity │ └── sentence-similarity.java ├── 739.Daily_Temperatures │ └── daily-temperatures.java ├── 74.Search_a_2D_Matrix │ └── search-a-2d-matrix.java ├── 744.Find_Smallest_Letter_Greater_Than_Target │ └── find-smallest-letter-greater-than-target.java ├── 746.Min_Cost_Climbing_Stairs │ └── min-cost-climbing-stairs.java ├── 747.Largest_Number_At_Least_Twice_of_Others │ └── largest-number-at-least-twice-of-others.java ├── 75.Sort_Colors │ └── sort-colors.java ├── 754.Reach_a_Number │ └── reach-a-number.java ├── 760.Find_Anagram_Mappings │ └── find-anagram-mappings.java ├── 763.Partition_Labels │ └── partition-labels.java ├── 769.Max_Chunks_To_Make_Sorted │ └── max-chunks-to-make-sorted.java ├── 771.Jewels_and_Stones │ └── jewels-and-stones.java ├── 78.Subsets │ └── subsets.java ├── 781.Rabbits_in_Forest │ └── rabbits-in-forest.java ├── 783.Minimum_Distance_Between_BST_Nodes │ └── minimum-distance-between-bst-nodes.java ├── 784.Letter_Case_Permutation │ └── letter-case-permutation.java ├── 788.Rotated_Digits │ └── rotated-digits.java ├── 79.Word_Search │ └── word-search.java ├── 791.Custom_Sort_String │ └── longest-word-in-dictionary.java ├── 796.Rotate_String │ └── rotate-string.java ├── 797.All_Paths_From_Source_to_Target │ └── all-paths-from-source-to-target.java ├── 80.Remove_Duplicates_from_Sorted_Array_II │ └── remove-duplicates-from-sorted-array-ii.java ├── 804.Unique_Morse_Code_Words │ └── unique-morse-code-words.java ├── 807.Max_Increase_to_Keep_City_Skyline │ └── max-increase-to-keep-city-skyline.java ├── 811.Subdomain_Visit_Count │ └── subdomain-visit-count.java ├── 812.Largest_Triangle_Area │ └── largest-triangle-area.java ├── 814.Binary_Tree_Pruning │ └── binary-tree-pruning.java ├── 817.Linked_List_Components │ └── linked-list-components.java ├── 82.Remove_Duplicates_from_Sorted_List_II │ └── remove-duplicates-from-sorted-list-ii.java ├── 821.Shortest_Distance_to_a_Character │ └── shortest-distance-to-a-character.java ├── 83.Remove_Duplicates_from_Sorted_List │ └── remove-duplicates-from-sorted-list.java ├── 840.Magic_Squares_In_Grid │ └── magic-squares-in-grid.java ├── 841.Keys_and_Rooms │ └── keys-and-rooms.java ├── 849.Maximize_Distance_to_Closest_Person │ └── maximize-distance-to-closest-person.java ├── 86.Partition_List │ └── partition-list.java ├── 860.Lemonade_Change │ └── lemonade-change.java ├── 861.Score_After_Flipping_Matrix │ └── score-after-flipping-matrix.java ├── 872.Leaf-Similar_Trees │ └── leaf-similar-trees.java ├── 876.Middle_of_the_Linked_List │ └── middle-of-the-linked-list.java ├── 88.Merge_Sorted_Array │ └── merge-sorted-array.java ├── 9.Palindrome_Number │ └── palindrome-number.java ├── 92.Reverse_Linked_List_II │ └── reverse-linked-list-ii.java ├── 94.Binary_Tree_Inorder_Traversal │ └── binary-tree-inorder-traversal.java ├── 96.Unique_Binary_Search_Trees │ └── unique-binary-search-trees.java ├── 98.Validate_Binary_Search_Tree │ └── validate-binary-search-tree.java ├── README.md └── yuki.config.json ├── notes ├── 1.Two_Sum.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 ├── 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 ├── 11.Container_With_Most_Water.md ├── 110.Balanced_Binary_Tree.md ├── 111.Minimum_Depth_of_Binary_Tree.md ├── 112.Path_Sum.md ├── 113.Path_Sum_II.md ├── 116.Populating_Next_Right_Pointers_in_Each_Node.md ├── 118.Pascal's_Triangle.md ├── 119.Pascal's_Triangle_II.md ├── 121.Best_Time_to_Buy_and_Sell_Stock.md ├── 122.Best_Time_to_Buy_and_Sell_Stock_II.md ├── 129.Sum_Root_to_Leaf_Numbers.md ├── 133.Clone_Graph.md ├── 135.Candy.md ├── 136.Single_Number.md ├── 137.Single_Number_II.md ├── 138.Copy_List_with_Random_Pointer.md ├── 139.Word_Break.md ├── 14.Longest_Common_Prefix.md ├── 141.Linked_List_Cycle.md ├── 142.Linked_List_Cycle_II.md ├── 143.Reorder_List.md ├── 144.Binary_Tree_Preorder_Traversal.md ├── 15.3Sum.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 ├── 160.Intersection_of_Two_Linked_Lists.md ├── 162.Find_Peak_Element.md ├── 165.Compare_Version_Numbers.md ├── 167.Two_Sum_II_-_Input_array_is_sorted.md ├── 169.Majority_Element.md ├── 17.Letter_Combinations_of_a_Phone_Number.md ├── 172.Factorial_Trailing_Zeroes.md ├── 173.Binary_Search_Tree_Iterator.md ├── 179.Largest_Number.md ├── 181.Employees_Earning_More_Than_Their_Managers.md ├── 183.Customers_Who_Never_Order.md ├── 187.Repeated_DNA_Sequences.md ├── 189.Rotate_Array.md ├── 19.Remove_Nth_Node_From_End_of_List.md ├── 191.Number_of_1_Bits.md ├── 198.House_Robber.md ├── 199.Binary_Tree_Right_Side_View.md ├── 2.Add_Two_Numbers.md ├── 20.Valid_Parentheses.md ├── 200.Number_of_Islands.md ├── 202.Happy_Number.md ├── 203.Remove_Linked_List_Elements.md ├── 205.Isomorphic_Strings.md ├── 206.Reverse_Linked_List.md ├── 207.Course_Schedule.md ├── 209.Minimum_Size_Subarray_Sum.md ├── 21.Merge_Two_Sorted_Lists.md ├── 215.Kth_Largest_Element_in_an_Array.md ├── 217.Contains_Duplicate.md ├── 219.Contains_Duplicate_II.md ├── 223.Rectangle_Area.md ├── 225.Implement_Stack_using_Queues.md ├── 226.Invert_Binary_Tree.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 ├── 237.Delete_Node_in_a_Linked_List.md ├── 238.Product_of_Array_Except_Self.md ├── 24.Swap_Nodes_in_Pairs.md ├── 242.Valid_Anagram.md ├── 257.Binary_Tree_Paths.md ├── 258.Add_Digits.md ├── 26.Remove_Duplicates_from_Sorted_Array.md ├── 260.Single_Number_III.md ├── 263.Ugly_Number.md ├── 264.Ugly_Number_II.md ├── 268.Missing_Number.md ├── 27.Remove_Element.md ├── 274.H-Index.md ├── 275.H-Index_II.md ├── 278.First_Bad_Version.md ├── 279.Perfect_Squares.md ├── 28.Implement_strStr().md ├── 283.Move_Zeroes.md ├── 287.Find_the_Duplicate_Number.md ├── 290.Word_Pattern.md ├── 292.Nim_Game.md ├── 3.Longest_Substring_Without_Repeating_Characters.md ├── 300.Longest_Increasing_Subsequence.md ├── 303.Range_Sum_Query-Immutable.md ├── 31.Next_Permutation.md ├── 319.Bulb_Switcher.md ├── 32.Longest_Valid_Parentheses.md ├── 326.Power_of_Three.md ├── 328.Odd_Even_Linked_List.md ├── 33.Search_in_Rotated_Sorted_Array.md ├── 34.Search_for_a_Range.md ├── 342.Power_of_Four.md ├── 343.Integer_Break.md ├── 344.Reverse_String.md ├── 345.Reverse_Vowels_of_a_String.md ├── 347.Top_K_Frequent_Elements.md ├── 349.Intersection_of_Two_Arrays.md ├── 35.Search_Insert_Position.md ├── 350.Intersection_of_Two_Arrays_II.md ├── 36.Valid_Sudoku.md ├── 367.Valid_Perfect_Square.md ├── 374.Guess_Number_Higher_or_Lower.md ├── 375.Guess_Number_Higher_or_Lower_II.md ├── 378.Kth_Smallest_Element_in_a_Sorted_Matrix.md ├── 38.Count_and_Say.md ├── 382.Linked_List_Random_Node.md ├── 383.Ransom_Note.md ├── 384.Shuffle_an_Array.md ├── 387.First_Unique_Character_in_a_String.md ├── 389.Find_the_Difference.md ├── 392.Is_Subsequence.md ├── 398.Random_Pick_Index.md ├── 400.Nth_Digit.md ├── 404.Sum_of_Left_Leaves.md ├── 409.Longest_Palindrome.md ├── 412.Fizz_Buzz.md ├── 413.Arithmetic_Slices.md ├── 414.Third_Maximum_Number.md ├── 415.Add_Strings.md ├── 419.Battleships_in_a_Board.md ├── 429.N-ary_Tree_Level_Order_Traversal.md ├── 434.Number_of_Segments_in_a_String.md ├── 438.Find_All_Anagrams_in_a_String.md ├── 441.Arranging_Coins.md ├── 442.Find_All_Duplicates_in_an_Array.md ├── 443.String_Compression.md ├── 448.Find_All_Numbers_Disappeared_in_an_Array.md ├── 451.Sort_Characters_By_Frequency.md ├── 453.Minimum_Moves_to_Equal_Array_Elements.md ├── 455.Assign_Cookies.md ├── 459.Repeated_Substring_Pattern.md ├── 46.Permutations.md ├── 461.Hamming_Distance.md ├── 462.Minimum_Moves_to_Equal_Array_Elements_II.md ├── 463.Island_Perimeter.md ├── 476.Number_Complement.md ├── 482.License_Key_Formatting.md ├── 485.Max_Consecutive_Ones.md ├── 492.Construct_the_Rectangle.md ├── 495.Teemo_Attacking.md ├── 496.Next_Greater_Element_I.md ├── 50.Pow(x,n).md ├── 500.Keyboard_Row.md ├── 501.Find_Mode_in_Binary_Search_Tree.md ├── 503.Next_Greater_Element_II.md ├── 506.Relative_Ranks.md ├── 507.Perfect_Number.md ├── 508.Most_Frequent_Subtree_Sum.md ├── 513.Find_Bottom_Left_Tree_Value.md ├── 515.Find_Largest_Value_in_Each_Tree_Row.md ├── 520.Detect_Capital.md ├── 521.Longest_Uncommon_Subsequence_I.md ├── 525.Contiguous_Array.md ├── 53.Maximum_Subarray.md ├── 530.Minimum_Absolute_Difference_in_BST.md ├── 532.K-diff_Pairs_in_an_Array.md ├── 537.Complex_Number_Multiplication.md ├── 538.Convert_BST_to_Greater_Tree.md ├── 539.Minimum_Time_Difference.md ├── 54.Spiral_Matrix.md ├── 540.Single_Element_in_a_Sorted_Array.md ├── 541.Reverse_String_II.md ├── 543.Diameter_of_Binary_Tree.md ├── 547.Friend_Circles.md ├── 551.Student_Attendance_Record_I.md ├── 553.Optimal_Division.md ├── 554.Brick_Wall.md ├── 557.Reverse_Words_in_a_String_III.md ├── 561.Array_Partition_I.md ├── 563.Binary_Tree_Tilt.md ├── 566.Reshape_the_Matrix.md ├── 572.Subtree_of_Another_Tree.md ├── 575.Distribute_Candies.md ├── 58.Length_of_Last_Word.md ├── 581.Shortest_Unsorted_Continuous_Subarray.md ├── 589.N-ary_Tree_Preorder_Traversal.md ├── 590.N-ary_Tree_Postorder_Traversal.md ├── 594.Longest_Harmonious_Subsequence.md ├── 595.Big_Countries.md ├── 596.Classes_More_Than_5_Students.md ├── 598.Range_Addition_II.md ├── 599.Minimum_Index_Sum_of_Two_Lists.md ├── 6.ZigZag_Conversion.md ├── 605.Can_Place_Flowers.md ├── 606.Construct_String_from_Binary_Tree.md ├── 61.Rotate_List.md ├── 617.Merge_Two_Binary_Trees.md ├── 62.Unique_Paths.md ├── 620.Not_Boring_Movies.md ├── 623.Add_One_Row_to_Tree.md ├── 628.Maximum_Product_of_Three_Numbers.md ├── 633.Sum_of_Square_Numbers.md ├── 637.Average_of_Levels_in_Binary_Tree.md ├── 643.Maximum_Average_Subarray_I.md ├── 645.Set_Mismatch.md ├── 646.Maximum_Length_of_Pair_Chain.md ├── 647.Palindromic_Substrings.md ├── 653.Two_Sum_IV-Input_is_a_BST.md ├── 654.Maximum_Binary_Tree.md ├── 657.Judge_Route_Circle.md ├── 66.Plus_One.md ├── 661.Image_Smoother.md ├── 662.Maximum_Width_of_Binary_Tree.md ├── 665.Non-decreasing_Array.md ├── 669.Trim_a_Binary_Search_Tree.md ├── 67.Add_Binary.md ├── 671.Second_Minimum_Node_In_a_Binary_Tree.md ├── 672.Bulb_Switcher_II.md ├── 674.Longest_Continuous_Increasing_Subsequence.md ├── 676.Implement_Magic_Dictionary.md ├── 677.Map_Sum_Pairs.md ├── 680.Valid_Palindrome_II.md ├── 684.Redundant_Connection.md ├── 686.Repeated_String_Match.md ├── 687.Longest_Univalue_Path.md ├── 69.Sqrt(x).md ├── 690.Employee_Importance.md ├── 693.Binary_Number_with_Alternating_Bits.md ├── 695.Max_Area_of_Island.md ├── 697.Degree_of_an_Array.md ├── 7.Reverse_Integer.md ├── 70.Climbing_Stairs.md ├── 700.Search_in_a_Binary_Search_Tree.md ├── 701.Insert_into_a_Binary_Search_Tree.md ├── 704.Binary_Search.md ├── 709.To_Lower_Case.md ├── 717.1-bit_and_2-bit_Characters.md ├── 720.Longest_Word_in_Dictionary.md ├── 724.Find_Pivot_Index.md ├── 725.Split_Linked_List_in_Parts.md ├── 728.Self_Dividing_Numbers.md ├── 733.Flood_Fill.md ├── 734.Sentence_Similarity.md ├── 739.Daily_Temperatures.md ├── 74.Search_a_2D_Matrix.md ├── 744.Find_Smallest_Letter_Greater_Than_Target.md ├── 746.Min_Cost_Climbing_Stairs.md ├── 747.Largest_Number_At_Least_Twice_of_Others.md ├── 75.Sort_Colors.md ├── 754.Reach_a_Number.md ├── 760.Find_Anagram_Mappings.md ├── 763.Partition_Labels.md ├── 769.Max_Chunks_To_Make_Sorted.md ├── 771.Jewels_and_Stones.md ├── 78.Subsets.md ├── 781.Rabbits_in_Forest.md ├── 783.Minimum_Distance_Between_BST_Nodes.md ├── 784.Letter_Case_Permutation.md ├── 788.Rotated_Digits.md ├── 79.Word_Search.md ├── 791.Custom_Sort_String.md ├── 796.Rotate_String.md ├── 797.All_Paths_From_Source_to_Target.md ├── 80.Remove_Duplicates_from_Sorted_Array_II.md ├── 804.Unique_Morse_Code_Words.md ├── 807.Max_Increase_to_Keep_City_Skyline.md ├── 811.Subdomain_Visit_Count.md ├── 812.Largest_Triangle_Area.md ├── 814.Binary_Tree_Pruning.md ├── 817.Linked_List_Components.md ├── 82.Remove_Duplicates_from_Sorted_List_II.md ├── 821.Shortest_Distance_to_a_Character.md ├── 83.Remove_Duplicates_from_Sorted_List.md ├── 840.Magic_Squares_In_Grid.md ├── 841.Keys_and_Rooms.md ├── 849.Maximize_Distance_to_Closest_Person.md ├── 86.Partition_List.md ├── 860.Lemonade_Change.md ├── 861.Score_After_Flipping_Matrix.md ├── 872.Leaf-Similar_Trees.md ├── 876.Middle_of_the_Linked_List.md ├── 88.Merge_Sorted_Array.md ├── 9.Palindrome_Number.md ├── 92.Reverse_Linked_List_II.md ├── 94.Binary_Tree_Inorder_Traversal.md ├── 96.Unique_Binary_Search_Trees.md └── 98.Validate_Binary_Search_Tree.md └── yuki.config.json /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | test/unit/coverage 8 | test/e2e/reports 9 | selenium-debug.log 10 | 11 | .coveralls.yml 12 | 13 | # Editor directories and files 14 | .idea 15 | *.suo 16 | *.ntvs* 17 | *.njsproj 18 | *.sln -------------------------------------------------------------------------------- /code/1.Two_Sum/two-sum.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/two-sum/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-26 4 | 5 | class Solution { 6 | public int[] twoSum(int[] nums, int target) { 7 | Map map = new HashMap(); 8 | for(int i = 0; i < nums.length; i++) { 9 | if(map.containsKey(nums[i])) 10 | return new int[]{map.get(nums[i]), i}; 11 | map.put(target-nums[i], i); 12 | } 13 | return new int[]{0, 1}; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /code/1.Two_Sum/two-sum.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/two-sum/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-16 4 | 5 | // 第一思路,非最优解法 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @param {number} target 10 | * @return {number[]} 11 | */ 12 | var twoSum = function(nums, target) { 13 | for(let i = 0; i < nums.length; i++) 14 | for(let j = i + 1; j < nums.length; j++) 15 | if(nums[i] + nums[j] === target) 16 | return [i, j] 17 | }; 18 | -------------------------------------------------------------------------------- /code/100.Same_Tree/same-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/same-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-24 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public boolean isSameTree(TreeNode p, TreeNode q) { 16 | return search(p, q); 17 | } 18 | 19 | private boolean search(TreeNode p, TreeNode q) { 20 | if(p == null && q == null) 21 | return true; 22 | if((p != null && q != null) && p.val == q.val) 23 | return (search(p.left, q.left) && search(p.right, q.right)); 24 | return false; 25 | } 26 | } -------------------------------------------------------------------------------- /code/101.Symmetric_Tree/symmetric-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/symmetric-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-05 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public boolean isSymmetric(TreeNode root) { 16 | if(root == null) 17 | return true; 18 | return isSymmetricHelp(root.left, root.right); 19 | } 20 | 21 | private boolean isSymmetricHelp(TreeNode left, TreeNode right) { 22 | if(left == null && right == null) 23 | return true; 24 | else if(left == null || right == null || left.val != right.val) 25 | return false; 26 | else 27 | return isSymmetricHelp(left.left, right.right) && isSymmetricHelp(left.right, right.left); 28 | } 29 | } -------------------------------------------------------------------------------- /code/104.Maximum_Depth_of_Binary_Tree/maximum-depth-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-14 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public int maxDepth(TreeNode root) { 16 | if(root != null) { 17 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 18 | } 19 | return 0; 20 | } 21 | } -------------------------------------------------------------------------------- /code/11.Container_With_Most_Water/container-with-most-water.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/container-with-most-water/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-26 4 | 5 | class Solution { 6 | public int maxArea(int[] height) { 7 | int left = 0, right = height.length - 1; 8 | int maxArea = 0; 9 | 10 | while (left < right) { 11 | maxArea = Math.max(maxArea, Math.min(height[left], height[right]) 12 | * (right - left)); 13 | if (height[left] < height[right]) 14 | left++; 15 | else 16 | right--; 17 | } 18 | 19 | return maxArea; 20 | } 21 | } -------------------------------------------------------------------------------- /code/110.Balanced_Binary_Tree/balanced-binary-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/balanced-binary-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-12 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public boolean isBalanced(TreeNode root) { 16 | return getBalancedHeight(root) >= 0; 17 | } 18 | 19 | private int getBalancedHeight(TreeNode root) { 20 | if(root == null) 21 | return 0; 22 | int leftBalancedHeight = getBalancedHeight(root.left); 23 | int rightBalancedHeight = getBalancedHeight(root.right); 24 | if(leftBalancedHeight < 0 || rightBalancedHeight < 0 || Math.abs(leftBalancedHeight-rightBalancedHeight) > 1) 25 | return -1; 26 | else 27 | return Math.max(leftBalancedHeight, rightBalancedHeight)+1; 28 | } 29 | } -------------------------------------------------------------------------------- /code/112.Path_Sum/path-sum.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/path-sum/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-16 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public boolean hasPathSum(TreeNode root, int sum) { 16 | if(root == null) 17 | return false; 18 | if(sum - root.val == 0 && root.left == null && root.right == null) 19 | return true; 20 | return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); 21 | } 22 | } -------------------------------------------------------------------------------- /code/116.Populating_Next_Right_Pointers_in_Each_Node/populating-next-right-pointers-in-each-node.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ 2 | // Author : Kyon Huang 3 | // Date : 2018-03-04 4 | 5 | /** 6 | * Definition for binary tree with next pointer. 7 | * public class TreeLinkNode { 8 | * int val; 9 | * TreeLinkNode left, right, next; 10 | * TreeLinkNode(int x) { val = x; } 11 | * } 12 | */ 13 | public class Solution { 14 | public void connect(TreeLinkNode root) { 15 | if(root == null) 16 | return; 17 | if(root.left != null) { 18 | root.left.next = root.right; 19 | for(TreeLinkNode node1 = root.left; node1.right != null; node1 = node1.right) 20 | node1.right.next = node1.next.left; 21 | } 22 | 23 | connect(root.left); 24 | connect(root.right); 25 | } 26 | } -------------------------------------------------------------------------------- /code/121.Best_Time_to_Buy_and_Sell_Stock/best-time-to-buy-and-sell-stock.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-08 4 | 5 | class Solution { 6 | public int maxProfit(int[] prices) { 7 | if(prices.length == 0) 8 | return 0; 9 | int maxPro = 0; 10 | int minPrice = prices[0]; 11 | for(int i = 0; i < prices.length; i++) { 12 | minPrice = Math.min(minPrice, prices[i]); 13 | maxPro = Math.max(maxPro, prices[i] - minPrice); 14 | } 15 | 16 | return maxPro; 17 | } 18 | } -------------------------------------------------------------------------------- /code/122.Best_Time_to_Buy_and_Sell_Stock_II/best-time-to-buy-and-sell-stock-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-27 4 | 5 | // 第一思路,非最佳解法 6 | 7 | class Solution { 8 | public int maxProfit(int[] prices) { 9 | if(prices.length == 0) 10 | return 0; 11 | int sum = 0; 12 | int min = prices[0]; 13 | for(int i = 1; i < prices.length; i++) { 14 | if(prices[i] > min) { 15 | sum += prices[i] - min; 16 | min = prices[i]; 17 | } 18 | else if(prices[i] < min) 19 | min = prices[i]; 20 | } 21 | return sum; 22 | } 23 | } -------------------------------------------------------------------------------- /code/129.Sum_Root_to_Leaf_Numbers/sum-root-to-leaf-numbers.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sum-root-to-leaf-numbers/ 2 | // Author : Kyon Huang 3 | // Date : 2018-03-05 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public int sumNumbers(TreeNode root) { 16 | return helper(root, 0); 17 | } 18 | 19 | private int helper(TreeNode root, int sum) { 20 | if(root == null) 21 | return 0; 22 | if(root.left == null && root.right == null) 23 | return sum * 10 + root.val; 24 | return helper(root.left, sum * 10 + root.val) + helper(root.right, sum * 10 + root.val); 25 | } 26 | } -------------------------------------------------------------------------------- /code/135.Candy/candy.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/candy/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-29 4 | 5 | class Solution { 6 | public int candy(int[] ratings) { 7 | int len = ratings.length; 8 | int[] result = new int[len]; 9 | int sum = 0; 10 | result[0] = 1; 11 | 12 | for(int i = 1; i < len; i++) 13 | if(ratings[i] > ratings[i-1]) 14 | result[i] = result[i-1] + 1; 15 | else 16 | result[i] = 1; 17 | 18 | for(int i = len-1; i > 0; i--) 19 | if(ratings[i] < ratings[i-1]) 20 | result[i-1] = Math.max(result[i] + 1, result[i-1]); 21 | 22 | for(int s : result) 23 | sum += s; 24 | return sum; 25 | } 26 | } -------------------------------------------------------------------------------- /code/136.Single_Number/single-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/single-number/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-28 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var singleNumber = function(nums) { 10 | let result = 0, 11 | len = nums.length; 12 | 13 | for(let i = 0; i < len; i++) { 14 | result ^= nums[i]; 15 | } 16 | 17 | return result; 18 | }; 19 | -------------------------------------------------------------------------------- /code/137.Single_Number_II/single-number-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/single-number-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-03-02 4 | 5 | class Solution { 6 | public int singleNumber(int[] nums) { 7 | int result = 0; 8 | for(int i = 0; i < 32; i++) { 9 | int sum = 0; 10 | for(int num : nums) 11 | if(((num >> i) & 1) == 1) 12 | sum++; 13 | if(sum % 3 != 0) 14 | result |= 1 << i; 15 | } 16 | 17 | return result; 18 | } 19 | } -------------------------------------------------------------------------------- /code/138.Copy_List_with_Random_Pointer/copy-list-with-random-pointer.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/copy-list-with-random-pointer/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-04 4 | 5 | public class Solution { 6 | public RandomListNode copyRandomList(RandomListNode head) { 7 | if(head == null) 8 | return null; 9 | Map nodeMap = new HashMap(); 10 | for(RandomListNode cur = head; cur != null; cur = cur.next) 11 | nodeMap.put(cur, new RandomListNode(cur.label)); 12 | for(RandomListNode cur = head; cur != null; cur = cur.next) { 13 | nodeMap.get(cur).next = nodeMap.get(cur.next); 14 | nodeMap.get(cur).random = nodeMap.get(cur.random); 15 | } 16 | return nodeMap.get(head); 17 | } 18 | } -------------------------------------------------------------------------------- /code/139.Word_Break/word-break.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/word-break/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-05 4 | 5 | class Solution { 6 | 7 | public boolean wordBreak(String s, List wordDict) { 8 | HashSet set = new HashSet(); 9 | set.addAll(wordDict); 10 | 11 | boolean[] dp = new boolean[s.length() + 1]; 12 | dp[0] = true; 13 | for(int i = 1; i <= s.length(); i++) { 14 | for(int j = i-1; j >= 0; j--) { 15 | dp[i] = dp[j] && set.contains(s.substring(j, i)); 16 | if(dp[i]) 17 | break; 18 | } 19 | } 20 | return dp[s.length()]; 21 | } 22 | } -------------------------------------------------------------------------------- /code/14.Longest_Common_Prefix/longest-common-prefix.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-common-prefix/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-27 4 | 5 | public String longestCommonPrefix(String[] strs) { 6 | if (strs.length == 0) 7 | return ""; 8 | String pre = strs[0]; 9 | for (int i = 1; i < strs.length; i++) 10 | while(strs[i].indexOf(pre) != 0) 11 | pre = pre.substring(0, pre.length()-1); 12 | return pre; 13 | } -------------------------------------------------------------------------------- /code/141.Linked_List_Cycle/linked-list-cycle.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/linked-list-cycle/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-16 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { 11 | * val = x; 12 | * next = null; 13 | * } 14 | * } 15 | */ 16 | public class Solution { 17 | public boolean hasCycle(ListNode head) { 18 | if(head != null) { 19 | ListNode walker = head; 20 | ListNode runner = head; 21 | while(runner.next != null && runner.next.next != null) { 22 | walker = walker.next; 23 | runner = runner.next.next; 24 | if(walker == runner) 25 | return true; 26 | } 27 | } 28 | return false; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /code/142.Linked_List_Cycle_II/linked-list-cycle-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/linked-list-cycle-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-03-01 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { 11 | * val = x; 12 | * next = null; 13 | * } 14 | * } 15 | */ 16 | public class Solution { 17 | public ListNode detectCycle(ListNode head) { 18 | ListNode slow = head, fast = head; 19 | while(fast != null && fast.next != null) { 20 | slow = slow.next; 21 | fast = fast.next.next; 22 | if(slow == fast) { 23 | while(head != slow) { 24 | head = head.next; 25 | slow = slow.next; 26 | } 27 | return slow; 28 | } 29 | } 30 | return null; 31 | } 32 | } -------------------------------------------------------------------------------- /code/144.Binary_Tree_Preorder_Traversal/binary-tree-preorder-traversal.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-preorder-traversal/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-21 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public List preorderTraversal(TreeNode root) { 16 | List result = new ArrayList(); 17 | Stack stack = new Stack(); 18 | if(root != null) 19 | stack.push(root); 20 | while(!stack.isEmpty()) { 21 | TreeNode node = stack.pop(); 22 | result.add(node.val); 23 | if(node.right != null) 24 | stack.push(node.right); 25 | if(node.left != null) 26 | stack.push(node.left); 27 | } 28 | return result; 29 | } 30 | } -------------------------------------------------------------------------------- /code/151.Reverse_Words_in_a_String/reverse-words-in-a-string.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-words-in-a-string/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-08 4 | 5 | public class Solution { 6 | public String reverseWords(String s) { 7 | s = s.trim(); 8 | String[] words = s.split(" +"); 9 | StringBuilder sb = new StringBuilder(); 10 | for(int i = 0; i < words.length; i++) { 11 | sb.append(words[words.length-1-i]); 12 | if(i != words.length-1) 13 | sb.append(" "); 14 | } 15 | return sb.toString(); 16 | } 17 | } -------------------------------------------------------------------------------- /code/152.Maximum_Product_Subarray/maximum-product-subarray.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-product-subarray/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-21 4 | 5 | class Solution { 6 | public int maxProduct(int[] nums) { 7 | int len = nums.length; 8 | int Imax = nums[0]; 9 | int Imin = nums[0]; 10 | int max = nums[0]; 11 | 12 | for(int i = 1; i < len; i++) { 13 | if(nums[i] > 0) { 14 | Imax = Math.max(Imax * nums[i], nums[i]); 15 | Imin = Math.min(Imin * nums[i], nums[i]); 16 | } else { 17 | int temp = Imax; 18 | Imax = Math.max(Imin * nums[i], nums[i]); 19 | Imin = Math.min(temp * nums[i], nums[i]); 20 | } 21 | max = Math.max(Imax, max); 22 | } 23 | 24 | return max; 25 | } 26 | } -------------------------------------------------------------------------------- /code/153.Find_Minimum_in_Rotated_Sorted_Array/find-minimum-in-rotated-sorted-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-01 4 | 5 | class Solution { 6 | public int findMin(int[] nums) { 7 | for(int i = 0; i < nums.length-1; i++) 8 | if(nums[i+1] < nums[i]) 9 | return nums[i+1]; 10 | return nums[0]; 11 | } 12 | } -------------------------------------------------------------------------------- /code/155.Min_Stack/min-stack.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/min-stack/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-18 4 | 5 | class MinStack { 6 | long min = Integer.MAX_VALUE; 7 | Stack stack = new Stack<>(); 8 | public MinStack() {} 9 | 10 | public void push(int x) { 11 | stack.push((long)x-min); 12 | min = Math.min(x, min); 13 | } 14 | 15 | public void pop() { 16 | min = Math.max(min - stack.pop(), min); 17 | } 18 | 19 | public int top() { 20 | return (int)Math.max(stack.peek() + min, min); 21 | } 22 | 23 | public int getMin() { 24 | return (int)min; 25 | } 26 | } 27 | 28 | /** 29 | * Your MinStack object will be instantiated and called as such: 30 | * MinStack obj = new MinStack(); 31 | * obj.push(x); 32 | * obj.pop(); 33 | * int param_3 = obj.top(); 34 | * int param_4 = obj.getMin(); 35 | */ -------------------------------------------------------------------------------- /code/162.Find_Peak_Element/find-peak-element.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-peak-element/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-13 4 | 5 | class Solution { 6 | public int findPeakElement(int[] num) { 7 | return helper(num, 0, num.length-1); 8 | } 9 | 10 | public int helper(int[] num, int start, int end){ 11 | if(start == end){ 12 | return start; 13 | } 14 | else if(start+1 == end){ 15 | if(num[start] > num[end]) 16 | return start; 17 | return end; 18 | } 19 | else{ 20 | int m = (end - start) / 2 + start; 21 | if(num[m] > num[m-1] && num[m] > num[m+1]) 22 | return m; 23 | else if(num[m-1] > num[m] && num[m] > num[m+1]) 24 | return helper(num, start, m-1); 25 | else 26 | return helper(num, m+1, end); 27 | 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /code/165.Compare_Version_Numbers/compare-version-numbers.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/compare-version-numbers/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-10 4 | 5 | class Solution { 6 | public int compareVersion(String version1, String version2) { 7 | String[] levels1 = version1.split("\\."); 8 | String[] levels2 = version2.split("\\."); 9 | 10 | int length = Math.max(levels1.length, levels2.length); 11 | for (int i=0; i= 5) { 9 | n /= 5; 10 | result += n; 11 | } 12 | return result; 13 | } 14 | } -------------------------------------------------------------------------------- /code/181.Employees_Earning_More_Than_Their_Managers/employees-earning-more-than-their-managers.sql: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/employees-earning-more-than-their-managers/ 2 | # Author : Kyon Huang 3 | # Date : 2017-10-13 4 | 5 | # Write your MySQL query statement below 6 | SELECT e.Name AS Employee FROM Employee e 7 | WHERE e.ManagerId IS NOT NULL AND e.Salary > (SELECT Salary FROM Employee 8 | WHERE Id = e.ManagerId) -------------------------------------------------------------------------------- /code/183.Customers_Who_Never_Order/customers-who-never-order.sql: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/customers-who-never-order/ 2 | # Author : Kyon Huang 3 | # Date : 2017-10-13 4 | 5 | # Write your MySQL query statement below 6 | SELECT Name AS Customers FROM Customers 7 | WHERE Id NOT IN (SELECT CustomerId FROM Orders) -------------------------------------------------------------------------------- /code/187.Repeated_DNA_Sequences/repeated-dna-sequences.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/repeated-dna-sequences/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-09 4 | 5 | class Solution { 6 | public List findRepeatedDnaSequences(String s) { 7 | HashSet temp = new HashSet(); 8 | HashSet ans = new HashSet(); 9 | for(int i = 0; i < s.length() - 9; i++) { 10 | String sub = s.substring(i, i+10); 11 | if(temp.contains(sub)) 12 | ans.add(sub); 13 | else 14 | temp.add(sub); 15 | } 16 | return new ArrayList(ans); 17 | } 18 | } -------------------------------------------------------------------------------- /code/189.Rotate_Array/rotate-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-array/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-14 4 | 5 | class Solution { 6 | public void rotate(int[] nums, int k) { 7 | k %= nums.length; 8 | reverse(nums, 0, nums.length-1); 9 | reverse(nums, 0, k-1); 10 | reverse(nums, k, nums.length-1); 11 | } 12 | 13 | public void reverse(int[] nums, int start, int end) { 14 | while(start < end) { 15 | int temp = nums[start]; 16 | nums[start] = nums[end]; 17 | nums[end] = temp; 18 | start++; 19 | end--; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /code/191.Number_of_1_Bits/number-of-1-bits.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-1-bits/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-14 4 | 5 | public class Solution { 6 | // you need to treat n as an unsigned value 7 | public int hammingWeight(int n) { 8 | int result = 0; 9 | while(n != 0) { 10 | result += n & 1; 11 | n = n >>> 1; 12 | } 13 | return result; 14 | } 15 | } -------------------------------------------------------------------------------- /code/198.House_Robber/house-robber.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/house-robber/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-18 4 | 5 | // 第一思路,非最佳方案 6 | 7 | class Solution { 8 | public int rob(int[] nums) { 9 | int n = nums.length; 10 | int[] d = new int[n]; 11 | if(n == 0) 12 | return 0; 13 | for(int i = 0; i < n; i++) 14 | fill(d, nums, i); 15 | return d[n-1]; 16 | } 17 | 18 | private void fill(int[] d, int[] nums, int i) { 19 | if(i == 0) 20 | d[i] = nums[0]; 21 | else if(i == 1) 22 | d[i] = Math.max(nums[0], nums[1]); 23 | else 24 | d[i] = Math.max(d[i-2]+nums[i], d[i-1]); 25 | } 26 | } -------------------------------------------------------------------------------- /code/199.Binary_Tree_Right_Side_View/binary-tree-right-side-view.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-right-side-view/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-09 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public List rightSideView(TreeNode root) { 16 | List result = new ArrayList(); 17 | rightView(root, result, 0); 18 | return result; 19 | } 20 | 21 | public void rightView(TreeNode curr, List result, int currDepth){ 22 | if(curr == null) 23 | return; 24 | if(currDepth == result.size()) 25 | result.add(curr.val); 26 | 27 | rightView(curr.right, result, currDepth + 1); 28 | rightView(curr.left, result, currDepth + 1); 29 | } 30 | } -------------------------------------------------------------------------------- /code/200.Number_of_Islands/number-of-islands.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-islands/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-24 4 | 5 | class Solution { 6 | public int numIslands(char[][] grid) { 7 | int num = 0; 8 | for(int i = 0; i < grid.length; i++) 9 | for(int j = 0; j < grid[0].length; j++) 10 | if(grid[i][j] == '1') { 11 | num++; 12 | DFS(grid, i, j); 13 | } 14 | 15 | return num; 16 | } 17 | 18 | private void DFS(char[][] grid, int x, int y) { 19 | if(grid[x][y] == '1') { 20 | grid[x][y] = '0'; 21 | if(x > 0) 22 | DFS(grid, x-1, y); 23 | if(y > 0) 24 | DFS(grid, x, y-1); 25 | if(y < grid[0].length-1) 26 | DFS(grid, x, y+1); 27 | if(x < grid.length-1) 28 | DFS(grid, x+1, y); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /code/202.Happy_Number/happy-number.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/happy-number/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-19 4 | 5 | class Solution { 6 | public boolean isHappy(int n) { 7 | Set inLoop = new HashSet(); 8 | int squareSum, remain; 9 | while (inLoop.add(n)) { 10 | squareSum = 0; 11 | while (n > 0) { 12 | remain = n % 10; 13 | squareSum += remain * remain; 14 | n /= 10; 15 | } 16 | if (squareSum == 1) 17 | return true; 18 | else 19 | n = squareSum; 20 | } 21 | return false; 22 | } 23 | } -------------------------------------------------------------------------------- /code/203.Remove_Linked_List_Elements/remove-linked-list-elements.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-linked-list-elements/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-31 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode removeElements(ListNode head, int val) { 15 | ListNode newHead = new ListNode(0); 16 | newHead.next = head; 17 | head = newHead; 18 | while(head != null && head.next != null) { 19 | while(head.next != null && head.next.val == val) { 20 | head.next = head.next.next; 21 | } 22 | head = head.next; 23 | } 24 | 25 | return newHead.next; 26 | } 27 | } -------------------------------------------------------------------------------- /code/205.Isomorphic_Strings/isomorphic-strings.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/isomorphic-strings/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-17 4 | 5 | class Solution { 6 | public boolean isIsomorphic(String s, String t) { 7 | for(int i = 0; i < s.length(); i++) 8 | if(value(i, s) != value(i, t)) 9 | return false; 10 | return true; 11 | } 12 | 13 | private int value(int pos, String source) { 14 | char c = source.charAt(pos); 15 | int index = source.indexOf(c); 16 | if(index < pos) 17 | return index; 18 | return pos; 19 | } 20 | } -------------------------------------------------------------------------------- /code/206.Reverse_Linked_List/reverse-linked-list.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-26 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode reverseList(ListNode head) { 15 | if(head == null) 16 | return null; 17 | if(head.next == null) 18 | return head; 19 | ListNode first = head; 20 | ListNode second = head.next; 21 | head.next = null; 22 | while(second.next != null) { 23 | ListNode temp = second.next; 24 | second.next = first; 25 | first = second; 26 | second = temp; 27 | } 28 | second.next = first; 29 | return second; 30 | } 31 | } -------------------------------------------------------------------------------- /code/209.Minimum_Size_Subarray_Sum/minimum-size-subarray-sum.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-size-subarray-sum/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-14 4 | 5 | // 非最佳解法 6 | 7 | class Solution { 8 | public int minSubArrayLen(int s, int[] nums) { 9 | if (nums == null || nums.length == 0) 10 | return 0; 11 | 12 | int i = 0, j = 0, sum = 0, res = Integer.MAX_VALUE; 13 | while(i < nums.length) { 14 | sum += nums[i++]; 15 | 16 | while(sum >= s) { 17 | res = Math.min(res, i-j); 18 | sum -= nums[j++]; 19 | } 20 | } 21 | return res == Integer.MAX_VALUE ? 0 : res; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /code/215.Kth_Largest_Element_in_an_Array/kth-largest-element-in-an-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/kth-largest-element-in-an-array/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-27 4 | 5 | // 第一思路,非最佳解法 6 | 7 | class Solution { 8 | public int findKthLargest(int[] nums, int k) { 9 | Arrays.sort(nums); 10 | return nums[nums.length-k]; 11 | } 12 | } -------------------------------------------------------------------------------- /code/217.Contains_Duplicate/missing-number.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-08 4 | 5 | class Solution { 6 | public boolean containsDuplicate(int[] nums) { 7 | 8 | final Set distinct = new HashSet(); 9 | for(int num : nums) { 10 | if(distinct.contains(num)) { 11 | return true; 12 | } 13 | distinct.add(num); 14 | } 15 | return false; 16 | } 17 | } -------------------------------------------------------------------------------- /code/219.Contains_Duplicate_II/contains-duplicate-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-30 4 | 5 | class Solution { 6 | public boolean containsNearbyDuplicate(int[] nums, int k) { 7 | 8 | HashMap map = new HashMap(); 9 | for(int i = 0, len = nums.length; i < len; i++) { 10 | // 以值为 key,以 index 为 value 11 | // 若 key 已存在,计算 index 与 value 的差来判断是否返回 true,并更新 index 12 | if(map.containsKey(nums[i])) { 13 | if(i - map.get(nums[i]) <= k) 14 | return true; 15 | else 16 | map.replace(nums[i], i); 17 | } 18 | // 若 key 不存在,存入 19 | else 20 | map.put(nums[i], i); 21 | } 22 | 23 | return false; 24 | } 25 | } -------------------------------------------------------------------------------- /code/223.Rectangle_Area/rectangle-area.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rectangle-area/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-28 4 | 5 | class Solution { 6 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 7 | return getSingleArea(A, B, C, D) + getSingleArea(E, F, G, H) - getBothArea(A, B, C, D, E, F, G, H); 8 | } 9 | 10 | private int getSingleArea(int A, int B, int C, int D) { 11 | return (C - A) * (D - B); 12 | } 13 | 14 | private int getBothArea(int A, int B, int C, int D, int E, int F, int G, int H) { 15 | int left = Math.max(A, E), right = Math.max(Math.min(C,G), left); 16 | int bottom = Math.max(B, F), top = Math.max(Math.min(D,H), bottom); 17 | return (right - left) * (top - bottom); 18 | } 19 | } -------------------------------------------------------------------------------- /code/226.Invert_Binary_Tree/invert-binary-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/invert-binary-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-29 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public TreeNode invertTree(TreeNode root) { 16 | if(root != null && (root.left != null || root.right != null)) { 17 | TreeNode temp = root.left; 18 | root.left = root.right; 19 | root.right = temp; 20 | if(root.left != null) 21 | invertTree(root.left); 22 | if(root.right != null) 23 | invertTree(root.right); 24 | } 25 | return root; 26 | } 27 | } -------------------------------------------------------------------------------- /code/230.Kth_Smallest_Element_in_a_BST/kth-smallest-element-in-a-bst.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/kth-smallest-element-in-a-bst/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-05 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public int kthSmallest(TreeNode root, int k) { 16 | Stack stack = new Stack(); 17 | while(root != null) { 18 | stack.push(root); 19 | root = root.left; 20 | } 21 | TreeNode node = null; 22 | for(int i = 0; i < k; i++) { 23 | node = stack.pop(); 24 | TreeNode cur = node.right; 25 | while(cur != null) { 26 | stack.push(cur); 27 | cur = cur.left; 28 | } 29 | } 30 | return node.val; 31 | } 32 | } -------------------------------------------------------------------------------- /code/231.Power_of_Two/power-of-two.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-two/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-06 4 | 5 | class Solution { 6 | public boolean isPowerOfTwo(int n) { 7 | return (n > 0) && ((n & (n-1)) == 0); 8 | } 9 | } -------------------------------------------------------------------------------- /code/237.Delete_Node_in_a_Linked_List/delete-node-in-a-linked-list.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/delete-node-in-a-linked-list/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-26 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | class Solution { 14 | public void deleteNode(ListNode node) { 15 | node.val = node.next.val; 16 | node.next = node.next.next; 17 | } 18 | } -------------------------------------------------------------------------------- /code/238.Product_of_Array_Except_Self/product-of-array-except-self.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/product-of-array-except-self/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-13 4 | 5 | class Solution { 6 | public int[] productExceptSelf(int[] nums) { 7 | int[] result = new int[nums.length]; 8 | result[0] = 1; 9 | for(int i = 1; i < nums.length; i++) 10 | result[i] = result[i-1] * nums[i-1]; 11 | int right = 1; 12 | for(int j = nums.length-2; j >= 0; j--) { 13 | right *= nums[j+1]; 14 | result[j] *= right; 15 | } 16 | return result; 17 | } 18 | } -------------------------------------------------------------------------------- /code/24.Swap_Nodes_in_Pairs/swap-nodes-in-pairs.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/swap-nodes-in-pairs/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-22 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @return {ListNode} 15 | */ 16 | var swapPairs = function(head) { 17 | if(!head || !head.next) 18 | return head; 19 | var n = head.next; 20 | head.next = swapPairs(n.next); 21 | n.next = head; 22 | return n; 23 | }; -------------------------------------------------------------------------------- /code/242.Valid_Anagram/valid-anagram.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-anagram/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-27 4 | 5 | class Solution { 6 | public boolean isAnagram(String s, String t) { 7 | int[] arr = new int[26]; 8 | for(char ch : s.toCharArray()) 9 | arr[ch - 'a']++; 10 | for(char ch : t.toCharArray()) 11 | arr[ch - 'a']--; 12 | for(int num : arr) 13 | if(num != 0) 14 | return false; 15 | return true; 16 | } 17 | } -------------------------------------------------------------------------------- /code/258.Add_Digits/add-digits.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-digits/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-10 4 | 5 | class Solution { 6 | public int addDigits(int num) { 7 | if(num == 0) 8 | return 0; 9 | return (num % 9 == 0) ? 9 : num % 9; 10 | } 11 | } -------------------------------------------------------------------------------- /code/26.Remove_Duplicates_from_Sorted_Array/remove-duplicates-from-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-21 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var removeDuplicates = function(nums) { 10 | if(nums.length !== 0) { 11 | let i = 0, 12 | j = 0, 13 | len = nums.length; 14 | 15 | while(j !== len - 1) { 16 | if(nums[i] !== nums[++j]) { 17 | nums[++i] = nums[j]; 18 | } 19 | } 20 | return i+1; 21 | } 22 | return 0; 23 | }; -------------------------------------------------------------------------------- /code/260.Single_Number_III/single-number-iii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/single-number-iii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-09 4 | 5 | class Solution { 6 | public int[] singleNumber(int[] nums) { 7 | int diff = 0; 8 | for(int num : nums) 9 | diff ^= num; 10 | diff &= -diff; 11 | 12 | int i = 0; 13 | int j = 0; 14 | for(int num : nums) 15 | if((num & diff) == 0) 16 | i ^= num; 17 | else 18 | j ^= num; 19 | int[] result = new int[2]; 20 | result[0] = i; 21 | result[1] = j; 22 | return result; 23 | } 24 | } -------------------------------------------------------------------------------- /code/263.Ugly_Number/ugly-number.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ugly-number/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-14 4 | 5 | class Solution { 6 | public boolean isUgly(int num) { 7 | if(num <= 0) 8 | return false; 9 | while(num % 2 == 0) 10 | num /= 2; 11 | while(num % 3 == 0) 12 | num /= 3; 13 | while(num % 5 == 0) 14 | num /= 5; 15 | return (num == 1); 16 | } 17 | } -------------------------------------------------------------------------------- /code/264.Ugly_Number_II/ugly-number-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ugly-number-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-23 4 | 5 | class Solution { 6 | public int nthUglyNumber(int n) { 7 | if(n <= 0) 8 | return 0; 9 | List list = new ArrayList(); 10 | list.add(1); 11 | int a = 0, b = 0, c = 0; 12 | while(list.size() < n) { 13 | int min = Math.min(list.get(a) * 2, Math.min(list.get(b) * 3, list.get(c) * 5)); 14 | list.add(min); 15 | if(min == list.get(a) * 2) 16 | a++; 17 | if(min == list.get(b) * 3) 18 | b++; 19 | if(min == list.get(c) * 5) 20 | c++; 21 | } 22 | return list.get(n-1); 23 | } 24 | } -------------------------------------------------------------------------------- /code/268.Missing_Number/missing-number.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/missing-number/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-08 4 | 5 | // 第一思路,非最佳方案 6 | 7 | class Solution { 8 | public int missingNumber(int[] nums) { 9 | int len = nums.length; 10 | boolean[] arr = new boolean[len+1]; 11 | for(int i = 0; i < len; i++) { 12 | arr[nums[i]] = true; 13 | } 14 | for(int i = 0; i < len+1; i++) { 15 | if(!arr[i]) 16 | return i; 17 | } 18 | return 0; 19 | } 20 | } -------------------------------------------------------------------------------- /code/268.Missing_Number/missing-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/missing-number/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-08 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var missingNumber = function(nums) { 10 | let len = nums.length + 1; 11 | let result; 12 | for(let i = 0; i < len; i++) { 13 | result ^= i; 14 | } 15 | nums.forEach((num) => { 16 | result ^= num; 17 | }); 18 | return result; 19 | }; 20 | -------------------------------------------------------------------------------- /code/27.Remove_Element/remove-element.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-element/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-22 4 | 5 | 6 | /** 7 | * @param {number[]} nums 8 | * @param {number} val 9 | * @return {number} 10 | */ 11 | var removeElement = function(nums, val) { 12 | let i = 0, 13 | j = 0, 14 | len = nums.length; 15 | 16 | while(j !== len) { 17 | if(nums[j] !== val) { 18 | nums[i++] = nums[j]; 19 | } 20 | j++; 21 | } 22 | 23 | return i; 24 | }; -------------------------------------------------------------------------------- /code/274.H-Index/h-index.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/h-index/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-15 4 | 5 | // 第一思路,非最佳方案 6 | 7 | class Solution { 8 | public int hIndex(int[] citations) { 9 | if(citations.length == 0 || citations == null) 10 | return 0; 11 | Arrays.sort(citations); 12 | int len = citations.length; 13 | int i = 0; 14 | while(i < len) { 15 | if(len-i <= citations[i]) 16 | break; 17 | i++; 18 | } 19 | 20 | return len-i; 21 | } 22 | } -------------------------------------------------------------------------------- /code/275.H-Index_II/h-index-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/h-index-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-22 4 | 5 | class Solution { 6 | public int hIndex(int[] citations) { 7 | int len = citations.length; 8 | int lo = 0, hi = len - 1; 9 | while (lo <= hi) { 10 | int mid = (hi + lo) / 2; 11 | if (citations[mid] == len - mid) 12 | return len - mid; 13 | else if (citations[mid] < len - mid) 14 | lo = mid + 1; 15 | else 16 | //(citations[mid] > len-mid), mid qualified as a hIndex, 17 | // but we have to continue to search for a higher one. 18 | hi = mid - 1; 19 | } 20 | return len - lo; 21 | } 22 | } -------------------------------------------------------------------------------- /code/278.First_Bad_Version/first-bad-version.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/first-bad-version/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-09 4 | 5 | /* The isBadVersion API is defined in the parent class VersionControl. 6 | boolean isBadVersion(int version); */ 7 | 8 | public class Solution extends VersionControl { 9 | public int firstBadVersion(int n) { 10 | int first = 1; 11 | int last = n; 12 | while(first <= last) { 13 | int middle = first + (last - first)/2; 14 | boolean middleResult = isBadVersion(middle); 15 | if(!middleResult) 16 | first = middle+1; 17 | else { 18 | if(!isBadVersion(middle-1)) 19 | return middle; 20 | else 21 | last = middle-1; 22 | } 23 | 24 | } 25 | return 1; 26 | } 27 | } -------------------------------------------------------------------------------- /code/279.Perfect_Squares/perfect-squares.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/perfect-squares/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-15 4 | 5 | // 非最佳解法 6 | 7 | class Solution { 8 | public int numSquares(int n) { 9 | List list = new ArrayList(); 10 | for(int i = 1; i * i <= n; i++) 11 | list.add(i * i); 12 | int[] results = new int[n+1]; 13 | results[0] = 0; 14 | for(int i = 1; i <= n; i++) { 15 | int result = i; // 最差的情况是 i 个 1 相加 16 | for(int num : list) { 17 | if(num > i) 18 | break; 19 | result = Math.min(result, results[i - num] + 1); 20 | } 21 | results[i] = result; 22 | } 23 | return results[n]; 24 | } 25 | } -------------------------------------------------------------------------------- /code/28.Implement_strStr()/implement-strstr.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/implement-strstr/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-22 4 | 5 | /** 6 | * @param {string} haystack 7 | * @param {string} needle 8 | * @return {number} 9 | */ 10 | var strStr = function(haystack, needle) { 11 | if(needle === '') return 0; 12 | 13 | let i = 0, j = 0; 14 | 15 | while(j !== haystack.length) { 16 | if(needle[i] === haystack[j]) i++; 17 | else { 18 | j -= i; 19 | i = 0; 20 | } 21 | j++; 22 | if(i === needle.length) return j - i; 23 | } 24 | 25 | return -1; 26 | }; -------------------------------------------------------------------------------- /code/283.Move_Zeroes/move-zeroes.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/move-zeroes/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-29 4 | 5 | // 第一思路,非最优解法 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @return {void} Do not return anything, modify nums in-place instead. 10 | */ 11 | var moveZeroes = function(nums) { 12 | let i = 0, 13 | j = 0; 14 | 15 | while(j !== nums.length - 1) { 16 | while(nums[i] !== 0 && i < nums.length - 1) 17 | i++; 18 | if(i === nums.length - 1) 19 | return; 20 | j = i + 1; 21 | while(nums[j] === 0 && j !== nums.length - 1) 22 | j++; 23 | nums[i] = nums[j]; 24 | nums[j] = 0; 25 | } 26 | }; -------------------------------------------------------------------------------- /code/287.Find_the_Duplicate_Number/find-the-duplicate-number.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-the-duplicate-number/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-22 4 | 5 | class Solution { 6 | public int findDuplicate(int[] nums) { 7 | int slow = 0, fast = 0; 8 | do{ 9 | slow = nums[slow]; 10 | fast = nums[nums[fast]]; 11 | }while(slow != fast); 12 | slow = 0; 13 | while(slow != fast){ 14 | slow = nums[slow]; 15 | fast = nums[fast]; 16 | } 17 | return slow; 18 | } 19 | } -------------------------------------------------------------------------------- /code/290.Word_Pattern/word-pattern.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/word-pattern/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-15 4 | 5 | class Solution { 6 | public boolean wordPattern(String pattern, String str) { 7 | char[] patternArr = pattern.toCharArray(); 8 | String[] strArr = str.split(" "); 9 | if(patternArr.length != strArr.length) 10 | return false; 11 | 12 | Map map = new HashMap(); 13 | for(int i = 0; i < patternArr.length; i++) { 14 | if(!map.containsKey(patternArr[i])) { 15 | if(map.containsValue(strArr[i])) 16 | return false; 17 | else 18 | map.put(patternArr[i], strArr[i]); 19 | } 20 | else 21 | if(!map.get(patternArr[i]).equals(strArr[i])) 22 | return false; 23 | } 24 | return true; 25 | } 26 | } -------------------------------------------------------------------------------- /code/292.Nim_Game/nim-game.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/nim-game/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-03 4 | 5 | class Solution { 6 | public boolean canWinNim(int n) { 7 | return n%4 == 1 || n%4 == 2 || n%4 == 3; 8 | } 9 | } -------------------------------------------------------------------------------- /code/3.Longest_Substring_Without_Repeating_Characters/longest-substring-without-repeating-characters.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-substring-without-repeating-characters/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-20 4 | 5 | class Solution { 6 | public int lengthOfLongestSubstring(String s) { 7 | int maxLength = 0; 8 | Map map = new HashMap(); 9 | for(int i = 0, j = 0; i < s.length(); i++) { 10 | if(map.containsKey(s.charAt(i))) { 11 | j = Math.max(j, map.get(s.charAt(i))+1); 12 | } 13 | map.put(s.charAt(i), i); 14 | maxLength = Math.max(maxLength, i-j+1); 15 | } 16 | return maxLength; 17 | } 18 | } -------------------------------------------------------------------------------- /code/300.Longest_Increasing_Subsequence/longest-increasing-subsequence.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-increasing-subsequence/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-22 4 | 5 | class Solution { 6 | public int lengthOfLIS(int[] nums) { 7 | if(nums == null || nums.length == 0) 8 | return 0; 9 | int[] arr = new int[nums.length+1]; 10 | int ans = 1; 11 | arr[1] = 1; 12 | for(int i = 2; i <= nums.length; i++) { 13 | arr[i] = 1; 14 | for(int j = 1; j < i; j++) 15 | if(nums[i-1] > nums[j-1]) 16 | arr[i] = Math.max(arr[i], arr[j]+1); 17 | ans = Math.max(ans, arr[i]); 18 | } 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /code/303.Range_Sum_Query-Immutable/range-sum-query-immutable.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/range-sum-query-immutable/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-22 4 | 5 | class NumArray { 6 | int[] sums; 7 | 8 | public NumArray(int[] nums) { 9 | sums = new int[nums.length]; 10 | int sum = 0; 11 | for(int i = 0; i < nums.length; i++) { 12 | sum += nums[i]; 13 | sums[i] = sum; 14 | } 15 | } 16 | 17 | public int sumRange(int i, int j) { 18 | return (i > 0) ? sums[j] - sums[i-1] : sums[j] ; 19 | } 20 | } 21 | 22 | /** 23 | * Your NumArray object will be instantiated and called as such: 24 | * NumArray obj = new NumArray(nums); 25 | * int param_1 = obj.sumRange(i,j); 26 | */ -------------------------------------------------------------------------------- /code/31.Next_Permutation/next-permutation.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/next-permutation/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-27 4 | 5 | public class Solution { 6 | public static void nextPermutation(int[] nums) { 7 | int i = nums.length - 2; 8 | while(i >= 0 && nums[i] >= nums[i+1]) 9 | i--; 10 | 11 | if(i >= 0) { 12 | int j = i+1; 13 | while(j < nums.length && nums[i] < nums[j]) 14 | j++; 15 | exchange(nums, i, j-1); 16 | } 17 | 18 | i++; 19 | for(int k = nums.length-1 ; i < k; i++, k--) 20 | exchange(nums, i, k); 21 | } 22 | 23 | private static void exchange(int[] nums, int i, int j) { 24 | int temp = nums[i]; 25 | nums[i] = nums[j]; 26 | nums[j] = temp; 27 | } 28 | } -------------------------------------------------------------------------------- /code/319.Bulb_Switcher/bulb-switcher.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/bulb-switcher/ 2 | // Author : Kyon Huang 3 | // Date : 2018-06-28 4 | 5 | class Solution { 6 | public int bulbSwitch(int n) { 7 | return (int)Math.sqrt(n); 8 | } 9 | } -------------------------------------------------------------------------------- /code/32.Longest_Valid_Parentheses/longest-valid-parentheses.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-valid-parentheses/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-25 4 | 5 | public class Solution { 6 | public int longestValidParentheses(String s) { 7 | Stack stack = new Stack(); 8 | int max = 0; 9 | int left = -1; 10 | for(int j = 0; j < s.length(); j++){ 11 | if(s.charAt(j)=='(') stack.push(j); 12 | else { 13 | if (stack.isEmpty()) left=j; 14 | else { 15 | stack.pop(); 16 | if(stack.isEmpty()) max=Math.max(max,j-left); 17 | else max=Math.max(max,j-stack.peek()); 18 | } 19 | } 20 | } 21 | return max; 22 | } 23 | } -------------------------------------------------------------------------------- /code/326.Power_of_Three/power-of-three.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-three/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-11 4 | 5 | class Solution { 6 | public boolean isPowerOfThree(int n) { 7 | int Max3PowerInt = 1162261467; // 3^19, 3^20 = 3486784401 > MaxInt32 8 | int MaxInt32 = 2147483647; // 2^31 - 1 9 | if (n <= 0 || n > Max3PowerInt) return false; 10 | return Max3PowerInt % n == 0; 11 | } 12 | } -------------------------------------------------------------------------------- /code/328.Odd_Even_Linked_List/odd-even-linked-list.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/odd-even-linked-list/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-04 4 | 5 | class Solution { 6 | public ListNode oddEvenList(ListNode head) { 7 | if(head == null) 8 | return null; 9 | ListNode evenHead = head.next; 10 | ListNode odd = head; 11 | ListNode even = evenHead; 12 | while(even != null && odd != null) { 13 | odd.next = even.next; 14 | if(odd.next == null) 15 | break; 16 | odd = odd.next; 17 | even.next = odd.next; 18 | even = even.next; 19 | } 20 | odd.next = evenHead; 21 | return head; 22 | } 23 | } -------------------------------------------------------------------------------- /code/34.Search_for_a_Range/search-for-a-range.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-for-a-range/ 2 | // Author : Kyon Huang 3 | // Date : 2018-03-08 4 | 5 | class Solution { 6 | public int[] searchRange(int[] nums, int target) { 7 | int start = binaryFind(nums, target); 8 | int[] result = new int[]{-1, -1}; 9 | if(start == nums.length || nums[start] != target) 10 | return result; 11 | 12 | int end = binaryFind(nums, target+1)-1; 13 | result[0] = start; 14 | result[1] = end; 15 | return result; 16 | } 17 | 18 | private int binaryFind(int[] nums, int target) { 19 | int start = 0; 20 | int end = nums.length; 21 | while(start < end) { 22 | int middle = (end - start) / 2 + start; 23 | if(nums[middle] < target) 24 | start = middle + 1; 25 | else 26 | end = middle; 27 | } 28 | return start; 29 | } 30 | } -------------------------------------------------------------------------------- /code/342.Power_of_Four/power-of-four.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-four/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-04 4 | 5 | // 第一思路,非最佳解法 6 | 7 | class Solution { 8 | 9 | public int getPower(int j, int i) { 10 | long result = 1; 11 | while(i != 0) { 12 | result *= j; 13 | i--; 14 | } 15 | return (int)result; 16 | } 17 | 18 | public boolean isPowerOfFour(int num) { 19 | for(int i = 0; i < 16; i++) { 20 | if (getPower(4, i) == num) 21 | return true; 22 | } 23 | return false; 24 | } 25 | } -------------------------------------------------------------------------------- /code/343.Integer_Break/integer-break.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/integer-break/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-25 4 | 5 | class Solution { 6 | public int integerBreak(int n) { 7 | if(n == 2) 8 | return 1; 9 | if(n == 3) 10 | return 2; 11 | int result = 1; 12 | while(n > 4) { 13 | n -= 3; 14 | result *= 3; 15 | } 16 | result *= n; 17 | return result; 18 | } 19 | } -------------------------------------------------------------------------------- /code/344.Reverse_String/reverse-string.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-string/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-03 4 | 5 | class Solution { 6 | public String reverseString(String s) { 7 | char[] input = s.toCharArray(); 8 | if(input.length == 0) 9 | return ""; 10 | for(int i = 0, len = input.length; i < len/2; i++) { 11 | char temp = input[i]; 12 | input[i] = input[len-1-i]; 13 | input[len-1-i] = temp; 14 | } 15 | return String.valueOf(input); 16 | } 17 | } -------------------------------------------------------------------------------- /code/347.Top_K_Frequent_Elements/top-k-frequent-elements.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/top-k-frequent-elements/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-21 4 | 5 | class Solution { 6 | public List topKFrequent(int[] nums, int k) { 7 | List[] lists = new ArrayList[nums.length+1]; 8 | Map map = new HashMap(); 9 | for(int num : nums) 10 | map.put(num, map.getOrDefault(num, 0)+1); 11 | for(int key : map.keySet()) { 12 | if(lists[map.get(key)] == null) 13 | lists[map.get(key)] = new ArrayList(); 14 | lists[map.get(key)].add(key); 15 | } 16 | ArrayList result = new ArrayList(); 17 | for(int i = nums.length; i > 0 && result.size() < k; i--) 18 | if(lists[i] != null) 19 | result.addAll(lists[i]); 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /code/349.Intersection_of_Two_Arrays/intersection-of-two-arrays.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/intersection-of-two-arrays/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-02 4 | 5 | class Solution { 6 | public int[] intersection(int[] nums1, int[] nums2) { 7 | HashSet set1 = new HashSet(); 8 | HashSet set2 = new HashSet(); 9 | for(int num : nums1) 10 | set1.add(num); 11 | for(int num : nums2) 12 | if(set1.contains(num)) 13 | set2.add(num); 14 | int[] result = new int[set2.size()]; 15 | int i = 0; 16 | for(int num : set2) 17 | result[i++] = num; 18 | return result; 19 | 20 | } 21 | } -------------------------------------------------------------------------------- /code/35.Search_Insert_Position/search-insert-position.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-insert-position/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-17 4 | 5 | class Solution { 6 | public int searchInsert(int[] nums, int target) { 7 | int low = 0, high = nums.length-1; 8 | while(low <= high){ 9 | int mid = (low+high) / 2; 10 | if(nums[mid] == target) return mid; 11 | else if(nums[mid] > target) high = mid-1; 12 | else low = mid+1; 13 | } 14 | return low; 15 | } 16 | } -------------------------------------------------------------------------------- /code/35.Search_Insert_Position/search-insert-position.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-insert-position/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-17 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} target 8 | * @return {number} 9 | */ 10 | var searchInsert = function(nums, target) { 11 | var start = 0, 12 | end = nums.length - 1; 13 | 14 | while(start <= end) { 15 | let mid = (start + end) / 2; 16 | if(nums[mid] < target) { 17 | start = mid + 1; 18 | } 19 | else if(nums[mid] > target){ 20 | end = mid - 1; 21 | } 22 | else 23 | return mid; 24 | } 25 | 26 | return start 27 | }; -------------------------------------------------------------------------------- /code/350.Intersection_of_Two_Arrays_II/intersection-of-two-arrays-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/intersection-of-two-arrays-ii// 2 | // Author : Kyon Huang 3 | // Date : 2018-02-02 4 | 5 | class Solution { 6 | public int[] intersect(int[] nums1, int[] nums2) { 7 | HashMap map = new HashMap(); 8 | ArrayList list = new ArrayList(); 9 | for(int num : nums1) { 10 | if(!map.containsKey(num)) 11 | map.put(num, 1); 12 | else 13 | map.put(num, map.get(num)+1); 14 | } 15 | for(int num : nums2) { 16 | if(map.containsKey(num) && map.get(num) > 0) { 17 | list.add(num); 18 | map.put(num, map.get(num)-1); 19 | } 20 | } 21 | int[] result = new int[list.size()]; 22 | for(int i = 0; i < list.size(); i++) 23 | result[i] = list.get(i); 24 | return result; 25 | } 26 | } -------------------------------------------------------------------------------- /code/367.Valid_Perfect_Square/valid-perfect-square.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-perfect-square/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-14 4 | 5 | class Solution { 6 | public boolean isPerfectSquare(int num) { 7 | long i = num; 8 | while(i * i > num) 9 | i = (i + num / i) >>> 1; 10 | return i * i == num; 11 | } 12 | } -------------------------------------------------------------------------------- /code/374.Guess_Number_Higher_or_Lower/guess-number-higher-or-lower.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/guess-number-higher-or-lower/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-05 4 | 5 | /* The guess API is defined in the parent class GuessGame. 6 | @param num, your guess 7 | @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 8 | int guess(int num); */ 9 | 10 | public class Solution extends GuessGame { 11 | public int guessNumber(int n) { 12 | int first = 1, last = n; 13 | while(first < last) { 14 | int mid = first + (last - first) / 2; 15 | if(guess(mid) == 0) { 16 | return mid; 17 | } else if(guess(mid) == 1) { 18 | first = mid + 1; 19 | } else { 20 | last = mid; 21 | } 22 | } 23 | return first; 24 | } 25 | } -------------------------------------------------------------------------------- /code/375.Guess_Number_Higher_or_Lower_II/guess-number-higher-or-lower-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/guess-number-higher-or-lower-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-17 4 | 5 | class Solution { 6 | public int getMoneyAmount(int n) { 7 | int[][] table = new int[n+1][n+1]; 8 | return DP(table, 1, n); 9 | } 10 | 11 | public int DP(int[][] table, int start, int end) { 12 | if(start >= end) 13 | return 0; 14 | if(table[start][end] != 0) 15 | return table[start][end]; 16 | int res = Integer.MAX_VALUE; 17 | for(int i = start; i <= end; i++) { 18 | int sum = i + Math.max(DP(table, i+1, end), DP(table, start, i-1)); 19 | res = Math.min(sum, res); 20 | } 21 | table[start][end] = res; 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /code/378.Kth_Smallest_Element_in_a_Sorted_Matrix/kth-smallest-element-in-a-sorted-matrix.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-02 4 | 5 | class Solution { 6 | public int kthSmallest(int[][] matrix, int k) { 7 | int lo = matrix[0][0], hi = matrix[matrix.length - 1][matrix[0].length - 1] + 1;//[lo, hi) 8 | while(lo < hi) { 9 | int mid = lo + (hi - lo) / 2; 10 | int count = 0, j = matrix[0].length - 1; 11 | for(int i = 0; i < matrix.length; i++) { 12 | while(j >= 0 && matrix[i][j] > mid) j--; 13 | count += (j + 1); 14 | } 15 | if(count < k) lo = mid + 1; 16 | else hi = mid; 17 | } 18 | return lo; 19 | } 20 | } -------------------------------------------------------------------------------- /code/38.Count_and_Say/count-and-say.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/count-and-say/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-21 4 | 5 | class Solution { 6 | public String countAndSay(int n) { 7 | if(n == 1) 8 | return "1"; 9 | else { 10 | char[] prevSay = countAndSay(n - 1).toCharArray(); 11 | String result = ""; 12 | for(int i = 0; i < prevSay.length;) { 13 | int currentNum = Integer.valueOf(prevSay[i] - '0'); 14 | int times = 0; 15 | while(i < prevSay.length && Integer.valueOf(prevSay[i] - '0') == currentNum) { 16 | times++; 17 | i++; 18 | } 19 | result += String.valueOf(times) + String.valueOf(currentNum); 20 | } 21 | return result; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /code/383.Ransom_Note/ransom-note.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ransom-note/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-07 4 | 5 | // 第一思路,非最佳方案 6 | 7 | class Solution { 8 | public boolean canConstruct(String ransomNote, String magazine) { 9 | int[] alpha = new int[26]; 10 | for(char c: magazine.toCharArray()) { 11 | alpha[c - 'a']++; 12 | } 13 | 14 | for(char c: ransomNote.toCharArray()) { 15 | alpha[c - 'a']--; 16 | } 17 | 18 | for(int i: alpha) { 19 | if(i < 0) 20 | return false; 21 | } 22 | 23 | return true; 24 | } 25 | } -------------------------------------------------------------------------------- /code/387.First_Unique_Character_in_a_String/first-unique-character-in-a-string.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/first-unique-character-in-a-string/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-12 4 | 5 | class Solution { 6 | public int firstUniqChar(String s) { 7 | int[] timesArr = new int[26]; 8 | char[] c = s.toCharArray(); 9 | for(char ch: c){ 10 | timesArr[ch-'a']++; 11 | } 12 | for(int i = 0; i < c.length; i++){ 13 | if(timesArr[c[i]-'a'] == 1) 14 | return i; 15 | } 16 | return -1; 17 | } 18 | } -------------------------------------------------------------------------------- /code/389.Find_the_Difference/find-the-difference.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-the-difference/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-02 4 | 5 | class Solution { 6 | public char findTheDifference(String s, String t) { 7 | int[] arr = new int[26]; 8 | for(char c : s.toCharArray()) { 9 | arr[c-'a']++; 10 | } 11 | for(char c : t.toCharArray()) { 12 | if(arr[c-'a'] == 0) 13 | return c; 14 | arr[c-'a']--; 15 | } 16 | return 0; 17 | } 18 | } -------------------------------------------------------------------------------- /code/392.Is_Subsequence/is-subsequence.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/is-subsequence/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-16 4 | 5 | class Solution { 6 | public boolean isSubsequence(String s, String t) { 7 | int pre = -1; 8 | for(char ch : s.toCharArray()) { 9 | if(t.indexOf(ch, pre+1) <= pre) 10 | return false; 11 | pre = t.indexOf(ch, pre+1); 12 | } 13 | return true; 14 | } 15 | } -------------------------------------------------------------------------------- /code/398.Random_Pick_Index/random-pick-index.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/random-pick-index/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-21 4 | 5 | class Solution { 6 | 7 | int[] nums; 8 | Random random; 9 | 10 | public Solution(int[] nums) { 11 | this.nums = nums; 12 | random = new Random(); 13 | } 14 | 15 | public int pick(int target) { 16 | int result = -1; 17 | int n = 0; 18 | for(int i = 0; i < nums.length; i++) { 19 | if(target != nums[i]) 20 | continue; 21 | if(random.nextInt(++n) == 0) 22 | result = i; 23 | } 24 | return result; 25 | } 26 | } 27 | 28 | /** 29 | * Your Solution object will be instantiated and called as such: 30 | * Solution obj = new Solution(nums); 31 | * int param_1 = obj.pick(target); 32 | */ -------------------------------------------------------------------------------- /code/400.Nth_Digit/nth-digit.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/nth-digit/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-16 4 | 5 | class Solution { 6 | public int findNthDigit(int n) { 7 | int len = 1; 8 | long count = 9; 9 | int start = 1; 10 | 11 | while(n > len * count) { 12 | n -= len * count; 13 | len++; 14 | count *= 10; 15 | start *= 10; 16 | } 17 | 18 | start += (n-1) / len; 19 | String s = String.valueOf(start); 20 | return Character.getNumericValue(s.charAt((n-1) % len)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /code/404.Sum_of_Left_Leaves/sum-of-left-leaves.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sum-of-left-leaves/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-13 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public int sumOfLeftLeaves(TreeNode root) { 16 | int sum = 0; 17 | if(root != null) { 18 | sum += sumOfLeftLeaves(root.left); 19 | sum += sumOfLeftLeaves(root.right); 20 | if(root.left != null && root.left.left == null && root.left.right == null) 21 | sum += root.left.val; 22 | } 23 | return sum; 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /code/409.Longest_Palindrome/longest-palindrome.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-palindrome/ 2 | // Author : Kyon Huang 3 | // Date : 2018-06-07 4 | 5 | class Solution { 6 | public int longestPalindrome(String s) { 7 | int[] arr = new int[60]; 8 | for(char ch : s.toCharArray()) 9 | arr[ch - 'A']++; 10 | int result = 0; 11 | boolean hasOdd = false; 12 | for(int num : arr) { 13 | result += num; 14 | if(num % 2 == 1 && hasOdd) 15 | result--; 16 | if(num % 2 == 1) 17 | hasOdd = true; 18 | } 19 | return result; 20 | } 21 | } -------------------------------------------------------------------------------- /code/412.Fizz_Buzz/fizz-buzz.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/fizz-buzz/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-07 4 | 5 | class Solution { 6 | public List fizzBuzz(int n) { 7 | List list = new ArrayList(); 8 | for(int i = 1; i <= n; i++) { 9 | String word; 10 | if(i % 3 != 0 && i % 5 != 0) 11 | word = "" + i; 12 | else if(i % 3 == 0 && i % 5 == 0) 13 | word = "FizzBuzz"; 14 | else if(i % 3 == 0) 15 | word = "Fizz"; 16 | else 17 | word = "Buzz"; 18 | list.add(word); 19 | } 20 | 21 | return list; 22 | } 23 | } -------------------------------------------------------------------------------- /code/413.Arithmetic_Slices/arithmetic-slices.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/arithmetic-slices/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-26 4 | 5 | class Solution { 6 | public int numberOfArithmeticSlices(int[] A) { 7 | int cur = 0, result = 0; 8 | for(int i = 2; i < A.length; i++) { 9 | if(A[i-1] - A[i-2] == A[i] - A[i-1]) { 10 | cur++; 11 | result += cur; 12 | } else 13 | cur = 0; 14 | } 15 | return result; 16 | } 17 | } -------------------------------------------------------------------------------- /code/414.Third_Maximum_Number/single-element-in-a-sorted-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/third-maximum-number/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-14 4 | 5 | class Solution { 6 | public int thirdMax(int[] nums) { 7 | Integer max1 = null; 8 | Integer max2 = null; 9 | Integer max3 = null; 10 | 11 | for(Integer num: nums) { 12 | if(num.equals(max1) || num.equals(max2) || num.equals(max3)) continue; 13 | if(max1 == null || max1 < num) { 14 | max3 = max2; 15 | max2 = max1; 16 | max1 = num; 17 | } 18 | else if(max2 == null || max2 < num) { 19 | max3 = max2; 20 | max2 = num; 21 | } 22 | else if(max3 == null || max3 < num) { 23 | max3 = num; 24 | } 25 | } 26 | 27 | return max3 == null ? max1 : max3 ; 28 | } 29 | } -------------------------------------------------------------------------------- /code/415.Add_Strings/add-strings.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-strings/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-13 4 | 5 | class Solution { 6 | public String addStrings(String num1, String num2) { 7 | StringBuilder sb = new StringBuilder(); 8 | int goUp = 0; 9 | for(int i = num1.length()-1, j = num2.length()-1; i >= 0 || j >= 0 || goUp != 0; i--, j--) { 10 | int a = i < 0 ? 0 : Integer.valueOf(num1.charAt(i) - '0'); 11 | int b = j < 0 ? 0 : Integer.valueOf(num2.charAt(j) - '0'); 12 | goUp += a + b; 13 | sb.append(goUp % 10); 14 | goUp /= 10; 15 | } 16 | return sb.reverse().toString(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /code/419.Battleships_in_a_Board/battleships-in-a-board.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/battleships-in-a-board/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-24 4 | 5 | class Solution { 6 | public int countBattleships(char[][] board) { 7 | int m = board.length; 8 | if (m == 0) return 0; 9 | int n = board[0].length; 10 | 11 | int count = 0; 12 | 13 | for (int i = 0; i < m; i++) { 14 | for (int j = 0; j < n; j++) { 15 | if (board[i][j] == '.') continue; 16 | if (i > 0 && board[i-1][j] == 'X') continue; 17 | if (j > 0 && board[i][j-1] == 'X') continue; 18 | count++; 19 | } 20 | } 21 | 22 | return count; 23 | } 24 | } -------------------------------------------------------------------------------- /code/434.Number_of_Segments_in_a_String/number-of-segments-in-a-string.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-segments-in-a-string/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-20 4 | 5 | /** 6 | * @param {string} s 7 | * @return {number} 8 | */ 9 | var countSegments = function(s) { 10 | if(s.trim().length === 0) // 除去""、" " 11 | return 0; 12 | let arr = s.trim().split(/\s+/); 13 | return arr.length; 14 | }; 15 | -------------------------------------------------------------------------------- /code/441.Arranging_Coins/arranging-coins.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/arranging-coins/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-23 4 | 5 | // 第一思路,非最优解法 6 | 7 | /** 8 | * @param {number} n 9 | * @return {number} 10 | */ 11 | var getRow = function(i) { 12 | return (1+i)*i/2; 13 | } 14 | 15 | var arrangeCoins = function(n) { 16 | let i = 0; 17 | while(getRow(i+1) <= n){ 18 | i++; 19 | } 20 | return i; 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /code/442.Find_All_Duplicates_in_an_Array/find-all-duplicates-in-an-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-all-duplicates-in-an-array/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-19 4 | 5 | // 第一思路,非最优解法 6 | 7 | class Solution { 8 | public List findDuplicates(int[] nums) { 9 | List list = new ArrayList(); 10 | int len = nums.length; 11 | int[] arr = new int[len+1]; 12 | for(int i = 0; i < len; i++) { 13 | arr[nums[i]]++; 14 | } 15 | for(int i = 1; i <= len; i++) { 16 | if(arr[i] > 1) { 17 | list.add(i); 18 | } 19 | } 20 | return list; 21 | } 22 | } -------------------------------------------------------------------------------- /code/442.Find_All_Duplicates_in_an_Array/find-all-duplicates-in-an-array.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/find-all-duplicates-in-an-array/ 2 | # Author : Kyon Huang 3 | # Date : 2017-09-19 4 | 5 | class Solution(object): 6 | def findDuplicates(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: List[int] 10 | """ 11 | res = [] 12 | for x in nums: 13 | if nums[abs(x)-1] < 0: 14 | res.append(abs(x)) 15 | else: 16 | nums[abs(x)-1] *= -1 17 | return res 18 | -------------------------------------------------------------------------------- /code/448.Find_All_Numbers_Disappeared_in_an_Array/find-all-numbers-disappeared-in-an-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-05 4 | 5 | // 第一思路,非最佳方案 6 | 7 | class Solution { 8 | public List findDisappearedNumbers(int[] nums) { 9 | int n = nums.length; 10 | List list = new ArrayList(); 11 | boolean[] hasAppeared = new boolean[n+1]; 12 | for(int num : nums) { 13 | if(!hasAppeared[num]) 14 | hasAppeared[num] = true; 15 | } 16 | 17 | for(int i = 1; i <= n; i++) 18 | if(!hasAppeared[i]) 19 | list.add(i); 20 | 21 | return list; 22 | } 23 | } -------------------------------------------------------------------------------- /code/453.Minimum_Moves_to_Equal_Array_Elements/minimum-moves-to-equal-array-elements.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-moves-to-equal-array-elements/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-12 4 | 5 | class Solution { 6 | public int minMoves(int[] nums) { 7 | int min = nums[0]; 8 | for(int i: nums) { 9 | min = Math.min(i, min); 10 | } 11 | int times = 0; 12 | for(int i: nums) { 13 | times += i - min; 14 | } 15 | return times; 16 | } 17 | } -------------------------------------------------------------------------------- /code/455.Assign_Cookies/assign-cookies.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/assign-cookies/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-25 4 | 5 | class Solution { 6 | public int findContentChildren(int[] g, int[] s) { 7 | Arrays.sort(g); 8 | Arrays.sort(s); 9 | int result = 0; 10 | int i = 0; 11 | while(result < g.length && i < s.length) { 12 | if(g[result] <= s[i]) 13 | result++; 14 | i++; 15 | } 16 | 17 | return result; 18 | } 19 | } -------------------------------------------------------------------------------- /code/459.Repeated_Substring_Pattern/repeated-substring-pattern.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/repeated-substring-pattern/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-18 4 | 5 | class Solution { 6 | public boolean repeatedSubstringPattern(String str) { 7 | int l = str.length(); 8 | for(int i = l/2; i >= 1; i--) { 9 | if(l%i == 0) { 10 | int m = l/i; 11 | String subS = str.substring(0, i); 12 | StringBuilder sb = new StringBuilder(); 13 | for(int j = 0; j < m; j++) 14 | sb.append(subS); 15 | if(sb.toString().equals(str)) 16 | return true; 17 | } 18 | } 19 | return false; 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /code/46.Permutations/permutations.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/permutations/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-28 4 | 5 | class Solution { 6 | public List> permute(int[] nums) { 7 | LinkedList> result = new LinkedList>(); 8 | result.add(new ArrayList()); 9 | for(int n : nums) { 10 | int size = result.size(); 11 | for(; size > 0; size--) { 12 | List list = result.pollFirst(); 13 | for(int i = 0; i <= list.size(); i++) { 14 | List newList = new ArrayList(list); 15 | newList.add(i, n); 16 | result.add(newList); 17 | } 18 | } 19 | } 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /code/461.Hamming_Distance/hamming-distance.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/hamming-distance/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-27 4 | 5 | // 第一思路,非最佳解法 6 | 7 | class Solution { 8 | public int hammingDistance(int x, int y) { 9 | int z = x ^ y, 10 | result = 0, 11 | i = 32; 12 | while(z != 0) { 13 | 14 | if(Math.pow(2, i) <= z) { 15 | result++; 16 | z -= Math.pow(2, i); 17 | } 18 | i--; 19 | } 20 | return result; 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /code/462.Minimum_Moves_to_Equal_Array_Elements_II/minimum-moves-to-equal-array-elements-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-08 4 | 5 | class Solution { 6 | public int minMoves2(int[] nums) { 7 | Arrays.sort(nums); 8 | int steps = 0; 9 | int i = 0; 10 | while(i < nums.length/2) { 11 | steps += (nums[nums.length-1-i] - nums[i]); 12 | i++; 13 | } 14 | return steps; 15 | } 16 | } -------------------------------------------------------------------------------- /code/463.Island_Perimeter/island-perimeter.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/island-perimeter/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-18 4 | 5 | class Solution { 6 | public int islandPerimeter(int[][] grid) { 7 | int lands = 0; 8 | int neighbor = 0; 9 | for(int i = 0; i < grid.length; i++) 10 | for(int j = 0; j < grid[0].length; j++) 11 | if(grid[i][j] == 1) { 12 | lands++; 13 | if(j < grid[0].length-1 && grid[i][j+1] == 1) 14 | neighbor++; 15 | if(i < grid.length-1 && grid[i+1][j] == 1) 16 | neighbor++; 17 | } 18 | 19 | return 4 * lands - 2 * neighbor; 20 | } 21 | } -------------------------------------------------------------------------------- /code/476.Number_Complement/number-complement.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-complement/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-17 4 | 5 | class Solution { 6 | public int findComplement(int num) { 7 | int i = 0; 8 | int j = 0; 9 | 10 | while (i < num) { 11 | i += Math.pow(2, j); 12 | j++; 13 | } 14 | 15 | return i - num; 16 | } 17 | } -------------------------------------------------------------------------------- /code/482.License_Key_Formatting/license-key-formatting.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/license-key-formatting/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-24 4 | 5 | class Solution { 6 | public String licenseKeyFormatting(String S, int K) { 7 | String s = S.toUpperCase(); 8 | int len = 0; 9 | for(char ch : s.toCharArray()) 10 | if(ch != '-') 11 | len++; 12 | int k = len % K; 13 | if(k == 0) 14 | k = K; 15 | StringBuilder sb = new StringBuilder(); 16 | for(char ch : s.toCharArray()) { 17 | if(ch == '-') 18 | continue; 19 | if(k == 0) { 20 | sb.append("-"); 21 | k = K; 22 | } 23 | sb.append(ch); 24 | k--; 25 | } 26 | return sb.toString(); 27 | } 28 | } -------------------------------------------------------------------------------- /code/485.Max_Consecutive_Ones/max-consecutive-ones.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/max-consecutive-ones/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-05 4 | 5 | class Solution { 6 | public int findMaxConsecutiveOnes(int[] nums) { 7 | int n = 0; 8 | int consecutiveTime = 0; 9 | for(int num : nums) { 10 | if(num == 1) 11 | consecutiveTime++; 12 | else { 13 | n = Math.max(n, consecutiveTime); 14 | consecutiveTime = 0; 15 | } 16 | } 17 | n = Math.max(n, consecutiveTime); 18 | return n; 19 | } 20 | } -------------------------------------------------------------------------------- /code/492.Construct_the_Rectangle/construct-the-rectangle:description.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/construct-the-rectangle/description/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-18 4 | 5 | class Solution { 6 | public int[] constructRectangle(int area) { 7 | int width = (int)Math.sqrt(area); 8 | while(area % width != 0) 9 | width--; 10 | int length = area / width; 11 | return new int[]{length, width}; 12 | } 13 | } -------------------------------------------------------------------------------- /code/495.Teemo_Attacking/teemo-attacking.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/teemo-attacking/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-24 4 | 5 | class Solution { 6 | public int findPoisonedDuration(int[] timeSeries, int duration) { 7 | if(timeSeries.length == 0 || timeSeries == null) 8 | return 0; 9 | int result = 0; 10 | for(int i = 0; i < timeSeries.length-1; i++) 11 | result += Math.min(duration, (timeSeries[i+1] - timeSeries[i])); 12 | 13 | return result + duration; 14 | } 15 | } -------------------------------------------------------------------------------- /code/496.Next_Greater_Element_I/next-greater-element-i.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/next-greater-element-i/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-11 4 | 5 | class Solution { 6 | public int[] nextGreaterElement(int[] nums1, int[] nums2) { 7 | Stack stack = new Stack(); 8 | Map map = new HashMap(); 9 | int[] result = new int[nums1.length]; 10 | for(int num : nums2) { 11 | while(!stack.isEmpty() && stack.peek() < num) 12 | map.put(stack.pop(), num); 13 | stack.push(num); 14 | } 15 | for(int i = 0; i < nums1.length; i++) 16 | if(map.containsKey(nums1[i])) 17 | result[i] = map.get(nums1[i]); 18 | else 19 | result[i] = -1; 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /code/50.Pow(x,n)/powx-n.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/powx-n/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-26 4 | 5 | class Solution { 6 | public double myPow(double x, int n) { 7 | if(n == 0) 8 | return 1; 9 | if(n<0){ 10 | n = -n; 11 | x = 1/x; 12 | } 13 | return (n%2 == 0) ? myPow(x*x, n/2) : x*myPow(x*x, n/2); 14 | } 15 | } -------------------------------------------------------------------------------- /code/500.Keyboard_Row/keyboard-row.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/keyboard-row/ 2 | // Author : Kyon Huang 3 | // Date : 2018-07-25 4 | 5 | class Solution { 6 | public String[] findWords(String[] words) { 7 | String[] rows = { 8 | "qwertyuiop", 9 | "asdfghjkl", 10 | "zxcvbnm" 11 | }; 12 | ArrayList ans = new ArrayList(); 13 | for(String word : words) { 14 | String tempWord = word.toLowerCase(); 15 | for(String row : rows) { 16 | int index = 0; 17 | while(index < word.length() && row.indexOf(tempWord.charAt(index)) != -1) 18 | index++; 19 | if(index == word.length()) 20 | ans.add(word); 21 | } 22 | } 23 | String[] result = new String[ans.size()]; 24 | for(int i = 0; i < ans.size(); i++) 25 | result[i] = ans.get(i); 26 | return result; 27 | } 28 | } -------------------------------------------------------------------------------- /code/503.Next_Greater_Element_II/next-greater-element-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/next-greater-element-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-12 4 | 5 | class Solution { 6 | public int[] nextGreaterElements(int[] nums) { 7 | Stack stack = new Stack(); 8 | int n = nums.length; 9 | int[] result = new int[n]; 10 | for(int i = 0; i < n*2; i++) { 11 | if(i < n) 12 | result[i] = -1; 13 | while(!stack.isEmpty() && nums[stack.peek()] < nums[i%n]) 14 | result[stack.pop()] = nums[i%n]; 15 | if(i < n) 16 | stack.push(i); 17 | } 18 | return result; 19 | } 20 | } -------------------------------------------------------------------------------- /code/506.Relative_Ranks/relative-ranks.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/relative-ranks/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-06 4 | 5 | class Solution { 6 | public String[] findRelativeRanks(int[] nums) { 7 | int[] arr = nums.clone(); 8 | Arrays.sort(arr); 9 | String[] result = new String[nums.length]; 10 | HashMap map = new HashMap(); 11 | for(int i = 0; i < nums.length; i++) 12 | map.put(arr[i], nums.length-i); 13 | for(int i = 0; i < nums.length; i++) { 14 | int ranking = map.get(nums[i]); 15 | if(ranking == 1) 16 | result[i] = "Gold Medal"; 17 | else if(ranking == 2) 18 | result[i] = "Silver Medal"; 19 | else if(ranking == 3) 20 | result[i] = "Bronze Medal"; 21 | else 22 | result[i] = ""+ranking; 23 | } 24 | return result; 25 | } 26 | } -------------------------------------------------------------------------------- /code/507.Perfect_Number/perfect-number.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/perfect-number/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-17 4 | 5 | class Solution { 6 | public boolean checkPerfectNumber(int num) { 7 | if (num == 1) 8 | return false; 9 | int sum = 1; 10 | for (int i = 2; i <= Math.sqrt(num); i++) { 11 | if (num % i == 0) 12 | sum += i + num / i; 13 | } 14 | 15 | return sum == num; 16 | } 17 | } -------------------------------------------------------------------------------- /code/520.Detect_Capital/detect-capital.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/detect-capital/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-30 4 | 5 | // 第一思路,非最优解法 6 | 7 | /** 8 | * @param {string} word 9 | * @return {boolean} 10 | */ 11 | var detectCapitalUse = function(word) { 12 | if(word === word.toUpperCase() || word === word.toLowerCase() || (word[0] === word[0].toUpperCase() && word.slice(1) === word.slice(1).toLowerCase())) return true; 13 | return false; 14 | }; -------------------------------------------------------------------------------- /code/521.Longest_Uncommon_Subsequence_I/longest-uncommon-subsequence-i.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-uncommon-subsequence-i/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-25 4 | 5 | class Solution { 6 | public int findLUSlength(String a, String b) { 7 | return a.equals(b) ? -1 : Math.max(a.length(), b.length()); 8 | } 9 | } -------------------------------------------------------------------------------- /code/525.Contiguous_Array/contiguous-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contiguous-array/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-28 4 | 5 | class Solution { 6 | public int findMaxLength(int[] nums) { 7 | int max = 0; 8 | HashMap map = new HashMap(); 9 | int[] prefix = new int[nums.length+1]; 10 | map.put(0, 0); 11 | for(int i = 1; i <= nums.length; i++) { 12 | prefix[i] = prefix[i-1] + (nums[i-1] == 0 ? -1 : 1); 13 | if(map.containsKey(prefix[i])) 14 | max = Math.max(max, i - map.get(prefix[i])); 15 | else 16 | map.put(prefix[i], i); 17 | } 18 | return max; 19 | } 20 | } -------------------------------------------------------------------------------- /code/53.Maximum_Subarray/maximum-subarray.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-subarray/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-21 4 | 5 | class Solution { 6 | public int maxSubArray(int[] nums) { 7 | int len = nums.length; 8 | int[] result = new int[len]; 9 | result[0] = nums[0]; 10 | int max = nums[0]; 11 | 12 | for(int i = 1; i < len; i++) { 13 | result[i] = (result[i-1] > 0) ? result[i-1] + nums[i] : nums[i]; 14 | max = Math.max(result[i], max); 15 | } 16 | return max; 17 | } 18 | } -------------------------------------------------------------------------------- /code/532.K-diff_Pairs_in_an_Array/k-diff-pairs-in-an-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/k-diff-pairs-in-an-array/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-15 4 | 5 | class Solution { 6 | public int findPairs(int[] nums, int k) { 7 | if(nums == null || nums.length == 0 || k < 0) 8 | return 0; 9 | Map map = new HashMap(); 10 | int result = 0; 11 | for(int num : nums) 12 | map.put(num, map.getOrDefault(num, 0) + 1); 13 | 14 | Iterator iter = map.entrySet().iterator(); 15 | while (iter.hasNext()) { 16 | Map.Entry entry = (Map.Entry) iter.next(); 17 | int key = (int)entry.getKey(); 18 | if (k == 0 && map.get(key) > 1) 19 | result++; 20 | if (k != 0 && map.containsKey(key - k)) 21 | result++; 22 | } 23 | return result; 24 | } 25 | } -------------------------------------------------------------------------------- /code/537.Complex_Number_Multiplication/complex-number-multiplication.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/complex-number-multiplication/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-03 4 | 5 | class Solution { 6 | public String complexNumberMultiply(String a, String b) { 7 | String[] asplit = a.split("\\+"); // 要转义 8 | String[] bsplit = b.split("\\+"); 9 | int aint = Integer.parseInt(asplit[0]); 10 | int ai = Integer.parseInt(asplit[1].split("i")[0]); 11 | int bint = Integer.parseInt(bsplit[0]); 12 | int bi = Integer.parseInt(bsplit[1].split("i")[0]); 13 | 14 | int resultint = aint * bint - ai * bi; 15 | int resulti = aint * bi + ai * bint; 16 | return resultint + "+" + resulti + "i"; 17 | } 18 | } -------------------------------------------------------------------------------- /code/538.Convert_BST_to_Greater_Tree/convert-bst-to-greater-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/convert-bst-to-greater-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-08 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | 16 | int sum = 0; 17 | 18 | public TreeNode convertBST(TreeNode root) { 19 | helper(root); 20 | return root; 21 | } 22 | 23 | private void helper(TreeNode root) { 24 | if(root == null) 25 | return; 26 | helper(root.right); 27 | root.val += sum; 28 | sum = root.val; 29 | helper(root.left); 30 | } 31 | } -------------------------------------------------------------------------------- /code/540.Single_Element_in_a_Sorted_Array/single-element-in-a-sorted-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/single-element-in-a-sorted-array/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-18 4 | 5 | class Solution { 6 | public int singleNonDuplicate(int[] nums) { 7 | int len = nums.length, 8 | start = 0, 9 | end = len / 2; 10 | 11 | while(start < end) { 12 | int mid = (start + end) / 2; 13 | if(nums[2 * mid] != nums[2 * mid + 1]) { 14 | end = mid; 15 | } else { 16 | start = mid + 1; 17 | } 18 | } 19 | 20 | return nums[2 * start]; 21 | } 22 | } -------------------------------------------------------------------------------- /code/541.Reverse_String_II/reverse-string-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-string-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-11 4 | 5 | class Solution { 6 | public String reverseStr(String s, int k) { 7 | StringBuilder sb = new StringBuilder(); 8 | int i = 0; 9 | for(; i < s.length() - 2*k; i+= 2 * k) { 10 | sb.append(reverse(s.substring(i, i+k))); 11 | sb.append(s.substring(i+k, i+2*k)); 12 | } 13 | 14 | if(i + k > s.length()) 15 | sb.append(reverse(s.substring(i, s.length()))); 16 | else { 17 | sb.append(reverse(s.substring(i, i+k))); 18 | sb.append(s.substring(i+k, s.length())); 19 | } 20 | 21 | return sb.toString(); 22 | } 23 | 24 | private static String reverse(String str) { 25 | StringBuilder sb = new StringBuilder(str); 26 | return sb.reverse().toString(); 27 | } 28 | } -------------------------------------------------------------------------------- /code/543.Diameter_of_Binary_Tree/diameter-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/diameter-of-binary-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-07 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | private int diameter = 0; 16 | 17 | public int diameterOfBinaryTree(TreeNode root) { 18 | getHeight(root); 19 | return diameter; 20 | } 21 | 22 | private int getHeight(TreeNode root) { 23 | if(root == null) 24 | return 0; 25 | int leftHeight = getHeight(root.left); 26 | int rightHeight = getHeight(root.right); 27 | diameter = Math.max(diameter, leftHeight + rightHeight); 28 | return Math.max(leftHeight, rightHeight)+1; 29 | } 30 | } -------------------------------------------------------------------------------- /code/547.Friend_Circles/friend-circles.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/friend-circles/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-01 4 | 5 | class Solution { 6 | public int findCircleNum(int[][] M) { 7 | boolean[] visited = new boolean[M.length]; 8 | int cirnum = 0; 9 | for(int i = 0; i < M.length; i++) 10 | if(!visited[i]) { 11 | DFS(M, visited, i); 12 | cirnum++; 13 | } 14 | return cirnum; 15 | } 16 | 17 | private void DFS(int[][] M, boolean[] visited, int k) { 18 | for(int j = 0; j < M.length; j++) 19 | if(M[k][j] == 1 && !visited[j]) { 20 | visited[j] = true; 21 | DFS(M, visited, j); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /code/551.Student_Attendance_Record_I/student-attendance-record-i.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/student-attendance-record-i/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-17 4 | 5 | class Solution { 6 | public boolean checkRecord(String s) { 7 | int absentTimes = 0; 8 | char[] array = s.toCharArray(); 9 | for(int i = 0, len = array.length; i < len; i++) { // more than two continuous 'L' (late) 10 | if(array[i] == 'A') { 11 | absentTimes++; 12 | if(absentTimes > 1) 13 | return false; 14 | } 15 | else if(array[i] == 'L') { 16 | if(i+1 < len && array[i+1] == 'L') { 17 | i++; 18 | if(i+1 < len && array[i+1] == 'L') 19 | return false; 20 | } 21 | } 22 | 23 | } 24 | return true; 25 | } 26 | } -------------------------------------------------------------------------------- /code/553.Optimal_Division/optimal-division.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/optimal-division/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-17 4 | 5 | class Solution { 6 | public String optimalDivision(int[] nums) { 7 | int len = nums.length; 8 | if(len == 1) 9 | return String.valueOf(nums[0]); 10 | else if(len == 2) 11 | return nums[0] + "/" + nums[1]; 12 | else { 13 | StringBuffer str = new StringBuffer(); 14 | for(int i = 0; i < len-1; i++) { 15 | if(i == 1) 16 | str.append("("); 17 | str.append(nums[i]+"/"); 18 | } 19 | str.append(nums[len-1] + ")"); 20 | return str.toString(); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /code/554.Brick_Wall/brick-wall.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/brick-wall/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-21 4 | 5 | class Solution { 6 | public int leastBricks(List> wall) { 7 | if(wall == null || wall.size() == 0) 8 | return 0; 9 | Map map = new HashMap(); 10 | for(List list : wall) { 11 | int i = 0; 12 | for(int j = 0; j < list.size()-1; j++) { 13 | i += list.get(j); 14 | map.put(i, map.getOrDefault(i, 0)+1); 15 | } 16 | } 17 | int max = 0; 18 | for(int key : map.keySet()) 19 | max = Math.max(max, map.get(key)); 20 | return wall.size()-max; 21 | } 22 | } -------------------------------------------------------------------------------- /code/557.Reverse_Words_in_a_String_III/reverse-words-in-a-string-iii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-words-in-a-string-iii/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-18 4 | 5 | class Solution { 6 | public String reverseWords(String s) { 7 | char[] wordsCharArr = s.toCharArray(); 8 | int j = 0; 9 | for(int i = 0; i < wordsCharArr.length; i++) { 10 | if(wordsCharArr[i] == ' ') { 11 | reverseArr(wordsCharArr, j, i-1); 12 | j = i+1; 13 | } 14 | } 15 | 16 | reverseArr(wordsCharArr, j, wordsCharArr.length-1); 17 | 18 | return String.valueOf(wordsCharArr); 19 | } 20 | 21 | private void reverseArr(char[] charArr, int start, int end) { 22 | while(start < end) { 23 | char temp = charArr[start]; 24 | charArr[start] = charArr[end]; 25 | charArr[end] = temp; 26 | start++; 27 | end--; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /code/561.Array_Partition_I/array-partition-i.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/array-partition-i/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-17 4 | 5 | class Solution { 6 | public int arrayPairSum(int[] nums) { 7 | Arrays.sort(nums); 8 | int sum = 0; 9 | for(int i = 0; i < nums.length; i += 2) { 10 | sum += nums[i]; 11 | } 12 | return sum; 13 | } 14 | } -------------------------------------------------------------------------------- /code/563.Binary_Tree_Tilt/binary-tree-tilt.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-tilt/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-25 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | private int wholeTill = 0; 16 | 17 | public int findTilt(TreeNode root) { 18 | addTilt(root); 19 | return wholeTill; 20 | } 21 | 22 | private int addTilt(TreeNode root) { 23 | if(root == null) 24 | return 0; 25 | int leftTilt = addTilt(root.left); 26 | int rightTilt = addTilt(root.right); 27 | wholeTill += Math.abs(leftTilt - rightTilt); 28 | return leftTilt + rightTilt + root.val; 29 | } 30 | } -------------------------------------------------------------------------------- /code/566.Reshape_the_Matrix/reshape-the-matrix.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reshape-the-matrix/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-31 4 | 5 | class Solution { 6 | public int[][] matrixReshape(int[][] nums, int r, int c) { 7 | int height = nums.length; 8 | int length = nums[0].length; 9 | if(r * c != height * length) 10 | return nums; 11 | int[][] result = new int[r][c]; 12 | for(int i = 0; i < height * length; i++) 13 | result[i/c][i%c] = nums[i/length][i%length]; 14 | return result; 15 | } 16 | } -------------------------------------------------------------------------------- /code/572.Subtree_of_Another_Tree/subtree-of-another-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/subtree-of-another-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-17 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public boolean isSubtree(TreeNode s, TreeNode t) { 16 | if(s == null) 17 | return false; 18 | else if(isSame(s, t)) 19 | return true; 20 | return isSubtree(s.left, t) || isSubtree(s.right, t); 21 | } 22 | 23 | private boolean isSame(TreeNode s, TreeNode t) { 24 | if(t == null && s == null) 25 | return true; 26 | if(s != null && t != null && s.val == t.val) 27 | return isSame(s.left, t.left) && isSame(s.right, t.right); 28 | return false; 29 | } 30 | } -------------------------------------------------------------------------------- /code/575.Distribute_Candies/distribute-candies.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/distribute-candies/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-04 4 | 5 | // 第一思路,非最佳方案 6 | 7 | class Solution { 8 | public int distributeCandies(int[] candies) { 9 | Arrays.sort(candies); 10 | int kind = 1; 11 | int cur = candies[0]; 12 | int index = 0; 13 | int len = candies.length; 14 | while(index < len && kind < len/2) { 15 | if(candies[index] == cur) 16 | index++; 17 | else { 18 | kind++; 19 | cur = candies[index]; 20 | index++; 21 | } 22 | } 23 | return kind; 24 | } 25 | } -------------------------------------------------------------------------------- /code/58.Length_of_Last_Word/length-of-last-word.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/length-of-last-word/ 2 | // Author : Kyon Huang 3 | // Date : 2017-09-26 4 | 5 | // 第一思路,非最优解法 6 | 7 | /** 8 | * @param {string} s 9 | * @return {number} 10 | */ 11 | var lengthOfLastWord = function(s) { 12 | if(s == 0) return 0; 13 | let arr = s.split(/\s+/); 14 | return (arr[arr.length-1].length === 0) ? arr[arr.length-2].length : arr[arr.length-1].length; 15 | }; -------------------------------------------------------------------------------- /code/581.Shortest_Unsorted_Continuous_Subarray/shortest-unsorted-continuous-subarray.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-02 4 | 5 | public int findUnsortedSubarray(int[] A) { 6 | int n = A.length, beg = -1, end = -2, min = A[n-1], max = A[0]; 7 | for (int i = 1; i < n; i++) { 8 | max = Math.max(max, A[i]); 9 | min = Math.min(min, A[n-1-i]); 10 | if (A[i] < max) end = i; 11 | if (A[n-1-i] > min) beg = n-1-i; 12 | } 13 | return end - beg + 1; 14 | } -------------------------------------------------------------------------------- /code/590.N-ary_Tree_Postorder_Traversal/n-ary-tree-postorder-traversal.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/n-ary-tree-postorder-traversal/ 2 | // Author : Kyon Huang 3 | // Date : 2018-09-06 4 | 5 | /* 6 | // Definition for a Node. 7 | class Node { 8 | public int val; 9 | public List children; 10 | 11 | public Node() {} 12 | 13 | public Node(int _val,List _children) { 14 | val = _val; 15 | children = _children; 16 | } 17 | }; 18 | */ 19 | class Solution { 20 | List res = new ArrayList(); 21 | public List postorder(Node root) { 22 | if(root == null) 23 | return res; 24 | for(Node child : root.children) 25 | postorder(child); 26 | res.add(root.val); 27 | return res; 28 | } 29 | } -------------------------------------------------------------------------------- /code/594.Longest_Harmonious_Subsequence/longest-harmonious-subsequence.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-harmonious-subsequence/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-12 4 | 5 | class Solution { 6 | public int findLHS(int[] nums) { 7 | Arrays.sort(nums); 8 | int result = 0; 9 | for(int i = 0; i < nums.length;) { // 注意这里不能有 i++ 10 | int cur = nums[i]; 11 | int num = 0; 12 | for(; i < nums.length && nums[i] == cur; i++) 13 | num++; 14 | if(i < nums.length && nums[i] == cur+1) { 15 | for(int j = i; j < nums.length && nums[j] == cur+1; j++) 16 | num++; 17 | result = Math.max(result, num); 18 | } 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /code/595.Big_Countries/big-countries.sql: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/big-countries/ 2 | # Author : Kyon Huang 3 | # Date : 2017-09-27 4 | 5 | # Write your MySQL query statement below 6 | SELECT name, population, area FROM World 7 | WHERE area > 3000000 OR population > 25000000; -------------------------------------------------------------------------------- /code/596.Classes_More_Than_5_Students/classes-more-than-5-students.sql: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/classes-more-than-5-students/ 2 | # Author : Kyon Huang 3 | # Date : 2017-11-01 4 | 5 | SELECT class FROM courses 6 | GROUP BY class 7 | HAVING COUNT(DISTINCT student) >= 5; -------------------------------------------------------------------------------- /code/598.Range_Addition_II/range-addition-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/range-addition-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-05 4 | 5 | class Solution { 6 | public int maxCount(int m, int n, int[][] ops) { 7 | int minHeight = m; 8 | int minWidth = n; 9 | for(int[] arr : ops) { 10 | minHeight = Math.min(minHeight, arr[0]); 11 | minWidth = Math.min(minWidth, arr[1]); 12 | } 13 | return minHeight * minWidth; 14 | } 15 | } -------------------------------------------------------------------------------- /code/599.Minimum_Index_Sum_of_Two_Lists/minimum-index-sum-of-two-lists.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-index-sum-of-two-lists/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-08 4 | 5 | class Solution { 6 | public String[] findRestaurant(String[] list1, String[] list2) { 7 | Map map = new HashMap<>(); 8 | List result = new LinkedList<>(); 9 | int minSum = Integer.MAX_VALUE; 10 | for (int i = 0; i < list1.length; i++) 11 | map.put(list1[i], i); 12 | for (int i = 0; i < list2.length; i++) { 13 | Integer j = map.get(list2[i]); 14 | if (j != null && i + j <= minSum) { 15 | if (i + j < minSum) { 16 | result.clear(); 17 | minSum = i+j; 18 | } 19 | result.add(list2[i]); 20 | } 21 | } 22 | return result.toArray(new String[result.size()]); 23 | } 24 | } -------------------------------------------------------------------------------- /code/6.ZigZag_Conversion/zigzag-conversion.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/zigzag-conversion/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-19 4 | 5 | class Solution { 6 | public String convert(String s, int nRows) { 7 | char[] c = s.toCharArray(); 8 | int len = c.length; 9 | StringBuffer[] sb = new StringBuffer[nRows]; 10 | for (int i = 0; i < sb.length; i++) 11 | sb[i] = new StringBuffer(); 12 | 13 | int i = 0; 14 | while (i < len) { 15 | for (int idx = 0; idx < nRows && i < len; idx++) // vertically down 16 | sb[idx].append(c[i++]); 17 | for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up 18 | sb[idx].append(c[i++]); 19 | } 20 | for (int idx = 1; idx < sb.length; idx++) 21 | sb[0].append(sb[idx]); 22 | return sb[0].toString(); 23 | } 24 | } -------------------------------------------------------------------------------- /code/61.Rotate_List/rotate-list.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-list/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-25 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode rotateRight(ListNode head, int n) { 15 | if (head == null || head.next == null) 16 | return head; 17 | ListNode dummy = new ListNode(0); 18 | dummy.next = head; 19 | ListNode fast = dummy, slow = dummy; 20 | 21 | int len; 22 | for (len = 0; fast.next != null; i++) 23 | fast = fast.next; 24 | 25 | for (int j = 0; j < len-n%len; j++) 26 | slow = slow.next; 27 | 28 | fast.next = dummy.next; 29 | dummy.next = slow.next; 30 | slow.next = null; 31 | 32 | return dummy.next; 33 | } 34 | } -------------------------------------------------------------------------------- /code/617.Merge_Two_Binary_Trees/merge-two-binary-trees.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-two-binary-trees/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-12 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 16 | if(t1 == null) 17 | return t2; 18 | if(t2 == null) 19 | return t1; 20 | TreeNode root = new TreeNode(t1.val + t2.val); 21 | root.left = mergeTrees(t1.left, t2.left); 22 | root.right = mergeTrees(t1.right, t2.right); 23 | return root; 24 | } 25 | } -------------------------------------------------------------------------------- /code/62.Unique_Paths/unique-paths.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/unique-paths/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-24 4 | 5 | class Solution { 6 | public int uniquePaths(int m, int n) { 7 | int[] paths = new int[n]; 8 | for(int i = 0; i < n; i++) 9 | paths[i] = 1; 10 | for(int t = 1; t < m; t++) 11 | for(int i = 1; i < n; i++) 12 | paths[i] += paths[i-1]; 13 | return paths[n-1]; 14 | } 15 | } -------------------------------------------------------------------------------- /code/620.Not_Boring_Movies/not-boring-movies.sql: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/not-boring-movies/ 2 | # Author : Kyon Huang 3 | # Date : 2017-09-29 4 | 5 | # Write your MySQL query statement below 6 | SELECT * FROM cinema 7 | WHERE (id % 2 = 1) AND (description != 'boring') 8 | ORDER BY rating DESC; -------------------------------------------------------------------------------- /code/633.Sum_of_Square_Numbers/sum-of-square-numbers.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sum-of-square-numbers/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-16 4 | 5 | class Solution { 6 | public boolean judgeSquareSum(int c) { 7 | int a = (int)Math.sqrt(c); 8 | int b = 0; 9 | while(b <= a) { 10 | int temp = a*a + b*b; 11 | if(temp == c) 12 | return true; 13 | else if(temp < c) 14 | b++; 15 | else 16 | a--; 17 | } 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /code/643.Maximum_Average_Subarray_I/maximum-average-subarray-i.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-average-subarray-i/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-23 4 | 5 | class Solution { 6 | public double findMaxAverage(int[] nums, int k) { 7 | double sum = 0; 8 | for(int i = 0; i < k; i++) { 9 | sum += nums[i]; 10 | } 11 | double maxSum = sum; 12 | for(int i = k; i < nums.length; i++) { 13 | sum += nums[i] - nums[i-k]; 14 | maxSum = Math.max(sum, maxSum); 15 | } 16 | return maxSum / k; 17 | } 18 | } -------------------------------------------------------------------------------- /code/645.Set_Mismatch/set-mismatch.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/set-mismatch/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-29 4 | 5 | class Solution { 6 | public int[] findErrorNums(int[] nums) { 7 | int len = nums.length; 8 | int[] arr = new int[len+1]; 9 | for(int num : nums) 10 | arr[num]++; 11 | int[] result = new int[2]; 12 | for(int i = 1; i <= len; i++) { 13 | if(arr[i] == 0) 14 | result[1] = i; 15 | if(arr[i] == 2) 16 | result[0] = i; 17 | if(result[1] != 0 && result[0] != 0) 18 | break; 19 | } 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /code/646.Maximum_Length_of_Pair_Chain/maximum-length-of-pair-chain.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-length-of-pair-chain/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-19 4 | 5 | // 第一思路,非最佳解法 6 | 7 | class Solution { 8 | public int findLongestChain(int[][] pairs) { 9 | Arrays.sort(pairs, (a, b) -> a[1] - b[1]); 10 | int len = pairs.length; 11 | int[] arr = new int[len]; 12 | int l = 1; 13 | for(int i = 0; i < len; i++) { 14 | arr[i] = 1; 15 | for(int j = 0; j < i; j++) 16 | if(pairs[j][1] < pairs[i][0] && arr[j] + 1 > arr[i]) 17 | arr[i] = arr[j] + 1; 18 | if(arr[i] > l) 19 | l = arr[i]; 20 | } 21 | return l; 22 | } 23 | } -------------------------------------------------------------------------------- /code/647.Palindromic_Substrings/palindromic-substrings.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/palindromic-substrings/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-23 4 | 5 | public class Solution { 6 | int count = 0; 7 | 8 | public int countSubstrings(String s) { 9 | if (s == null || s.length() == 0) 10 | return 0; 11 | for (int i = 0; i < s.length(); i++) { // i is the mid point 12 | extendPalindrome(s, i, i); // odd length; 13 | extendPalindrome(s, i, i + 1); // even length 14 | } 15 | return count; 16 | } 17 | 18 | private void extendPalindrome(String s, int left, int right) { 19 | while (left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)) { 20 | count++; 21 | left--; 22 | right++; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /code/657.Judge_Route_Circle/judge-route-circle.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/judge-route-circle/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-01 4 | 5 | /** 6 | * @param {string} moves 7 | * @return {boolean} 8 | */ 9 | var judgeCircle = function(moves) { 10 | let x = 0, 11 | y = 0; 12 | moves.split('').forEach(function(elem) { 13 | switch(elem) { 14 | case 'L': 15 | x--; 16 | break; 17 | case 'R': 18 | x++; 19 | break; 20 | case 'U': 21 | y++; 22 | break; 23 | case 'D': 24 | y--; 25 | break; 26 | } 27 | }); 28 | 29 | if(x === 0 && y === 0) 30 | return true; 31 | return false; 32 | }; 33 | -------------------------------------------------------------------------------- /code/66.Plus_One/plus-one.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/plus-one/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-22 4 | 5 | class Solution { 6 | public int[] plusOne(int[] digits) { 7 | int len = digits.length; 8 | for(int i = len-1; i >= 0; i--) { 9 | if(digits[i] != 9) { 10 | digits[i]++; 11 | return digits; 12 | } 13 | digits[i] = 0; 14 | } 15 | int[] result = new int[len+1]; 16 | result[0] = 1; 17 | for(int j = 1; j <= len; j++) 18 | result[j] = 0; 19 | return result; 20 | } 21 | } -------------------------------------------------------------------------------- /code/665.Non-decreasing_Array/non-decreasing-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/non-decreasing-array/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-04 4 | 5 | class Solution { 6 | public boolean checkPossibility(int[] nums) { 7 | int cnt = 0; // the number of changes 8 | for(int i = 1; i < nums.length && cnt <= 1; i++){ 9 | if(nums[i-1] > nums[i]){ 10 | cnt++; 11 | if(i-2 < 0 || nums[i-2] <= nums[i]) 12 | nums[i-1] = nums[i]; // modify nums[i-1] of a priority 13 | else 14 | nums[i] = nums[i-1]; // have to modify nums[i] 15 | } 16 | } 17 | return cnt<=1; 18 | } 19 | } -------------------------------------------------------------------------------- /code/669.Trim_a_Binary_Search_Tree/trim-a-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/trim-a-binary-search-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2018-09-14 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public TreeNode trimBST(TreeNode root, int L, int R) { 16 | if(root == null) 17 | return root; 18 | if(root.val < L) 19 | return trimBST(root.right, L, R); 20 | if(root.val > R) 21 | return trimBST(root.left, L, R); 22 | root.left = trimBST(root.left, L, R); 23 | root.right = trimBST(root.right, L, R); 24 | return root; 25 | } 26 | } -------------------------------------------------------------------------------- /code/67.Add_Binary/add-binary.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-binary/ 2 | // Author : Kyon Huang 3 | // Date : 2018-03-09 4 | 5 | class Solution { 6 | public String addBinary(String a, String b) { 7 | StringBuilder sb = new StringBuilder(); 8 | int carry = 0; 9 | for(int i = a.length()-1, j = b.length()-1; i >= 0 || j >= 0; i--, j--) { 10 | int sum = carry; 11 | if(i >= 0) 12 | sum += a.charAt(i) - '0'; 13 | if(j >= 0) 14 | sum += b.charAt(j) - '0'; 15 | sb.append(sum % 2); 16 | carry = sum / 2; 17 | } 18 | if(carry != 0) 19 | sb.append(carry); 20 | return sb.reverse().toString(); 21 | } 22 | } -------------------------------------------------------------------------------- /code/672.Bulb_Switcher_II/bulb-switcher-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/bulb-switcher-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-06-29 4 | 5 | class Solution { 6 | public int flipLights(int n, int m) { 7 | if(m == 0) return 1; 8 | if(n == 1) return 2; 9 | if(n == 2 && m == 1) return 3; 10 | if(n == 2) return 4; 11 | if(m == 1) return 4; 12 | if(m == 2) return 7; 13 | if(m >= 3) return 8; 14 | return 8; 15 | } 16 | } -------------------------------------------------------------------------------- /code/674.Longest_Continuous_Increasing_Subsequence/longest-continuous-increasing-subsequence.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-continuous-increasing-subsequence/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-18 4 | 5 | class Solution { 6 | public int findLengthOfLCIS(int[] nums) { 7 | int result = 0; 8 | for(int i = 0; i < nums.length; i++) { 9 | int len = 1; 10 | while(i < nums.length-1 && nums[i] < nums[i+1]) { 11 | len++; 12 | i++; 13 | } 14 | result = Math.max(result, len); 15 | } 16 | return result; 17 | } 18 | } -------------------------------------------------------------------------------- /code/680.Valid_Palindrome_II/valid-palindrome-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-palindrome-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-31 4 | 5 | class Solution { 6 | public boolean validPalindrome(String s) { 7 | return validPalindrome(s, 0, s.length()-1, false); 8 | } 9 | 10 | private boolean validPalindrome(String s, int start, int end, boolean hasDelete) { 11 | while(start <= end) { 12 | if(s.charAt(start) == s.charAt(end)) { 13 | start++; 14 | end--; 15 | } 16 | else if(hasDelete) 17 | return false; 18 | else 19 | return validPalindrome(s, start+1, end, true) || validPalindrome(s, start, end-1, true); 20 | } 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /code/684.Redundant_Connection/redundant-connection.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/redundant-connection/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-23 4 | 5 | class Solution { 6 | public int[] findRedundantConnection(int[][] edges) { 7 | int[] parent = new int[edges.length+1]; 8 | for (int i = 0; i < parent.length; i++) 9 | parent[i] = i; 10 | 11 | for (int[] edge: edges){ 12 | int f = edge[0], t = edge[1]; 13 | if (find(parent, f) == find(parent, t)) // 说明此时已经成环,与环有关的边不会再出现 14 | return edge; 15 | else parent[find(parent, f)] = find(parent, t); 16 | } 17 | 18 | return new int[2]; 19 | } 20 | 21 | private int find(int[] parent, int f) { 22 | if (f != parent[f]) 23 | parent[f] = find(parent, parent[f]); 24 | return parent[f]; 25 | } 26 | } -------------------------------------------------------------------------------- /code/686.Repeated_String_Match/repeated-string-match.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/repeated-string-match/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-16 4 | 5 | // 第一思路,非最佳方案 6 | 7 | class Solution { 8 | public int repeatedStringMatch(String A, String B) { 9 | int minTimes = B.length() / A.length(); 10 | int maxTimes = (B.length() - 2) / A.length() + 2; 11 | for(int i = minTimes; i <= maxTimes; i++) { 12 | if(getnA(i, A).contains(B)) 13 | return i; 14 | } 15 | return -1; 16 | } 17 | 18 | private String getnA(int i, String A) { 19 | String nA = ""; 20 | for(int j = 0; j < i; j++) { 21 | nA += A; 22 | } 23 | return nA; 24 | } 25 | } -------------------------------------------------------------------------------- /code/687.Longest_Univalue_Path/longest-univalue-path.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-univalue-path/ 2 | // Author : Kyon Huang 3 | // Date : 2018-09-02 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | int len = 0; 16 | public int longestUnivaluePath(TreeNode root) { 17 | if(root == null) 18 | return 0; 19 | getLen(root, root.val); 20 | return len; 21 | } 22 | 23 | private int getLen(TreeNode root, int val) { 24 | if(root == null) 25 | return 0; 26 | int leftVal = getLen(root.left, root.val); 27 | int rightVal = getLen(root.right, root.val); 28 | len = Math.max(len, leftVal+rightVal); 29 | if(root.val == val) 30 | return Math.max(leftVal, rightVal)+1; 31 | return 0; 32 | } 33 | } -------------------------------------------------------------------------------- /code/69.Sqrt(x)/sqrtx.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sqrtx/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-19 4 | 5 | class Solution { 6 | public int mySqrt(int x) { 7 | if (x == 0) 8 | return 0; 9 | int left = 1, right = x; 10 | while (true) { 11 | int mid = left + (right - left)/2; 12 | if (mid > x/mid) { 13 | right = mid - 1; 14 | } else { 15 | if (mid + 1 > x/(mid + 1)) 16 | return mid; 17 | left = mid + 1; 18 | } 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /code/693.Binary_Number_with_Alternating_Bits/binary-number-with-alternating-bits.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-number-with-alternating-bits/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-06 4 | 5 | class Solution { 6 | public boolean hasAlternatingBits(int n) { 7 | long k = 1; 8 | long j = n; 9 | while(k < j) 10 | k = 2*k + (k % 2 == 0 ? 1 : 0); 11 | return k==j; 12 | } 13 | } -------------------------------------------------------------------------------- /code/695.Max_Area_of_Island/max-area-of-island.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/max-area-of-island/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-17 4 | 5 | class Solution { 6 | int maxArea = 0; 7 | public int maxAreaOfIsland(int[][] grid) { 8 | for(int i = 0; i < grid.length; i++) 9 | for(int j = 0; j < grid[i].length; j++) 10 | if(grid[i][j] > 0) 11 | maxArea = Math.max(maxArea, cal(grid, i, j)); 12 | return maxArea; 13 | } 14 | 15 | private int cal(int[][] grid, int i, int j) { 16 | if(grid[i][j] == 1) { 17 | grid[i][j] = 0; 18 | return 1 + (i>0 ? cal(grid, i-1, j) : 0) + (i0 ? cal(grid, i, j-1) : 0); 20 | } 21 | return 0; 22 | } 23 | } -------------------------------------------------------------------------------- /code/7.Reverse_Integer/reverse-integer.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/reverse-integer/ 2 | # Author : Kyon Huang 3 | # Date : 2017-09-20 4 | 5 | # 第一思路,非最优解法 6 | 7 | class Solution(object): 8 | def reverse(self, x): 9 | """ 10 | :type x: int 11 | :rtype: int 12 | """ 13 | result = 0 14 | isNegative = abs(x) != x 15 | max = 2 ** 31 - 1 16 | if x % 10 == 0 and x != 0: 17 | while x % 10 == 0: 18 | x /= 10 19 | 20 | if isNegative: 21 | x *= -1 22 | 23 | while x != 0: 24 | result = result * 10 + x % 10 25 | x /= 10 26 | 27 | if result >= max: 28 | return 0 29 | 30 | if isNegative: 31 | result *= -1 32 | 33 | return result 34 | -------------------------------------------------------------------------------- /code/70.Climbing_Stairs/climbing-stairs.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/climbing-stairs/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-18 4 | 5 | class Solution { 6 | public int climbStairs(int n) { 7 | int[] arr = new int[n+1]; 8 | for(int i = 1; i < n+1; i++) 9 | fill(i, arr); 10 | return arr[n]; 11 | } 12 | 13 | private void fill(int n, int[] arr) { 14 | if(n == 1) 15 | arr[n] = 1; 16 | else if(n == 2) 17 | arr[n] = 2; 18 | else 19 | arr[n] = arr[n-1] + arr[n-2]; 20 | } 21 | } -------------------------------------------------------------------------------- /code/700.Search_in_a_Binary_Search_Tree/search-in-a-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-in-a-binary-search-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2018-09-05 4 | 5 | class Solution { 6 | public TreeNode searchBST(TreeNode root, int val) { 7 | while(root != null && root.val != val) 8 | root = root.val > val ? root.left : root.right; 9 | return root; 10 | } 11 | } -------------------------------------------------------------------------------- /code/704.Binary_Search/binary-search.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-search/ 2 | // Author : Kyon Huang 3 | // Date : 2018-09-01 4 | 5 | class Solution { 6 | public int search(int[] nums, int target) { 7 | if(nums == null || nums.length == 0) 8 | return -1; 9 | int start = 0, end = nums.length-1; 10 | while(start <= end) { 11 | int mid = (end - start) / 2 + start; 12 | if(nums[mid] < target) 13 | start = mid+1; 14 | else if(nums[mid] > target) 15 | end = mid-1; 16 | else 17 | return mid; 18 | } 19 | return -1; 20 | } 21 | } -------------------------------------------------------------------------------- /code/709.To_Lower_Case/to-lower-case.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/to-lower-case/ 2 | // Author : Kyon Huang 3 | // Date : 2018-07-21 4 | 5 | class Solution { 6 | public String toLowerCase(String str) { 7 | StringBuilder sb = new StringBuilder(); 8 | for(char ch : str.toCharArray()) 9 | if(ch >= 'A' && ch <= 'Z') 10 | sb.appends((char)('a' + ch - 'A')); 11 | else 12 | sb.append(ch); 13 | return sb.toString(); 14 | } 15 | } -------------------------------------------------------------------------------- /code/717.1-bit_and_2-bit_Characters/1-bit-and-2-bit-characters.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/1-bit-and-2-bit-characters/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-01 4 | 5 | class Solution { 6 | public boolean isOneBitCharacter(int[] bits) { 7 | for(int i = 0, len = bits.length; i < len-1; i++) 8 | if(bits[i] == 1) 9 | if(++i >= len-1) 10 | return false; 11 | 12 | return true; 13 | } 14 | } -------------------------------------------------------------------------------- /code/724.Find_Pivot_Index/find-pivot-index.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-pivot-index/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-16 4 | 5 | class Solution { 6 | public int pivotIndex(int[] nums) { 7 | int sum = 0, leftSum = 0; 8 | for(int num : nums) 9 | sum += num; 10 | for(int i = 0, len = nums.length; i < len; i++) { 11 | if(leftSum * 2 + nums[i] == sum) 12 | return i; 13 | else 14 | leftSum += nums[i]; 15 | } 16 | return -1; 17 | } 18 | } -------------------------------------------------------------------------------- /code/728.Self_Dividing_Numbers/self-dividing-numbers.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/self-dividing-numbers/ 2 | // Author : Kyon Huang 3 | // Date : 2017-11-22 4 | 5 | class Solution { 6 | public List selfDividingNumbers(int left, int right) { 7 | List list = new LinkedList(); 8 | for(int i = left; i <= right; i++) { 9 | if(i < 10 || isSelfDividing(i)) 10 | list.add(i); 11 | } 12 | return list; 13 | } 14 | 15 | private boolean isSelfDividing(int n) { 16 | int m = n; 17 | while(m > 0) { 18 | int i = m % 10; 19 | if(i == 0 || n % i != 0) 20 | return false; 21 | m /= 10; 22 | } 23 | return true; 24 | } 25 | } -------------------------------------------------------------------------------- /code/733.Flood_Fill/flood-fill.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/flood-fill/ 2 | // Author : Kyon Huang 3 | // Date : 2018-09-24 4 | 5 | class Solution { 6 | public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { 7 | int oldColor = image[sr][sc]; 8 | if(oldColor != newColor) 9 | DFS(image, sr, sc, oldColor, newColor); 10 | return image; 11 | } 12 | 13 | public void DFS(int[][] image, int sr, int sc, int oldColor, int newColor) { 14 | if(sr >= 0 && sr < image.length && sc >= 0 && sc < image[0].length && image[sr][sc] == oldColor) { 15 | image[sr][sc] = newColor; 16 | DFS(image, sr+1, sc, oldColor, newColor); 17 | DFS(image, sr-1, sc, oldColor, newColor); 18 | DFS(image, sr, sc+1, oldColor, newColor); 19 | DFS(image, sr, sc-1, oldColor, newColor); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /code/739.Daily_Temperatures/daily-temperatures.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/daily-temperatures/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-15 4 | 5 | class Solution { 6 | public int[] dailyTemperatures(int[] temperatures) { 7 | int len = temperatures.length; 8 | int[] stack = new int[len]; 9 | int[] result = new int[len]; 10 | int top = -1; 11 | for(int i = 0; i < len; i++) { 12 | while(top != -1 && temperatures[i] > temperatures[stack[top]]) { 13 | int j = stack[top--]; 14 | result[j] = i - j; 15 | } 16 | stack[++top] = i; 17 | } 18 | 19 | return result; 20 | } 21 | } -------------------------------------------------------------------------------- /code/74.Search_a_2D_Matrix/search-a-2d-matrix.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-a-2d-matrix/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-03 4 | 5 | class Solution { 6 | public boolean searchMatrix(int[][] matrix, int target) { 7 | if(matrix.length == 0 || matrix[0].length == 0) 8 | return false; 9 | int m = matrix.length, n = matrix[0].length; 10 | int low = 0, high = m * n - 1; 11 | while(low <= high) { 12 | int mid = (high - low) / 2 + low, curVal = matrix[mid / n][mid % n]; 13 | if(curVal == target) 14 | return true; 15 | else if(curVal < target) 16 | low = mid + 1; 17 | else 18 | high = mid - 1; 19 | } 20 | return false; 21 | } 22 | } -------------------------------------------------------------------------------- /code/744.Find_Smallest_Letter_Greater_Than_Target/find-smallest-letter-greater-than-target.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-smallest-letter-greater-than-target/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-14 4 | 5 | class Solution { 6 | public char nextGreatestLetter(char[] letters, char target) { 7 | 8 | int len = letters.length; 9 | if(target >= letters[len-1]) 10 | target -= 26; 11 | int start = 0; 12 | int end = len - 1; 13 | while(start < end) { 14 | int middle = start + (end - start) / 2; 15 | if(letters[middle] > target) { 16 | end = middle; 17 | } else { 18 | start = middle + 1; 19 | } 20 | } 21 | return letters[start]; 22 | } 23 | } -------------------------------------------------------------------------------- /code/746.Min_Cost_Climbing_Stairs/min-cost-climbing-stairs.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/min-cost-climbing-stairs/ 2 | // Author : Kyon Huang 3 | // Date : 2017-12-20 4 | 5 | class Solution { 6 | public int minCostClimbingStairs(int[] cost) { 7 | int len = cost.length; 8 | int m = 0, n = 0, k = 0; 9 | for(int i = 2; i <= len; i++) { 10 | k = Math.min(m+cost[i-2], n+cost[i-1]); 11 | m = n; 12 | n = k; 13 | } 14 | return k; 15 | } 16 | } -------------------------------------------------------------------------------- /code/747.Largest_Number_At_Least_Twice_of_Others/largest-number-at-least-twice-of-others.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/largest-number-at-least-twice-of-others/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-13 4 | 5 | class Solution { 6 | public int dominantIndex(int[] nums) { 7 | int biggest = nums[0]; 8 | int second = Integer.MIN_VALUE; 9 | int index = 0; 10 | for(int i = 0; i < nums.length; i++) { 11 | if(nums[i] > biggest) { 12 | index = i; 13 | second = biggest; 14 | biggest = nums[i]; 15 | } 16 | else if(biggest > nums[i] && nums[i] > second) 17 | second = nums[i]; 18 | } 19 | return (biggest >= second * 2) ? index : -1; 20 | } 21 | } -------------------------------------------------------------------------------- /code/75.Sort_Colors/sort-colors.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sort-colors/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-11 4 | 5 | // 非最佳方案 6 | 7 | class Solution { 8 | public void sortColors(int[] nums) { 9 | int zero = 0; 10 | int one = 0; 11 | for(int num : nums) { 12 | if(num == 0) 13 | zero++; 14 | else if(num == 1) 15 | one++; 16 | } 17 | for(int i = 0; i < nums.length; i++) { 18 | if(zero != 0) { 19 | nums[i] = 0; 20 | zero--; 21 | } 22 | else if(one != 0) { 23 | nums[i] = 1; 24 | one--; 25 | } 26 | else 27 | nums[i] = 2; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /code/754.Reach_a_Number/reach-a-number.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reach-a-number/ 2 | // Author : Kyon Huang 3 | // Date : 2018-06-30 4 | 5 | class Solution { 6 | public int reachNumber(int target) { 7 | if(target == 0) 8 | return 0; 9 | if(target < 0) 10 | target = -target; 11 | int n = (int)Math.sqrt(target) - 1; 12 | while(n * (n + 1) < target * 2 || (n * (n + 1) / 2 - target) % 2 == 1) 13 | n++; 14 | return n; 15 | } 16 | } -------------------------------------------------------------------------------- /code/760.Find_Anagram_Mappings/find-anagram-mappings.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-anagram-mappings/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-11 4 | 5 | class Solution { 6 | public int[] anagramMappings(int[] A, int[] B) { 7 | Map> map = new HashMap>(); 8 | for(int i = 0; i < B.length; i++) { 9 | if(!map.containsKey(B[i])) 10 | map.put(B[i], new ArrayList()); 11 | map.get(B[i]).add(i); 12 | } 13 | int[] arr = new int[A.length]; 14 | for(int i = 0; i < arr.length; i++) { 15 | arr[i] = map.get(A[i]).get(0); 16 | map.get(A[i]).remove(0); 17 | } 18 | return arr; 19 | } 20 | } -------------------------------------------------------------------------------- /code/763.Partition_Labels/partition-labels.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/partition-labels/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-19 4 | 5 | class Solution { 6 | public List partitionLabels(String S) { 7 | if(S == null || S.length() == 0) 8 | return null; 9 | int[] arr = new int[26]; 10 | List list = new ArrayList(); 11 | for(int i = 0; i < S.length(); i++) 12 | arr[S.charAt(i) - 'a'] = i; 13 | int tail = 0; 14 | int head = 0; 15 | for(int i = 0; i < S.length(); i++) { 16 | tail = Math.max(tail, arr[S.charAt(i) - 'a']); 17 | if(tail == i) { 18 | list.add(tail - head + 1); 19 | head = tail + 1; 20 | } 21 | } 22 | return list; 23 | } 24 | } -------------------------------------------------------------------------------- /code/769.Max_Chunks_To_Make_Sorted/max-chunks-to-make-sorted.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/max-chunks-to-make-sorted/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-23 4 | 5 | class Solution { 6 | public int maxChunksToSorted(int[] arr) { 7 | int result = 0; 8 | for(int left = 0; left < arr.length;) { 9 | int right = arr[left]; 10 | for(; left <= right; i++) 11 | right = Math.max(right, arr[left]); 12 | result++; 13 | } 14 | return result; 15 | } 16 | } -------------------------------------------------------------------------------- /code/771.Jewels_and_Stones/jewels-and-stones.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/jewels-and-stones/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-30 4 | 5 | class Solution { 6 | public int numJewelsInStones(String J, String S) { 7 | HashSet set = new HashSet(); 8 | for(char ch : J.toCharArray()) 9 | set.add(ch); 10 | int result = 0; 11 | for(char ch : S.toCharArray()) 12 | if(set.contains(ch)) 13 | result++; 14 | return result; 15 | } 16 | } -------------------------------------------------------------------------------- /code/78.Subsets/subsets.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/subsets/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-18 4 | 5 | class Solution { 6 | 7 | ArrayList> result = new ArrayList>(); 8 | 9 | public List> subsets(int[] nums) { 10 | BFS(nums, 0, new ArrayList()); 11 | return result; 12 | } 13 | 14 | private void BFS(int[] nums, int i, ArrayList list) { 15 | ArrayList a = new ArrayList(list); 16 | ArrayList b = new ArrayList(list); 17 | a.add(nums[i]); 18 | if(i == nums.length-1) { 19 | result.add(a); 20 | result.add(b); 21 | } 22 | else { 23 | BFS(nums, i+1, a); 24 | BFS(nums, i+1, b); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /code/781.Rabbits_in_Forest/rabbits-in-forest.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rabbits-in-forest/ 2 | // Author : Kyon Huang 3 | // Date : 2018-02-21 4 | 5 | class Solution { 6 | public int numRabbits(int[] answers) { 7 | Map map = new HashMap(); 8 | int result = 0; 9 | for(int num : answers) 10 | map.put(num, map.getOrDefault(num, 0)+1); 11 | for(int key : map.keySet()) { 12 | int i = map.get(key) / (key+1) + (map.get(key) % (key+1) != 0 ? 1 : 0); 13 | result += (key+1) * i; 14 | } 15 | return result; 16 | } 17 | } -------------------------------------------------------------------------------- /code/783.Minimum_Distance_Between_BST_Nodes/minimum-distance-between-bst-nodes.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-distance-between-bst-nodes/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-14 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | 16 | int minDiff = Integer.MAX_VALUE; 17 | Integer preVal = null; 18 | 19 | public int minDiffInBST(TreeNode root) { 20 | DFS(root); 21 | return minDiff; 22 | } 23 | 24 | public void DFS(TreeNode root) { 25 | if(root != null) { 26 | DFS(root.left); 27 | if(preVal != null) 28 | minDiff = Math.min(minDiff, root.val - preVal); 29 | preVal = root.val; 30 | DFS(root.right); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /code/788.Rotated_Digits/rotated-digits.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotated-digits/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-06 4 | 5 | class Solution { 6 | public int rotatedDigits(int N) { 7 | int result = 0; 8 | for(int i = 1; i <= N; i++) 9 | if(isRotatedDigit(i)) 10 | result++; 11 | return result; 12 | } 13 | 14 | public boolean isRotatedDigit(int n) { 15 | boolean has2569 = false; 16 | while(n != 0) { 17 | int i = n % 10; 18 | if(i == 2 || i == 5 || i == 6 || i == 9) 19 | has2569 = true; 20 | else if(i == 3 || i == 4 || i == 7) 21 | return false; 22 | n = n / 10; 23 | } 24 | return has2569; 25 | } 26 | } -------------------------------------------------------------------------------- /code/791.Custom_Sort_String/longest-word-in-dictionary.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/custom-sort-string/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-11 4 | 5 | class Solution { 6 | public String customSortString(String S, String T) { 7 | StringBuilder sb = new StringBuilder(); 8 | int[] map = new int[26]; 9 | for(char ch : T.toCharArray()) 10 | map[ch-'a']++; 11 | for(char ch : S.toCharArray()) { 12 | int times = map[ch-'a']; 13 | for(int i = 0; i < times; i++) 14 | sb.append(ch); 15 | map[ch-'a'] = 0; 16 | } 17 | for(int i = 0; i < 26; i++) 18 | for(int j = 0; j < map[i]; j++) 19 | sb.append((char)('a'+i)); 20 | return sb.toString(); 21 | } 22 | } -------------------------------------------------------------------------------- /code/796.Rotate_String/rotate-string.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-string/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-15 4 | 5 | class Solution { 6 | public boolean rotateString(String A, String B) { 7 | return A.length() == B.length() && (A+A).contains(B); 8 | } 9 | } -------------------------------------------------------------------------------- /code/797.All_Paths_From_Source_to_Target/all-paths-from-source-to-target.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/all-paths-from-source-to-target/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-19 4 | 5 | class Solution { 6 | private int N; 7 | private List> result; 8 | 9 | public List> allPathsSourceTarget(int[][] graph) { 10 | N = graph.length; 11 | result = new ArrayList>(); 12 | DFS(0, new ArrayList(), graph); 13 | return result; 14 | } 15 | 16 | private void DFS(int point, List list, int[][] graph) { 17 | List newList = new ArrayList(); 18 | newList.addAll(list); 19 | newList.add(point); 20 | if(point == N-1) 21 | result.add(newList); 22 | else 23 | for(int num : graph[point]) 24 | DFS(num, newList, graph); 25 | } 26 | } -------------------------------------------------------------------------------- /code/80.Remove_Duplicates_from_Sorted_Array_II/remove-duplicates-from-sorted-array-ii.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-02 4 | 5 | class Solution { 6 | public int removeDuplicates(int[] nums) { 7 | int i = 0; 8 | for(int num : nums) 9 | if(i < 2 || num > nums[i-2]) 10 | nums[i++] = num; 11 | return i; 12 | } 13 | } -------------------------------------------------------------------------------- /code/804.Unique_Morse_Code_Words/unique-morse-code-words.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/unique-morse-code-words/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-04 4 | 5 | class Solution { 6 | public int uniqueMorseRepresentations(String[] words) { 7 | String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; 8 | Set set = new HashSet(); 9 | for(String word : words) { 10 | StringBuilder sb = new StringBuilder(); 11 | for(char ch : word.toCharArray()) 12 | sb.append(morse[ch - 'a']); 13 | set.add(sb.toString()); 14 | } 15 | return set.size(); 16 | } 17 | } -------------------------------------------------------------------------------- /code/812.Largest_Triangle_Area/largest-triangle-area.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/largest-triangle-area/ 2 | // Author : Kyon Huang 3 | // Date : 2018-04-10 4 | 5 | class Solution { 6 | public double largestTriangleArea(int[][] p) { 7 | double res = 0; 8 | for (int[] i: p) 9 | for (int[] j: p) 10 | for (int[] k: p) 11 | res = Math.max(res, 0.5 * Math.abs(i[0] * j[1] + j[0] * k[1] + k[0] * i[1]- j[0] * i[1] - k[0] * j[1] - i[0] * k[1])); 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /code/814.Binary_Tree_Pruning/binary-tree-pruning.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-pruning/ 2 | // Author : Kyon Huang 3 | // Date : 2018-07-07 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public TreeNode pruneTree(TreeNode root) { 16 | if(root == null) 17 | return null; 18 | if(root.left != null) 19 | root.left = pruneTree(root.left); 20 | if(root.right != null) 21 | root.right = pruneTree(root.right); 22 | if(root.left == null && root.right == null && root.val == 0) 23 | return null; 24 | return root; 25 | } 26 | } -------------------------------------------------------------------------------- /code/817.Linked_List_Components/linked-list-components.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/linked-list-components/ 2 | // Author : Kyon Huang 3 | // Date : 2018-07-16 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | class Solution { 14 | 15 | Set set = new HashSet(); 16 | 17 | public int numComponents(ListNode head, int[] G) { 18 | int result = 0; 19 | for(int v : G) 20 | set.add(v); 21 | while(head != null) { 22 | while(head != null && !set.contains(head.val)) 23 | head = head.next; 24 | if(head != null && set.contains(head.val)) { 25 | while(head != null && set.contains(head.val)) 26 | head = head.next; 27 | result++; 28 | } 29 | } 30 | return result; 31 | } 32 | } -------------------------------------------------------------------------------- /code/821.Shortest_Distance_to_a_Character/shortest-distance-to-a-character.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/shortest-distance-to-a-character/ 2 | // Author : Kyon Huang 3 | // Date : 2018-05-07 4 | 5 | class Solution { 6 | public int[] shortestToChar(String S, char C) { 7 | int[] result = new int[S.length()]; 8 | int preIndex = 0; 9 | for(; preIndex < S.length() && S.charAt(preIndex) != C; preIndex++) 10 | result[preIndex] = Integer.MAX_VALUE; 11 | for(int i = preIndex; i < S.length(); i++) { 12 | if(S.charAt(i) == C) 13 | preIndex = i; 14 | result[i] = i - preIndex; 15 | } 16 | for(int i = preIndex; i >= 0; i--) { 17 | if(S.charAt(i) == C) 18 | preIndex = i; 19 | result[i] = Math.min(result[i], preIndex - i); 20 | } 21 | return result; 22 | } 23 | } -------------------------------------------------------------------------------- /code/841.Keys_and_Rooms/keys-and-rooms.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/keys-and-rooms/ 2 | // Author : Kyon Huang 3 | // Date : 2018-06-11 4 | 5 | class Solution { 6 | 7 | boolean[] openRooms; 8 | 9 | public boolean canVisitAllRooms(List> rooms) { 10 | openRooms = new boolean[rooms.size()]; 11 | DFS(rooms, 0); 12 | for(boolean flag : openRooms) 13 | if(!flag) 14 | return false; 15 | return true; 16 | } 17 | 18 | private void DFS(List> rooms, int num) { 19 | openRooms[num] = true; 20 | List curRoom = rooms.get(num); 21 | for(int key : curRoom) 22 | if(!openRooms[key]) 23 | DFS(rooms, key); 24 | } 25 | } -------------------------------------------------------------------------------- /code/860.Lemonade_Change/lemonade-change.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/lemonade-change/ 2 | // Author : Kyon Huang 3 | // Date : 2018-09-15 4 | 5 | class Solution { 6 | public boolean lemonadeChange(int[] bills) { 7 | int fiveBillNum = 0, tenBillNum = 0; 8 | for(int i = 0; i < bills.length; i++) { 9 | if(bills[i] == 5) 10 | fiveBillNum++; 11 | else if(bills[i] == 10) { 12 | fiveBillNum--; 13 | tenBillNum++; 14 | } 15 | else { 16 | if(tenBillNum > 0) 17 | tenBillNum--; 18 | else 19 | fiveBillNum -= 2; 20 | fiveBillNum--; 21 | } 22 | if(fiveBillNum < 0 || tenBillNum < 0) { 23 | return false; 24 | } 25 | 26 | } 27 | return true; 28 | } 29 | } -------------------------------------------------------------------------------- /code/861.Score_After_Flipping_Matrix/score-after-flipping-matrix.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/score-after-flipping-matrix/ 2 | // Author : Kyon Huang 3 | // Date : 2018-07-08 4 | 5 | class Solution { 6 | public int matrixScore(int[][] A) { 7 | int sum = 0; 8 | // 处理每一行开头,使其为 1 9 | for(int[] arr : A) 10 | if(arr[0] == 0) 11 | for(int i = 0; i < arr.length; i++) 12 | arr[i] = 1 - arr[i]; 13 | int height = A.length; 14 | int width = A[0].length; 15 | // 处理每一列,使每一列的 1 尽可能多 16 | for(int i = 0; i < width; i++) { 17 | int sumOf1 = 0; 18 | for(int j = 0; j < height; j++) 19 | if(A[j][i] == 1) 20 | sumOf1++; 21 | if(sumOf1 < height - sumOf1) 22 | sumOf1 = height - sumOf1; 23 | sum += sumOf1 * Math.pow(2, width-1-i); 24 | } 25 | 26 | return sum; 27 | } 28 | } -------------------------------------------------------------------------------- /code/872.Leaf-Similar_Trees/leaf-similar-trees.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/leaf-similar-trees/ 2 | // Author : Kyon Huang 3 | // Date : 2018-09-13 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public boolean leafSimilar(TreeNode root1, TreeNode root2) { 16 | return traverse(root1).equals(traverse(root2)); 17 | } 18 | String traverse(TreeNode root){ 19 | if(root==null) return ""; 20 | if(root.left==null && root.right==null) return root.val+"-"; 21 | return traverse(root.left)+traverse(root.right); 22 | } 23 | } -------------------------------------------------------------------------------- /code/876.Middle_of_the_Linked_List/middle-of-the-linked-list.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/middle-of-the-linked-list/ 2 | // Author : Kyon Huang 3 | // Date : 2018-09-09 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode middleNode(ListNode head) { 15 | ListNode quick = head, slow = head; 16 | while(quick != null && quick.next != null) { 17 | slow = slow.next; 18 | quick = quick.next.next; 19 | } 20 | return slow; 21 | } 22 | } -------------------------------------------------------------------------------- /code/88.Merge_Sorted_Array/merge-sorted-array.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-sorted-array/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-25 4 | 5 | class Solution { 6 | public void merge(int[] nums1, int m, int[] nums2, int n) { 7 | 8 | int nums1Len = m-1; 9 | int nums2Len = n-1; 10 | for(int totalLen = m+n-1; totalLen >= 0; totalLen--) { 11 | if(nums1Len >= 0 && nums2Len >= 0) 12 | if(nums1[nums1Len] > nums2[nums2Len]) 13 | nums1[totalLen] = nums1[nums1Len--]; 14 | else 15 | nums1[totalLen] = nums2[nums2Len--]; 16 | else if(nums1Len < 0) 17 | nums1[totalLen] = nums2[nums2Len--]; 18 | else 19 | nums1[totalLen] = nums1[nums1Len--]; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /code/9.Palindrome_Number/palindrome-number.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/palindrome-number/ 2 | // Author : Kyon Huang 3 | // Date : 2018-01-18 4 | 5 | class Solution { 6 | public boolean isPalindrome(int x) { 7 | if(x < 0) 8 | return false; 9 | int y = x; 10 | int reverse = 0; 11 | while(y != 0) { 12 | reverse = reverse * 10 + y % 10; 13 | y /= 10; 14 | } 15 | return reverse == x; 16 | } 17 | } -------------------------------------------------------------------------------- /code/94.Binary_Tree_Inorder_Traversal/binary-tree-inorder-traversal.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ 2 | // Author : Kyon Huang 3 | // Date : 2017-10-27 4 | 5 | // 递归方法 6 | 7 | /** 8 | * Definition for a binary tree node. 9 | * public class TreeNode { 10 | * int val; 11 | * TreeNode left; 12 | * TreeNode right; 13 | * TreeNode(int x) { val = x; } 14 | * } 15 | */ 16 | class Solution { 17 | public List inorderTraversal(TreeNode root) { 18 | List newList = new ArrayList(); 19 | if(root == null) 20 | return newList; 21 | 22 | if(root.left != null) 23 | newList.addAll(inorderTraversal(root.left)); 24 | newList.add(root.val); 25 | if(root.right != null) 26 | newList.addAll(inorderTraversal(root.right)); 27 | 28 | return newList; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /code/96.Unique_Binary_Search_Trees/unique-binary-search-trees.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/unique-binary-search-trees/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-01 4 | 5 | class Solution { 6 | public int numTrees(int n) { 7 | if(n == 0 || n == 1) 8 | return 1; 9 | int[] arr = new int[n+1]; 10 | arr[1] = arr[0] = 1; 11 | for(int i = 2; i <= n; i++) 12 | for(int j = 1; j <= i; j++) 13 | arr[i] += arr[j-1] * arr[i-j]; 14 | return arr[n]; 15 | } 16 | } -------------------------------------------------------------------------------- /code/98.Validate_Binary_Search_Tree/validate-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/validate-binary-search-tree/ 2 | // Author : Kyon Huang 3 | // Date : 2018-08-02 4 | 5 | class Solution { 6 | 7 | public boolean isValidBST(TreeNode root) { 8 | return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); 9 | } 10 | 11 | private boolean isValidBST(TreeNode root, long minVal, long maxVal) { 12 | if(root == null) 13 | return true; 14 | if(root.val <= minVal || root.val >= maxVal) 15 | return false; 16 | return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal); 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /code/yuki.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "代码目录", 3 | "repository": { 4 | "index": "https://github.com/bighuang624/LeetCode-everyday", 5 | "branch": "master/code" 6 | }, 7 | "startLevel": 2, 8 | "ignore": { 9 | "dir": [".git"], 10 | "extname": [".md"], 11 | "file": [ 12 | "yuki.config.json", 13 | ".gitignore", 14 | "README.md", 15 | ".DS_Store" 16 | ] 17 | } 18 | } -------------------------------------------------------------------------------- /notes/100.Same_Tree.md: -------------------------------------------------------------------------------- 1 | # Same Tree 2 | 3 | ## 题目 4 | 5 | Given two binary trees, write a function to check if they are equal or not. 6 | 7 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 8 | 9 | ## 解题思路 10 | 11 | 第一次 submit 失败了,忘记考虑一边是 null 一边不是的情况。总体来说比较简单,就递归就行了,也不涉及遍历的区别。Discuss 里的非递归方法也不推荐,太麻烦了。 -------------------------------------------------------------------------------- /notes/104.Maximum_Depth_of_Binary_Tree.md: -------------------------------------------------------------------------------- 1 | # Maximum Depth of Binary Tree 2 | 3 | ## 题目 4 | 5 | Given a binary tree, find its maximum depth. 6 | 7 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 8 | 9 | ## 解题思路 10 | 11 | 没啥好说的。 -------------------------------------------------------------------------------- /notes/111.Minimum_Depth_of_Binary_Tree.md: -------------------------------------------------------------------------------- 1 | # Minimum Depth of Binary Tree 2 | 3 | ## 题目 4 | 5 | Given a binary tree, find its minimum depth. 6 | 7 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 8 | 9 | ## 解题思路 10 | 11 | 要从某个树节点有没有左右子节点来判断是否为叶节点。 12 | 13 | ## 其他解法 14 | 15 | 同样思路,更短的做法。当然更短不代表更好理解。 16 | 17 | ```java 18 | public class Solution { 19 | public int minDepth(TreeNode root) { 20 | if(root == null) return 0; 21 | int left = minDepth(root.left); 22 | int right = minDepth(root.right); 23 | return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1; 24 | 25 | } 26 | } 27 | ``` -------------------------------------------------------------------------------- /notes/112.Path_Sum.md: -------------------------------------------------------------------------------- 1 | # Path Sum 2 | 3 | ## 题目 4 | 5 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 6 | For example: 7 | Given the below binary tree and `sum = 22`, 8 | 9 | 5 10 | / \ 11 | 4 8 12 | / / \ 13 | 11 13 4 14 | / \ \ 15 | 7 2 1 16 | 17 | return true, as there exist a root-to-leaf path `5->4->11->2` which sum is 22. 18 | 19 | ## 解题思路 20 | 21 | 深度遍历。注意两点: 22 | 23 | 1. 叶子结点。所以不能判断`root == null`,要判断`root.left == null && root.right == null`; 24 | 2. 有负数。 25 | 26 | -------------------------------------------------------------------------------- /notes/135.Candy.md: -------------------------------------------------------------------------------- 1 | # Candy 2 | 3 | ## 题目 4 | 5 | There are N children standing in a line. Each child is assigned a rating value. 6 | 7 | You are giving candies to these children subjected to the following requirements: 8 | 9 | * Each child must have at least one candy. 10 | * Children with a higher rating get more candies than their neighbors. 11 | 12 | What is the minimum candies you must give? 13 | 14 | ## 解题思路 15 | 16 | 贪心算法。需要拿一个与输入数组同样大小的数组来存储每个孩子的糖果树。 17 | 18 | 先从 0 开始向右遍历一次:第 0 个孩子先拿一块;i > 0 时,如果 ratings[i] > ratings[i-1],那么第 i 个孩子在第 i-1 个孩子所拥有的糖果数上多拿一块,否则拿保底的一块。这一次遍历将右边的 rating 比左边大的情况全部搞定。 19 | 20 | 再从 len-1 开始向左遍历一次:第 len-1 个孩子不变,如果 ratings[i] < ratings[i-1],那么,除非第 i-1 个孩子本身拥有的糖果数已经比多拿这一块后还要多,否则第 i-1 个孩子在第 i 个孩子所拥有的糖果数上多拿一块。这一次遍历将左边的 rating 比右边大的情况全部搞定。 21 | 22 | 这两次遍历相互不影响。最后求和输出即可。 23 | 24 | ## 最优方法 25 | 26 | 尽管时间复杂度和空间复杂度都不是最优的,但上述解法能够 AC,并且简洁易懂。 27 | 28 | 还有只需要常数级空间的方法,暂时还没读懂,贴个地址:[One-pass constant space Java solution](https://leetcode.com/problems/candy/discuss/42770) -------------------------------------------------------------------------------- /notes/141.Linked_List_Cycle.md: -------------------------------------------------------------------------------- 1 | # Linked List Cycle 2 | 3 | ## 题目 4 | 5 | Given a linked list, determine if it has a cycle in it. 6 | 7 | Follow up: 8 | Can you solve it without using extra space? 9 | 10 | ## 解题思路 11 | 12 | 设置两个哨兵,一个每次往后移动一位,一个每次往后移动两位。如果有环,则两个在移的多的那个到头之前一定会遇见。 13 | 14 | ```java 15 | public class Solution { 16 | public boolean hasCycle(ListNode head) { 17 | if(head != null) { 18 | ListNode walker = head; 19 | ListNode runner = head; 20 | while(runner.next != null && runner.next.next != null) { 21 | walker = walker.next; 22 | runner = runner.next.next; 23 | if(walker == runner) 24 | return true; 25 | } 26 | } 27 | return false; 28 | } 29 | } 30 | ``` 31 | 32 | -------------------------------------------------------------------------------- /notes/172.Factorial_Trailing_Zeroes.md: -------------------------------------------------------------------------------- 1 | # Factorial Trailing Zeroes 2 | 3 | ## 题目 4 | 5 | Given an integer *n*, return the number of trailing zeroes in *n*!. 6 | 7 | **Note:** Your solution should be in logarithmic time complexity. 8 | 9 | ## 解题思路 10 | 11 | 每有一个 5 多一个 0,有一个 25 再额外多一个 0...以此类推。 12 | 13 | 代码: 14 | 15 | ```java 16 | class Solution { 17 | public int trailingZeroes(int n) { 18 | int result = 0; 19 | int times = 1; 20 | while(n >= Math.pow(5, times)) { 21 | result += n / Math.pow(5, times); 22 | times++; 23 | } 24 | return result; 25 | } 26 | } 27 | ``` 28 | 29 | ## 其他方案 30 | 31 | ```java 32 | int ans = 0; 33 | while (n >= 5) { 34 | n /= 5; 35 | ans += n; 36 | } 37 | return ans; 38 | ``` 39 | 40 | 每次算出有多少个 5,多少个 25...一样的思路,少定义一个变量。 -------------------------------------------------------------------------------- /notes/183.Customers_Who_Never_Order.md: -------------------------------------------------------------------------------- 1 | # Customers Who Never Order 2 | 3 | ## 题目 4 | 5 | Suppose that a website contains two tables, the `Customers` table and the `Orders` table. Write a SQL query to find all customers who never order anything. 6 | 7 | Table: `Customers`. 8 | 9 | ``` 10 | +----+-------+ 11 | | Id | Name | 12 | +----+-------+ 13 | | 1 | Joe | 14 | | 2 | Henry | 15 | | 3 | Sam | 16 | | 4 | Max | 17 | +----+-------+ 18 | ``` 19 | 20 | Table: `Orders`. 21 | 22 | ``` 23 | +----+------------+ 24 | | Id | CustomerId | 25 | +----+------------+ 26 | | 1 | 3 | 27 | | 2 | 1 | 28 | +----+------------+ 29 | ``` 30 | 31 | Using the above tables as example, return the following: 32 | 33 | ``` 34 | +-----------+ 35 | | Customers | 36 | +-----------+ 37 | | Henry | 38 | | Max | 39 | +-----------+ 40 | ``` 41 | 42 | ## 解题思路 43 | 44 | ```sql 45 | SELECT Name AS Customers FROM Customers 46 | WHERE Id NOT IN (SELECT CustomerId FROM Orders) 47 | ``` 48 | 49 | 嘛,数据库还是很重要的对吧... 50 | -------------------------------------------------------------------------------- /notes/202.Happy_Number.md: -------------------------------------------------------------------------------- 1 | # Happy Number 2 | 3 | ## 题目 4 | 5 | Write an algorithm to determine if a number is "happy". 6 | 7 | A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 8 | 9 | Example: 19 is a happy number 10 | 11 | ![Happy Number.png](http://upload-images.jianshu.io/upload_images/2702529-98035ac4bcc8edfa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 12 | 13 | ## 解题思路 14 | 15 | 这题比较绕,需要慢慢思考。 16 | 17 | 另外,为了避免无限循环,可以用一个 Set 来存储每次计算得到的结果。如果`set.add(n)`返回 false,说明这次计算得到的结果已经在之前出现过,因此`isHappy()`返回 false。 -------------------------------------------------------------------------------- /notes/203.Remove_Linked_List_Elements.md: -------------------------------------------------------------------------------- 1 | # Remove Linked List Elements 2 | 3 | ## 题目 4 | 5 | Remove all elements from a linked list of integers that have value **val**. 6 | 7 | **Example** 8 | **Given**: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, **val** = 6 9 | **Return**: 1 --> 2 --> 3 --> 4 --> 5 10 | 11 | ## 解题思路 12 | 13 | 注意一些特殊情况即可,比如`[1,1] 1`等。 14 | 15 | ## 其他方案 16 | 17 | ```java 18 | public ListNode removeElements(ListNode head, int val) { 19 | if (head == null) return null; 20 | head.next = removeElements(head.next, val); 21 | return head.val == val ? head.next : head; 22 | } 23 | ``` 24 | 25 | 用递归也可以,但是感觉没有减少时间复杂度,反而增大了空间复杂度(递归需要开辟栈)。 -------------------------------------------------------------------------------- /notes/219.Contains_Duplicate_II.md: -------------------------------------------------------------------------------- 1 | # Contains Duplicate II 2 | 3 | ## 题目 4 | 5 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that **nums[i] = nums[j]** and the **absolute** difference between i and j is at most k. 6 | 7 | ## 解题思路 8 | 9 | Contains Duplicate 这道题可以用 HashSet。这道题需要知道元素在 nums 中的原 index,因此不能再用 HashSet 了。思维很容易扩散到使用 HashMap。对于 nums 中的每个元素,以值为 key,以 index 为 value。若 key 已存在,计算 index 与 value 的差来判断是否返回 true,并更新 index;若 key 不存在,存入。 10 | 11 | 因为这道题的思路在别的课上写的,没有网,所以还写了简单的注释。 12 | 13 | ## 其他方案 14 | 15 | 前面是我的想法,其实 HashSet 也是可以用的。参见 Discuss 中的下述方法: 16 | 17 | ```java 18 | public boolean containsNearbyDuplicate(int[] nums, int k) { 19 | Set set = new HashSet(); 20 | for(int i = 0; i < nums.length; i++){ 21 | if(i > k) set.remove(nums[i-k-1]); 22 | if(!set.add(nums[i])) return true; 23 | } 24 | return false; 25 | } 26 | ``` 27 | 28 | 保证 set 中只有 k 个值。 29 | 30 | -------------------------------------------------------------------------------- /notes/226.Invert_Binary_Tree.md: -------------------------------------------------------------------------------- 1 | # Invert Binary Tree 2 | 3 | ## 题目 4 | 5 | Invert a binary tree. 6 | 7 | ``` 8 | 4 9 | / \ 10 | 2 7 11 | / \ / \ 12 | 1 3 6 9 13 | ``` 14 | 15 | to 16 | 17 | ``` 18 | 4 19 | / \ 20 | 7 2 21 | / \ / \ 22 | 9 6 3 1 23 | ``` 24 | 25 | ## 解题思路 26 | 27 | 左右交换,递归调用。 28 | 29 | ## P.S. 30 | 31 | 原题的题干还有这么几行: 32 | 33 | **Trivia:** 34 | This problem was inspired by this original tweet by Max Howell: 35 | 36 | > Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off. 37 | 38 | 意思是写出 Homebrew 的 Max Howell 因为不会写这个题被 Google 拒了。这是这道题出出来的灵感。 39 | 40 | 是你 LeetCode 飘了,还是我 Max Howell 拿不动刀了?!! 41 | 42 | 43 | -------------------------------------------------------------------------------- /notes/231.Power_of_Two.md: -------------------------------------------------------------------------------- 1 | # Power of Two 2 | 3 | ## 题目 4 | 5 | Given an integer, write a function to determine if it is a power of two. 6 | 7 | ## 解题思路 8 | 9 | 没啥好说的,我先做的 Power of Four... 10 | 11 | ```java 12 | class Solution { 13 | public boolean isPowerOfTwo(int n) { 14 | return (n > 0) && ((n & (n-1)) == 0); 15 | } 16 | } 17 | ``` -------------------------------------------------------------------------------- /notes/232.Implement_Queue_using_Stacks.md: -------------------------------------------------------------------------------- 1 | # Implement Queue using Stacks 2 | 3 | ## 题目 4 | 5 | Implement the following operations of a queue using stacks. 6 | 7 | * push(x) -- Push element x to the back of queue. 8 | * pop() -- Removes the element from in front of queue. 9 | * peek() -- Get the front element. 10 | * empty() -- Return whether the queue is empty. 11 | 12 | **Notes:** 13 | 14 | * You must use only standard operations of a stack -- which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. 15 | * Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. 16 | * You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). 17 | 18 | 19 | ## 解题思路 20 | 21 | 容易想到只有`push()`方法需要修改,也很简单,再 new 一个栈相互倒腾即可。 -------------------------------------------------------------------------------- /notes/237.Delete_Node_in_a_Linked_List.md: -------------------------------------------------------------------------------- 1 | # Delete Node in a Linked List 2 | 3 | ## 题目 4 | 5 | Write a function to delete a node **(except the tail)** in a singly linked list, given only access to that node. 6 | 7 | Supposed the linked list is `1 -> 2 -> 3 -> 4` and you are given the third node with value `3`, the linked list should become `1 -> 2 -> 4` after calling your function. 8 | 9 | ## 解题思路 10 | 11 | 开始做题时发现,惊了!只给了要删除的结点,没有给首结点。 12 | 13 | 禁锢的思维找不到好方法,无奈看了看 Discuss,发现将要删除的下一个结点的值和指针拷贝到这一个要删除的结点上,删掉下一个结点即可。这才发觉条件中的 **(except the tail)** 别有深意... -------------------------------------------------------------------------------- /notes/242.Valid_Anagram.md: -------------------------------------------------------------------------------- 1 | # Valid Anagram 2 | 3 | ## 题目 4 | 5 | Given two strings s and t, write a function to determine if t is an anagram of s. 6 | 7 | For example, 8 | s = "anagram", t = "nagaram", return true. 9 | s = "rat", t = "car", return false. 10 | 11 | **Note:** 12 | You may assume the string contains only lowercase alphabets. 13 | 14 | **Follow up:** 15 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 16 | 17 | ## 解题思路 18 | 19 | 如果只有小写字母存在的话,用一个长度为 26 的数组存储每个字符出现的次数即可。 20 | 21 | ```java 22 | class Solution { 23 | public boolean isAnagram(String s, String t) { 24 | int[] arr = new int[26]; 25 | for(char ch : s.toCharArray()) 26 | arr[ch - 'a']++; 27 | for(char ch : t.toCharArray()) 28 | arr[ch - 'a']--; 29 | for(int num : arr) 30 | if(num != 0) 31 | return false; 32 | return true; 33 | } 34 | } 35 | ``` 36 | 37 | 如果是包含所有的 unicode,那把数组换成 HashMap 即可。 -------------------------------------------------------------------------------- /notes/257.Binary_Tree_Paths.md: -------------------------------------------------------------------------------- 1 | # Binary Tree Paths 2 | 3 | ## 题目 4 | 5 | Given a binary tree, return all root-to-leaf paths. 6 | 7 | For example, given the following binary tree: 8 | 9 | ``` 10 | 1 11 | / \ 12 | 2 3 13 | \ 14 | 5 15 | ``` 16 | 17 | All root-to-leaf paths are: 18 | 19 | ``` 20 | ["1->2->5", "1->3"] 21 | ``` 22 | 23 | ## 解题思路 24 | 25 | 递归。要注意,只有当一个节点没有左右字节点时,才将对应的字符串加入队列,否则不是叶子节点,继续向下遍历。 26 | 27 | Run time 15ms,打败了 90.69% 的 Java 玩家。 28 | 29 | Discuss 里的做法差不多,处理字符串稍有不同。 -------------------------------------------------------------------------------- /notes/26.Remove_Duplicates_from_Sorted_Array.md: -------------------------------------------------------------------------------- 1 | # Remove Duplicates from Sorted Array 2 | 3 | ## 题目 4 | 5 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 6 | 7 | Do not allocate extra space for another array, you must do this in place with constant memory. 8 | 9 | For example, 10 | Given input array nums = `[1,1,2]`, 11 | 12 | Your function should return length = `2`, with the first two elements of nums being `1` and `2` respectively. It doesn't matter what you leave beyond the new length. 13 | 14 | ## 解题思路 15 | 16 | 思路上没什么好说的,O(n) 应该就是最佳实践。主要是注意,题目要求在返回不冗余数组的长度的同时,要将原来的数组前一部分变为不冗余数组,之后的部分不做要求。像我这样的英语渣可能对这个要求就没能注意和理解,有点坑...(话说这题截至我做为止有 171 个赞,615 个反对,不会很多人都被这个条件坑了吧...) 17 | 18 | -------------------------------------------------------------------------------- /notes/263.Ugly_Number.md: -------------------------------------------------------------------------------- 1 | # Ugly Number 2 | 3 | ## 题目 4 | 5 | Write a program to check whether a given number is an ugly number. 6 | 7 | Ugly numbers are positive numbers whose prime factors only include `2, 3, 5`. For example, `6, 8` are ugly while `14` is not ugly since it includes another prime factor `7`. 8 | 9 | Note that `1` is typically treated as an ugly number. 10 | 11 | ## 解题思路 12 | 13 | ```java 14 | class Solution { 15 | public boolean isUgly(int num) { 16 | if(num <= 0) 17 | return false; 18 | while(num % 2 == 0) 19 | num /= 2; 20 | while(num % 3 == 0) 21 | num /= 3; 22 | while(num % 5 == 0) 23 | num /= 5; 24 | return (num == 1); 25 | } 26 | } 27 | ``` 28 | 29 | 比较粗心,写错了好几次...另外,所有非正整数全部返回 false。 -------------------------------------------------------------------------------- /notes/268.Missing_Number.md: -------------------------------------------------------------------------------- 1 | # Missing Number 2 | 3 | ## 题目 4 | 5 | Given an array containing n distinct numbers taken from `0, 1, 2, ..., n`, find the one that is missing from the array. 6 | 7 | For example, 8 | Given nums = `[0, 1, 3]` return `2`. 9 | 10 | **Note:** 11 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 12 | 13 | ## 解题思路 14 | 15 | 方法的参数为 int 类型数组 nums。根据题意,n = nums.length + 1。则开一个 boolean 数组来存储数字是否出现。 16 | 17 | ## 优化思路 18 | 19 | 根据`n ^ n = 0, n ^ 0 = n`,我们可以利用按位异或来优化。优化的解法写在相应的 js 文件里了。 20 | 21 | 然而不知道为什么,前面一种解法用 Java 写的,1ms;后面这种用 JavaScript 写的,122ms。js 日常风评被害... 22 | 23 | 看了一下 Discuss,同用按位异或,以下方法应该要更快(因为遍历次数较少): 24 | 25 | ```java 26 | public int missingNumber(int[] nums) { 27 | 28 | int xor = 0, i = 0; 29 | for (i = 0; i < nums.length; i++) { 30 | xor = xor ^ i ^ nums[i]; 31 | } 32 | 33 | return xor ^ i; 34 | } 35 | ``` -------------------------------------------------------------------------------- /notes/27.Remove_Element.md: -------------------------------------------------------------------------------- 1 | # Remove Element 2 | 3 | ## 题目 4 | 5 | Given an array and a value, remove all instances of that value in place and return the new length. 6 | 7 | Do not allocate extra space for another array, you must do this in place with constant memory. 8 | 9 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 10 | 11 | **Example:** 12 | Given input array nums = `[3,2,2,3]`, val = `3` 13 | 14 | Your function should return length = 2, with the first two elements of nums being 2. 15 | 16 | ## 注意点 17 | 18 | 解题思路没什么好说的,全部要遍历一遍,O(n)。注意点有以下几个: 19 | 20 | 1. 注意 if 条件里的 i++ 在 if 的作用域之前就执行了,在 if 的作用域里再调用 i 已经加 1 了; 21 | 2. 充分简化代码,去掉不必要的变量。例如这一题一开始写了一个 result 来计算最终数组的长度,其实返回 i 就行,很傻。还是**要在代码简化方面下一些心思**。 22 | 23 | -------------------------------------------------------------------------------- /notes/292.Nim_Game.md: -------------------------------------------------------------------------------- 1 | # Nim Game 2 | 3 | ## 题目 4 | 5 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 6 | 7 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 8 | 9 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 10 | 11 | ## 解题思路 12 | 13 | 小学奥数题。 -------------------------------------------------------------------------------- /notes/303.Range_Sum_Query-Immutable.md: -------------------------------------------------------------------------------- 1 | # Range Sum Query - Immutable 2 | 3 | ## 题目 4 | 5 | Given an integer array *nums*, find the sum of the elements between indices *i* and *j* (i ≤ j), inclusive. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Given nums = [-2, 0, 3, -5, 2, -1] 11 | 12 | sumRange(0, 2) -> 1 13 | sumRange(2, 5) -> -1 14 | sumRange(0, 5) -> -3 15 | ``` 16 | 17 | **Note:** 18 | 19 | 1. You may assume that the array does not change. 20 | 2. There are many calls to *sumRange* function. 21 | 22 | ## 解题思路 23 | 24 | 提示说会对 *sumRange* 函数进行多次调用,所以不能在每次调用时根据参数再来计算。或者说,要将 *sumRange* 函数的时间复杂度控制在 O(1)。 25 | 26 | 根据动态规划思想,很容易想到用一个数组来存储从 0 到 i 的元素和,取出时最多做一个减法即可。 -------------------------------------------------------------------------------- /notes/32.Longest_Valid_Parentheses.md: -------------------------------------------------------------------------------- 1 | # Longest Valid Parentheses 2 | 3 | ## 题目 4 | 5 | Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring. 6 | 7 | For `"(()"`, the longest valid parentheses substring is `"()"`, which has length = 2. 8 | 9 | Another example is `")()())"`, where the longest valid parentheses substring is `"()()"`, which has length = 4. 10 | 11 | 12 | -------------------------------------------------------------------------------- /notes/344.Reverse_String.md: -------------------------------------------------------------------------------- 1 | # Reverse String 2 | 3 | ## 题目 4 | 5 | Write a function that takes a string as input and returns the string reversed. 6 | 7 | **Example:** 8 | Given s = "hello", return "olleh". 9 | 10 | ## 解题思路 11 | 12 | 字符串转字符数组,进行二分交换。 -------------------------------------------------------------------------------- /notes/345.Reverse_Vowels_of_a_String.md: -------------------------------------------------------------------------------- 1 | # Reverse Vowels of a String 2 | 3 | ## 题目 4 | 5 | Write a function that takes a string as input and reverse only the vowels of a string. 6 | 7 | **Example 1:** 8 | Given s = "hello", return "holle". 9 | 10 | **Example 2:** 11 | Given s = "leetcode", return "leotcede". 12 | 13 | **Note:** 14 | The vowels does not include the letter "y". 15 | 16 | ## 解题思路 17 | 18 | 用一个 HashSet 来存储元音字母,这样查询的时间为 O(1)。然后从两头向里遍历。Run Time 11ms。 19 | 20 | 坑: 21 | 22 | 1. 注意元音字母的大写形式; 23 | 2. 每次交换后记得游标各向内收一位,否则无限循环; 24 | 3. `new String(arr)`可以用于 char[] 转换为 String。 -------------------------------------------------------------------------------- /notes/35.Search_Insert_Position.md: -------------------------------------------------------------------------------- 1 | # Search Insert Position 2 | 3 | ## 题目 4 | 5 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 6 | 7 | You may assume no duplicates in the array. 8 | 9 | Here are few examples. 10 | `[1,3,5,6]`, 5 → 2 11 | `[1,3,5,6]`, 2 → 1 12 | `[1,3,5,6]`, 7 → 4 13 | `[1,3,5,6]`, 0 → 0 14 | 15 | ## 疑问 16 | 17 | 一看就知道最好的方法是二分搜索,时间复杂度 logN。然而我用 JavaScript 写怎么都过不了。这里放上的两个版本,Java 版是最后 Accepted 的,我认为我写的 JavaScript 版和 Java 版是一样的。有一个示例机算给的结果和我算的不一样,不知道是什么原因... 18 | -------------------------------------------------------------------------------- /notes/38.Count_and_Say.md: -------------------------------------------------------------------------------- 1 | # Merge Two Sorted Lists 2 | 3 | ## 题目 4 | 5 | The count-and-say sequence is the sequence of integers with the first five terms as following: 6 | 7 | ``` 8 | 1. 1 9 | 2. 11 10 | 3. 21 11 | 4. 1211 12 | 5. 111221 13 | ``` 14 | 15 | `1` is read off as `"one 1"` or `11`. 16 | `11` is read off as `"two 1s"` or `21`. 17 | `21` is read off as `"one 2`, then `one 1"` or `1211`. 18 | 19 | Given an integer n, generate the nth term of the count-and-say sequence. 20 | 21 | Note: Each term of the sequence of integers will be represented as a string. 22 | 23 | **Example 1:** 24 | 25 | ``` 26 | Input: 1 27 | Output: "1" 28 | ``` 29 | 30 | **Example 2:** 31 | 32 | ``` 33 | Input: 4 34 | Output: "1211" 35 | ``` 36 | 37 | ## 解题思路 38 | 39 | `countAndSay(n)`要通过处理`countAndSay(n-1)`得到,因此要用递归。 40 | 41 | 没太多好说的,就是写的时候花的时间比较多,原因有: 42 | 43 | * 我都不记得 Java 有没有块作用域了...药丸 44 | * 把 char 变为 int,要`Integer.valueOf(prevSay[i] - '0')`; 45 | * 两个 int 变量加到 String 上不能累加,否则这两个 int 会自己先加。可以用`String.valueOf()`处理。 -------------------------------------------------------------------------------- /notes/383.Ransom_Note.md: -------------------------------------------------------------------------------- 1 | # Ransom Note 2 | 3 | ## 题目 4 | 5 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 6 | 7 | Each letter in the magazine string can only be used once in your ransom note. 8 | 9 | **Note:** 10 | You may assume that both strings contain only lowercase letters. 11 | 12 | ``` 13 | canConstruct("a", "b") -> false 14 | canConstruct("aa", "ab") -> false 15 | canConstruct("aa", "aab") -> true 16 | ``` 17 | 18 | ## 解题思路 19 | 20 | 开一个数组来存储字母出现次数。 -------------------------------------------------------------------------------- /notes/387.First_Unique_Character_in_a_String.md: -------------------------------------------------------------------------------- 1 | # First Unique Character in a String 2 | 3 | ## 题目 4 | 5 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 6 | 7 | **Examples:** 8 | 9 | ``` 10 | s = "leetcode" 11 | return 0. 12 | 13 | s = "loveleetcode", 14 | return 2. 15 | ``` 16 | 17 | **Note:** You may assume the string contain only lowercase letters. 18 | 19 | ## 解题思路 20 | 21 | 建一个长度为 26 的数组存储字母出现的次数。总共需要遍历两次,复杂度 O(n)。和 Discuss 里提供的方法思路一致。 22 | 23 | -------------------------------------------------------------------------------- /notes/389.Find_the_Difference.md: -------------------------------------------------------------------------------- 1 | # Find the Difference 2 | 3 | ## 题目 4 | 5 | Given two strings **s** and **t** which consist of only lowercase letters. 6 | 7 | String **t** is generated by random shuffling string **s** and then add one more letter at a random position. 8 | 9 | Find the letter that was added in **t**. 10 | 11 | **Example:** 12 | 13 | ``` 14 | Input: 15 | s = "abcd" 16 | t = "abcde" 17 | 18 | Output: 19 | e 20 | 21 | Explanation: 22 | 'e' is the letter that was added. 23 | ``` 24 | 25 | ## 解题思路 26 | 27 | 因为题目说明单词里只有小写字母,因此建一个长度为 26 的数组来记录字母出现的次数。用有 char 类型的语言写这题会在取目录值的时候方便一点。 28 | 29 | ## 其他思路 30 | 31 | 上面这个方法已经很快了。因此下面这个方法也不算最优解法。只是一种不同的思路。 32 | 33 | ```java 34 | public char findTheDifference(String s, String t) { 35 | int n = t.length(); 36 | char c = t.charAt(n - 1); 37 | for (int i = 0; i < n - 1; ++i) { 38 | c ^= s.charAt(i); 39 | c ^= t.charAt(i); 40 | } 41 | return c; 42 | } 43 | ``` 44 | 45 | char 类型本质上和 int 没什么区别,因此找那个不一样的也可以用按位取反。 -------------------------------------------------------------------------------- /notes/409.Longest_Palindrome.md: -------------------------------------------------------------------------------- 1 | # Longest Palindrome 2 | 3 | ## 题目 4 | 5 | Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. 6 | 7 | This is case sensitive, for example `"Aa"` is not considered a palindrome here. 8 | 9 | **Note:** 10 | Assume the length of given string will not exceed 1,010. 11 | 12 | **Example:** 13 | 14 | ``` 15 | Input: 16 | "abccccdd" 17 | 18 | Output: 19 | 7 20 | 21 | Explanation: 22 | One longest palindrome that can be built is "dccaccd", whose length is 7. 23 | ``` 24 | 25 | ## 解题思路 26 | 27 | 没啥好说的。出现次数若为偶数全加上,第一次出现的奇数加上,其他的奇数减一。 -------------------------------------------------------------------------------- /notes/412.Fizz_Buzz.md: -------------------------------------------------------------------------------- 1 | # Fizz Buzz 2 | 3 | ## 题目 4 | 5 | Write a program that outputs the string representation of numbers from 1 to n. 6 | 7 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 8 | 9 | **Example:** 10 | 11 | ``` 12 | n = 15, 13 | 14 | Return: 15 | [ 16 | "1", 17 | "2", 18 | "Fizz", 19 | "4", 20 | "Buzz", 21 | "Fizz", 22 | "7", 23 | "8", 24 | "Fizz", 25 | "Buzz", 26 | "11", 27 | "Fizz", 28 | "13", 29 | "14", 30 | "FizzBuzz" 31 | ] 32 | ``` 33 | 34 | ## 解题思路 35 | 36 | nothing to say -------------------------------------------------------------------------------- /notes/434.Number_of_Segments_in_a_String.md: -------------------------------------------------------------------------------- 1 | # Number of Segments in a String 2 | 3 | ## 题目 4 | 5 | Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. 6 | 7 | Please note that the string does not contain any non-printable characters. 8 | 9 | **Example:** 10 | 11 | ``` 12 | Input: "Hello, my name is John" 13 | Output: 5 14 | ``` 15 | 16 | ## 解题思路 17 | 18 | 因为对于 JavaScript 中的正则相关方法比 Java 熟悉一些,所以用 JS 写的。 19 | 20 | 对`""`、`" "`要先做一个判断。然后用`trim()`和`split()`方法解决。 21 | 22 | Run Time 75ms,打败 87.93% 的 JS 玩家。 -------------------------------------------------------------------------------- /notes/442.Find_All_Duplicates_in_an_Array.md: -------------------------------------------------------------------------------- 1 | # Find All Duplicates in an Array 2 | 3 | ## 题目 4 | 5 | Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear **twice** and others appear **once**. 6 | 7 | Find all the elements that appear **twice** in this array. 8 | 9 | Could you do it without extra space and in O(n) runtime? 10 | 11 | **Example:** 12 | 13 | ``` 14 | Input: 15 | [4,3,2,7,8,2,3,1] 16 | 17 | Output: 18 | [2,3] 19 | ``` 20 | 21 | ## 解题过程 22 | 23 | 初始思路是建一个大小为 n 的数组来存储出现次数。用这个思路很快 Accepted,除了不太熟悉 List 而写错了两次靠 Run Code 改正外...这个方法时间复杂度为 O(n),但开辟了新空间。所以找优化算法。 24 | 25 | 感觉优化的关键点在:数组里的数大小限制在 1 到 n 之间,以及每个数只会出现 0、1、2 26 | 次。 27 | 28 | ### 看完 Discuss 后... 29 | 30 | 对关键点的判断是对的,但我往交换方向想的...Discuss 里的解法是,for 循环数组每到一个元素,将元素值的绝对值 -1 作为索引找到数组对应元素,若为正数则乘一个 -1,若为负说明之前已经出现过一次,放入 list 中。 31 | 32 | 嗯...巧妙的用了一个负数解决问题... 33 | 34 | 用 Python 将这个算法实现了,练练手。 -------------------------------------------------------------------------------- /notes/453.Minimum_Moves_to_Equal_Array_Elements.md: -------------------------------------------------------------------------------- 1 | # Minimum Moves to Equal Array Elements 2 | 3 | ## 题目 4 | 5 | Given a **non-empty** integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: 11 | [1,2,3] 12 | 13 | Output: 14 | 3 15 | 16 | Explanation: 17 | Only three moves are needed (remember each move increments two elements): 18 | 19 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 20 | ``` 21 | 22 | ## 解题思路 23 | 24 | 逆向思维。每次将长度为 n 的数组里的 n - 1 个元素 +1,相当于给一个元素 -1。那么每次一个元素 -1,直到所有元素都跟数组中原本的最小的元素相等即可。即把题目所求变为求数组所有元素之和 - 最小元素值 * n。 25 | 26 | -------------------------------------------------------------------------------- /notes/53.Maximum_Subarray.md: -------------------------------------------------------------------------------- 1 | # Maximum Subarray 2 | 3 | ## 题目 4 | 5 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 6 | 7 | For example, given the array `[-2,1,-3,4,-1,2,1,-5,4]`, 8 | the contiguous subarray `[4,-1,2,1]` has the largest sum = `6`. 9 | 10 | ## 解题思路 11 | 12 | 动态规划。难点是找到合适的状态和状态转移方程。 13 | 14 | 一开始我想的是`d(i)`为 0 - i 的子数组中最大和。然后找不到状态转移方程。 15 | 16 | 比较合适的应该是`d(i)`为**包含第 i 个元素的子数组中的最大和**。那么有`d(i) = (d(i-1) > 0) ? d(i-1) + nums[i] : nums[i]`。 17 | 18 | 然后,用一个变量记录所求的最大和的值,和每个`d(i)`进行比较即可。 19 | 20 | 我的解法是用了数组来存储`d(i)`,当然,用一个变量来记录`d(i-1)`足矣。 21 | 22 | ## P.S. 23 | 24 | 上周去参加今日头条实习的笔试时,第一题是这样的: 25 | 26 | 给定一个数组,找出其不相邻的两个连续子数组,使这两个子数组所含的所有元素的和最大,求这个和的最大值。 27 | 28 | 目前的思路是用一个哨兵变量从 1 到 n-1,每次将数组先划分为左右子数组,再分别在每个子数组中再通过动态规划找一个元素和最大的子数组。 -------------------------------------------------------------------------------- /notes/537.Complex_Number_Multiplication.md: -------------------------------------------------------------------------------- 1 | # Complex Number Multiplication 2 | 3 | ## 题目 4 | 5 | Given two strings representing two complex numbers. 6 | 7 | You need to return a string representing their multiplication. Note i**2 = -1 according to the definition. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: "1+1i", "1+1i" 13 | Output: "0+2i" 14 | Explanation: (1 + i) * (1 + i) = 1 + i**2 + 2 * i = 2i, and you need convert it to the form of 0+2i. 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: "1+-1i", "1+-1i" 21 | Output: "0+-2i" 22 | Explanation: (1 - i) * (1 - i) = 1 + i**2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. 23 | ``` 24 | 25 | **Note:** 26 | 27 | 1. The input strings will not have extra blank. 28 | 2. The input strings will be given in the form of **a+bi**, where the integer **a** and **b** will both belong to the range of [-100, 100]. And **the output should be also in this form**. 29 | 30 | ## 解题思路 31 | 32 | 用`split()`分割再进行处理。 -------------------------------------------------------------------------------- /notes/561.Array_Partition_I.md: -------------------------------------------------------------------------------- 1 | # Array Partition I 2 | 3 | ## 题目 4 | 5 | Given an array of **2n** integers, your task is to group these integers into **n** pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: [1,4,3,2] 11 | 12 | Output: 4 13 | Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). 14 | ``` 15 | 16 | **Note:** 17 | 18 | 1. **n** is a positive integer, which is in the range of [1, 10000]. 19 | 2. All the integers in the array will be in the range of [-10000, 10000]. 20 | 21 | 22 | ## 解题思路 23 | 24 | 申清题意即可知,将数组由小到大排序,再两两结对,这样获得每对里的最小值之和是最大的。 25 | 26 | -------------------------------------------------------------------------------- /notes/637.Average_of_Levels_in_Binary_Tree.md: -------------------------------------------------------------------------------- 1 | # Average of Levels in Binary Tree 2 | 3 | ## 题目 4 | 5 | Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 11 | 3 12 | / \ 13 | 9 20 14 | / \ 15 | 15 7 16 | Output: [3, 14.5, 11] 17 | Explanation: 18 | The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. 19 | ``` 20 | 21 | **Note:** 22 | 23 | 1. The range of node's value is in the range of 32-bit signed integer. 24 | 25 | 26 | ## 解题思路 27 | 28 | 用一个队列(`LinkedList`)来 BFS。Run Time 10ms,打败了 76.43% 的 Java 玩家。 29 | 30 | 另附一个 Java 队列的概括性文章(对相关方法确实不熟):[java中queue的使用 - 风生水起 - 博客园](https://www.cnblogs.com/end/archive/2012/10/25/2738493.html) -------------------------------------------------------------------------------- /notes/643.Maximum_Average_Subarray_I.md: -------------------------------------------------------------------------------- 1 | # Maximum Average Subarray I 2 | 3 | ## 题目 4 | 5 | Given an array consisting of `n` integers, find the contiguous subarray of given length `k` that has the maximum average value. And you need to output the maximum average value. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: [1,12,-5,-6,50,3], k = 4 11 | Output: 12.75 12 | Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 13 | ``` 14 | 15 | **Note:** 16 | 17 | 1. 1 <= `k` <= `n` <= 30,000. 18 | 2. Elements of the given array will be in the range [-10,000, 10,000]. 19 | 20 | ## 解题思路 21 | 22 | sliding window。每次删一个元素加一个元素即可,不用每次都累加。 -------------------------------------------------------------------------------- /notes/654.Maximum_Binary_Tree.md: -------------------------------------------------------------------------------- 1 | # First Bad Version 2 | 3 | ## 题目 4 | 5 | Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: 6 | 7 | 1. The root is the maximum number in the array. 8 | 2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. 9 | 3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number. 10 | 11 | Construct the maximum tree by the given array and output the root node of this tree. 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: [3,2,1,6,0,5] 17 | Output: return the tree root node representing the following tree: 18 | 19 | 6 20 | / \ 21 | 3 5 22 | \ / 23 | 2 0 24 | \ 25 | 1 26 | ``` 27 | 28 | **Note:** 29 | 30 | 1. The size of the given array will be in the range [1,1000]. 31 | 32 | 33 | ## 解题思路 34 | 35 | 递归。 36 | 37 | 开始的时候想的比较复杂,想要复制创建子数组。其实只要用传 nums 本身,用 index 控制就行了。 38 | 39 | 尽量在递归函数中减少判断,容易把自己绕糊涂。 -------------------------------------------------------------------------------- /notes/657.Judge_Route_Circle.md: -------------------------------------------------------------------------------- 1 | # Judge Route Circle 2 | 3 | ## 题目 4 | 5 | Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to **the original place**. 6 | 7 | The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are `R` (Right), `L` (Left), `U` (Up) and `D` (down). The output should be true or false representing whether the robot makes a circle. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: "UD" 13 | Output: true 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: "LL" 20 | Output: false 21 | ``` 22 | 23 | ## 解题思路 24 | 25 | 没啥好说的。直接用两个 int 类型变量来存储,比开辟一个 int 数组的开销稍微小一点(废话)。 -------------------------------------------------------------------------------- /notes/67.Add_Binary.md: -------------------------------------------------------------------------------- 1 | # Add Binary 2 | 3 | ## 题目 4 | 5 | Given two binary strings, return their sum (also a binary string). 6 | 7 | For example, 8 | a = `"11"` 9 | b = `"1"` 10 | Return `"100"`. 11 | 12 | ## 解题思路 13 | 14 | 通过一个变量`carry = sum / 2`记录进位,用`sum % 2`表示当前位结果。代码如下: 15 | 16 | ```java 17 | class Solution { 18 | public String addBinary(String a, String b) { 19 | StringBuilder sb = new StringBuilder(); 20 | int carry = 0; 21 | for(int i = a.length()-1, j = b.length()-1; i >= 0 || j >= 0; i--, j--) { 22 | int sum = carry; 23 | if(i >= 0) 24 | sum += a.charAt(i) - '0'; 25 | if(j >= 0) 26 | sum += b.charAt(j) - '0'; 27 | sb.append(sum % 2); 28 | carry = sum / 2; 29 | } 30 | if(carry != 0) 31 | sb.append(carry); 32 | return sb.reverse().toString(); 33 | } 34 | } 35 | ``` -------------------------------------------------------------------------------- /notes/677.Map_Sum_Pairs.md: -------------------------------------------------------------------------------- 1 | # Map Sum Pairs 2 | 3 | ## 题目 4 | 5 | Implement a MapSum class with `insert`, and `sum` methods. 6 | 7 | For the method `insert`, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one. 8 | 9 | For the method `sum`, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value **whose key starts with the prefix**. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: insert("apple", 3), Output: Null 15 | Input: sum("ap"), Output: 3 16 | Input: insert("app", 2), Output: Null 17 | Input: sum("ap"), Output: 5 18 | ``` 19 | 20 | ## 解题思路 21 | 22 | 没啥,就比较考对 HashMap 的了解,以及注意子串要在父串的起始位置。 23 | 24 | ## 其他解法 25 | 26 | 弄个结点弄个链。 -------------------------------------------------------------------------------- /notes/796.Rotate_String.md: -------------------------------------------------------------------------------- 1 | # Rotate String 2 | 3 | ## 题目 4 | 5 | We are given two strings, `A` and `B`. 6 | 7 | `A` shift on `A` consists of taking string `A` and moving the leftmost character to the rightmost position. For example, if `A = 'abcde'`, then it will be `'bcdea'` after one shift on `A`. Return `True` if and only if `A` can become `B` after some number of shifts on `A`. 8 | 9 | ``` 10 | Example 1: 11 | Input: A = 'abcde', B = 'cdeab' 12 | Output: true 13 | 14 | Example 2: 15 | Input: A = 'abcde', B = 'abced' 16 | Output: false 17 | ``` 18 | 19 | **Note:** 20 | 21 | * A and B will have length at most 100. 22 | 23 | 24 | ## 解题思路 25 | 26 | 比较容易想到,将源字符串拼接一次,通过`contains`就可以判断了。不过还要对字符串的长度做一个判断。代码如下: 27 | 28 | ```java 29 | class Solution { 30 | public boolean rotateString(String A, String B) { 31 | return A.length() == B.length() && (A+A).contains(B); 32 | } 33 | } 34 | ``` -------------------------------------------------------------------------------- /notes/83.Remove_Duplicates_from_Sorted_List.md: -------------------------------------------------------------------------------- 1 | # Remove Duplicates from Sorted List 2 | 3 | ## 题目 4 | 5 | Given a sorted linked list, delete all duplicates such that each element appear only *once*. 6 | 7 | For example, 8 | Given `1->1->2`, return `1->2`. 9 | Given `1->1->2->3->3`, return `1->2->3`. 10 | 11 | ## 解题思路 12 | 13 | 把为 null 的情况考虑好,还是比较简单的。 14 | 15 | ## 其他方案 16 | 17 | 我提供的解法算是比较好想的。Discuss 里有提供递归解法,不是很好想,但代码量小,且比较优雅: 18 | 19 | ```java 20 | public ListNode deleteDuplicates(ListNode head) { 21 | if(head == null || head.next == null)return head; 22 | head.next = deleteDuplicates(head.next); 23 | return head.val == head.next.val ? head.next : head; 24 | } 25 | ``` -------------------------------------------------------------------------------- /notes/88.Merge_Sorted_Array.md: -------------------------------------------------------------------------------- 1 | # Merge Sorted Array 2 | 3 | ## 题目 4 | 5 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 6 | 7 | **Note:** 8 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. 9 | 10 | ## 解题思路 11 | 12 | 倒着塞。 --------------------------------------------------------------------------------