├── .gitignore ├── solutions ├── 193.Valid_Phone_Numbers │ ├── file.txt │ ├── AC_egrep.sh │ ├── AC_grep.sh │ ├── AC_awk.sh │ ├── AC_sed.sh │ └── readme.md ├── 195.Tenth_Line │ ├── AC_sed.sh │ ├── AC_awk.sh │ └── readme.md ├── 196.Delete_Duplicate_Emails │ └── AC_delete.sql ├── 183.Customers_Who_Never_Order │ ├── AC_in.sql │ ├── AC_left_join.sql │ ├── AC_exists.sql │ └── readme.md ├── 197.Rising_Temperature │ ├── AC_TO_DAYS.sql │ ├── readme.md │ └── AC_CASE_WHEN.sql ├── 181.Employees_Earning_More_Than_Their_Managers │ ├── AC_join.sql │ └── AC_inner_join.sql ├── 182.Duplicate_Emails │ └── AC_join.sql ├── 176.Second_Highest_Salary │ └── AC_max.sql ├── 192.Word_Frequency │ ├── AC_tr_uniq.sh │ └── AC_awk.sh ├── 175.Combine_Two_Tables │ └── AC_left_join.sql ├── 178.Rank_Scores │ ├── AC_order.sql │ ├── readme.md │ └── AC_variables.sql ├── 326.Power_of_Three │ ├── AC_tricky1_1.py │ ├── AC_tricky2_1.java │ ├── AC_normal_logn.java │ ├── AC_math_1.cpp │ └── readme.md ├── 194.Transpose_File │ ├── readme.md │ └── AC_awk.sh ├── 184.Department_Highest_Salary │ ├── AC_MAX.sql │ └── readme.md ├── 006.ZigZag_Conversion │ ├── readme.md │ └── AC_simulation_n.py ├── 223.Rectangle_Area │ ├── readme.md │ └── AC_simulation_1.cpp ├── 014.Longest_Common_Prefix │ ├── readme.md │ ├── AC_bruteforce_n2.py │ └── AC_bruteforce_n2.java ├── 257.Binary_Tree_Paths │ └── readme.md ├── 263.Ugly_Number │ ├── readme.md │ ├── AC_simulation_1.py │ └── AC_simulation_1.cpp ├── 180.Consecutive_Numbers │ ├── AC_triple_join.sql │ ├── AC_case_when.sql │ └── readme.md ├── 278.First_Bad_Version │ ├── readme.md │ ├── AC_binary_search_logn.py │ ├── AC_dfs_logn.py │ └── AC_binary_search_logn.cpp ├── 166.Fraction_to_Recurring_Decimal │ └── readme.md ├── 242.Valid_Anagram │ ├── readme.md │ ├── AC_simulation_nlogn.py │ └── AC_simulation_n.cpp ├── 016.3Sum_Closest │ └── readme.md ├── 200.Number_of_Islands │ └── readme.md ├── 203.Remove_Linked_List_Elements │ ├── README.md │ └── AC_simulation_n.py ├── 024.Swap_Nodes_in_Pairs │ └── readme.md ├── 027.Remove_Element │ ├── readme.md │ └── AC_simulate_n.cpp ├── 124.Binary_Tree_Maximum_Path_Sum │ └── readme.md ├── 205.Isomorphic_Strings │ ├── README.md │ └── AC_dict_n.py ├── 017.Letter_Combinations_of_a_Phone_Number │ └── readme.md ├── 136.Single_Number │ ├── readme.md │ └── AC_xor_n.cpp ├── 237.Delete_Node_in_a_Linked_List │ ├── readme.md │ ├── AC_simulation_1.py │ └── AC_simulation_1.cpp ├── 334.Increasing_Triplet_Subsequence │ └── readme.md ├── 009.Palindrome_Number │ ├── readme.md │ ├── AC_simulation_n.py │ ├── AC_simulation2_n.py │ ├── AC_simulation2_n.cpp │ ├── AC_simulation2_n.java │ └── AC_simulation_n.cpp ├── 102.Binary_Tree_Level_Order_Traversal │ ├── readme.md │ └── AC_dfs_n.py ├── 177.Nth_Highest_Salary │ ├── AC_LIMIT.sql │ └── readme.md ├── 231.Power_of_Two │ ├── readme.md │ ├── AC_bitwize_1.py │ ├── AC_bitwize2_1.cpp │ └── AC_bitwize_1.cpp ├── 268.Missing_Number │ ├── AC_simulation_n.py │ ├── readme.md │ ├── AC_xor_n.java │ └── AC_simulation_n.cpp ├── 013.Roman_to_Integer │ ├── readme.md │ └── AC_simulation_1.py ├── 015.3Sum │ └── readme.md ├── 025.Reverse_Nodes_in_k-Group │ └── readme.md ├── 040.Combination_Sum_II │ └── readme.md ├── 131.Palindrome_Partitioning │ └── readme.md ├── 290.Word_Pattern │ └── readme.md ├── 035.Search_Insert_Position │ └── readme.md ├── 038.Count_and_Say │ ├── readme.md │ └── AC_simulation_n.py ├── 107.Binary_Tree_Level_Order_Traversal_II │ └── readme.md ├── 207.Course_Schedule │ └── readme.md ├── 228.Summary_Ranges │ ├── readme.md │ └── AC_simulation_n.py ├── 328.Odd_Even_Linked_List │ ├── readme.md │ └── AC_double_n.py ├── 021.Merge_Two_Sorted_Lists │ └── readme.md ├── 108.Convert_Sorted_Array_to_Binary_Search_Tree │ └── readme.md ├── 190.Reverse_Bits │ ├── AC_one_line_n.java │ ├── readme.md │ ├── AC_one_line_n.py │ └── AC_bitset_n.cpp ├── 208.Implement_Trie_(Prefix_Tree) │ └── readme.md ├── 034.Search_for_a_Range │ └── readme.md ├── 068.Text_Justification │ └── readme.md ├── 105.Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal │ └── readme.md ├── 007.Reverse_Integer │ ├── readme.md │ ├── AC_simulation_n.py │ ├── AC_simulation_n.cpp │ └── AC_simulation_n.java ├── 039.Combination_Sum │ └── readme.md ├── 198.House_Robber │ ├── readme.md │ └── AC_dp_n.cpp ├── 012.Integer_to_Roman │ ├── readme.md │ └── AC_simulation_1.py ├── 033.Search_in_Rotated_Sorted_Array │ └── readme.md ├── 109.Convert_Sorted_List_to_Binary_Search_Tree │ └── readme.md ├── 241.Different_Ways_to_Add_Parentheses │ └── readme.md ├── 258.Add_Digits │ ├── AC_mod_1.py │ ├── readme.md │ └── AC_simulation_n.cpp ├── 022.Generate_Parentheses │ ├── readme.md │ └── AC_dfs_less2^n.py ├── 103.Binary_Tree_Zigzag_Level_Order_Traversal │ └── readme.md ├── 150.Evaluate_Reverse_Polish_Notation │ └── readme.md ├── 114.Flatten_Binary_Tree_to_Linked_List │ └── readme.md ├── 154.Find_Minimum_in_Rotated_Sorted_Array_II │ ├── AC_lazy_n.py │ └── README.md ├── 155.Min_Stack │ └── readme.md ├── 199.Binary_Tree_Right_Side_View │ └── readme.md ├── 029.Divide_Two_Integers │ ├── readme.md │ └── AC_binary_nlogn.py ├── 096.Unique_Binary_Search_Trees_II │ └── readme.md ├── 121.Best_Time_to_Buy_and_Sell_Stock │ ├── readme.md │ ├── AC_simulatoin_n.py │ └── AC_simulatoin_n.cpp ├── 151.Reverse_Words_in_a_String │ ├── AC_split_n.py │ ├── readme.md │ ├── AC_stringstream_n.cpp │ └── AC_split_n.java ├── 283.Move_Zeroes │ ├── readme.md │ ├── AC_stl_n.cpp │ └── AC_two_point_n.cpp ├── 126.Word_Ladder │ └── readme.md ├── 292.Nim_Game │ ├── AC_nim_1.cpp │ └── readme.md ├── 019.Remove_Nth_Node_From_End_of_List │ ├── readme.md │ └── AC_two_point_n.py ├── 201.Bitwise_AND_of_Numbers_Range │ ├── README.md │ ├── AC_loop_logn.cpp │ └── AC_math_1.py ├── 020.Valid_Parentheses │ ├── readme.md │ └── AC_stack_dict_n.py ├── 172.Factorial_Trailing_Zeroes │ ├── AC_math_logn.py │ ├── AC_math_logn.cpp │ └── AC_math_logn.java ├── 171.Excel_Sheet_Column_Number │ ├── AC_simulation_1.py │ ├── AC_simulation_1.cpp │ └── AC_simulation_1.java ├── 216.Combination_Sum_III │ └── readme.md ├── 224.Basic_Calculator │ └── readme.md ├── 235.Lowest_Common_Ancestor_of_a_Binary_Search_Tree │ └── readme.md ├── 093.Restore_IP_Addresses │ ├── readme.md │ └── AC_for_27.py ├── 106.Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal │ └── readme.md ├── 153.Find_Minimum_in_Rotated_Sorted_Array │ └── readme.md ├── 089.Gray_Code │ ├── AC_simulation_2^n.py │ ├── AC_simulation_2^n.java │ └── AC_simulation_2^n.cpp ├── 217.Contains_Duplicate │ ├── readme.md │ ├── AC_set_nlogn.py │ ├── AC_set_nlogn.cpp │ ├── AC_sort_nlogn.cpp │ ├── AC_map_nlogn.cpp │ └── TLE_brute_force_n2.cpp ├── 008.String_to_Integer │ ├── readme.md │ └── AC_regex_n.py ├── 215.Kth_Largest_Element_in_an_Array │ ├── AC_sort_nlogn.py │ ├── AC_sort_nlogn.cpp │ ├── AC_priority_queue_nlogn.cpp │ └── readme.md ├── 011.Container_With_Most_Water │ ├── readme.md │ ├── AC_two_points_n.py │ └── AC_two_points_n.cpp ├── 031.Next_Permutation │ ├── readme.md │ └── AC_STL_1.cpp ├── 098.Validate_Binary_Search_Tree │ ├── readme.md │ └── AC_dfs_n.py ├── 010.Regular_Expression_Matching │ ├── AC_regex_n!.py │ └── readme.md ├── 230.Kth_Smallest_Element_in_a_BST │ └── readme.md ├── 026.Remove_Duplicates_from_Sorted_Array │ ├── AC_STL_nlogn.cpp │ ├── readme.md │ └── AC_map_nlogn.cpp ├── 225.Implement_Stack_using_Queues │ ├── readme.md │ └── AC_simulation_1.java ├── 139.Word_Break │ ├── readme.md │ └── AC_dp_n2.py ├── 164.Maximum_Gap │ └── readme.md ├── 069.Sqrt(x) │ ├── AC_Newton_logn.py │ ├── AC_binary_logn.py │ ├── AC_Newton_logn.cpp │ ├── AC_Newton_logn.java │ └── AC_binary_logn.java ├── 189.Rotate_Array │ └── readme.md ├── 238.Product_of_Array_Except_Self │ ├── readme.md │ ├── TLE_brute_force_n2.py │ └── AC_array_n.java ├── 191.Number_of_1_Bits │ ├── AC_bitset_n.cpp │ ├── readme.md │ └── AC_bitwise_n.java ├── 076.Minimum_Window_Substring │ └── readme.md ├── 078.Subsets │ ├── AC_collections_combinations_2^n.py │ └── AC_dfs_2^n.py ├── 122.Best_Time_to_Buy_and_Sell_Stock_II │ ├── readme.md │ ├── AC_greedy_n.py │ └── AC_greedy_n.cpp ├── 134.Gas_Station │ └── readme.md ├── 173.Binary_Search_Tree_Iterator │ └── readme.md ├── 168.Excel_Sheet_Column_Title │ ├── AC_simulation_1.py │ ├── AC_simulation_1.java │ └── AC_simulation_1.cpp ├── 202.Happy_Number │ ├── readme.md │ └── AC_two_point_n.py ├── 232.Implement_Queue_using_Stacks │ └── readme.md ├── 169.Majority_Element │ ├── AC_Moore_n.py │ ├── AC_Moore_n.cpp │ ├── AC_Moore_n.java │ └── AC_Bits_n.py ├── 001.Two_Sum │ └── AC_dict_nlogn.py ├── 003.Longest_Substring_Without_Repeating_Characters │ ├── AC_record_n.py │ └── readme.md ├── 239.Sliding_Window_Maximum │ ├── readme.md │ ├── AC_brute_force_nk.py │ └── AC_multiset_nlogn.cpp ├── 032.Longest_Valid_Parentheses │ └── readme.md ├── 037.Sudoku_Solver │ └── readme.md ├── 005.Longest_Palindromic_Substring │ └── readme.md ├── 210.Course_Schedule_II │ └── readme.md ├── 179.Largest_Number │ └── AC_sort_nlogn.py ├── 002.Add_Two_Numbers │ └── readme.md ├── 132.Palindrome_Partitioning_II │ └── readme.md ├── 188.Best_Time_to_Buy_and_Sell_Stock_IV │ └── readme.md ├── 071.Simplify_Path │ └── AC_simulation_n.py ├── 060.Permutation_Sequence │ └── TLE_STL_n!.cpp ├── 279.Perfect_Squares │ ├── readme.md │ ├── AC_memorization_nsqrtn.cpp │ └── MLE_dp_nsqrtn.py ├── 226.Invert_Binary_Tree │ ├── readme.md │ ├── AC_stack_n.py │ └── AC_recursive_n.cpp ├── 046.Permutations │ └── AC_stl_n!.cpp ├── 219.Contains_Duplicate_II │ ├── readme.md │ ├── TLE_brute_force_n2.cpp │ └── AC_unordered_map_nlogn.cpp ├── 095.Unique_Binary_Search_Trees │ ├── readme.md │ └── AC_dp_n2.cpp ├── 221.Maximal_Square │ └── readme.md ├── 018.4Sum │ └── readme.md ├── 120.Triangle │ └── AC_dp_n2.py ├── 130.Surrounded_Regions │ └── readme.md ├── 289.Game_of_Life │ └── readme.md ├── 234.Palindrome_Linked_List │ ├── README.md │ └── AC_simulation_n.py ├── 065.Valid_Number │ ├── AC_DFA_n.java │ └── AC_strtod_n.cpp ├── 104.Maximum_Depth_of_Binary_Tree │ └── AC_recursive_n.cpp ├── 222.Count_Complete_Tree_Nodes │ ├── TLE_recursive_n.cpp │ ├── readme.md │ └── AC_binary_search_lognlogn.py ├── 115.Distinct_Subsequences │ ├── readme.md │ └── AC_dp_less_space_n*m.cpp ├── 055.Jump_Game │ └── AC_greedy2_n.cpp ├── 050.Pow(x,_n) │ └── AC_simulation_n.cpp ├── 053.Maximum_Subarray │ └── AC_dp_n.cpp ├── 085.Maximal_Rectangle │ └── readme.md ├── 123.Best_Time_to_Buy_and_Sell_Stock_III │ ├── AC_1_space_dp_n.py │ └── readme.md ├── 036.Valid_Sudoku │ └── readme.md ├── 112.Path_Sum │ └── AC_recursive_n.cpp ├── 097.Interleaving_String │ └── readme.md ├── 023.Merge_k_Sorted_Lists │ └── readme.md ├── 091.Decode_Ways │ └── AC_dp_n.py ├── 028.Implement_strStr() │ ├── AC_brute_force_n2.cpp │ └── readme.md ├── 204.Count_Primes │ └── AC_prime_n2.cpp ├── 070.Climbing_Stairs │ └── AC_recursive_n.cpp ├── 084.Largest_Rectangle_in_Histogram │ └── AC_bruteforce_less_than_n2.cpp ├── 138.Copy_List_with_Random_Pointer │ └── readme.md ├── 117.Populating_Next_Right_Pointers_in_Each_Node_II │ └── AC_simulation_n.py ├── 100.Same_Tree │ └── AC_silulation_n.cpp ├── 041.First_Missing_Positive │ └── AC_array_n.cpp ├── 058.Length_of_Last_Word │ └── AC_simulation_n.cpp ├── 111.Minimum_Depth_of_Binary_Tree │ └── AC_recursive_n.cpp ├── 146.LRU_Cache │ └── readme.md ├── 074.Search_a_2D_Matrix │ └── AC_binary_search_log(nm).cpp ├── 162.Find_Peak_Element │ └── AC_binary_search.py └── 004.Median_of_Two_Sorted_Arrays │ └── readme.md └── readme_generator.sh /.gitignore: -------------------------------------------------------------------------------- 1 | *.[oa] 2 | *.out 3 | in 4 | out 5 | *.swp 6 | a.out.*/ 7 | *~ 8 | *.bak 9 | -------------------------------------------------------------------------------- /solutions/193.Valid_Phone_Numbers/file.txt: -------------------------------------------------------------------------------- 1 | 987-123-4567 2 | 123 456 7890 3 | (123) 456-7890 4 | (001) 345-0000 5 | 123-456-78910 6 | -------------------------------------------------------------------------------- /solutions/195.Tenth_Line/AC_sed.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AC_sed.sh created by illuz at 2015-03-27 09:18:24 3 | sed -n '10p' file.txt 4 | -------------------------------------------------------------------------------- /solutions/195.Tenth_Line/AC_awk.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AC_awk.sh created by illuz at 2015-03-27 09:18:50 3 | awk 'NR == 10' file.txt 4 | -------------------------------------------------------------------------------- /solutions/195.Tenth_Line/readme.md: -------------------------------------------------------------------------------- 1 | ## 195. Tenth Line (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/tenth-line/ 5 | -------------------------------------------------------------------------------- /solutions/196.Delete_Duplicate_Emails/AC_delete.sql: -------------------------------------------------------------------------------- 1 | DELETE p1 2 | FROM Person p1, Person p2 3 | WHERE p1.Email = p2.Email AND p1.Id > p2.Id 4 | -------------------------------------------------------------------------------- /solutions/183.Customers_Who_Never_Order/AC_in.sql: -------------------------------------------------------------------------------- 1 | SELECT Name Customers 2 | FROM Customers A 3 | WHERE A.Id NOT IN ( 4 | SELECT B.CustomerId 5 | FROM Orders B 6 | ) 7 | -------------------------------------------------------------------------------- /solutions/183.Customers_Who_Never_Order/AC_left_join.sql: -------------------------------------------------------------------------------- 1 | SELECT Name Customers 2 | FROM Customers a LEFT JOIN Orders b ON a.Id = b.CustomerId 3 | WHERE CustomerId is NULL 4 | -------------------------------------------------------------------------------- /solutions/197.Rising_Temperature/AC_TO_DAYS.sql: -------------------------------------------------------------------------------- 1 | SELECT a.Id 2 | FROM Weather a, Weather b 3 | WHERE TO_DAYS(a.Date) = TO_DAYS(b.Date) + 1 AND a.Temperature > b.Temperature 4 | -------------------------------------------------------------------------------- /solutions/181.Employees_Earning_More_Than_Their_Managers/AC_join.sql: -------------------------------------------------------------------------------- 1 | SELECT A.Name Employee 2 | FROM Employee A, Employee B 3 | WHERE A.ManagerId = B.Id AND A.Salary > B.Salary 4 | -------------------------------------------------------------------------------- /solutions/182.Duplicate_Emails/AC_join.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT DISTINCT a.Email 3 | FROM Person a JOIN Person b 4 | WHERE a.Email = b.Email AND a.id <> b.id 5 | -------------------------------------------------------------------------------- /solutions/193.Valid_Phone_Numbers/AC_egrep.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AC_egrep.sh created by illuz at 2015-03-25 13:05:10 3 | 4 | egrep -o '^(([0-9]{3}-)|(\([0-9]{3}\) ))[0-9]{3}-[0-9]{4}$' file.txt 5 | -------------------------------------------------------------------------------- /solutions/176.Second_Highest_Salary/AC_max.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT MAX(Salary) 3 | FROM Employee 4 | WHERE Salary < ( 5 | SELECT MAX(Salary) 6 | FROM Employee 7 | ) 8 | -------------------------------------------------------------------------------- /solutions/181.Employees_Earning_More_Than_Their_Managers/AC_inner_join.sql: -------------------------------------------------------------------------------- 1 | SELECT A.Name Employee 2 | FROM Employee A INNER JOIN Employee B 3 | ON A.ManagerId = B.Id 4 | WHERE A.Salary > B.Salary 5 | -------------------------------------------------------------------------------- /solutions/183.Customers_Who_Never_Order/AC_exists.sql: -------------------------------------------------------------------------------- 1 | SELECT Name Customers 2 | FROM Customers A 3 | WHERE NOT EXISTS ( 4 | SELECT 1 5 | FROM Orders B 6 | WHERE A.Id = B.CustomerId 7 | ) 8 | -------------------------------------------------------------------------------- /solutions/193.Valid_Phone_Numbers/AC_grep.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AC_grep.sh created by illuz at 2015-03-25 13:05:45 3 | grep '^\(\([0-9]\{3\}-\)\|\(([0-9]\{3\}) \)\)[0-9]\{3\}-[0-9]\{4\}$' file.txt 4 | 5 | -------------------------------------------------------------------------------- /solutions/192.Word_Frequency/AC_tr_uniq.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AC_tr_uniq.sh created by illuz at 2015-03-24 09:32:37 3 | 4 | cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -rn | awk '{ print $2, $1}' 5 | 6 | -------------------------------------------------------------------------------- /solutions/175.Combine_Two_Tables/AC_left_join.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT FirstName, LastName, City, State 3 | FROM Person LEFT OUTER JOIN Address 4 | ON Person.PersonId = Address.PersonId 5 | -------------------------------------------------------------------------------- /solutions/178.Rank_Scores/AC_order.sql: -------------------------------------------------------------------------------- 1 | SELECT A.Score Score, 2 | ( 3 | SELECT COUNT(DISTINCT B.Score) 4 | FROM Scores B 5 | WHERE B.Score >= A.Score 6 | ) Rank 7 | FROM Scores A 8 | ORDER BY A.Score DESC 9 | 10 | -------------------------------------------------------------------------------- /solutions/326.Power_of_Three/AC_tricky1_1.py: -------------------------------------------------------------------------------- 1 | def isPowerOfThree(n): 2 | return n in [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, 3486784401] 3 | -------------------------------------------------------------------------------- /solutions/326.Power_of_Three/AC_tricky2_1.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPowerOfThree(int n) { 3 | // 1162261467 is 3^19, 3^20 is bigger than int 4 | return ( n>0 && 1162261467%n==0); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /solutions/194.Transpose_File/readme.md: -------------------------------------------------------------------------------- 1 | ## 194. Transpose File (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/transpose-file/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 用 awk 做就像用 C 一样。 10 | -------------------------------------------------------------------------------- /solutions/183.Customers_Who_Never_Order/readme.md: -------------------------------------------------------------------------------- 1 | ## 183. Customers Who Never Order (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/customers-who-never-order/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 从两个表中得到从没买过东西的家伙。 9 | -------------------------------------------------------------------------------- /solutions/193.Valid_Phone_Numbers/AC_awk.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AC_awk.sh created by illuz at 2015-03-25 13:10:51 3 | 4 | awk '/^[0-9][0-9][0-9]\-[0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9]$/ || /^\([0-9][0-9][0-9]\) [0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9]$/ {print}' file.txt 5 | -------------------------------------------------------------------------------- /solutions/184.Department_Highest_Salary/AC_MAX.sql: -------------------------------------------------------------------------------- 1 | SELECT d.Name Department, e.Name Employee, Salary 2 | FROM Employee e, Department d 3 | WHERE e.DepartmentId = d.Id AND e.Salary = ( 4 | SELECT MAX(Salary) 5 | FROM Employee 6 | WHERE DepartmentId = d.Id 7 | ) 8 | -------------------------------------------------------------------------------- /solutions/193.Valid_Phone_Numbers/AC_sed.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AC_sed.sh created by illuz at 2015-03-25 12:49:25 3 | # Read from the file file.txt and output all valid phone numbers to stdout. 4 | sed -n -e '/^\(\([0-9]\{3\}-\)\|\(([0-9]\{3\}) \)\)[0-9]\{3\}-[0-9]\{4\}$/ p' file.txt 5 | -------------------------------------------------------------------------------- /solutions/326.Power_of_Three/AC_normal_logn.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPowerOfThree(int n) { 3 | while (n >= 3) { 4 | if (n % 3 != 0) return false; 5 | n /= 3; 6 | } 7 | return n == 1; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /solutions/006.ZigZag_Conversion/readme.md: -------------------------------------------------------------------------------- 1 | ## 006.ZigZag_Conversion (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/zigzag-conversion/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把一个字符串按横写的折线排列。 9 | 10 | ### **分析**: 11 | 直接模拟就行了。 12 | -------------------------------------------------------------------------------- /solutions/223.Rectangle_Area/readme.md: -------------------------------------------------------------------------------- 1 | ## 223. Rectangle Area (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/rectangle-area/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 求两个矩形的面积。 10 | 11 | ### **分析**: 12 | 13 | 有相交和不相交两种情况,分类讨论就行了。 14 | 15 | -------------------------------------------------------------------------------- /solutions/014.Longest_Common_Prefix/readme.md: -------------------------------------------------------------------------------- 1 | ## 014.Longest_Common_Prefix (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/longest-common-prefix/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求多个字符串的最长公共前缀。 9 | 10 | ### **分析**: 11 | 一位一位判断即可,没什么坑点。 12 | -------------------------------------------------------------------------------- /solutions/257.Binary_Tree_Paths/readme.md: -------------------------------------------------------------------------------- 1 | ## 257. Binary Tree Paths (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/binary-tree-paths/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 求跟到叶子的所有路径。 10 | 11 | ### **分析**: 12 | 13 | 直接 DFS 过去求求行了,也就是前序+记录路径。 14 | -------------------------------------------------------------------------------- /readme_generator.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # readme_generator.sh created by illuz at 2015-02-04 10:44:34 3 | # 4 | 5 | # delete 'solved' to end 6 | sed -i.bak '/for a fee/, $ d' readme.md 7 | 8 | # generate table and append 9 | cd solutions 10 | python ./table_generator.py >> ../readme.md 11 | 12 | exit 0 13 | 14 | -------------------------------------------------------------------------------- /solutions/178.Rank_Scores/readme.md: -------------------------------------------------------------------------------- 1 | ## 178. Rank Scores (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/rank-scores/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给分数排名。 9 | 10 | ### **分析**: 11 | 12 | 1. 把 SELECT 套进去。 13 | 2. 用 CASE 和 变量,逐行处理,速度比 1 变了很多。 14 | 15 | -------------------------------------------------------------------------------- /solutions/192.Word_Frequency/AC_awk.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AC_awk.sh created by illuz at 2015-03-22 17:55:50 3 | # Read from the file words.txt and output the word frequency list to stdout. 4 | 5 | awk ' 6 | { for (i=1; i<=NF; i++) { ++S[$i]; } } 7 | END { for (i in S) { print i, S[i] } } 8 | ' words.txt | sort -nr -k 2 9 | -------------------------------------------------------------------------------- /solutions/263.Ugly_Number/readme.md: -------------------------------------------------------------------------------- 1 | ## 263. Ugly Number (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/ugly-number/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 判断一个数是不是 Ugly Number,Ugly Number 是因子中只包含 2, 3, 5 的数。 10 | 11 | ### **分析**: 12 | 13 | 直接模拟就可以了。 14 | -------------------------------------------------------------------------------- /solutions/180.Consecutive_Numbers/AC_triple_join.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | # !! This solution may be wrong when the id is not successive. 3 | SELECT DISTINCT t1.Num 4 | FROM Logs t1 JOIN Logs t2 ON t1.Num = t2.Num 5 | JOIN Logs t3 ON t1.Num = t3.Num 6 | WHERE t1.Id = t2.Id + 1 AND t2.Id = t3.Id + 1 7 | -------------------------------------------------------------------------------- /solutions/278.First_Bad_Version/readme.md: -------------------------------------------------------------------------------- 1 | ## 278. First Bad Version (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/first-bad-version/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 在一个版本序列中,后半部分的版本是坏的,给你一个判断版本是否坏掉的函数,问能不能用最少的判断次数找出第一个坏数。 9 | 10 | ### **分析**: 11 | 二分裸题。 12 | -------------------------------------------------------------------------------- /solutions/166.Fraction_to_Recurring_Decimal/readme.md: -------------------------------------------------------------------------------- 1 | ## 166. Fraction to Recurring Decimal (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/fraction-to-recurring-decimal/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 计算除法循环节。 10 | 11 | ### **分析**: 12 | 13 | 直接模拟即可。 14 | -------------------------------------------------------------------------------- /solutions/242.Valid_Anagram/readme.md: -------------------------------------------------------------------------------- 1 | ## 242. Valid Anagram (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/valid-anagram/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 判断两个字符串是不是由同一些字母组成的。 10 | 11 | ### **分析**: 12 | 13 | 模拟就行了,直接用个数组记录字母的出现次数下就行了。 14 | 也可以排序后再判断下。 15 | 16 | -------------------------------------------------------------------------------- /solutions/016.3Sum_Closest/readme.md: -------------------------------------------------------------------------------- 1 | ## 016.3Sum_Closest (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/3sum-closest/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 在给定数列中找出三个数,使和最接近 target。 9 | 10 | ### **分析**: 11 | 与 [015. 3Sum (Medium)](../015.3Sum) 类似,甚至更简单。 12 | 还是先排序,再左右夹逼。 13 | -------------------------------------------------------------------------------- /solutions/200.Number_of_Islands/readme.md: -------------------------------------------------------------------------------- 1 | ## 200. Number of Islands (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/number-of-islands/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 算一张 01 里面有几个 1 块。 10 | 11 | ### **分析**: 12 | 13 | 直接 BFS 就行了。 14 | 当然 DFS 也可以,这题没太大数据会卡 DFS。 15 | -------------------------------------------------------------------------------- /solutions/184.Department_Highest_Salary/readme.md: -------------------------------------------------------------------------------- 1 | ## 184. Department Highest Salary (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/department-highest-salary/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 给俩表,求各个部门的最高工资的人。 10 | 11 | ### **分析**: 12 | 13 | 直接 SELECT JOIN MAX 一通用就行了。 14 | -------------------------------------------------------------------------------- /solutions/203.Remove_Linked_List_Elements/README.md: -------------------------------------------------------------------------------- 1 | ## 203. Remove Linked List Elements (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/remove-linked-list-elements/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把链表里的等于 val 的节点都删掉。 9 | 10 | ### **分析**: 11 | 12 | 1. 直接模拟 13 | 2. 递归处理 14 | 15 | -------------------------------------------------------------------------------- /solutions/024.Swap_Nodes_in_Pairs/readme.md: -------------------------------------------------------------------------------- 1 | ## 024. Swap Nodes in Pairs (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/swap-nodes-in-pairs/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把一个链表中的每一对节点对换(不能只换值)。 9 | 10 | ### **分析**: 11 | 直接模拟即可。 12 | 开个前节点来做会比较方便。 13 | 用 Python 的异常处理和赋值会很方便。 14 | -------------------------------------------------------------------------------- /solutions/027.Remove_Element/readme.md: -------------------------------------------------------------------------------- 1 | ## 027. Remove Element (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/remove-element/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 删除一个数组里值为 elem 的所有数。 9 | 10 | ### **分析**: 11 | 用两个指针,一个为可放位置的指针,一个为扫描指针。 12 | 因为不难,Java 和 Python 的做法都和 C++ 一样,这里就不给出了。 13 | 14 | -------------------------------------------------------------------------------- /solutions/124.Binary_Tree_Maximum_Path_Sum/readme.md: -------------------------------------------------------------------------------- 1 | ## 124. Binary Tree Maximum Path Sum (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/binary-tree-maximum-path-sum/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求一棵二叉树上的最大路径。 9 | 10 | ### **分析**: 11 | 直接 DFS 就可以了,返回以这一棵子树且一端在上的最大路径,然后维护一个最大路径就行了。 12 | -------------------------------------------------------------------------------- /solutions/205.Isomorphic_Strings/README.md: -------------------------------------------------------------------------------- 1 | ## 205. Isomorphoic Strings (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/isomorphic-strings/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 判断两个字符串能否相互映射. 10 | 11 | ### **分析**: 12 | 13 | 1. 直接模拟,记录下映射关系 14 | 2. 用 Python 的 dict 和 zip 能够很方便处理映射关系 15 | 16 | -------------------------------------------------------------------------------- /solutions/017.Letter_Combinations_of_a_Phone_Number/readme.md: -------------------------------------------------------------------------------- 1 | ## 017.Letter_Combinations_of_a_Phone_Number 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 在手机上按字母,给出按的数字键,问所有的按的字母的情况。 9 | 10 | ### **分析**: 11 | DFS 过去是比较轻松的写法。 12 | -------------------------------------------------------------------------------- /solutions/136.Single_Number/readme.md: -------------------------------------------------------------------------------- 1 | ## 136. Single Number (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/single-number/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 一个整数数组中只有一个数出现了一次,其它都出现了两次,要你找出这个数。 10 | 11 | ### **分析**: 12 | 13 | 很经典的面试题,二进制异或的经典应用。 14 | 了解了异或的性质后就知道为什么所有数异或一遍这个数就能出来。 15 | -------------------------------------------------------------------------------- /solutions/180.Consecutive_Numbers/AC_case_when.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT b.Num 2 | From ( 3 | SELECT Num, ( 4 | CASE 5 | WHEN @prev = Num THEN @count := @count + 1 6 | WHEN (@prev := Num) IS NOT NULL THEN @count := 1 7 | END 8 | ) n 9 | FROM Logs, (SELECT @count := 1, @prev := NULL) a 10 | ) b 11 | WHERE b.n >= 3 12 | -------------------------------------------------------------------------------- /solutions/237.Delete_Node_in_a_Linked_List/readme.md: -------------------------------------------------------------------------------- 1 | ## 237. Delete Node in a Linked List (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/delete-node-in-a-linked-list/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 题目看了半天,其实是在一条单链表中删除一个节点,只给你指向这个节点的指针。 10 | 11 | ### **分析**: 12 | 13 | 知道题意后就很简单了。直接模拟。 14 | -------------------------------------------------------------------------------- /solutions/334.Increasing_Triplet_Subsequence/readme.md: -------------------------------------------------------------------------------- 1 | ## 334. Increasing Triplet Subsequence 2 | 3 | ### **链接**: 4 | 5 | 题目:https://leetcode.com/problems/increasing-triplet-subsequence/ 6 | 7 | 代码(github):https://github.com/illuz/leetcode 8 | 9 | ### **题意**: 10 | 11 | 问一个数组中有没有递增的三个数,不用连续。 12 | 13 | ### **分析**: 14 | 15 | 维护小中大三个数就行了。 16 | 17 | 18 | -------------------------------------------------------------------------------- /solutions/009.Palindrome_Number/readme.md: -------------------------------------------------------------------------------- 1 | ## 009.Palindrome_Number 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/palindrome-number/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 判断一个数是否是回文数。 9 | 10 | ### **分析**: 11 | 按自己想的去写就行了。 12 | 13 | 1. 可以先转为字符串,再判断。(这种解法用 Python 可以一句话完成 =w=) 14 | 2. 更好的方法是直接算出回文的数再直接比较。 15 | -------------------------------------------------------------------------------- /solutions/102.Binary_Tree_Level_Order_Traversal/readme.md: -------------------------------------------------------------------------------- 1 | ## 102. Binary Tree Level Order Traversal (Midium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/binary-tree-level-order-traversal/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求层次遍历。 9 | 10 | ### **分析**: 11 | 12 | 1. 用 BFS 遍历,放在数组中。 13 | 2. 用 DFS 时放到指定层数数组中。 14 | -------------------------------------------------------------------------------- /solutions/177.Nth_Highest_Salary/AC_LIMIT.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 2 | BEGIN 3 | DECLARE M INT; 4 | SET M=N-1; 5 | RETURN ( 6 | # Write your MySQL query statement below. 7 | SELECT DISTINCT Salary 8 | FROM Employee 9 | ORDER BY Salary DESC 10 | LIMIT M, 1 11 | ); 12 | END 13 | -------------------------------------------------------------------------------- /solutions/231.Power_of_Two/readme.md: -------------------------------------------------------------------------------- 1 | ## 231. Power of Two (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/power-of-two/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 判断一个数是否是 2 的 x 次方。 9 | 10 | ### **分析**: 11 | 12 | 1. 刚开始的思路是直接 log2,想想用位运算会好点 13 | 2. 传入值为 int,最多就 32 位,所以直接 for 一遍,然后位移判断 14 | 3. 后来发现直接可以用 n&(n-1) 去判断就行啊 15 | -------------------------------------------------------------------------------- /solutions/268.Missing_Number/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | 5 | class Solution(object): 6 | def missingNumber(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: int 10 | """ 11 | return len(nums) * (len(nums) + 1) / 2 - sum(nums) 12 | -------------------------------------------------------------------------------- /solutions/013.Roman_to_Integer/readme.md: -------------------------------------------------------------------------------- 1 | ## 013.Roman_to_Integer (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/roman-to-integer/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把罗马数转为十进制。 9 | 10 | ### **分析**: 11 | 跟 [012. Integer to Roman (Medium)](http://blog.csdn.net/hcbbt/article/details/44026099) 一样,只要知道转化规则就行了。 12 | 13 | -------------------------------------------------------------------------------- /solutions/015.3Sum/readme.md: -------------------------------------------------------------------------------- 1 | ## 015.3Sum (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/3sum/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 在给定数列中找出三个数,使和为 0。 9 | 10 | ### **分析**: 11 | 先排序,再左右夹逼,复杂度 O(n*n)。 12 | N-sum 的题目都可以用夹逼做,复杂度可以降一维。 13 | 14 | 这题数据更新后卡得很紧, C++ 不能全部加完再用 STL 的 erase 和 unique 去重,要一边判断一边加。 15 | 16 | -------------------------------------------------------------------------------- /solutions/025.Reverse_Nodes_in_k-Group/readme.md: -------------------------------------------------------------------------------- 1 | ## 025. Reverse Nodes in k-Group (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/reverse-nodes-in-k-group/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把一个链表每 k 个分为一组,每组内进行翻转。 9 | 只能用常数级的空间。 10 | 11 | ### **分析**: 12 | 13 | 这题比较考验链表的操作,用递归做会比较方便,先找到下一组的节点,把本组反转后再递归处理后面的节点。 14 | -------------------------------------------------------------------------------- /solutions/040.Combination_Sum_II/readme.md: -------------------------------------------------------------------------------- 1 | ## 040. Combination Sum II (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/combination-sum-ii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 跟 039 一样(给出一些正整数集合,以及一个目标数,从集合中选择一些数使得它们的和等于目标数),不过不能选重复的数。 9 | 10 | ### **分析**: 11 | 12 | 同样暴力 DFS,不过要考虑重复会复杂点。 13 | 还要考虑解集里不能有相同的解。 14 | -------------------------------------------------------------------------------- /solutions/131.Palindrome_Partitioning/readme.md: -------------------------------------------------------------------------------- 1 | ## 131. Palindrome Partitioning (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/palindrome-partitioning/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把一个字符串分割,使每一部分都是回文。 9 | 10 | ### **分析**: 11 | 12 | 1. **(C++)** 递归,找到回文,然后递归后面部分 13 | 2. **(Python)** 对 1 进行优化,预处理每个位置对应的回文 14 | -------------------------------------------------------------------------------- /solutions/290.Word_Pattern/readme.md: -------------------------------------------------------------------------------- 1 | ## 290. Word Pattern (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/word-pattern/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给出 pattern 和 str,问 pattern 里的字符串和 str 里的单词是否一一配对。 9 | 10 | ### **分析**: 11 | 12 | 可以先对 str 进行分词,也可以一边遍历 pattern 一边分词。 13 | `字符->字符串` 可以用 map 也可以用 array。 14 | 15 | -------------------------------------------------------------------------------- /solutions/035.Search_Insert_Position/readme.md: -------------------------------------------------------------------------------- 1 | ## 035. Search Insert Position (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/search-insert-position/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 要把一个数有序插入到一个有序数组里,问插入的位置。 9 | 10 | ### **分析**: 11 | 还是二分变形题。 12 | 13 | 1. 用 STL 的 `lower_bound` 偷懒。 14 | 2. 二分,最后注意判断一下是否找到,要输出什么。 15 | -------------------------------------------------------------------------------- /solutions/038.Count_and_Say/readme.md: -------------------------------------------------------------------------------- 1 | ## 038. Count and Say (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/Count-and-Say/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 数数,第一个是 1,第二个是数前一个数:1 个 1,就是 11,第三个是 2 个 1,就是 21,第三个是 1 个 2,1 个 1,就是 1211,第四个是 111221... 10 | 现在问第 n 个数是什么。 11 | 12 | ### **分析**: 13 | 14 | 可以直接模拟,一个个数过去。 15 | -------------------------------------------------------------------------------- /solutions/107.Binary_Tree_Level_Order_Traversal_II/readme.md: -------------------------------------------------------------------------------- 1 | ## 107. Binary Tree Level Order Traversal II (Midium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求层次遍历,不过这题要按层数从下到上。 9 | 10 | ### **分析**: 11 | 可以直接用 Binary Tree Level Order Traversal 的代码。 12 | -------------------------------------------------------------------------------- /solutions/207.Course_Schedule/readme.md: -------------------------------------------------------------------------------- 1 | ## 207. Course Schedule (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/course-schedule/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 学习课程 A 要先学课程 B,给出一些课程学习顺序,问这些课程能不能学完。 10 | 11 | ### **分析**: 12 | 13 | 经典的拓扑排序题,教科书般。 14 | 这题问的是图中有没有环,或都说这个图是不是拓扑图。存下图后可以用 DFS 或队列/栈做。 15 | 16 | -------------------------------------------------------------------------------- /solutions/228.Summary_Ranges/readme.md: -------------------------------------------------------------------------------- 1 | ## 228. Summary Ranges (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/summary-ranges/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 给一个递增的数组,求里面**自然递增**的序列。 10 | 11 | ### **分析**: 12 | 13 | 就是直接判断是否是上个数 +1,不是就记录下来。 14 | 如果 for 过去,最后一个递增区间得在 for 外面再写进去,可以偷懒在后面再放个最后一个数,事后再去掉。 15 | 16 | -------------------------------------------------------------------------------- /solutions/231.Power_of_Two/AC_bitwize_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_bitwize_1.py 5 | # Create Date: 2015-07-12 20:02:44 6 | # Usage: AC_bitwize_1.py 7 | # Descripton: 8 | 9 | class Solution: 10 | def isPowerOfTwo(self, n): 11 | return (n > 0) and (n & (n-1)) == 0 12 | -------------------------------------------------------------------------------- /solutions/328.Odd_Even_Linked_List/readme.md: -------------------------------------------------------------------------------- 1 | ## 328. Odd Even Linked List (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/odd-even-linked-list/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把一个链表的奇数位置上的节点拉到前面,偶数位置上的放到后面。 9 | 10 | ### **分析**: 11 | 考察链表操作。 12 | 13 | 1. 最简单的方法是构造两个链,再连起来就行了。 14 | 2. 构造链时可以一对一对构造。 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /solutions/180.Consecutive_Numbers/readme.md: -------------------------------------------------------------------------------- 1 | ## 180. Consecutive Numbers (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/consecutive-numbers/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 查询一个表中连续出现 3 次一上的 Num。 9 | 10 | ### **分析**: 11 | 12 | 1. 用 JOIN 三个表可以做,不过要跑 1800 ms,而且只有在 id 都是连续的情况下才可行。 13 | 2. 有更好的解法,就是用 CASE,不过也是要跑 1600 ms。 14 | -------------------------------------------------------------------------------- /solutions/021.Merge_Two_Sorted_Lists/readme.md: -------------------------------------------------------------------------------- 1 | ## 021.Merge_Two_Sorted_Lists (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/merge-two-sorted-lists/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 合并两个有序链表。 9 | 10 | ### **分析**: 11 | 很经典的题目,不过知道怎么做后很容易,模拟即可。 12 | 有两种做法: 13 | 1. 开一个节点做 head 的前节点 (下面的 Python 代码实现) 14 | 2. 不开直接做(C++ 代码实现) 15 | -------------------------------------------------------------------------------- /solutions/108.Convert_Sorted_Array_to_Binary_Search_Tree/readme.md: -------------------------------------------------------------------------------- 1 | ## 108. Convert Sorted Array to Binary Search Tree (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 为一个排过序的数组建一棵平衡的 BST。 9 | 10 | ### **分析**: 11 | 要平衡,只要取中间的那个数做根就行了。递归下去即可。 12 | 13 | -------------------------------------------------------------------------------- /solutions/190.Reverse_Bits/AC_one_line_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_one_line_n.java 4 | * Create Date: 2015-03-16 10:51:39 5 | * Descripton: 6 | */ 7 | 8 | public class Solution { 9 | // you need treat n as an unsigned value 10 | public int reverseBits(int n) { 11 | return Integer.reverse(n); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /solutions/208.Implement_Trie_(Prefix_Tree)/readme.md: -------------------------------------------------------------------------------- 1 | ## 208. Implement Trie (Prefix Tree) (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/implement-trie-prefix-tree/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 实现一个 trie(前缀树)。 10 | 11 | ### **分析**: 12 | 13 | Trie 这个数据结构是很经典的,所以就不再多说了。 14 | Trie 分提前开空间的数组型和动态开空间的指针型,这题目给的已经就是指针型的。 15 | -------------------------------------------------------------------------------- /solutions/197.Rising_Temperature/readme.md: -------------------------------------------------------------------------------- 1 | ## 197 Rising Temperature Easy 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/rising-temperature/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 1. 这题可以连接两个表来做,Date 类型的比较用 `TO_DAYS()` 来实现。 10 | 2. 如果先排序再用 `CASE-WHEN` 来做也可以,不过不知道怎么搞的,MySQL 的 `:=` 符号的优先级居然比 `AND\OR` 来得低,DEBUG 了半天才找到这个问题,郁闷。这样做快多了,速度跻身前列。 11 | 12 | -------------------------------------------------------------------------------- /solutions/034.Search_for_a_Range/readme.md: -------------------------------------------------------------------------------- 1 | ## 034. Search for a range (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/search-for-a-range/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 在有序数组中找到一个数的范围。(因为数有重复) 9 | 10 | ### **分析**: 11 | 还是二分搜索变形。 12 | 13 | 1. **(C++)**直接用 C++ STL 的 `lower_bound` 和 `upper_bound` 偷懒。 14 | 2. **(Java)**直接从普通的二分改一下就行了。 15 | -------------------------------------------------------------------------------- /solutions/068.Text_Justification/readme.md: -------------------------------------------------------------------------------- 1 | ## 068.Text_Justification (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/text-justification/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给出一些单词和一个宽度,要你把单词打包成宽度一样的字符串数组。 9 | 要求: 10 | 1. 每个字符串尽可能包含多个单词,多余的位置用空格代替。 11 | 2. 单词间空格尽量平均,不能平分的话,前面的空格要比后面的多。 12 | 13 | ### **分析**: 14 | 就是直接模拟,要注意细节处理。 15 | 16 | -------------------------------------------------------------------------------- /solutions/105.Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal/readme.md: -------------------------------------------------------------------------------- 1 | ## 105. Construct Binary Tree from Preorder and Inorder Traversal (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 从前序中序遍历建树。 9 | 10 | ### **分析**: 11 | 用递归直接模拟就可以了。 12 | -------------------------------------------------------------------------------- /solutions/007.Reverse_Integer/readme.md: -------------------------------------------------------------------------------- 1 | ## 007.Reverse_Integer (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/Reverse-Integer/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 反转一个数。 9 | 10 | ### **分析**: 11 | 注意读入和返回的数都是 int 型的,这时就要考虑反转后这个数会不会超 int,超的话就返回 0 。这时处理数时最好用比 int 大的类型,不然恐怕会超范围。 12 | 当然也可以用 int :`if (result > (INT_MAX/10))` 13 | 还有一点就是还要考虑前导零。 14 | -------------------------------------------------------------------------------- /solutions/268.Missing_Number/readme.md: -------------------------------------------------------------------------------- 1 | ## 268. Missing Number (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/missing-number/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 一个有 n 个元素数组,是由 0~n 去掉一个元素后构成的,求找出那个元素。 9 | 10 | ### **分析**: 11 | 12 | 1. 不用一个一个去找,直接求和就行了~ 然后和 0~n 的和的差就是那个数 13 | 2. 用异或的特性:`x^a^a=x`,对每个数异或一次后,再 0~n 异或一遍,缺的那个数就只异或一次,其它都异或两次,所以剩下的那个数就是缺的数。 14 | -------------------------------------------------------------------------------- /solutions/039.Combination_Sum/readme.md: -------------------------------------------------------------------------------- 1 | ## 039. Combination Sum (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/combination-sum/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给出一些正整数集合,以及一个目标数,从集合中选择一些数使得它们的和等于目标数,可以重复选择集合里的数。 9 | 得到的解的集合不能有重复。 10 | 11 | ### **分析**: 12 | 13 | 暴力搜索过去是可以的,先排好序,然后用 DFS,每次有两种选择,一是选中当前的数然后递归当前数,二是不选当前数直接递归下个数。 14 | 这题用来理解 DFS 是很不错的。 15 | -------------------------------------------------------------------------------- /solutions/198.House_Robber/readme.md: -------------------------------------------------------------------------------- 1 | ## 198.House Robber (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/house-robber/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 在一个序列中取数,不能连续取,求最大和。 10 | 11 | ### **分析**: 12 | 13 | 很明显的 DP,公式是 `dp[i] = max(dp[i - 1], dp[i - 2] + num[i])`。 14 | 你可以开个 DP 数组,不过这样就要用 O(n) 的空间了。 15 | 从公式中很容易看出这是可以降维的,滚动地 DP 只要 O(1) 的空间。 16 | 17 | -------------------------------------------------------------------------------- /solutions/009.Palindrome_Number/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_n.py 5 | # Create Date: 2015-02-28 22:57:39 6 | # Usage: AC_simulation_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @return a boolean 12 | def isPalindrome(self, x): 13 | return str(x) == str(x)[::-1] 14 | -------------------------------------------------------------------------------- /solutions/012.Integer_to_Roman/readme.md: -------------------------------------------------------------------------------- 1 | ## 012.Integer_to_Roman (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/integer-to-roman/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把十进制转为罗马数。 9 | 10 | ### **分析**: 11 | 模拟即可。 12 | 13 | “罗马数字的基本符号有I(表示十进制数1),V(表示5),X(表示10),L(表示50),C(表示100),D(表示500),M(表示1000)。” -- [罗马数制(百度百科)](http://baike.baidu.com/view/1246899.htm) 14 | 15 | 16 | -------------------------------------------------------------------------------- /solutions/033.Search_in_Rotated_Sorted_Array/readme.md: -------------------------------------------------------------------------------- 1 | ## 033. Search in Rotated Sorted Array (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/search-in-rotated-sorted-array/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 在一个旋转过的有序数组中找一个数。 9 | 比如 `4 5 6 7 0 1 2` 就是一个“旋转过的有序数组”。 10 | 11 | ### **分析**: 12 | 这是单纯二分搜索的变形。 13 | 因为旋转过不好定位,所以在找的时候可以先判断一下一个区间是完全有序的还是已经旋转过的,然后分类讨论。 14 | -------------------------------------------------------------------------------- /solutions/109.Convert_Sorted_List_to_Binary_Search_Tree/readme.md: -------------------------------------------------------------------------------- 1 | ## 109. Convert Sorted List to Binary Search Tree (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 为一个排过序的链表建一棵平衡的 BST。 9 | 10 | ### **分析**: 11 | 12 | 1. 跟上一题一样找中间数递归,不过由于这题是链表,所以要用双指针找中间数 13 | 2. 还有种思路是中序遍历,再一一加节点。 14 | -------------------------------------------------------------------------------- /solutions/190.Reverse_Bits/readme.md: -------------------------------------------------------------------------------- 1 | ## 190. Reverse Bits (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/reverse-bits/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 将一个 32 位无符号的数的二进制反转。 9 | 10 | ### **分析**: 11 | 12 | 1. 正常都是想先转 string 再转回去 13 | 2. 或者用位运算来反转 14 | 3. C++ Trick: 用 `bitset` 15 | 4. Python Trick: 用 `bin()` 和 `zfill()` 16 | 5. Java Trick: 用 `Integer.reverse()` 17 | -------------------------------------------------------------------------------- /solutions/241.Different_Ways_to_Add_Parentheses/readme.md: -------------------------------------------------------------------------------- 1 | ## 241. Different Ways to Add Parentheses (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/different-ways-to-add-parentheses/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个式子每一步操作都加上括号,会有不同的结果,把所有结果都输出来。 9 | 10 | ### **分析**: 11 | 12 | 可以用递归做,只看某个符号,计算符号左边的式子和右边的式子,再对得到的两个解集进行交叉运算(笛卡尔乘)。 13 | 因为有不少重复计算,可以进行记忆化。 14 | -------------------------------------------------------------------------------- /solutions/258.Add_Digits/AC_mod_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_mod_1.py 5 | # Create Date: 2015-08-17 00:44:30 6 | # Usage: AC_mod_1.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param {integer} num 12 | # @return {integer} 13 | def addDigits(self, num): 14 | return num % 9 or num and 9 -------------------------------------------------------------------------------- /solutions/022.Generate_Parentheses/readme.md: -------------------------------------------------------------------------------- 1 | ## 022.Generate_Parentheses (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/generate-parentheses/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 产生有 n 对括号的所有有效字符串。 9 | 10 | ### **分析**: 11 | 12 | 1. 用 DFS 可以很快做出来,能加'('就加'(',能加')'就加')'。(下面的 C++ 实现) 13 | 2. 还有很机智方法写出很短的 DFS 。 (Java 实现) 14 | 3. 对于 DFS 都可以进行记忆化,用空间换时间。 (Python 实现) 15 | -------------------------------------------------------------------------------- /solutions/103.Binary_Tree_Zigzag_Level_Order_Traversal/readme.md: -------------------------------------------------------------------------------- 1 | ## 103. Binary Tree Zigzag Level Order Traversal (Midium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 跟 `Binary Tree Level Order Traversal` 一样,求层次遍历,不过这题要让奇数层反着。 9 | 10 | ### **分析**: 11 | 可以直接用 Binary Tree Level Order Traversal 的代码。 12 | -------------------------------------------------------------------------------- /solutions/150.Evaluate_Reverse_Polish_Notation/readme.md: -------------------------------------------------------------------------------- 1 | ## 150. Evaluate Reverse Polish Notation (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/evaluate-reverse-polish-notation/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求一个逆波兰式的值。 9 | 10 | ### **分析**: 11 | 12 | 很经典的栈应用。 13 | 对字符串的处理,Python: `int()`,C++/C: `atoi()`,Java: `Integer.parseInt()`。 14 | 需要注意的是 Python 的 `/` 操作。 15 | -------------------------------------------------------------------------------- /solutions/114.Flatten_Binary_Tree_to_Linked_List/readme.md: -------------------------------------------------------------------------------- 1 | ## 114. Flatten Binary Tree to Linked List (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把一棵树变成一长条。 9 | 10 | ### **分析**: 11 | 12 | 1. (**C++**)DFS,先把左右两边的子树处理好,再合并。 13 | 2. (**Java**)不递归而用 Stack 来做。 14 | 15 | 这两种做法的时间复杂度和最坏空间都是 O(n)。 16 | 17 | -------------------------------------------------------------------------------- /solutions/154.Find_Minimum_in_Rotated_Sorted_Array_II/AC_lazy_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_lazy_n.py 5 | # Create Date: 2015-04-24 23:04:10 6 | # Usage: AC_lazy_n.py 7 | # Descripton: 8 | 9 | class Solution: 10 | # @param {integer[]} nums 11 | # @return {integer} 12 | def findMin(self, nums): 13 | return min(nums) 14 | -------------------------------------------------------------------------------- /solutions/155.Min_Stack/readme.md: -------------------------------------------------------------------------------- 1 | ## 155. Min Stack (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/min-stack/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 要实现一个栈,这个栈有跟别的栈不一样的地方是有个 getMin() 方法,这个方法返回这个栈的最小值。 10 | 11 | ### **分析**: 12 | 13 | 用暴力都只会 TLE 或 MLE。 14 | 要再开一个单调栈来放小值。 15 | 有一题用的就是这个思想,可以看看:[Sliding Window Maximum ](https://leetcode.com/problems/sliding-window-maximum/)。 16 | -------------------------------------------------------------------------------- /solutions/199.Binary_Tree_Right_Side_View/readme.md: -------------------------------------------------------------------------------- 1 | ## 199. Binary Tree Right Side View (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/binary-tree-right-side-view/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 假设你站在一棵树的右边,问从上到下看到的节点。 10 | 11 | ### **分析**: 12 | 13 | 其实就是求树每一层的最右边节点。 14 | 15 | 1. **(Python)** 可以直接 DFS 遍历一遍,维护最右节点就行了。 16 | 2. **(C++)** 也可以用两个 queue 来实现层次遍历。 17 | 18 | -------------------------------------------------------------------------------- /solutions/029.Divide_Two_Integers/readme.md: -------------------------------------------------------------------------------- 1 | ## 029. Divide Two Integers (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/divide-two-integers/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 实现除法,不能用乘、除和取模。 9 | 10 | ### **分析**: 11 | 不能用乘、除和取模,那剩下的,还有加、减和位运算。 12 | 13 | 1. 会想到的就是一次次去减,不过这样会超时。 14 | 2. 在 1 的基础上优化下,跟快速幂一样,每次把除数翻倍(用位运算即可)。 15 | 16 | 这里有坑,就是结果可能超 int 范围,所以最好用 long long 处理,之后再转 int。 17 | -------------------------------------------------------------------------------- /solutions/096.Unique_Binary_Search_Trees_II/readme.md: -------------------------------------------------------------------------------- 1 | ## 095. Unique Binary Search Trees II (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/unique-binary-search-trees-ii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求 {1, 2, ..., n} 的所有 BST。 9 | 10 | ### **分析**: 11 | 12 | 递归即可。 13 | 理解了“Unique Binary Search Trees”后应该不难解出这题。 14 | 15 | Java 和 Python 的解法和 C++ 一样,这里就不写出。 16 | -------------------------------------------------------------------------------- /solutions/121.Best_Time_to_Buy_and_Sell_Stock/readme.md: -------------------------------------------------------------------------------- 1 | ## 121. Best Time to Buy and Sell Stock (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个数组,`prices[i]` 表示第 i 天的交易值,也就是你在这天买入或卖出的交易值。 9 | 你只能买入及卖出一轮,求最大盈利。 10 | 11 | ### **分析**: 12 | 13 | 只要 `profit = prices[sell] - prices[buy] && buy < sell` 就行了,遍历一遍,维护 `profit` 即可。 14 | -------------------------------------------------------------------------------- /solutions/151.Reverse_Words_in_a_String/AC_split_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_split_n.py 5 | # Create Date: 2015-03-18 21:49:19 6 | # Usage: AC_split_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param s, a string 12 | # @return a string 13 | def reverseWords(self, s): 14 | return ' '.join(list(reversed(s.split()))) 15 | -------------------------------------------------------------------------------- /solutions/283.Move_Zeroes/readme.md: -------------------------------------------------------------------------------- 1 | ## 283. Move Zeroes (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/move-zeroes/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把数组里的 0 都移动到右边。 9 | 10 | ### **分析**: 11 | 12 | 1. 直接用两个指针模拟就行了,一个指向可填充的位置,一个指向检查的位置。 13 | 2. STL 大法:用 [remove](http://www.cplusplus.com/reference/algorithm/remove) 把 0 删掉,然后用 [fill](http://www.cplusplus.com/reference/algorithm/fill) 把后面那段置 0。 14 | -------------------------------------------------------------------------------- /solutions/126.Word_Ladder/readme.md: -------------------------------------------------------------------------------- 1 | ## 127. Word Ladder (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/word-ladder/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给出起点,终点的单词,每次变换要从 dict 中找到一个单词,且只变换一个字母。 9 | 问从起点到终点的最短变换路径长度。 10 | 11 | ### **分析**: 12 | 13 | 这是图论的题,把每个单词看成点,能变换就在点间连一条边,这样就出现一张无向图了。 14 | 15 | 1. BFS 一遍就行了。 16 | 2. 从起点和终点一起开始 BFS,就是 双端BFS(two-end BFS)。 17 | 18 | 对于图,可以先构造,也可以在 BFS 的时候再判断。 19 | -------------------------------------------------------------------------------- /solutions/268.Missing_Number/AC_xor_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_xor_n.java 4 | * Create Date: 2015-10-29 19:30:32 5 | * Descripton: 6 | */ 7 | 8 | public class Solution { 9 | public int missingNumber(int[] nums) { 10 | int res = nums.length; 11 | for (int i = 0; i < nums.length; ++i) { 12 | res = res ^ nums[i] ^ i; 13 | } 14 | return res; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /solutions/292.Nim_Game/AC_nim_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_nim_1.cpp 4 | * Create Date: 2016-02-22 19:44:50 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool canWinNim(int n) { 16 | return n % 4 != 0; 17 | } 18 | }; 19 | 20 | int main() { 21 | 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /solutions/019.Remove_Nth_Node_From_End_of_List/readme.md: -------------------------------------------------------------------------------- 1 | ## 019.Remove_Nth_Node_From_End_of_List (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 删除一个单向链表的倒数第 N 个节点。 9 | 10 | ### **分析**: 11 | 12 | 1. 直接模拟,先算出节点数,再找到节点删除 13 | 2. 用两个指针,一个先走 N 步,然后再一起走。 14 | 15 | 这里用 C++ 实现第一种, 用 Python 实现第二种。 16 | Java 的话和 C++/Python 差不多,不写出来了。 17 | -------------------------------------------------------------------------------- /solutions/201.Bitwise_AND_of_Numbers_Range/README.md: -------------------------------------------------------------------------------- 1 | ## 201. Bitwise AND of Numbers Range (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/bitwise-and-of-numbers-range/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 把 `[m, n]` 每个数进行与操作,问最后的数。 10 | 11 | ### **分析**: 12 | 13 | 问的是与操作,很容易发现结果都是 m 和 n 前面相同的部分 + 后面 0 填充,所以直接处理就行了。 14 | 15 | 1. 用 `while` 和位运算算出相同部分长度。 16 | 2. 不用循环,直接可以对 `n - m` 取 log 加 1 就是相同部分的长度了。 17 | -------------------------------------------------------------------------------- /solutions/020.Valid_Parentheses/readme.md: -------------------------------------------------------------------------------- 1 | ## 020.Valid_Parentheses (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/valid-parentheses/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 判断一个括号字符串是否是有效的。 9 | 10 | ### **分析**: 11 | 直接用栈模拟,很简单的。 12 | Java 的括号匹配可以用 if 写,也可以用 `HashMap` 存,还可以用 `"(){}[]".indexOf(s.substring(i, i + 1)`。 (这个讨论也可以用于 C++ 和 Python) 13 | 14 | 这里的 C++ 是用 if 匹配, Java 用 indexOf, Python 用 dict。 15 | -------------------------------------------------------------------------------- /solutions/172.Factorial_Trailing_Zeroes/AC_math_logn.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_math_logn.py 3 | # Create Date: 2015-02-05 11:45:02 4 | # Descripton: 5 | 6 | class Solution: 7 | # @return an integer 8 | def trailingZeroes(self, n): 9 | ans = 0 10 | while n: 11 | ans += n // 5 12 | n //= 5 13 | return ans 14 | 15 | # debug 16 | s = Solution() 17 | print s.trailingZeroes(5) 18 | 19 | -------------------------------------------------------------------------------- /solutions/194.Transpose_File/AC_awk.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AC_awk.sh created by illuz at 2015-03-26 16:40:27 3 | # Read from the file file.txt and print its transposed content to stdout. 4 | awk ' 5 | { 6 | for (i = 1; i <= NF; i++) { 7 | if(NR == 1) { 8 | s[i] = $i; 9 | } else { 10 | s[i] = s[i] " " $i; 11 | } 12 | } 13 | } 14 | END { 15 | for (i = 1; s[i] != ""; i++) { 16 | print s[i]; 17 | } 18 | }' file.txt 19 | -------------------------------------------------------------------------------- /solutions/171.Excel_Sheet_Column_Number/AC_simulation_1.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_simulation_1.py 3 | # Create Date: 2015-02-05 10:08:01 4 | # Descripton: Use lambda 5 | 6 | class Solution: 7 | # @param s, a string 8 | # @return an integer 9 | def titleToNumber(self, s): 10 | return reduce(lambda x, y: 26 * x + ord(y) - ord('A') + 1, s, 0) 11 | 12 | # debug 13 | s = Solution() 14 | print s.titleToNumber('AA') 15 | 16 | -------------------------------------------------------------------------------- /solutions/216.Combination_Sum_III/readme.md: -------------------------------------------------------------------------------- 1 | ## 216. Combination Sum III (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/combination-sum-iii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 从 1-9 中取出 k 个数,使他们的和是 n,问所有的取法。 9 | 10 | ### **分析**: 11 | 跟系列前两题差不多,不过这题的 candidates 是 1-9,而且限制了 k 个数。 12 | 13 | 1. 用 DFS 会比前两题好做,而且因为题目的原因,测试数据都不会很大,所以 DFS 都是 0 ms的。 14 | 2. 这题应该是可以用 DP 做的,因为 n,k 都不会很大,k 大于 10、n 大于一个最大值后是无解的。(然而要存的状态有点麻烦,所以先放着) 15 | -------------------------------------------------------------------------------- /solutions/224.Basic_Calculator/readme.md: -------------------------------------------------------------------------------- 1 | ## 224. Basic Calculator (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/basic-calculator/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 实现一个只有 `+-()` 的计算器。 10 | 11 | ### **分析**: 12 | 13 | 题目已经说不能用 `eval` 这种内建函数了。 14 | 由于只有 `+-`,题目难度小了很多。 15 | 16 | 1. 主要的难点在括号,在遇到括号时可以把之前算好的结果和括号前的符号放到栈里,括号结束后再取出来计算。 17 | 2. 用小学时学的去括号来做,括号前面是 `-` 要变号,这也要一个栈来保存每个 ( 前的符号。 18 | 3. 当然可以用递归来做,遇到左括号时进递归,右括号退出。 19 | -------------------------------------------------------------------------------- /solutions/235.Lowest_Common_Ancestor_of_a_Binary_Search_Tree/readme.md: -------------------------------------------------------------------------------- 1 | ## 235. Lowest Common Ancestor of a Binary Search Tree (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 求一个搜索二叉树的 LCA(最近公共祖先)。 10 | 11 | ### **分析**: 12 | 13 | 可以利用二叉树的性质做,只要从根节点向下找,如果 `leftval <= sub_root.val <= rightval`,那 sub_root 就是他们的 LCA。 14 | 可以用递归做,也可以迭代做。 15 | 16 | -------------------------------------------------------------------------------- /solutions/093.Restore_IP_Addresses/readme.md: -------------------------------------------------------------------------------- 1 | ## 093.Restore_IP_Addresses 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/restore-ip-addresses/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个都是字母的字符串,加上点后可能会变成合法的 IP 地址,求一个字符串的所有合法地址。 9 | 10 | ### **分析**: 11 | 12 | 不是很难的题目。 13 | 14 | 1. DFS 过去,注意要处理一些细节 15 | 2. 因为只有四个域,只要枚举每个域的长度,然后拆开字符串一个个判断就行了。 16 | 17 | 这里用的是第二种方法,比较容易理解。 18 | Python 有方便的 str() 和 int(),可以很方便的用 lambda 和 map 实现判断部分。 19 | -------------------------------------------------------------------------------- /solutions/106.Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal/readme.md: -------------------------------------------------------------------------------- 1 | ## 106. Construct Binary Tree from Inorder and Postorder Traversal (Medium) 2 | 3 | ### **链接**: 4 | https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 从中序后序遍历建树。 9 | 10 | ### **分析**: 11 | 用递归直接模拟就可以了。 12 | 这里可以倒着来,这样就跟 `105. Construct Binary Tree from Preorder and Inorder Traversal` 一样了,不用再想一遍。 13 | -------------------------------------------------------------------------------- /solutions/153.Find_Minimum_in_Rotated_Sorted_Array/readme.md: -------------------------------------------------------------------------------- 1 | ## 153. Find Minimum in Rotated Sorted Array (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 在一个旋转过的有序数组中找最小的数。 9 | 10 | ### **分析**: 11 | 跟 [033. Search in Rotated Sorted Array](https://github.com/illuz/leetcode/tree/master/solutions/033.Search_in_Rotated_Sorted_Array) 很像,同样是二分的变形。 12 | 二分的时候分类讨论就行了。 13 | -------------------------------------------------------------------------------- /solutions/178.Rank_Scores/AC_variables.sql: -------------------------------------------------------------------------------- 1 | SELECT Score, 2 | ( 3 | CASE 4 | # if prev = curRow.Score then return rank 5 | WHEN @prev = Score THEN @rank 6 | # else let prev = curRow.Score, rank++, and return rank 7 | WHEN (@prev := Score) IS NOT NULL THEN @rank := @rank + 1 8 | END 9 | ) 10 | FROM Scores, 11 | # SELECT to initialize rank, prev. The 'a': Every derived table must have its own alias 12 | (SELECT @rank := 0, @prev := NULL) a 13 | ORDER BY Score DESC 14 | 15 | -------------------------------------------------------------------------------- /solutions/089.Gray_Code/AC_simulation_2^n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_2^n.py 5 | # Create Date: 2015-02-20 10:21:11 6 | # Usage: AC_simulation_2^n.py 7 | # Descripton: 8 | 9 | class Solution: 10 | # @return a list of integers 11 | def grayCode(self, n): 12 | return map(lambda x: x^(x>>1), xrange(1< 4 | # File: AC_sort_nlogn.py 5 | # Create Date: 2015-08-11 20:41:43 6 | # Usage: AC_sort_nlogn.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param {integer[]} nums 12 | # @param {integer} k 13 | # @return {integer} 14 | def findKthLargest(self, nums, k): 15 | return sorted(nums)[-k] 16 | -------------------------------------------------------------------------------- /solutions/217.Contains_Duplicate/AC_set_nlogn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_set_nlogn.py 5 | # Create Date: 2015-07-13 21:46:54 6 | # Usage: AC_set_nlogn.py 7 | # Descripton: 8 | 9 | class Solution: 10 | def containDuplicate(self, nums): 11 | return len(set(nums)) != len(nums) 12 | 13 | s = Solution() 14 | print(s.containDuplicate([1, 2, 3, 4])) 15 | print(s.containDuplicate([2, 2, 3, 4])) 16 | -------------------------------------------------------------------------------- /solutions/011.Container_With_Most_Water/readme.md: -------------------------------------------------------------------------------- 1 | ## 011.Container_With_Most_Water 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/container-with-most-water/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一些挡板,选两个挡板,求最大蓄水容量。 9 | 10 | ### **分析**: 11 | 12 | 可以看看[这个大神的详细算法](http://www.cnblogs.com/TenosDoIt/p/3812880.html),给跪... 13 | 14 | 1. 暴力 O(n*n) 会超时 15 | 2. 双指针,O(n) 时间和 O(1) 空间,应该是最优的算法了,上述的文章有这个算法的正确性证明。 16 | 3. 预处理每个挡板的左边最高和右边最高,这样蓄水区间就可以知道了 17 | 18 | 这里只用了第二种算法。 19 | -------------------------------------------------------------------------------- /solutions/031.Next_Permutation/readme.md: -------------------------------------------------------------------------------- 1 | ## 031. Next Permutation (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/next-permutation/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求一个序列的下一个排列。 9 | 10 | ### **分析**: 11 | 12 | 可以用 STL 里的 'next_permutation' 偷懒。 13 | 14 | 具体算法是: 15 | 16 | > 首先,从最尾端开始往前寻找两个相邻的元素,令第一个元素是 i,第二个元素是 ii,且满足 `i 然后,再从最尾端开始往前搜索,找出第一个大于 i 的元素,设其为 j; 18 | > 然后,将 i 和 j 对调,再将 ii 及其后面的所有元素反转。 19 | 20 | -------------------------------------------------------------------------------- /solutions/098.Validate_Binary_Search_Tree/readme.md: -------------------------------------------------------------------------------- 1 | ## 098.Validate_Binary_Search_Tree 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/validate-binary-search-tree/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 判断一个树是否是搜索二叉树 (BST) 9 | 10 | ### **分析**: 11 | 12 | 有几种解法: 13 | 14 | 1. 直接 DFS ,判断这棵子树是否是在 [maxval, minval] 范围中 15 | 2. 中序遍历下,判断序列是否是递增的 16 | 3. DFS ,每次返回最大值或最小值,再进行判断 17 | 18 | 都不是很难实现。 19 | 这里用的是第一种方法,需要注意的坑是 maxval 和 minval 会有超 int 的情况,所以用 long long 类型。 20 | -------------------------------------------------------------------------------- /solutions/190.Reverse_Bits/AC_one_line_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_one_line_n.py 5 | # Create Date: 2015-03-16 10:42:01 6 | # Usage: AC_one_line_n.py 7 | # Descripton: 8 | 9 | class Solution: 10 | # @param n, an integer 11 | # @return an integer 12 | def reverseBits(self, n): 13 | return int(bin(n)[2:].zfill(32)[::-1], 2) 14 | 15 | # debug 16 | s = Solution() 17 | print s.reverseBits(25235) 18 | -------------------------------------------------------------------------------- /solutions/326.Power_of_Three/AC_math_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_math_1.cpp 4 | * Create Date: 2016-02-23 01:18:19 5 | * Descripton: i 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | const int N = 0; 13 | 14 | class Solution { 15 | public: 16 | bool isPowerOfThree(int n) { 17 | return fmod(log10(n)/log10(3), 1)==0; 18 | } 19 | }; 20 | 21 | int main() { 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /solutions/010.Regular_Expression_Matching/AC_regex_n!.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_regex_n!.py 5 | # Create Date: 2015-03-02 09:50:01 6 | # Usage: AC_regex_n!.py 7 | # Descripton: 8 | 9 | 10 | import re 11 | 12 | class Solution: 13 | # @return a boolean 14 | def isMatch(self, s, p): 15 | return re.match('^' + p + '$', s) != None 16 | 17 | # debug 18 | s = Solution() 19 | print s.isMatch("aa", "a*") 20 | 21 | -------------------------------------------------------------------------------- /solutions/230.Kth_Smallest_Element_in_a_BST/readme.md: -------------------------------------------------------------------------------- 1 | ## 230. Kth Smallest Element in a BST (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/kth-smallest-element-in-a-bst/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 标题清楚说明了题意,求 BST 上的第 k 小。 10 | 11 | ### **分析**: 12 | 13 | 因为是 BST,所以直接 DFS 求树大小,在求的时候找出第 k 大就行了。 14 | 当然 DFS 的缺陷就是用了 O(log(n)) 的空间。 15 | 用非递归的解法就可以 O(1) 空间了。可以看:https://leetcode.com/discuss/46160/o-n-time-o-1-space-by-using-morris-inorder-traverse 16 | -------------------------------------------------------------------------------- /solutions/283.Move_Zeroes/AC_stl_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_stl_n.cpp 4 | * Create Date: 2015-09-24 11:13:56 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | void moveZeroes(vector& nums) { 16 | return fill(remove(nums.begin(), nums.end(), 0), nums.end(), 0); 17 | } 18 | }; 19 | 20 | int main() { 21 | 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /solutions/026.Remove_Duplicates_from_Sorted_Array/AC_STL_nlogn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_STL_nlogn.cpp 4 | * Create Date: 2015-03-05 15:34:55 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int removeDuplicates(int A[], int n) { 16 | return distance(A, unique(A, A + n)); 17 | } 18 | }; 19 | 20 | int main() { 21 | 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /solutions/026.Remove_Duplicates_from_Sorted_Array/readme.md: -------------------------------------------------------------------------------- 1 | ## 026. Remove Duplicates from Sorted Array (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个有序数列,删重复的元素。 9 | 10 | ### **分析**: 11 | 如果可以开一个数组来存就非常容易。但是这题不让你用多余的空间。 12 | 不过也不难,只要维护一个新的坐标就行了。 13 | 用 C++ 的 STL 可以只要一句话:用 `unique` 实现功能,用 `distance` 计算大小。 14 | (之前看错题以为是无序的,写了几个无序的版本) 15 | 16 | Java 和 Python 的写法都和 C++ 的一样,这里就不写出来了。 17 | -------------------------------------------------------------------------------- /solutions/031.Next_Permutation/AC_STL_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_STL_1.cpp 4 | * Create Date: 2015-01-17 11:02:10 5 | * Descripton: Use next_permutation 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | void nextPermutation(vector &num) { 16 | next_permutation(num.begin(), num.end()); 17 | } 18 | }; 19 | 20 | int main() { 21 | 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /solutions/154.Find_Minimum_in_Rotated_Sorted_Array_II/README.md: -------------------------------------------------------------------------------- 1 | ## 154. Find Minimum in Rotated Sorted Array II (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 在一个旋转过的有序数组中找最小的数。不过里面的数有重复。 9 | 10 | ### **分析**: 11 | 12 | 与[上一题](https://github.com/illuz/leetcode/tree/master/solutions/153.Find_Minimum_in_Rotated_Sorted_Array) 差不多,不过在判断到前后相同时,不能一下子就判断,要把范围向内缩。 13 | 因此,这个解法复杂度最坏是 O(n) 是全部都一样的数的。 14 | -------------------------------------------------------------------------------- /solutions/225.Implement_Stack_using_Queues/readme.md: -------------------------------------------------------------------------------- 1 | ## 225. Implement Stack using Queues (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/Implement-Stack-using-Queues/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 用 queue 实现 stack。 9 | 只能用 queue 的基本操作。 10 | 11 | ### **分析**: 12 | 13 | 1. 直接用两个 queue 模拟,在 pop 和 top 的时候需要 O(n) 时间(top 可以用一个值维护,可以O(1))(我不想用 size 方法,所以用两个 queue,不然用一个 queue 就行了) 14 | 2. O(1) 的算法是用链表实现 Queue,这样在 pop 和 top 时使用连接操作,就只要 O(1) 时间了,不过这可能有违题意(Java 的 Queue) 15 | -------------------------------------------------------------------------------- /solutions/151.Reverse_Words_in_a_String/readme.md: -------------------------------------------------------------------------------- 1 | ## 151. Reverse Words in a String (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/reverse-words-in-a-string/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 反转句子里的单词。 9 | 10 | ### **分析**: 11 | 12 | 1. **(C++)** 用 stringstream 可以很方便求出来,不过空间还是用得不少。时间复杂度 O(n),空间 O(n)。 13 | 2. **(Java)** 用 `String` 的 `trim` 和 `split` 分成字符串数组,再处理 14 | 3. **(Python)** 一句话就行了。 15 | 4. **(C)** 如何达到 O(1) 空间?这才是这题真正考察的地方。其实只要反转每个单词,最后再反转整个句子就行了。时间复杂度同样是 O(n)。 16 | -------------------------------------------------------------------------------- /solutions/139.Word_Break/readme.md: -------------------------------------------------------------------------------- 1 | ## 139. Word Break (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/word-break/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 给一个字符串和一个字典,问这个字符串能否用字典中的单词拼接成。 10 | 11 | ### **分析**: 12 | 13 | 1. 直接暴力地把字符串切割了,是 O(2^n) 复杂度,必须超时。(这里用 DFS 实现) 14 | 2. 很明显,暴力做了太多的重复问题,所以可以在 DFS 时记忆化一下,当然也可以用 DP 转移公式来做:`dp[i][j] = dp[i][k] && dp[k][j],(i 2 | # File: AC_Newton_logn.py 3 | # Create Date: 2015-02-06 23:33:33 4 | # Descripton: 5 | 6 | class Solution: 7 | # @param x, an integer 8 | # @return an integer 9 | def sqrt(self, x): 10 | if x == 0: 11 | return 0 12 | lasty, y = 0.0, 1.0 13 | while y != lasty: 14 | lasty = y 15 | y = (y + x / y) / 2.0 16 | return int(y) 17 | 18 | s = Solution() 19 | print s.sqrt(3) 20 | 21 | -------------------------------------------------------------------------------- /solutions/177.Nth_Highest_Salary/readme.md: -------------------------------------------------------------------------------- 1 | ## 177. Nth Highest Salary (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/nth-highest-salary/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求第 N 大的工资。 9 | 10 | ### **分析**: 11 | 12 | [176.Second_Highest_Salary](https://github.com/illuz/leetcode/tree/master/solutions/176.Second_Highest_Salary) 的变形题。 13 | 算法题做多了,我一下就写了个递归,然后被告知 SQL 不能用递归。 14 | 可以用 `ORDER BY` 排序,再用 `LIMIT` 返回第 N 大值。 15 | 题目要求返回值是 INT 或 NULL,所以我们可以用 `DISTINCT` 或用 `IFNULL(..., NULL)`。 16 | -------------------------------------------------------------------------------- /solutions/189.Rotate_Array/readme.md: -------------------------------------------------------------------------------- 1 | ## 189. Rotate Array (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/rotate-array/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 把一个数组左旋转 k 步。如 `[1,2,3,4,5,6,7]` is rotated to `[5,6,7,1,2,3,4]`。 10 | 11 | ### **分析**: 12 | 13 | 这题很容易,模拟一下就能出来了。 14 | 不过如果要用 O(1) 的空间就要想想了。 15 | 把 `[0, n-k-1]` 和 `[n-k,n-1]` 看成一个单词,这样就和 [151 Reverse Words in a String](https://github.com/illuz/leetcode/tree/master/solutions/151.Reverse_Words_in_a_String) 一样可以 O(1) 的空间完成了。 16 | 17 | -------------------------------------------------------------------------------- /solutions/238.Product_of_Array_Except_Self/readme.md: -------------------------------------------------------------------------------- 1 | ## 238. Product of Array Except Self (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/product-of-array-except-self/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把一个数组中的每个数 替换为 这个数组中除了它自身的其它数的积。 9 | 10 | ### **分析**: 11 | 12 | 1. 最暴力的是直接在每个位置计算其它数的积,时间复杂度 O(n*n)。 13 | 2. 先算出所有的数的积,再去用除法求出解,要注意数组里可能会有 0,一个 0 和多个 0 的情况是不一样的。空间复杂度是 O(1),时间是 O(n)。 14 | 3. 其实就是算每个位置上左边的数和右边的数的积,所以可以开数组预处理出每个位置左右两边的积,然后再相乘就行了。实际做的时候只要用一个数组记录一边就行了,另一边可以一边算一边得出解来。 15 | 16 | -------------------------------------------------------------------------------- /solutions/191.Number_of_1_Bits/AC_bitset_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_bitset_n.cpp 4 | * Create Date: 2015-03-16 10:58:56 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int hammingWeight(uint32_t n) { 16 | const int size = 32; 17 | bitset bits(n); 18 | return bits.count(); 19 | } 20 | }; 21 | 22 | int main() { 23 | 24 | return 0; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /solutions/009.Palindrome_Number/AC_simulation2_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation2_n.py 5 | # Create Date: 2015-02-28 22:51:48 6 | # Usage: AC_simulation2_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @return a boolean 12 | def isPalindrome(self, x): 13 | xx = x 14 | new_xx = 0 15 | while xx > 0: 16 | new_xx = new_xx * 10 + xx % 10 17 | xx /= 10 18 | 19 | return new_xx == x 20 | -------------------------------------------------------------------------------- /solutions/076.Minimum_Window_Substring/readme.md: -------------------------------------------------------------------------------- 1 | ## 076. Minimum Window Substring (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/minimum-window-substring/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个原字符串 S,和一个匹配串 T,求 S 最小的子串(窗口)包含全部 T 的字符。 9 | 10 | ### **分析**: 11 | 跟 '030.Substring_with_Concatenation_of_All_Words' 很像,思路和做法是一样的。 12 | 用快慢指针,快指针跑到匹配的位置,再向前缩慢指针。 13 | 计算匹配可以利用 Hash 来计算有效的字母,Hash 可以用 HashMap(Java),unordered_map(C++),也可以直接用数组。用数组会比较快。 14 | 15 | 这里 Java 和 Python 的写法和 C++ 的基本一样,就不给出了。 16 | -------------------------------------------------------------------------------- /solutions/078.Subsets/AC_collections_combinations_2^n.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_collections_combinations_2^n.py 3 | # Create Date: 2015-02-08 10:45:15 4 | # Descripton: 5 | 6 | from itertools import * 7 | class Solution: 8 | # @param S, a list of integer 9 | # @return a list of lists of integer 10 | def subsets(self, S): 11 | S.sort() 12 | res = [] 13 | for i in xrange(len(S) + 1): 14 | res += list(list(x) for x in combinations(S, i)) 15 | return res 16 | 17 | -------------------------------------------------------------------------------- /solutions/122.Best_Time_to_Buy_and_Sell_Stock_II/readme.md: -------------------------------------------------------------------------------- 1 | ## 122. Best Time to Buy and Sell Stock II (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个数组,`prices[i]` 表示第 i 天的交易值,也就是你在这天买入或卖出的交易值。 9 | 你可以买入及卖出多轮,不过你一个时间只能拥有一个股票,求最大盈利。 10 | 11 | ### **分析**: 12 | 刚开始以为一天只能交易一次,没想到同一天你可以先卖出再买入。 13 | 这样就很容易了,贪心就行了,考虑 [1, 2, 3],你可以 [-1, +2-2, +3],跟 [-1, +3] 是一样的,也就是说只要比前一天多,你就可以在前一天买入,接下去一天卖出,这样稳赚不赔。 14 | 用 Python 可以用一句话解决~ 15 | 16 | -------------------------------------------------------------------------------- /solutions/134.Gas_Station/readme.md: -------------------------------------------------------------------------------- 1 | ## 134. Gas Station (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/gas-station/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 提供数组 gas、cost,gas表示第i个点的汽油量,cost表示从i到i+1所需的汽油量,问是否有一点,出发能驶过所有点(路径是环)。 9 | 10 | ### **分析**: 11 | 12 | 1. 暴力枚举每个点,走一遍。复杂度是 O(n^2),不理想。 13 | 2. 考虑从 i 点出发,只能走到 j 点,其原因是从 i 到 j 积累的汽油量 `sum_gas[i~j]` 不够从 j 到 j+1 的费用 `cost[j]`,因为 gas,cost 都是非负的,所以即使从 [i,j] 中的一个点出发,积累的汽油量也不会大于 `sum_gas[i~j]` 的,所以从 [i,j] 出发是徒劳的,一旦走失败了,就可以跳过 [i,j] 从 j+1 开始,这样就可以很大的优化了。复杂度是 O(n)。 14 | -------------------------------------------------------------------------------- /solutions/173.Binary_Search_Tree_Iterator/readme.md: -------------------------------------------------------------------------------- 1 | ## 173. Binary Search Tree Iterator (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/binary-search-tree-iterator/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 实现一个 BST 的类。 9 | 10 | ### **分析**: 11 | 12 | 1. **(C++)** 初始化的时候就将中序遍历处理好,保存在 queue 里 13 | 2. **(Python)** 用 stack 做,一边求一边处理即可。 14 | 3. Morris Travese Tree,可以用 O(1) 的空间解决这题,详见 [099. Recover Binary Search Tree (Hard)](https://github.com/illuz/leetcode/blob/master/solutions/099.Recover_Binary_Search_Tree) 15 | -------------------------------------------------------------------------------- /solutions/197.Rising_Temperature/AC_CASE_WHEN.sql: -------------------------------------------------------------------------------- 1 | # 1056 ms 2 | 3 | SELECT Id 4 | FROM ( 5 | SELECT Id, ( 6 | CASE 7 | WHEN (@prevDate + 1 = TO_DAYS(Date)) AND (@prevTemp < Temperature) THEN ((@prevTemp := Temperature) IS NOT NULL AND (@prevDate := TO_DAYS(Date)) IS NOT NULL) 8 | WHEN ((@prevTemp := Temperature) IS NOT NULL AND (@prevDate := TO_DAYS(Date)) IS NOT NULL) THEN FALSE 9 | END 10 | ) flag 11 | FROM Weather, (SELECT @prevTemp := NULL, @prevDate := NULL) a 12 | ORDER BY Date 13 | ) c 14 | WHERE flag = TRUE 15 | -------------------------------------------------------------------------------- /solutions/217.Contains_Duplicate/AC_set_nlogn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_set_nlogn.cpp 4 | * Create Date: 2015-07-13 20:48:14 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool containsDuplicate(vector& nums) { 16 | set s(nums.begin(), nums.end()); 17 | return s.size() != nums.size(); 18 | } 19 | }; 20 | 21 | int main() { 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /solutions/231.Power_of_Two/AC_bitwize2_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_bitwize2_1.cpp 4 | * Create Date: 2015-07-12 20:00:44 5 | * Descripton: Better bitwize 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | 12 | class Solution { 13 | public: 14 | bool isPowerOfTwo(int n) { 15 | if (n <= 0) { 16 | return false; 17 | } 18 | n &= (n - 1); 19 | return n == 0; 20 | } 21 | }; 22 | 23 | int main() { 24 | 25 | return 0; 26 | } 27 | 28 | -------------------------------------------------------------------------------- /solutions/168.Excel_Sheet_Column_Title/AC_simulation_1.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_simulation_1.py 3 | # Create Date: 2015-02-05 09:41:17 4 | # Descripton: 5 | 6 | 7 | class Solution: 8 | # @return a string 9 | def convertToTitle(self, num): 10 | ret = [] 11 | while num > 0: 12 | ret += chr(ord('A') + (num - 1) % 26) 13 | num = (num - 1) // 26 14 | ret.reverse() 15 | return ''.join(ret) 16 | 17 | # debug 18 | s = Solution() 19 | print s.convertToTitle(29) 20 | 21 | -------------------------------------------------------------------------------- /solutions/191.Number_of_1_Bits/readme.md: -------------------------------------------------------------------------------- 1 | ## 191. Number of 1 Bits (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/number-of-1-bits/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 计算一个数二进制里 1 的个数。 9 | 10 | ### **分析**: 11 | 12 | 跟 [190. Reverse Bits (Easy)]https://github.com/illuz/leetcode/tree/master/solutions/190.Reverse_Bits) 一样。 13 | 14 | 1. 先转 string 再计算 15 | 2. 或者用位运算来算 (Java 实现时要用 `>>>` 来进行位移,因为 `>>` 是会移到符号位的,`>>>` 是用来操作 unsigned 数的) 16 | 3. C++ Trick: 用 `bitset` 的 `count` 17 | 4. Python Trick: 用 `bin()` 和 `count()` 18 | -------------------------------------------------------------------------------- /solutions/193.Valid_Phone_Numbers/readme.md: -------------------------------------------------------------------------------- 1 | ## 193. Valid Phone Numbers (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/valid-phone-numbers/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 用 Shell Script 输出 `(xxx) xxx-xxxx` or `xxx-xxx-xxxx` 格式的号码。 9 | 10 | ### **分析**: 11 | 12 | 这题考察的是正则表达式。 13 | 可惜我写的正则是很挫的。 14 | 15 | 1. 用 sed 做:`sed -n '/expression/p'` 16 | 2. 用 grep 做:`grep 'expression'` 17 | 3. 用 egrep 做:`egrep 'expression'`,egrep 的正则和 grep 的不太一样。 18 | 4. 用 awk 做:`awk '/expression/ {print}`,awk 的匹配式不太支持正则表达式,比较难用。 19 | -------------------------------------------------------------------------------- /solutions/231.Power_of_Two/AC_bitwize_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_bitwize_1.cpp 4 | * Create Date: 2015-07-12 19:47:54 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | 12 | class Solution { 13 | public: 14 | bool isPowerOfTwo(int n) { 15 | for (int i = 0; i < 32; ++i) 16 | if (((n >> i) == 1) && (1 << i) == n) 17 | return true; 18 | return false; 19 | } 20 | }; 21 | 22 | int main() { 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /solutions/326.Power_of_Three/readme.md: -------------------------------------------------------------------------------- 1 | ## 326. Power of Three (Easy) 2 | 3 | 4 | 5 | ### **链接**: 6 | 7 | 题目:https://leetcode.com/problems/power-of-three/ 8 | 代码(github):https://github.com/illuz/leetcode 9 | 10 | ### **题意**: 11 | 12 | 判断一个数是否是 3 的次方数。 13 | 14 | ### **分析**: 15 | 16 | 1. 最普通的做法:用 3 一次一次除,能除尽就是了。 17 | 2. 用 log 去做,中学数学题,`x=log3(y)=(log2(y)/log2(3))`,然后判断 x 是不是整数就行了。(考察点:浮点数的计算) 18 | 3. tricky 的做法,因为参数是 int 类型的,所以 3 的次方就那么几个,先全算出来。 19 | 4. 也是 tricky 的做法,直接判断能不能被 1162261467 整除,1162261467 是 int 内最大的 (3^x) 数,也就是说它的因子都是 3,能被它整除的数就一定也是 (3^x) 数。 20 | 21 | 22 | -------------------------------------------------------------------------------- /solutions/202.Happy_Number/readme.md: -------------------------------------------------------------------------------- 1 | ## 202. Happy Number (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/submissions/detail/26084443/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 给一个操作,每次对一个数的每一位平方求和。 10 | 现在给一个数,对这个数循环操作,如果这个数可以变成 1,那这个数就是 Happy Number。 11 | 问这个数是不是 Happy Number。 12 | 13 | ### **分析**: 14 | 15 | 1. 可以直接模拟,用 HashMap 可以很方便地做。 16 | 2. 参考 [141. Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) 的 [Two Point 解法](https://github.com/illuz/leetcode/tree/master/solutions/141.Linked_List_Cycle) 来做,很方便的。 17 | -------------------------------------------------------------------------------- /solutions/215.Kth_Largest_Element_in_an_Array/AC_sort_nlogn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_sort_nlogn.cpp 4 | * Create Date: 2015-08-11 20:07:33 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int findKthLargest(vector& nums, int k) { 16 | sort(nums.begin(), nums.end()); 17 | return nums[nums.size() - k - 1]; 18 | } 19 | }; 20 | 21 | int main() { 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /solutions/232.Implement_Queue_using_Stacks/readme.md: -------------------------------------------------------------------------------- 1 | ## 232. Implement Queue using Stacks (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/implement-queue-using-stacks/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 用栈实现队列。 10 | 11 | ### **分析**: 12 | 13 | 1. 用两个栈做,一个主要数据,一个在 push 时临时倒出数据用的(当然也可以反着放数据,在 pop 和 peek 时再倒出数据) 14 | 2. 用两个栈做,一个做为前面专门做 pop(),一个做为后面的栈专门做 push(),通过两个栈协调可以做到平均 O(1) 的操作。(参考 [c++solution using two stack ,average O(1) time](https://leetcode.com/discuss/44482/c-solution-using-two-stack-average-o-1-time)) 15 | -------------------------------------------------------------------------------- /solutions/122.Best_Time_to_Buy_and_Sell_Stock_II/AC_greedy_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_greedy_n.py 5 | # Create Date: 2015-03-12 11:14:05 6 | # Usage: AC_greedy_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param prices, a list of integer 12 | # @return an integer 13 | def maxProfit(self, prices): 14 | return sum(y - x for x, y in zip(prices[:-1], prices[1:]) if x < y) 15 | 16 | # debug 17 | s = Solution() 18 | print s.maxProfit([1, 3, 4]) 19 | 20 | -------------------------------------------------------------------------------- /solutions/169.Majority_Element/AC_Moore_n.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_Moore_n.py 3 | # Create Date: 2015-02-05 10:48:49 4 | # Descripton: 5 | 6 | class Solution: 7 | # @param num, a list of integers 8 | # @return an integer 9 | def majorityElement(self, num): 10 | cnt = 0 11 | for i in num: 12 | if cnt == 0: 13 | ret = i 14 | cnt += 1 if ret == i else -1 15 | return ret 16 | 17 | # debug 18 | s = Solution() 19 | print s.majorityElement([1, 2, 2, 2, 3]) 20 | 21 | -------------------------------------------------------------------------------- /solutions/217.Contains_Duplicate/AC_sort_nlogn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_sort_nlogn.cpp 4 | * Create Date: 2015-07-13 21:41:31 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool containsDuplicate(vector& nums) { 16 | sort(nums.begin(), nums.end()); 17 | return unique(nums.begin(), nums.end()) != nums.end(); 18 | } 19 | }; 20 | 21 | int main() { 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /solutions/263.Ugly_Number/AC_simulation_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_1.py 5 | # Create Date: 2015-08-20 09:32:20 6 | # Usage: AC_simulation_1.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param {integer} num 12 | # @return {boolean} 13 | def isUgly(self, num): 14 | if num <= 0: 15 | return False 16 | for i in [2, 3, 5]: 17 | while num % i == 0: 18 | num /= i 19 | return num == 1 20 | -------------------------------------------------------------------------------- /solutions/242.Valid_Anagram/AC_simulation_nlogn.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_n.py 5 | # Create Date: 2015-08-04 18:33:10 6 | # Usage: AC_simulation_n.py 7 | # Descripton: 8 | 9 | class Solution: 10 | # @param {string} s 11 | # @param {string} t 12 | # @return {boolean} 13 | def isAnagram(self, s, t): 14 | s = sorted(s) 15 | t = sorted(t) 16 | return s == t 17 | 18 | # test 19 | s = Solution() 20 | print s.isAnagram('abc', 'cba') -------------------------------------------------------------------------------- /solutions/001.Two_Sum/AC_dict_nlogn.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_dict_nlogn.py 3 | # Create Date: 2015-02-01 23:03:27 4 | # Descripton: Using dict 5 | 6 | class Solution: 7 | # @return a tuple, (index1, index2) 8 | def twoSum(self, num, target): 9 | dictMap = {} 10 | for index, value in enumerate(num): 11 | if target - value in dictMap: 12 | return dictMap[target - value] + 1, index + 1 13 | dictMap[value] = index 14 | 15 | 16 | # debug 17 | s = Solution() 18 | print s.twoSum([1, 2, 3, 4], 4) 19 | 20 | -------------------------------------------------------------------------------- /solutions/003.Longest_Substring_Without_Repeating_Characters/AC_record_n.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_record_n.py 3 | # Create Date: 2015-02-02 21:15:02 4 | # Descripton: 5 | 6 | 7 | class Solution: 8 | # @return an integer 9 | def lengthOfLongestSubstring(self, s): 10 | res = 0 11 | left = 0 12 | d = {} 13 | 14 | for i, ch in enumerate(s): 15 | if ch in d and d[ch] >= left: 16 | left = d[ch] + 1 17 | d[ch] = i 18 | res = max(res, i - left + 1) 19 | return res 20 | 21 | -------------------------------------------------------------------------------- /solutions/239.Sliding_Window_Maximum/readme.md: -------------------------------------------------------------------------------- 1 | ## 239. Sliding Window Maximum (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/sliding-window-maximum/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 求一个数组中,固定大小的滑动窗口滑过,这个窗口中每一步的最大值。 10 | 11 | ### **分析**: 12 | 13 | 暴力 O(n*k) 是可以过的。(测试数据不够给力啊,这还是 Hard 的呢。) 14 | 要如何在在更快的时间内解决这个问题呢?其实有几种做法。 15 | 16 | 1. 求一个窗口的最大值,不就是一个堆吗。维护一个最大堆,每次把要去掉的去掉,要加进来的加进来,然后取最大的。不过要找到该去掉的,在堆里面要 O(log(k)) 的时间,所以复杂度是 O(n*logk) 17 | 2. 要做到 O(n) 的话,要用到 Max-queue,这个数据结构的思想和 [155. Min Stack](https://leetcode.com/problems/min-stack/) 有点像,不过这里面是一个单调队列。 18 | -------------------------------------------------------------------------------- /solutions/032.Longest_Valid_Parentheses/readme.md: -------------------------------------------------------------------------------- 1 | ## 032. Longest Valid Parentheses (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/longest-valid-parentheses/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 问一个字符串里最长的合法括号串的长度。 9 | 10 | ### **分析**: 11 | 12 | 1. **(C++)**用栈来做,如果匹配就出栈,然后长度就是 `cur - stack_top_pos` 也就是 - 匹配的前一个位置。 O(n) time, O(n) space。 13 | 2. **(C++)**栈消耗空间太多了,其实可以维护 () 匹配的长度,不过可能出现 `()))` 和 `((()` 的情况,所以要前后各扫一遍。O(n) time, O(1) space。 14 | 3. 用较复杂的 DP 来做,不过空间可没解法 2 那么优了。刚看到[我很久前的一个解法](http://blog.csdn.net/hcbbt/article/details/15494035),用太多空间了Orz。现在来看还是 1、2 的做法好。 15 | -------------------------------------------------------------------------------- /solutions/037.Sudoku_Solver/readme.md: -------------------------------------------------------------------------------- 1 | ## 037. Sudoku Solver (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/sudoku-solver/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求解一个数独。 9 | 10 | ### **分析**: 11 | DFS 暴力就行了。 12 | 用二进制表示,位运算处理的话,会快很多的。 13 | 14 | 其实在一个 `(n^2) * (n^2)` 的格中放 `n * n` 数,这是个 NP 难问题,就 9x9 的方格,就有 `9^81` 种组合,用 DFS 遍历一遍是不可想象的,所以在解一个空一点的 9x9 时就要跑好久。 15 | 有个比较常用的优化方法就是用 `Dancing Links`,不过这也只是个剪枝,它仍是个 NP 难问题。 16 | 17 | Link: 18 | - [Sudoku - Wikipedia](http://en.wikipedia.org/wiki/Sudoku) 19 | - - [Dancing Links](http://en.wikipedia.org/wiki/Dancing_Links) 20 | -------------------------------------------------------------------------------- /solutions/205.Isomorphic_Strings/AC_dict_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_dict_n.py 5 | # Create Date: 2015-05-02 11:47:46 6 | # Usage: AC_dict_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param {string} s 12 | # @param {string} t 13 | # @return {boolean} 14 | def isIsomorphic(self, s, t): 15 | return dict(zip(s, t)) == dict(reversed(list(zip(s, t)))) and dict(zip(t, s)) == dict(reversed(list(zip(t, s)))) 16 | 17 | # debug 18 | s = Solution() 19 | print (s.isIsomorphic('abcde', 'sdfgx')) 20 | -------------------------------------------------------------------------------- /solutions/005.Longest_Palindromic_Substring/readme.md: -------------------------------------------------------------------------------- 1 | ## 005.Longest_Palindromic_Substring (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/Longest-Palindromic-Substring/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求一个字符串中的最长回文子串。 9 | 10 | ### **分析**: 11 | 12 | 回文的解法有不少: 13 | 14 | 1. 暴力搜索 O(n^3) 15 | 2. 动态规划 O(n^2), `dp[i][j] = dp[i + 1][j - 1] (if s[i] == s[j])` 16 | 3. 用[Manacher's ALGORITHM](http://blog.csdn.net/hcbbt/article/details/18952129)可达到 O(n) 时间。 17 | 18 | 本题要用第三种算法。 19 | 需要注意的是, Python 和 Java 的字符串和 C++ 的不一样,没有 `\0` 结尾,用'Manacher's ALGORITHM'的时候是不一样的。 20 | -------------------------------------------------------------------------------- /solutions/007.Reverse_Integer/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_n.py 5 | # Create Date: 2015-02-27 10:03:36 6 | # Usage: AC_simulation_n.py 7 | # Descripton: 8 | 9 | 10 | import math 11 | 12 | class Solution: 13 | # @return an integer 14 | def reverse(self, x): 15 | revx = int(str(abs(x))[::-1]) 16 | if revx > math.pow(2, 31): 17 | return 0 18 | else: 19 | return revx * cmp(x, 0) 20 | 21 | # debug 22 | s = Solution() 23 | print s.reverse(1234) 24 | 25 | -------------------------------------------------------------------------------- /solutions/210.Course_Schedule_II/readme.md: -------------------------------------------------------------------------------- 1 | ## 210. Course Schedule II (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/course-schedule-ii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 学习课程 A 要先学课程 B,给出一些课程学习顺序,给出学完这些课程的全部顺序。 9 | 10 | ### **分析**: 11 | 跟 [207](https://github.com/illuz/leetcode/tree/master/solutions/207.Course_Schedule) 一样拓扑排序,不过要记录路径。 12 | 13 | 1. 用栈,只要每次记一下节点就行了。 14 | 2. 用 dfs,不能跟 207 一样直接一个一个 check 过去。先找出入度为 0 的节点,再 dfs 过去。dfs 中每个节点处理完子节点后再把自己节点加到路径中,这样就维护了一个倒序的路径,最后把这个路径反向一下就行了。 15 | 16 | 资料:[Topological sorting](https://en.wikipedia.org/wiki/Topological_sorting) -------------------------------------------------------------------------------- /solutions/027.Remove_Element/AC_simulate_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulate_n.cpp 4 | * Create Date: 2014-12-06 22:00:43 5 | * Descripton: simulate 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int removeElement(int A[], int n, int elem) { 16 | int ret = 0; 17 | for (int i = 0; i < n; i++) 18 | if (A[i] != elem) 19 | A[ret++] = A[i]; 20 | return ret; 21 | } 22 | }; 23 | 24 | int main() { 25 | 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /solutions/179.Largest_Number/AC_sort_nlogn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_sort_nlogn.py 5 | # Create Date: 2015-02-26 10:33:39 6 | # Usage: AC_sort_nlogn.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param num, a list of integers 12 | # @return a string 13 | def largestNumber(self, num): 14 | comp = lambda a, b: -1 if a + b > b + a else 1 if a + b < b + a else 0 15 | return str(int("".join(sorted(map(str, num), comp)))) 16 | 17 | # debug 18 | s = Solution() 19 | print s.largestNumber([0, 0, 5]) 20 | -------------------------------------------------------------------------------- /solutions/002.Add_Two_Numbers/readme.md: -------------------------------------------------------------------------------- 1 | ## 002.Add_Two_Numbers (Medium) 2 | 3 | 4 | ### **链接**: 5 | 题目:https://leetcode.com/problems/add-two-numbers/ 6 | 代码(github):https://github.com/illuz/leetcode 7 | 8 | ### **题意**: 9 | 求两个 List 相加产生的新的一个 List。 10 | 11 | ### **分析**: 12 | 直接模拟就可以了。 13 | 14 | --- 15 | 16 | **(English version)** 17 | 18 | ## 002.Add_Two_Numbers (Medium) 19 | 20 | 21 | **Link**: 22 | Problem: https://leetcode.com/problems/add-two-numbers/ 23 | Newest solutions in my Github: https://github.com/illuz/leetcode 24 | 25 | **Analysis**: 26 | Just simulation is enough. 27 | -------------------------------------------------------------------------------- /solutions/132.Palindrome_Partitioning_II/readme.md: -------------------------------------------------------------------------------- 1 | ## 132. Palindrome Partitioning II (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/palindrome-partitioning-ii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 把一个字符串分割,使每一部分都是回文。问最少的割数。 9 | 10 | ### **分析**: 11 | 12 | 1. **(C++)** 跟上题一样,递归求过去,不过会 TLE 13 | 2. 优化一,考虑对 1 进行优化,可以预处理子串是否是回文,就不用在这步重复算了 14 | 3. 优化二,既然可以用 DFS,当然可以记忆化了 15 | 4. **(Java)** 既然可以用记忆化,当然可以写成 DP 了 16 | 5. **(C++)** 在 DP 的时候,可以不用预处理判断是否回文,直接分奇偶讨论,见:[not need a table for palindrome](https://leetcode.com/discuss/9476/solution-does-not-need-table-palindrome-right-uses-only-space) 17 | -------------------------------------------------------------------------------- /solutions/188.Best_Time_to_Buy_and_Sell_Stock_IV/readme.md: -------------------------------------------------------------------------------- 1 | ## 188. Best Time to Buy and Sell Stock IV (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个数组,prices[i] 表示第 i 天的交易值,也就是你在这天买入或卖出的交易值。 9 | 你可以买入及卖出**最多k轮**,不过你一个时间只能拥有一个股票,求最大盈利。 10 | 11 | ### **分析**: 12 | 13 | 只要理解了 [`123. Best Time to Buy and Sell Stock III `](https://github.com/illuz/leetcode/tree/master/solutions/123.Best_Time_to_Buy_and_Sell_Stock_III) 的那个 O(1) 空间的算法,这个也可以那样变形过来。 14 | 15 | 注意,如果 k 大于数组的大小的一半,那就可以每相邻两天都能买了,所以可以直接用 III 版本的算法 O(n) 解决。 16 | -------------------------------------------------------------------------------- /solutions/201.Bitwise_AND_of_Numbers_Range/AC_loop_logn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_loop_logn.cpp 4 | * Create Date: 2015-04-24 22:16:36 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int rangeBitwiseAnd(int m, int n) { 16 | int move = 0; 17 | while (m != n) { 18 | m >>= 1; 19 | n >>= 1; 20 | ++move; 21 | } 22 | return m << move; 23 | } 24 | }; 25 | 26 | int main() { 27 | 28 | return 0; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /solutions/238.Product_of_Array_Except_Self/TLE_brute_force_n2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: TLE_brute_force_n2.py 5 | # Create Date: 2016-02-24 19:09:56 6 | # Usage: AC_brute_force_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution(object): 11 | def productExceptSelf(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: List[int] 15 | """ 16 | return [reduce(lambda x, y: x * y, nums[:i] + nums[i+1:]) for i in range(len(nums))] 17 | 18 | s = Solution() 19 | print(s.productExceptSelf([1, 2, 3, 4])) 20 | -------------------------------------------------------------------------------- /solutions/258.Add_Digits/readme.md: -------------------------------------------------------------------------------- 1 | ## 258. Add Digits (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/add-digits/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 用一个规则求一个数:38 -> 3+8=11 -> 1+1=2,结果是 2。 10 | 问能不能不用递归或迭代 O(1) 算出来。 11 | 12 | ### **分析**: 13 | 14 | 模拟很快。不过要 O(1) 算出来要想想了。 15 | 1 的结果是 1,2->2....9->9, 10->1, 11->2....18->9,19->1....27->9,28->1.... 16 | 是不是有点头绪了,没错,结果都是有规律的,到 9\18\27... 的时候会进一变成 1。 17 | 所以这样就容易了,答案是 (n-1)%9+1。 18 | 这是数论中的数根,感兴趣可以看 [Digital root - Wikipedia](https://en.wikipedia.org/wiki/Digital_root#Congruence_formula) 和 [A010888 - OEIS](https://oeis.org/A010888)。 19 | -------------------------------------------------------------------------------- /solutions/268.Missing_Number/AC_simulation_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_n.cpp 4 | * Create Date: 2015-10-29 18:10:37 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int missingNumber(vector& nums) { 16 | long long len = nums.size(); 17 | long long sum = len * (len + 1) / 2, sum2 = 0; 18 | for (auto i : nums) 19 | sum2 += i; 20 | return sum - sum2; 21 | } 22 | }; 23 | 24 | int main() { 25 | 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /solutions/071.Simplify_Path/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_simulation_n.py 3 | # Create Date: 2015-02-04 09:59:44 4 | # Descripton: 5 | 6 | 7 | class Solution: 8 | # @param path, a string 9 | # @return a string 10 | def simplifyPath(self, path): 11 | ps = path.split('/') 12 | res = [] 13 | for d in ps: 14 | if d == '..': 15 | if res: 16 | res.pop() 17 | elif d == '.' or d == '': 18 | pass 19 | else: 20 | res.append(d) 21 | return '/' + '/'.join(res) 22 | 23 | -------------------------------------------------------------------------------- /solutions/215.Kth_Largest_Element_in_an_Array/AC_priority_queue_nlogn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_priority_queue_nlogn.cpp 4 | * Create Date: 2015-08-11 20:43:23 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int findKthLargest(vector& nums, int k) { 16 | priority_queue q(nums.begin(), nums.end()); 17 | for (int i = 0; i < k - 1; ++i) 18 | q.pop(); 19 | return q.top(); 20 | } 21 | }; 22 | 23 | int main() { 24 | 25 | return 0; 26 | } 27 | 28 | -------------------------------------------------------------------------------- /solutions/020.Valid_Parentheses/AC_stack_dict_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_stack_dict_n.py 5 | # Create Date: 2015-03-04 19:47:43 6 | # Usage: AC_stack_dict_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @return a boolean 12 | def isValid(self, s): 13 | mp = {')': '(', ']': '[', '}': '{'} 14 | stk = [] 15 | for ch in s: 16 | if ch in '([{': 17 | stk.append(ch) 18 | else: 19 | if not stk or mp[ch] != stk.pop(): 20 | return False 21 | return not stk 22 | -------------------------------------------------------------------------------- /solutions/172.Factorial_Trailing_Zeroes/AC_math_logn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_math_logn.cpp 4 | * Create Date: 2015-02-05 11:34:26 5 | * Descripton: See my blog: 6 | * blog.csdn.net/hcbbt/article/details/27110103 7 | */ 8 | 9 | #include 10 | 11 | using namespace std; 12 | const int N = 0; 13 | 14 | class Solution { 15 | public: 16 | int trailingZeroes(int n) { 17 | int ans = 0; 18 | while (n != 0) { 19 | ans += n / 5; 20 | n /= 5; 21 | } 22 | return ans; 23 | } 24 | }; 25 | 26 | int main() { 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /solutions/122.Best_Time_to_Buy_and_Sell_Stock_II/AC_greedy_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_greedy_n.cpp 4 | * Create Date: 2015-03-12 11:10:07 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int maxProfit(vector &prices) { 16 | int profit = 0; 17 | for (int i = 1; i < prices.size(); ++i) 18 | if (prices[i] > prices[i - 1]) 19 | profit += prices[i] - prices[i - 1]; 20 | return profit; 21 | } 22 | }; 23 | 24 | int main() { 25 | 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /solutions/060.Permutation_Sequence/TLE_STL_n!.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: TLE_STL_n!.cpp 4 | * Create Date: 2015-01-17 10:17:40 5 | * Descripton: Use next_permutation 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | string getPermutation(int n, int k) { 16 | string str; 17 | for (int i = 0; i < n; i++) 18 | str.push_back(i + '1'); 19 | while (k--) 20 | next_permutation(str.begin(), str.end()); 21 | return str; 22 | } 23 | }; 24 | 25 | int main() { 26 | 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /solutions/237.Delete_Node_in_a_Linked_List/AC_simulation_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_1.py 5 | # Create Date: 2015-07-19 16:02:56 6 | # Usage: AC_simulation_1.py 7 | # Descripton: 8 | 9 | 10 | # Definition for singly-linked list. 11 | class ListNode: 12 | def __init__(self, x): 13 | self.val = x 14 | self.next = None 15 | 16 | class Solution: 17 | # @param {ListNode} node 18 | # @return {void} Do not return anything, modify node in-place instead. 19 | def deleteNode(self, node): 20 | node.val = node.next.val 21 | node.next = node.next.next 22 | -------------------------------------------------------------------------------- /solutions/279.Perfect_Squares/readme.md: -------------------------------------------------------------------------------- 1 | ## 279. Perfect Squares (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/perfect-squares/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给出一个数,要求把这个数用最少的平方数分解,求最少用几个。 9 | 10 | ### **分析**: 11 | 12 | 这题最先的想法是用递归来做,后面发现可以转化为递推。用 C++ 做都能过。然后试了试 Python,发现如果没有用 static 的 Trick,这题用 Python 递归 MLE,递推 TLE。 13 | 14 | 1. 递归。 15 | 2. 递推。 16 | 3. 递归或递推+static。static 就是在 class 下开一个静态的解集来记录所有解,每次调用时先去看看有没有解过,解过就直接返回。Memorization 的 reuse 思想。 17 | 4. BFS。把求解的过程看成一棵要,在里面找最短的路径就是解。 18 | 5. 数学。归纳出答案与解的关系,然后直接求。 19 | 20 | https://leetcode.com/discuss/58056/summary-of-different-solutions-bfs-static-and-mathematics 上面有很详细的解法,值得一看。 21 | -------------------------------------------------------------------------------- /solutions/217.Contains_Duplicate/AC_map_nlogn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_map_nlogn.cpp 4 | * Create Date: 2015-07-13 21:39:31 5 | * Descripton: 6 | */ 7 | 8 | 9 | #include 10 | 11 | using namespace std; 12 | const int N = 0; 13 | 14 | class Solution { 15 | public: 16 | bool containsDuplicate(vector& nums) { 17 | map mp; 18 | for (auto i : nums) { 19 | if (mp.find(i) != mp.end()) { 20 | return true; 21 | } 22 | mp[i] = 1; 23 | } 24 | return false; 25 | } 26 | }; 27 | 28 | int main() { 29 | 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /solutions/226.Invert_Binary_Tree/readme.md: -------------------------------------------------------------------------------- 1 | ## 226. Invert Binary Tree (Easy) 2 | 3 | ### **链接**: 4 | 题目: 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | Google 著名的反转二叉树问题,把整棵树横着反转过去。 9 | [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.](https://www.reddit.com/r/programming/comments/39d0u1/google_90_of_our_engineers_use_the_software_you/) 10 | 11 | ### **分析**: 12 | 13 | 其实这是一个遍历问题。可以递归做也可以用栈做。 14 | 我在考虑能不能用 O(1) 空间的算法来解开这个(类似 [099. Recover Binary Search Tree](https://github.com/illuz/leetcode/tree/master/solutions/099.Recover_Binary_Search_Tree) 用到的 Threaded binary tree),然而并不行,因为这题的目的是反转。 15 | -------------------------------------------------------------------------------- /solutions/013.Roman_to_Integer/AC_simulation_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_1.py 5 | # Create Date: 2015-03-02 23:19:56 6 | # Usage: AC_simulation_1.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @return an integer 12 | def romanToInt(self, s): 13 | val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 14 | ret = 0 15 | for i in range(len(s)): 16 | if i > 0 and val[s[i]] > val[s[i - 1]]: 17 | ret += val[s[i]] - 2 * val[s[i - 1]] 18 | else: 19 | ret += val[s[i]] 20 | return ret 21 | -------------------------------------------------------------------------------- /solutions/046.Permutations/AC_stl_n!.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_stl_n!.cpp 4 | * Create Date: 2014-12-24 11:39:42 5 | * Descripton: use STL next_permutation(). 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | vector > permute(vector &num) { 16 | sort(num.begin(), num.end()); 17 | vector > res; 18 | do { 19 | res.push_back(num); 20 | } while (next_permutation(num.begin(), num.end())); 21 | return res; 22 | } 23 | }; 24 | 25 | int main() { 26 | 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /solutions/069.Sqrt(x)/AC_binary_logn.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_binary_logn.py 3 | # Create Date: 2015-02-06 10:26:57 4 | # Descripton: 5 | 6 | class Solution: 7 | # @param x, an integer 8 | # @return an integer 9 | def sqrt(self, x): 10 | if x == 0: 11 | return 0 12 | l, r = 1, x/2 + 1 13 | while l <= r: 14 | m = (l + r) // 2 15 | if m <= x // m and x // (m + 1) < m + 1: 16 | return m 17 | if x // m < m: 18 | r = m - 1 19 | else: 20 | l = m + 1 21 | return 0 22 | 23 | s = Solution() 24 | print s.sqrt(16) 25 | 26 | -------------------------------------------------------------------------------- /solutions/263.Ugly_Number/AC_simulation_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_1.cpp 4 | * Create Date: 2015-08-20 09:16:20 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool 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 | int main() { 29 | 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /solutions/171.Excel_Sheet_Column_Number/AC_simulation_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_1.cpp 4 | * Create Date: 2015-02-05 09:51:20 5 | * Descripton: Simulation 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int titleToNumber(string s) { 16 | int col = 0; 17 | for (char i : s) 18 | col = col * 26 + (i - 'A' + 1); 19 | return col; 20 | } 21 | }; 22 | 23 | int main() { 24 | string str; 25 | Solution s; 26 | while (cin >> str) 27 | cout << s.titleToNumber(str) << endl; 28 | return 0; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /solutions/201.Bitwise_AND_of_Numbers_Range/AC_math_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_math_1.py 5 | # Create Date: 2015-04-24 22:32:42 6 | # Usage: AC_math_1.py 7 | # Descripton: 8 | 9 | import math 10 | 11 | class Solution: 12 | # @param m, an integer 13 | # @param n, an integer 14 | # @return an integer 15 | def rangeBitwiseAnd(self, m, n): 16 | if m == n: 17 | return m 18 | move = int(math.log(n - m) / math.log(2)) + 1 19 | m >>= move 20 | n >>= move 21 | return (n&m) << move 22 | 23 | # debug 24 | s = Solution() 25 | print s.rangeBitwiseAnd(5, 7) 26 | -------------------------------------------------------------------------------- /solutions/219.Contains_Duplicate_II/readme.md: -------------------------------------------------------------------------------- 1 | ## 219. Contains Duplicate II 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/contains-duplicate-ii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 问一个数组中有没有重复的数,且这两个数的下标差距不超过 k。 10 | 11 | 系列文章: 12 | 13 | - [217. Contains Duplicate](https://leetcode.com/problems/contains-duplicate) 14 | - - [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) 15 | - - [220. Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) 16 | - 17 | - ### **分析**: 18 | - 19 | - 1. 直接用 217 的解法 2,再加上一个 k 大小的窗口限制就行了(sliding window)。 20 | - 2. 考虑不用加窗口,直接上 hashmap,存每个数的下标,每次判断之前有没有存在和下标合法性,更新下标就行了。 21 | - 22 | -------------------------------------------------------------------------------- /solutions/095.Unique_Binary_Search_Trees/readme.md: -------------------------------------------------------------------------------- 1 | ## 096. Unique Binary Search Trees (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/unique-binary-search-trees/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求 {1, 2, ..., n} 的 BST 个数。 9 | 10 | ### **分析**: 11 | 12 | DP 公式为: 13 | `dp[i] = dp[k] * dp[i-k-1] { 0<=k<=i-1 }` 14 | 可以这样理解: 15 | 求 {1, 2, ...., i} 的 BST,我们拿其中的一个数作根(假设为 k),根据 BST 的特性,左子树就是 {1, 2, ..., k-1},右子树就是 {k+1, k+2, ..., i} 了。 16 | 而很明显 {k+1, k+2, ..., i} 化 BST 的可能性和 {1, 2, ..., i-(k+1)} 是一样的。 17 | 记 {1, 2, ..., n} 的 BST 个数为 f(n),上述就可以表达为 `f(i) = f(k-1) * f(i-k-1)`。 18 | 而我们选择的 k 就是 {1, 2, ...., i} 中的任意一个,而不同的 k 等到的 BST 是不会重复的。 19 | -------------------------------------------------------------------------------- /solutions/172.Factorial_Trailing_Zeroes/AC_math_logn.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_math_logn.java 4 | * Create Date: 2015-02-05 11:44:55 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public int trailingZeroes(int n) { 13 | int ans = 0; 14 | while (n != 0) { 15 | ans += n / 5; 16 | n /= 5; 17 | } 18 | return ans; 19 | } 20 | 21 | // debug 22 | public static void main(String[] args) { 23 | Scanner cin = new Scanner(System.in); 24 | Solution s = new Solution(); 25 | System.out.println("no case"); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /solutions/009.Palindrome_Number/AC_simulation2_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation2_n.cpp 4 | * Create Date: 2015-02-28 22:35:45 5 | * Descripton: Get the reverse number and compare. 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool isPalindrome(int x) { 16 | long long xx = x; 17 | long long new_xx = 0; 18 | 19 | while (xx > 0) { 20 | new_xx = new_xx * 10 + xx % 10; 21 | xx /= 10; 22 | } 23 | 24 | return new_xx == (long long)x; 25 | } 26 | }; 27 | 28 | int main() { 29 | 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /solutions/014.Longest_Common_Prefix/AC_bruteforce_n2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_bruteforce_n2.py 5 | # Create Date: 2015-03-03 15:14:14 6 | # Usage: AC_bruteforce_n2.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @return a string 12 | def longestCommonPrefix(self, strs): 13 | if strs == []: 14 | return '' 15 | for i in range(len(strs[0])): 16 | for str in strs: 17 | if len(str) <= i or str[i] != strs[0][i]: 18 | return strs[0][:i] 19 | return strs[0] 20 | 21 | # debug 22 | s = Solution() 23 | print s.longestCommonPrefix(["aa","a"]) 24 | -------------------------------------------------------------------------------- /solutions/136.Single_Number/AC_xor_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_xor_n.cpp 4 | * Create Date: 2015-01-03 12:58:31 5 | * Descripton: xor 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int singleNumber(int A[], int n) { 16 | int res = 0; 17 | for (int i = 0; i < n; i++) 18 | res ^= A[i]; 19 | return res; 20 | } 21 | }; 22 | 23 | int main() { 24 | int n, A[100]; 25 | Solution s; 26 | 27 | cin >> n; 28 | for (int i = 0; i < n; i++) 29 | cin >> A[i]; 30 | cout << s.singleNumber(A, n) << endl; 31 | return 0; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /solutions/242.Valid_Anagram/AC_simulation_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_n.cpp 4 | * Create Date: 2015-08-04 09:08:17 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool isAnagram(string s, string t) { 16 | vector rec(26, 0); 17 | for (char i : s) { 18 | ++rec[i - 'a']; 19 | } 20 | for (char i : t) { 21 | if (--rec[i - 'a'] < 0) 22 | return false; 23 | } 24 | return s.length() == t.length(); 25 | } 26 | }; 27 | 28 | int main() { 29 | 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /solutions/221.Maximal_Square/readme.md: -------------------------------------------------------------------------------- 1 | 2 | ## 221. Maximal Square (Medium) 3 | 4 | ### **链接**: 5 | 题目:https://leetcode.com/problems/maximal-square/ 6 | 代码(github):https://github.com/illuz/leetcode 7 | 8 | ### **题意**: 9 | 10 | 求一个 01 矩阵中的最大正方形的面积。 11 | 12 | ### **分析**: 13 | 14 | 如果直接做是枚举正方形的起点,再枚举边长,复杂度是 O(n^4),不可能过的。 15 | 一看就知道是 DP。 16 | 17 | 1. 开 3 个辅助数组,跟地图一样大小,一个记录从当前位置往上走有几个 1,一个记录往左走有几个,一个就是 DP 数据。先处理出前两个数组,然后 DP 式就是 `dp[i][j] = min(dp[i-1][j-1]+1, up[i][j], left[i][j])`,时间用了 O(n)。 18 | 2. 对 1 解法优化空间,只要开一维的数组就行了,用滚动数组进行降维。 19 | 3. 这题可以暴力搞的(我的基友搞过了),枚举长度,然后把不能构成正方形的点标为 0,这样之后就可以跳过了。 20 | 4. 看了 Discuss 后发现他们用的 DP 很神奇:`dp[i][j] = min(dp[i][j-1],dp[i-1][j],dp[i-1][j-1])+1 if (i,j) == 1`,其实不难想,因为那三个位置只要有一个值不够大就不能,那 dp[i][j] 也不可能变大的。 21 | -------------------------------------------------------------------------------- /solutions/018.4Sum/readme.md: -------------------------------------------------------------------------------- 1 | ## 018.4Sum (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/4sum/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个数列 S ,找出四个数 a,b,c,d 使得`a + b + c + d = target`。 9 | 10 | ### **分析**: 11 | 12 | 1. 跟之前的 2Sum, 3Sum 和 3Sum Closest 一样的做法,先排序,再左右夹逼,复杂度 O(n^3)。不过用 Python 可能会被卡超时。 13 | 2. 先求出每两个数的和,放到 `HashSet` 里,再利用之前的 2Sum 去求。这种算法比较快,复杂度 `O(n*n*log(n))`,不过细节要处理的不少。 14 | 15 | 这里 C++ 用的是算法1, Java, Python 用的是 2。 16 | 这题 Java 可以好好地学学 `HashMap` 的使用, Python 可以学习 `set`, `collection` 和 `itertools` 的一些用法。 17 | 18 | **(2015-04-02 UPDATE)** 19 | 这题解法 2 的复杂度是 `O(n*n*log(n))`,是在 `HashMap` 操作复杂度是 `O(log(n))` 的情况下算出的。 20 | 不过是正常都把 `HashMap` 当成 `O(1)` 操作的,所以也会把总的复杂度算成 `O(n*n)`。 21 | -------------------------------------------------------------------------------- /solutions/171.Excel_Sheet_Column_Number/AC_simulation_1.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_1.java 4 | * Create Date: 2015-02-05 10:11:44 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public int titleToNumber(String s) { 13 | int col = 0; 14 | for (char i : s.toCharArray()) { 15 | col = col * 26 + i - 'A' + 1; 16 | } 17 | return col; 18 | } 19 | 20 | // debug 21 | public static void main(String[] args) { 22 | Scanner cin = new Scanner(System.in); 23 | Solution s = new Solution(); 24 | System.out.println(s.titleToNumber("AB")); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /solutions/120.Triangle/AC_dp_n2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_dp_n2.py 5 | # Create Date: 2015-02-25 12:48:55 6 | # Usage: AC_dp_n2.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param triangle, a list of lists of integers 12 | # @return an integer 13 | def minimumTotal(self, triangle): 14 | dp = [1000000] * (len(triangle) + 1) 15 | dp[1] = triangle[0][0] 16 | for i in range(1, len(triangle)): 17 | for j in range(i + 1, 0, -1): 18 | dp[j] = min(dp[j - 1], dp[j]) + triangle[i][j - 1] 19 | return min(dp) 20 | 21 | # debug 22 | s = Solution() 23 | print s.minimumTotal([[1],[2,3]]) 24 | -------------------------------------------------------------------------------- /solutions/217.Contains_Duplicate/TLE_brute_force_n2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: TLE_brute_force_n2.cpp 4 | * Create Date: 2015-07-13 19:55:30 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool containsDuplicate(vector& nums) { 16 | for (int i = 0; i < nums.size(); ++i) { 17 | for (int j = i + 1; j < nums.size(); ++j) { 18 | if (nums[i] == nums[j]) { 19 | return true; 20 | } 21 | } 22 | } 23 | return false; 24 | } 25 | }; 26 | 27 | int main() { 28 | 29 | return 0; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /solutions/011.Container_With_Most_Water/AC_two_points_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_two_points_n.py 5 | # Create Date: 2015-03-02 22:48:19 6 | # Usage: AC_two_points_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @return an integer 12 | def maxArea(self, height): 13 | lp, rp = 0, len(height) - 1 14 | area = 0 15 | while lp < rp: 16 | area = max(area, min(height[lp], height[rp]) * (rp - lp)) 17 | if height[lp] > height[rp]: 18 | rp -= 1 19 | else: 20 | lp += 1 21 | return area 22 | 23 | # debug 24 | s = Solution() 25 | print s.maxArea([2, 1, 2]) 26 | -------------------------------------------------------------------------------- /solutions/121.Best_Time_to_Buy_and_Sell_Stock/AC_simulatoin_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulatoin_n.py 5 | # Create Date: 2015-03-12 10:51:45 6 | # Usage: AC_simulatoin_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param prices, a list of integer 12 | # @return an integer 13 | def maxProfit(self, prices): 14 | if not prices: 15 | return 0 16 | buy_price, profit = prices[0], 0 17 | for price in prices: 18 | buy_price = min(buy_price, price) 19 | profit = max(profit, price - buy_price) 20 | return profit 21 | 22 | # debug 23 | s = Solution() 24 | print s.maxProfit([]) 25 | -------------------------------------------------------------------------------- /solutions/130.Surrounded_Regions/readme.md: -------------------------------------------------------------------------------- 1 | ## 130. Surrounded Regions (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/surrounded-regions/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个地图,把地图里被 X 包围的 O 块填充为 X。 9 | 10 | ### **分析**: 11 | 12 | 1. 找到 O 点就 DFS 填充。不过 DFS 递归是要占用栈的,最糟的空间复杂度是 O(n*n),这题会卡爆栈,所以 DFS 会 Memory Limit Exceed。 13 | 2. 找到 O 点就 BFS 填充。BFS 才是正解。 14 | 15 | 不过一找到 O 就开始处理的话,如果来个全是 O 的,时间复杂度就会变成 O(n*n) 了,就会 TLE,有两种解决方案:1. 开个数组来记录是否访问过,需要 O(n*n) 的空间;2. 遍历 O 的时候把遍历过的 O 而不用变 X 的点变成 +,全部处理后再变回来,这样就不用另开空间了。 16 | 17 | 在上面的“把遍历过的 O 而不用变 X 的点变成 +”这个方法中,如果正常去做就要先来一遍 BFS 看看有没有被包围,再一遍 BFS 变点。能不能把两遍 BFS 缩成一遍呢?其实是可以的,我们还是把不用变的化作 '+',那反过来想,我们只要处理需要化作 '+' 的点不就行了,找到边界的点再 BFS 把 O 变成 +,最后处理时还是 O 的就是可以填充的点了。 18 | -------------------------------------------------------------------------------- /solutions/238.Product_of_Array_Except_Self/AC_array_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_array_n.java 4 | * Create Date: 2016-02-24 23:23:27 5 | * Descripton: 6 | */ 7 | 8 | public static class Solution { 9 | public int[] productExceptSelf(int[] nums) { 10 | if (nums.length == 0) return nums; 11 | int[] left = new int[nums.length]; 12 | left[0] = 1; 13 | for (int i = 1; i < nums.length; ++i) { 14 | left[i] = left[i - 1] * nums[i - 1]; 15 | } 16 | int right = 1; 17 | for (int i = nums.length - 2; i >= 0; --i) { 18 | right *= nums[i + 1]; 19 | left[i] *= right; 20 | } 21 | return left; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solutions/121.Best_Time_to_Buy_and_Sell_Stock/AC_simulatoin_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulatoin_n.cpp 4 | * Create Date: 2015-03-12 10:46:21 5 | * Descripton: profit = prices[sell] - prices[buy] 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int maxProfit(vector &prices) { 16 | int buy = 0; 17 | int profit = 0; 18 | for (int i = 0; i < prices.size(); ++i) { 19 | if (prices[buy] > prices[i]) 20 | buy = i; 21 | profit = max(profit, prices[i] - prices[buy]); 22 | } 23 | } 24 | }; 25 | 26 | int main() { 27 | 28 | return 0; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /solutions/289.Game_of_Life/readme.md: -------------------------------------------------------------------------------- 1 | me of Life (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/game-of-life/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | [康威生命游戏](https://zh.wikipedia.org/wiki/康威生命游戏)的规则是: 10 | 11 | 1. 当前细胞为存活状态时,当周围低于2个(不包含2个)存活细胞时, 该细胞变成死亡状态。(模拟生命数量稀少) 12 | 2. 当前细胞为存活状态时,当周围有2个或3个存活细胞时, 该细胞保持原样。 13 | 3. 当前细胞为存活状态时,当周围有3个以上的存活细胞时,该细胞变成死亡状态。(模拟生命数量过多) 14 | 4. 当前细胞为死亡状态时,当周围有3个存活细胞时,该细胞变成存活状态。 (模拟繁殖) 15 | 16 | 给出一个状态,求这个游戏的下个状态。 17 | 18 | ### **分析**: 19 | 20 | 模拟起来并不难,算一下周围的黑点就行了。 21 | 问题是要不开辟多余的空间来做,也就是说要在地图上直接搞。那就要处理一个问题了,就是计算总是有前后的,你不能同时算出所有的点,所以你要怎么既保存原来的状态(为了之后的计算用),又保存新的状态。 22 | 这里的状态只有 0 和 1,用一个 int 保存两个 0/1 状态不是很轻松吗,只要用两位就能保存下来了。 23 | 24 | 问题是如果题目给的不是 int 型的,而是 bool 型的,那这题就不好做了。 25 | -------------------------------------------------------------------------------- /solutions/095.Unique_Binary_Search_Trees/AC_dp_n2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_dp_n2.cpp 4 | * Create Date: 2015-01-07 10:48:26 5 | * Descripton: Interval dp 6 | * dp[i] = dp[k] * dp[i-k-1] { 0<=k<=i-1 } 7 | */ 8 | 9 | #include 10 | 11 | using namespace std; 12 | const int N = 0; 13 | 14 | class Solution { 15 | public: 16 | int numTrees(int n) { 17 | vector dp(n + 1); 18 | dp[1] = dp[0] = 1; 19 | for (int i = 2; i <= n; i++) { 20 | for (int k = 0; k < i; k++) 21 | dp[i] += dp[k] * dp[i - k - 1]; 22 | } 23 | 24 | return dp[n]; 25 | } 26 | }; 27 | 28 | int main() { 29 | 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /solutions/169.Majority_Element/AC_Moore_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_Moore_n.cpp 4 | * Create Date: 2015-02-05 10:41:09 5 | * Descripton: Moore vote algorithm. 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int majorityElement(vector &num) { 16 | int count = 0; 17 | int major; 18 | for (auto &i : num) { 19 | if (count == 0) 20 | major = i; 21 | if (i == major) 22 | count++; 23 | else 24 | cout--; 25 | } 26 | return major; 27 | } 28 | }; 29 | 30 | int main() { 31 | 32 | return 0; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /solutions/219.Contains_Duplicate_II/TLE_brute_force_n2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: TLE_brute_force_n2.cpp 4 | * Create Date: 2015-07-14 11:21:35 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool containsNearbyDuplicate(vector& nums, int k) { 16 | int n = nums.size(); 17 | for (int i = 0; i < n; ++i) { 18 | for (int j = i + 1; j < n && j < i + k + 1; ++j) { 19 | if (nums[i] == nums[j]) 20 | return true; 21 | } 22 | } 23 | return false; 24 | } 25 | }; 26 | 27 | int main() { 28 | 29 | return 0; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /solutions/234.Palindrome_Linked_List/README.md: -------------------------------------------------------------------------------- 1 | ## 234. Palindrome Linked List (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/palindrome-linked-list/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 判断一个单链表是否是回文。 9 | 10 | ### **分析**: 11 | 12 | 1. 最直接的做法是暴力去做,取第 i 个和 第 n-i 个对比,不过因为这是单链表,不能随机存取,这样的时间复杂是 O(n*2) 13 | 2. (Java) 如果转成数组不就能随机存取了?所以转数组做时间就可以缩减到 O(n),不过要用到 O(n) 的空间 14 | 3. (C++) 回文问题正常都可以递归做的,可以试试用递归做看看,不过空间同样也要 O(n) 15 | 4. (C++) 如何做到 O(1) 的空间呢?可以转化一下,如果这是双链表,可以怎么做到 O(1),只要两个指针,从中间向两边走就行了。然而单链表并不能往后走,那怎么办呢?Think for a while... 那让它可以往后走就行了,还记得 [092. Reverse Linked List II (Medium)](https://leetcode.com/problems/Reverse-Linked-List-II/) 这题吗。Think for a while... 没错,只要先将前一半反转,然后两个指针从头部和中间开始向前比较就行了,事后再转回来,时间复杂度是 O(n),空间是 O(1)。 16 | -------------------------------------------------------------------------------- /solutions/292.Nim_Game/readme.md: -------------------------------------------------------------------------------- 1 | ## 292. Nim Game (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/nim-game/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 很经典的博弈游戏,两个人从一堆石头中轮流取出 1-3 个石头,谁先取完谁就赢了。 9 | 你是先手,现在问如果石头有 n 个,你能不能赢。 10 | 11 | ### **分析**: 12 | 13 | > 这个游戏其实不管从推理还是从结论上说都和文章开头的游戏一样,不过这次我们尝试找出更普遍的规律。因为石子的数量总是递减的,所以这个游戏必将在有限步(15步)内结束。我们可以用余下石子的数目来表示局面,于是一共有16个局面。因为规定了拿走最后一个石子的人赢,换句话说当石子个数为0时,就是一个“轮到谁谁就输”的局面,我们通常叫这种局面为必败态。既然0是必败态,那么当局面为1,2,3时,先手就可以采取规则所允许的策略(拿走1个,2个,或是3个)来把局面变成0,于是称1,2,3为胜态;而当局面为4时,不论采取何种策略,局面都将走向胜态,从而4是一个必败态。 14 | 15 | 可以去了解下,入门:[博弈入门:从数学游戏开始](http://www.guokr.com/article/500/),进阶的就去看 [Nim 的 Wiki](https://en.wikipedia.org/wiki/Nim) 吧。 16 | 17 | 这题目可能有很多人看过,不过要讲清楚可能并不轻松。虽然解很简单,不过却是一道考察表达能力的好题。 18 | 19 | 20 | -------------------------------------------------------------------------------- /solutions/065.Valid_Number/AC_DFA_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_DFA_n.java 4 | * Create Date: 2015-02-24 00:51:33 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public boolean isNumber(String s) { 13 | String regex = "[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?"; 14 | if (s.trim().matches(regex)) 15 | return true; 16 | else 17 | return false; 18 | } 19 | 20 | // debug 21 | public static void main(String[] args) { 22 | Scanner cin = new Scanner(System.in); 23 | Solution s = new Solution(); 24 | int[] input = {1, 2, 3, 1}; 25 | System.out.println("no case"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /solutions/010.Regular_Expression_Matching/readme.md: -------------------------------------------------------------------------------- 1 | ## 010.Regular_Expression_Matching 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/regular-expression-matching/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 给一个原串和一个正则表达式,问能不能匹配。 10 | 11 | ### **分析**: 12 | 13 | 1. 偷懒的方法是直接用语言自带的正则实现。(Python 又是一句话 =w=) 14 | 2. 用 DFS 的方法 15 | 3. 可以用 DP 的方法 16 | - 用数组 DP :`dp[i][j]` 表示 s[0..i] 和 p[0..j] 是否 match,当 `p[j] != '*'`,`b[i + 1][j + 1] = b[i][j] && s[i] == p[j]` ,当 `p[j] == '*'` 要再分类讨论,具体可以参考 [DP C++](https://leetcode.com/discuss/18970/concise-recursive-and-dp-solutions-with-full-explanation-in),还可以压缩下把 dp 降成一维:参考[这里](https://leetcode.com/discuss/19902/share-a-scarce-dp-solution-in-java-time-o-mn-spaceo-n) 17 | - 用记忆化,就是把算过的结果保存下来,下次就不用再算了 18 | 19 | -------------------------------------------------------------------------------- /solutions/069.Sqrt(x)/AC_Newton_logn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_Newton_logn.cpp 4 | * Create Date: 2015-02-06 23:25:45 5 | * Descripton: Newton's method. 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int sqrt(int x) { 16 | if (x == 0) 17 | return 0; 18 | double lasty = 0; 19 | double y = 1; 20 | while (y != lasty) { 21 | lasty = y; 22 | y = (y + x / y) / 2; 23 | } 24 | return int(y); 25 | } 26 | }; 27 | 28 | int main() { 29 | int x; 30 | Solution s; 31 | while (cin >> x) 32 | cout << s.sqrt(x) << endl; 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/078.Subsets/AC_dfs_2^n.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_dfs_2^n.py 3 | # Create Date: 2015-02-07 19:10:02 4 | # Descripton: 5 | 6 | class Solution: 7 | def dfs(self, dep, S): 8 | if dep == len(S): 9 | self.res.append(self.cur[:]) 10 | else: 11 | self.dfs(dep + 1, S) 12 | self.cur.append(S[dep]) 13 | self.dfs(dep + 1, S) 14 | self.cur.pop() 15 | 16 | # @param S, a list of integer 17 | # @return a list of lists of integer 18 | def subsets(self, S): 19 | S.sort() 20 | self.res = [] 21 | self.cur = [] 22 | self.dfs(0, S) 23 | return self.res 24 | 25 | # debug 26 | s = Solution() 27 | print s.subsets([1, 2, 3]) 28 | 29 | -------------------------------------------------------------------------------- /solutions/069.Sqrt(x)/AC_Newton_logn.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_Newton_logn.java 4 | * Create Date: 2015-02-07 10:56:51 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public int sqrt(int x) { 13 | if (x == 0) 14 | return 0; 15 | double lasty = 0; 16 | double y = 1; 17 | while (y != lasty) { 18 | lasty = y; 19 | y = (y + x / y) / 2; 20 | } 21 | return (int)y; 22 | } 23 | 24 | // debug 25 | public static void main(String[] args) { 26 | Scanner cin = new Scanner(System.in); 27 | Solution s = new Solution(); 28 | System.out.println("no case"); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /solutions/169.Majority_Element/AC_Moore_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_Moore_n.java 4 | * Create Date: 2015-02-05 10:48:42 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public int majorityElement(int[] num) { 13 | int cnt = 0; 14 | int major = 0; 15 | for (int i : num) { 16 | if (cnt == 0) 17 | major = i; 18 | cnt += (major == i) ? 1 : -1; 19 | } 20 | return major; 21 | } 22 | 23 | // debug 24 | public static void main(String[] args) { 25 | Scanner cin = new Scanner(System.in); 26 | Solution s = new Solution(); 27 | System.out.println("no case"); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /solutions/104.Maximum_Depth_of_Binary_Tree/AC_recursive_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_recursive_n.cpp 4 | * Create Date: 2014-12-19 08:48:06 5 | * Descripton: recursive 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | 14 | // Definition for binary tree 15 | struct TreeNode { 16 | int val; 17 | TreeNode *left; 18 | TreeNode *right; 19 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 20 | }; 21 | 22 | class Solution { 23 | public: 24 | int maxDepth(TreeNode *root) { 25 | if (root == NULL) 26 | return 0; 27 | return max(maxDepth(root->left), maxDepth(root->right)) + 1; 28 | } 29 | }; 30 | 31 | int main() { 32 | 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/219.Contains_Duplicate_II/AC_unordered_map_nlogn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_unordered_map_nlogn.cpp 4 | * Create Date: 2015-07-15 10:10:44 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool containsNearbyDuplicate(vector& nums, int k) { 16 | // map 17 | unordered_map mp; 18 | for (int i = 0; i < nums.size(); ++i) { 19 | if (mp.find(nums[i]) != mp.end() && mp[nums[i]] >= i - k) 20 | return true; 21 | mp[nums[i]] = i; 22 | } 23 | return false; 24 | } 25 | }; 26 | 27 | int main() { 28 | 29 | return 0; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /solutions/222.Count_Complete_Tree_Nodes/TLE_recursive_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: TLE_recursive_n.cpp 4 | * Create Date: 2015-08-06 09:42:53 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | // Definition for a binary tree node. 14 | struct TreeNode { 15 | int val; 16 | TreeNode *left; 17 | TreeNode *right; 18 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | int countNodes(TreeNode* root) { 24 | if (root) { 25 | return countNodes(root->left) + countNodes(root->right); 26 | } 27 | return 0; 28 | } 29 | }; 30 | 31 | int main() { 32 | 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/009.Palindrome_Number/AC_simulation2_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation2_n.java 4 | * Create Date: 2015-02-28 22:52:04 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public boolean isPalindrome(int x) { 13 | long xx = x; 14 | long new_xx = 0; 15 | while (xx > 0) { 16 | new_xx = new_xx * 10 + xx % 10; 17 | xx /= 10; 18 | } 19 | return new_xx == x; 20 | } 21 | 22 | // debug 23 | public static void main(String[] args) { 24 | Scanner cin = new Scanner(System.in); 25 | Solution s = new Solution(); 26 | int[] input = {1, 2, 3, 1}; 27 | System.out.println("no case"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /solutions/190.Reverse_Bits/AC_bitset_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_bitset_n.cpp 4 | * Create Date: 2015-03-16 10:51:56 5 | * Descripton: Use bitset 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | uint32_t reverseBits(uint32_t n) { 16 | const int size = 32; 17 | bitset bits(n); 18 | for (int i = 0; i < size / 2; ++i) { 19 | // swap(bits[i], bits[size - i - 1]); 20 | int tmp = bits[i]; 21 | bits[i] = bits[size - i - 1]; 22 | bits[size - i - 1] = tmp; 23 | } 24 | return (uint32_t) bits.to_ulong(); 25 | } 26 | }; 27 | 28 | int main() { 29 | 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /solutions/283.Move_Zeroes/AC_two_point_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_two_point_n.cpp 4 | * Create Date: 2015-09-24 10:43:56 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | void moveZeroes(vector& nums) { 16 | if (nums.empty()) return; 17 | int fill = 0, cur = 0; 18 | int sz = nums.size(); 19 | while (cur < sz) { 20 | if (nums[cur] != 0) 21 | nums[fill++] = nums[cur]; 22 | ++cur; 23 | } 24 | while (fill < sz) { 25 | nums[fill++] = 0; 26 | } 27 | return; 28 | } 29 | }; 30 | 31 | int main() { 32 | 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/151.Reverse_Words_in_a_String/AC_stringstream_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_stringstream_n.cpp 4 | * Create Date: 2015-03-18 16:26:06 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | void reverseWords(string &s) { 16 | stringstream is(s); 17 | is >> s; 18 | string tmp; 19 | while (is >> tmp) 20 | s = tmp + ' ' + s; 21 | if (s[0] == ' ') // if input is all space then s will be the same 22 | s = ""; 23 | } 24 | }; 25 | 26 | int main() { 27 | Solution s; 28 | string str = " "; 29 | s.reverseWords(str); 30 | cout << str << endl; 31 | return 0; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /solutions/168.Excel_Sheet_Column_Title/AC_simulation_1.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_1.java 4 | * Create Date: 2015-02-05 09:46:58 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public String convertToTitle(int n) { 13 | StringBuilder ret = new StringBuilder(); 14 | while (n > 0) { 15 | ret.append((char)('A' + (n - 1) % 26)); 16 | n = (n - 1) / 26; 17 | } 18 | return ret.reverse().toString(); 19 | } 20 | 21 | // debug 22 | public static void main(String[] args) { 23 | Scanner cin = new Scanner(System.in); 24 | Solution s = new Solution(); 25 | System.out.println(s.convertToTitle(26)); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /solutions/215.Kth_Largest_Element_in_an_Array/readme.md: -------------------------------------------------------------------------------- 1 | ## 215. Kth Largest Element in an Array (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/Kth-Largest-Element-in-an-Array/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 求一个数组里的第 k 大。 10 | 11 | ### **分析**: 12 | 13 | 这题用 O(nlogn) 是可以过的,也就是说你可以先排序再找,也可以用 heap,priority_queu 等数据结构。 14 | 当然,用 Quicksort 里的 Quick-select(也就是 partion)方法是可以做到 O(n) 的。(对于为啥 quick select 是 O(n) 的可以看 [Why is the runtime of the Selection Algorithm O(n)?](http://stackoverflow.com/questions/8783408/why-is-the-runtime-of-the-selection-algorithm-on) 15 | 16 | 有个大神写了全套的解法:[4 C++ Solutions using Partition, Max-Heap, priority_queue and multiset respectively](https://leetcode.com/discuss/38336/solutions-partition-priority_queue-multiset-respectively)。 17 | -------------------------------------------------------------------------------- /solutions/168.Excel_Sheet_Column_Title/AC_simulation_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_1.cpp 4 | * Create Date: 2015-02-05 09:26:31 5 | * Descripton: Simulation 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | string convertToTitle(int n) { 16 | string ret = ""; 17 | --n; 18 | while (n >= 0) { 19 | ret += (char)('A' + n % 26); 20 | n /= 26; 21 | --n; 22 | } 23 | reverse(ret.begin(), ret.end()); 24 | return ret; 25 | } 26 | }; 27 | 28 | int main() { 29 | int n; 30 | Solution s; 31 | while (cin >> n) 32 | cout << s.convertToTitle(n) << endl; 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/239.Sliding_Window_Maximum/AC_brute_force_nk.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_brute_force_nk.py 5 | # Create Date: 2015-08-18 18:49:00 6 | # Usage: AC_brute_force_nk.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param {integer[]} nums 12 | # @param {integer} k 13 | # @return {integer[]} 14 | def maxSlidingWindow(self, nums, k): 15 | res = [] 16 | nums_len = len(nums) 17 | if nums_len < k or k == 0: 18 | return res 19 | for i in xrange(0, nums_len - k + 1): 20 | res.append(max(nums[i:i+k])) 21 | return res 22 | 23 | 24 | 25 | # test 26 | s = Solution() 27 | print s.maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3) -------------------------------------------------------------------------------- /solutions/279.Perfect_Squares/AC_memorization_nsqrtn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_memorization_nsqrtn.cpp 4 | * Create Date: 2015-10-26 12:24:30 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int numSquares(int n) { 16 | vector result(n + 1); 17 | for (int i = 1; i <= n; ++i) { 18 | int best = i; 19 | for (int j = 1; j * j <= i; ++j) { 20 | best = min(best, result[i - j * j] + 1); 21 | } 22 | result[i] = best; 23 | } 24 | return result[n]; 25 | } 26 | }; 27 | 28 | int main() { 29 | 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /solutions/115.Distinct_Subsequences/readme.md: -------------------------------------------------------------------------------- 1 | ## 115. Distinct Subsequences (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/distinct-subsequences/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 问有 S 中有几个子串是 T,S 的子串定义为在 S 中任意去掉 0 个或者多个字符形成的串。 9 | 10 | ### **分析**: 11 | 12 | 很明显得用 DP。 13 | 有两种 DP 思路: 14 | 15 | 1. 首先想到化为子问题:`dp[i][j]` 表示 `S[i...j]` 中有几个 `T`,但是转移不好想,而且 `dp[i][j]` 需要 O(n*n) 的空间,如果 S 长度大点就不行了。 16 | 2. 正解:`dp[i][j]` 表示 `S[1...i]` 与 `T[1...j]` 匹配的个数。转移公式就是:`dp[i][j]=dp[i][j-1]{(if S[i]==T[j])+dp[i-1][j-1]}`。这思路也可以用记忆化来想,也是子问题。 17 | 3. 对 2 进行优化,用滚动数组来减小空间,倒着滚可以降成一维。 18 | 19 | 复杂度都是 O(n*m)。 20 | PS:听说开数组时从小到大开比较快,如 `dp[10][1000]` 会比 `dp[1000][10]` 快。(虽然我这没这样开) 21 | 22 | C++ 实现了空间 O(n*m) 的 DP 和 O(m) 的一维 DP。 23 | Python 实现了空间 O(2m) 的 DP。 24 | -------------------------------------------------------------------------------- /solutions/055.Jump_Game/AC_greedy2_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_greedy_n.cpp 4 | * Create Date: 2015-01-30 09:40:38 5 | * Descripton: Greedy. Using O(1) space and O(n) time. 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool canJump(int A[], int n) { 16 | int reach = 1; 17 | for (int i = 0; i < reach && reach < n; ++i) 18 | reach = max(reach, i + 1 + A[i]); 19 | return reach >= n; 20 | } 21 | }; 22 | 23 | int main() { 24 | int n, A[1000]; 25 | Solution s; 26 | while (cin >> n) { 27 | for (int i = 0; i < n; i++) 28 | cin >> A[i]; 29 | cout << s.canJump(A, n) << endl; 30 | } 31 | return 0; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /solutions/191.Number_of_1_Bits/AC_bitwise_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_bitwise_n.java 4 | * Create Date: 2015-03-16 11:10:24 5 | * Descripton: 6 | */ 7 | 8 | import java.util.*; 9 | 10 | public class Solution { 11 | // you need to treat n as an unsigned value 12 | public int hammingWeight(int n) { 13 | int ret = 0; 14 | while (n != 0) { 15 | if ((n&1) == 1) { 16 | ret++; 17 | } 18 | n >>>= 1; 19 | } 20 | return ret; 21 | } 22 | 23 | // debug 24 | public static void main(String[] args) { 25 | Scanner cin = new Scanner(System.in); 26 | Solution s = new Solution(); 27 | int[] input = {1, 2, 3, 4}; 28 | System.out.println("no case"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /solutions/089.Gray_Code/AC_simulation_2^n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_2^n.java 4 | * Create Date: 2015-02-20 10:30:33 5 | * Descripton: 6 | */ 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.Scanner; 11 | 12 | public class Solution { 13 | public List grayCode(int n) { 14 | List res = new ArrayList(); 15 | for (int i = 0; i < (1<>1)); 17 | } 18 | return res; 19 | } 20 | 21 | // debug 22 | public static void main(String[] args) { 23 | Scanner cin = new Scanner(System.in); 24 | Solution s = new Solution(); 25 | int[] input = {1, 2, 3, 1}; 26 | System.out.println(s.grayCode(2)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /solutions/139.Word_Break/AC_dp_n2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_dp_n2.py 5 | # Create Date: 2015-04-21 10:21:18 6 | # Usage: AC_dp_n2.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param s, a string 12 | # @param dict, a set of string 13 | # @return a boolean 14 | def wordBreak(self, s, dict): 15 | n = len(s) 16 | dp = [False] * (n + 1) 17 | dp[0] = True 18 | for i in range(n): 19 | if dp[i]: 20 | for word in dict: 21 | j = len(word) 22 | if i + j <= n and s[i: i + j] == word: 23 | dp[i + j] = True 24 | return dp[n] 25 | 26 | # debug 27 | s = Solution() 28 | print s.wordBreak('a', ['a']) 29 | -------------------------------------------------------------------------------- /solutions/222.Count_Complete_Tree_Nodes/readme.md: -------------------------------------------------------------------------------- 1 | ## 222. Count Complete Tree Nodes (Medium) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/count-complete-tree-nodes/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 9 | 求一个完全二叉树的大小。 10 | 11 | ### **分析**: 12 | 13 | 1. 首先想到的是递归找下去,然而 TLE 了(不然题目的完全二叉树条件有什么用),看到要找 O(logn) 或 O(logn*logn) 的算法了。 14 | 2. 这题的本质就是要找最深层有几个节点。那么要如何定位最后的那个节点呢。看到之前递归算法写的 getDepth 方法,发现可以 O(logn) 去我得到 depth,那就可以获取左右的路径的深度,然后进行处理了:如果一样的话,这个子树就是满的,可以直接得到大小,如果不是一样的话,就分别求左右子树的大小。 15 | 3. 看了下 Discuss 有种跟我的差不多的做法,是求左子树的最左路径长度和右子树的最左路径长度,然后再递归。不过感觉没方法 2 好想。 16 | 4. 还有种方法,就是把最下面的数看成从 0 开始的数,然后这个数的二进制就是从根到叶子的左右拐向。这样每个数就对应一条唯一的路径了。然后去二分这个数,判断条件是在树上根据这个路径看能不能这个叶子节点。复杂度也是 O(lognlogn),不过思想是不错。感兴趣的可以去看看:[link](https://leetcode.com/discuss/45467/extremely-solution-time-using-manipulation-binary-search)。 17 | -------------------------------------------------------------------------------- /solutions/223.Rectangle_Area/AC_simulation_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_1.cpp 4 | * Create Date: 2015-07-19 16:13:45 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 16 | int s1 = (C - A) * (D - B); 17 | int s2 = (G - E) * (H - F); 18 | if (A > G || C < E || B > H || D < F) { 19 | return s1 + s2; 20 | } 21 | int a = max(A, E); 22 | int b = max(B, F); 23 | int c = min(C, G); 24 | int d = min(D, H); 25 | return s1 + s2 - (c - a) * (d - b); 26 | } 27 | }; 28 | 29 | int main() { 30 | 31 | return 0; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /solutions/237.Delete_Node_in_a_Linked_List/AC_simulation_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_1.cpp 4 | * Create Date: 2015-07-19 15:27:43 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | // Definition for singly-linked list. 14 | struct ListNode { 15 | int val; 16 | ListNode *next; 17 | ListNode(int x) : val(x), next(NULL) {} 18 | }; 19 | 20 | 21 | class Solution { 22 | public: 23 | void deleteNode(ListNode* node) { 24 | ListNode *next = node->next; 25 | *node = *next; 26 | // this statement is equivalent to 27 | // node->val = next->val; 28 | // node->next = next->next; 29 | delete next; 30 | } 31 | }; 32 | 33 | int main() { 34 | 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /solutions/089.Gray_Code/AC_simulation_2^n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_2^n.cpp 4 | * Create Date: 2015-02-20 10:00:25 5 | * Descripton: simulation, G(n) = B(n) XOR B(n>>1) 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | vector grayCode(int n) { 16 | const size_t sz = 1< res(sz); 18 | for (size_t i = 0; i < sz; ++i) 19 | res[i] = (i ^ (i>>1)); 20 | return res; 21 | } 22 | }; 23 | 24 | int main() { 25 | int n; 26 | Solution s; 27 | while (cin >> n) { 28 | vector res = s.grayCode(n); 29 | for (auto &i : res) 30 | cout << i << ' '; 31 | cout << endl; 32 | } 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/050.Pow(x,_n)/AC_simulation_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_n.cpp 4 | * Create Date: 2014-12-31 00:10:05 5 | * Descripton: simulation 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | double pow(double x, int n) { 16 | double res = 1; 17 | if (n < 0) { 18 | n = -n; 19 | x = 1.0 / x; 20 | } 21 | while (n > 0) { 22 | if (n % 2) 23 | res *= x; 24 | n >>= 1; 25 | x *= x; 26 | } 27 | return res; 28 | } 29 | }; 30 | 31 | int main() { 32 | int n; 33 | double x; 34 | Solution s; 35 | while (cin >> x >> n) 36 | cout << s.pow(x, n) << endl; 37 | return 0; 38 | } 39 | 40 | -------------------------------------------------------------------------------- /solutions/098.Validate_Binary_Search_Tree/AC_dfs_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_dfs_n.py 5 | # Create Date: 2015-03-03 14:53:53 6 | # Usage: AC_dfs_n.py 7 | # Descripton: 8 | 9 | 10 | # Definition for a binary tree node 11 | class TreeNode: 12 | def __init__(self, x): 13 | self.val = x 14 | self.left = None 15 | self.right = None 16 | 17 | class Solution: 18 | # @param root, a tree node 19 | # @return a boolean 20 | def isValidBST(self, root): 21 | 22 | def dfs(root, minval, maxval): 23 | if root is None: 24 | return True 25 | return minval < root.val < maxval and dfs(root.left, minval, root.val) and dfs(root.right, root.val, maxval) 26 | 27 | return dfs(root, -1<<32, 1<<32) 28 | -------------------------------------------------------------------------------- /solutions/053.Maximum_Subarray/AC_dp_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_dp_n.cpp 4 | * Create Date: 2014-12-24 11:16:17 5 | * Descripton: dp 6 | * http://blog.csdn.net/hcbbt/article/details/10454947 7 | * the way 4 8 | */ 9 | 10 | #include 11 | 12 | using namespace std; 13 | const int N = 0; 14 | 15 | class Solution { 16 | public: 17 | int maxSubArray(int A[], int n) { 18 | if (n == 0) 19 | return 0; 20 | int sum = A[0], mmax = A[0]; 21 | for (int i = 1; i < n; i++) { 22 | if (sum < 0) 23 | sum = A[i]; 24 | else 25 | sum += A[i]; 26 | mmax = max(mmax, sum); 27 | } 28 | return mmax; 29 | } 30 | }; 31 | 32 | int main() { 33 | 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /solutions/085.Maximal_Rectangle/readme.md: -------------------------------------------------------------------------------- 1 | ## 085. Maximal Rectangle (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/maximal-rectangle/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求一个 01 矩阵的全是 1 的子矩阵的最大规模。 9 | 10 | ### **分析**: 11 | 12 | 很有挑战性的题目。 13 | 一眼看过去就感觉要用 DP 做,可是从前个位置的答案和当前位置的行列延伸值的转移无法保持最优性。 14 | 15 | 看了下 discuss,发现提到了上一题 [084. Largest Rectangle in Histogram (Hard)](https://github.com/illuz/leetcode/tree/master/solutions/084.Largest_Rectangle_in_Histogram),想了下,简直机智得不得了! 16 | 我们可以转化为:求矩阵前 x 行,以第 x 行为底的最大矩形,这不就直接是上一题了吗。 17 | Largest Rectangle in Histogram 的复杂度是 O(n),所以这题的复杂度是 O(n^2),矩阵条(直方图)的处理可以用 O(n) 的空间来搞定。 18 | 19 | Largest Rectangle in Histogram 我写了两 AC 的算法,一个用 stack 的是 O(n),一个暴力加优化的 O(n^2),这题直接用上题的函数,都过了 = =b。 20 | 21 | (这里不得不提下 Discuss 上的一个[数组 DP 的算法](DP solution),其实它的思想跟直方图很像的) 22 | -------------------------------------------------------------------------------- /solutions/123.Best_Time_to_Buy_and_Sell_Stock_III/AC_1_space_dp_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_1_space_dp_n.py 5 | # Create Date: 2015-03-13 10:49:50 6 | # Usage: AC_1_space_dp_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param prices, a list of integer 12 | # @return an integer 13 | def maxProfit(self, prices): 14 | buy1, buy2 = -(1<<31), -(1<<31) 15 | sell1, sell2 = 0, 0 16 | 17 | for i in prices: 18 | sell2 = max(sell2, buy2 + i) # max money after sell 2 19 | buy2 = max(buy2, sell1 - i) # max money after buy 2 20 | sell1 = max(sell1, buy1 + i) # max money after sell 1 21 | buy1 = max(buy1, -i) # max money after buy 1 22 | 23 | return sell2 24 | 25 | 26 | -------------------------------------------------------------------------------- /solutions/278.First_Bad_Version/AC_binary_search_logn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_binary_search_logn.py 5 | # Create Date: 2015-09-24 09:49:08 6 | # Usage: AC_binary_search_logn.py 7 | # Descripton: https://leetcode.com/problems/first-bad-version/ 8 | 9 | 10 | # The isBadVersion API is already defined for you. 11 | # @param version, an integer 12 | # @return a bool 13 | # def isBadVersion(version): 14 | 15 | class Solution(object): 16 | def firstBadVersion(self, n): 17 | """ 18 | :type n: int 19 | :rtype: int 20 | """ 21 | l, r = 1, n 22 | while l < r: 23 | mid = (l + r) // 2 24 | if isBadVersion(mid): 25 | r = mid 26 | else: 27 | l = mid + 1 28 | return r 29 | -------------------------------------------------------------------------------- /solutions/036.Valid_Sudoku/readme.md: -------------------------------------------------------------------------------- 1 | ## 036. Valid Sudoku (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/valid-sudoku/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 判断一个数独是否有效。 9 | 有效的数独不强求有解。 10 | 11 | ### **分析**: 12 | 只要同一行、列、块里没有相同数字就行了。 13 | 开个数组记录就行了,没什么难度,可以用二进制来表示,表位运算加速。 14 | 15 | (注意是判断有效,不是有解,我刚开始给求解了,TLE 了好多次。。。) 16 | 17 | --- 18 | 19 | **English** 20 | 21 | ## 035.Valid_Sudoku 22 | 23 | Because it just checks whether the sudoku is valid, so we can just check the numbers in it only. 24 | But if we check if the sudoku has a solution, then we should use other algorithms. Because a sudoku is VALID doesn't mean that it has a solution. 25 | To check if it has a solution, we can use **DFS** to check it. But it may take a long time. Because the complexity is O((n*n)!) ! 26 | The better algorithm is **Dancing Link**. 27 | -------------------------------------------------------------------------------- /solutions/065.Valid_Number/AC_strtod_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_strtod_n.cpp 4 | * Create Date: 2015-02-23 18:08:07 5 | * Descripton: use strtod: www.cplusplus.com/reference/cstdlib/strtod 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool isNumber(string s) { 16 | const char *str = s.c_str(); 17 | char *end; 18 | strtod(str, &end); 19 | if (end == str) 20 | return false; 21 | for (; *end; ++end) 22 | if (!isspace(*end)) 23 | return false; 24 | return true; 25 | } 26 | }; 27 | 28 | int main() { 29 | Solution s; 30 | string ss; 31 | while (getline(cin, ss)) 32 | cout << s.isNumber(ss) << endl; 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/202.Happy_Number/AC_two_point_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_two_point_n.py 5 | # Create Date: 2015-04-22 17:56:59 6 | # Usage: AC_two_point_n.py 7 | # Descripton: 8 | 9 | class Solution: 10 | # @param {integer} n 11 | # @return {boolean} 12 | def isHappy(self, n): 13 | 14 | # define process function 15 | def proc(x): 16 | s = 0 17 | while x: 18 | s += (x % 10) ** 2 19 | x /= 10 20 | return s 21 | 22 | # loop 23 | a = proc(n) 24 | b = proc(a) 25 | while a != 1 and a != b: 26 | a = proc(a) 27 | b = proc(b) 28 | b = proc(b) 29 | 30 | return 1 == a 31 | 32 | # debug 33 | s = Solution() 34 | print s.isHappy(19) 35 | -------------------------------------------------------------------------------- /solutions/123.Best_Time_to_Buy_and_Sell_Stock_III/readme.md: -------------------------------------------------------------------------------- 1 | ## 123. Best Time to Buy and Sell Stock III (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 给一个数组,`prices[i]` 表示第 i 天的交易值,也就是你在这天买入或卖出的交易值。 9 | 你可以买入及卖出**最多两轮**,不过你一个时间只能拥有一个股票,求最大盈利。 10 | 11 | ### **分析**: 12 | 13 | 可以最多求两次,所以可以把它变成子问题,也就是枚举分界点,求左右两个子串的只能交易一次的最大值。 14 | 子问题要递归解决吗?NO!跟 `121. Best Time to Buy and Sell Stock` 一样,子问题的解决是需要 O(n) 的,总的就是 O(n^2) 这跟暴力没有区别。 15 | 所以我们就要用空间换时间了,只要预处理左子序列和右子序列的单次交易值 left[n] 和 right[n] 就行了,然后枚举分界点求 `max(left[i], right[i+1])` 就行了。总的复杂度是 O(n)。 16 | 17 | 有没有办法不用 O(n) 的空间? 18 | 大神告诉我们,有的:https://leetcode.com/discuss/18330/is-it-best-solution-with-o-n-o-1。 19 | 假设刚开始持有 0 元,只用 4 个变量,分别是两次交易买入后和卖出后所持钱的最大值,一遍扫过去,维护这些变量就行了。 20 | 其实还是不太好理解的。 21 | -------------------------------------------------------------------------------- /solutions/226.Invert_Binary_Tree/AC_stack_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_stack_n.py 5 | # Create Date: 2015-07-26 10:53:38 6 | # Usage: AC_stack_n.py 7 | # Descripton: 8 | 9 | 10 | # Definition for a binary tree node. 11 | class TreeNode: 12 | def __init__(self, x): 13 | self.val = x 14 | self.left = None 15 | self.right = None 16 | 17 | class Solution: 18 | # @param {TreeNode} root 19 | # @return {TreeNode} 20 | def invertTree(self, root): 21 | stack = [root] 22 | while stack: 23 | node = stack.pop() 24 | if node: 25 | node.left, node.right = node.right, node.left 26 | stack.append(node.left) 27 | stack.append(node.right) 28 | 29 | return root 30 | -------------------------------------------------------------------------------- /solutions/008.String_to_Integer/AC_regex_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_regex_n.py 5 | # Create Date: 2015-02-27 11:41:25 6 | # Usage: AC_regex_n.py 7 | # Descripton: 8 | 9 | 10 | import re 11 | 12 | class Solution: 13 | # @return an integer 14 | def atoi(self, str): 15 | str = str.strip() 16 | str = re.match(r'^[+-]?\d+', str).group() 17 | MAX_INT = 2147483647 18 | MIN_INT = -2147483648 19 | 20 | try: 21 | ret = int(str) 22 | if ret > MAX_INT: 23 | return MAX_INT 24 | elif ret < MIN_INT: 25 | return MIN_INT 26 | else: 27 | return ret 28 | except: 29 | return 0 30 | 31 | 32 | # debug 33 | s = Solution() 34 | print s.atoi(' 1324sdf') 35 | -------------------------------------------------------------------------------- /solutions/007.Reverse_Integer/AC_simulation_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_n.cpp 4 | * Create Date: 2014-11-29 23:21:10 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int reverse(int x) { 16 | long long tmp = abs((long long)x); 17 | long long ret = 0; 18 | while (tmp) { 19 | ret = ret * 10 + tmp % 10; 20 | if (ret > INT_MAX) 21 | return 0; 22 | tmp /= 10; 23 | } 24 | if (x > 0) 25 | return (int)ret; 26 | else 27 | return (int)-ret; 28 | } 29 | }; 30 | 31 | 32 | int main() { 33 | Solution a; 34 | int x; 35 | while (cin >> x) cout << a.reverse(x) << endl; 36 | return 0; 37 | } 38 | 39 | -------------------------------------------------------------------------------- /solutions/009.Palindrome_Number/AC_simulation_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_n.cpp 4 | * Create Date: 2014-11-30 00:38:29 5 | * Descripton: simulation 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool isPalindrome(int x) { 16 | if (x < 0) return false; 17 | int bit[10]; 18 | int cnt = 0; 19 | while (x) { 20 | bit[cnt++] = x % 10; 21 | x /= 10; 22 | } 23 | for (int i = 0; i < cnt; i++) 24 | if (bit[i] != bit[cnt - i - 1]) 25 | return false; 26 | return true; 27 | } 28 | }; 29 | 30 | int main() { 31 | Solution a; 32 | int x; 33 | while (cin >> x) 34 | cout << a.isPalindrome(x) << endl; 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /solutions/011.Container_With_Most_Water/AC_two_points_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_two_points_n.cpp 4 | * Create Date: 2014-12-31 11:13:00 5 | * Descripton: left point and right point 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int maxArea(vector &height) { 16 | int lpoint = 0, rpoint = height.size() - 1; 17 | int area = 0; 18 | while (lpoint < rpoint) { 19 | area = max(area, min(height[lpoint], height[rpoint]) * 20 | (rpoint - lpoint)); 21 | if (height[lpoint] > height[rpoint]) 22 | rpoint--; 23 | else 24 | lpoint++; 25 | } 26 | return area; 27 | } 28 | }; 29 | 30 | int main() { 31 | 32 | return 0; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /solutions/026.Remove_Duplicates_from_Sorted_Array/AC_map_nlogn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_map_nlogn.cpp 4 | * Create Date: 2014-12-06 21:46:42 5 | * Descripton: use map, map has logn complexity 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int removeDuplicates(int A[], int n) { 16 | map mp; 17 | int ret = 0; 18 | for (int i = 0; i < n; i++) 19 | if (!mp[A[i]]++) 20 | A[ret++] = A[i]; 21 | return ret; 22 | } 23 | }; 24 | 25 | int main() { 26 | Solution s; 27 | int n, A[100]; 28 | while (cin >> n) { 29 | for (int i = 0; i < n; i++) 30 | scanf("%d", &A[i]); 31 | cout << s.removeDuplicates(A, n) << endl; 32 | } 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/112.Path_Sum/AC_recursive_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_recursive_n.cpp 4 | * Create Date: 2014-12-19 09:03:10 5 | * Descripton: recursive 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | struct TreeNode { 14 | int val; 15 | TreeNode *left; 16 | TreeNode *right; 17 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 18 | }; 19 | 20 | class Solution { 21 | public: 22 | bool hasPathSum(TreeNode *root, int sum) { 23 | if (root == NULL) 24 | return false; 25 | if (!root->left && !root->right) 26 | return sum == root->val; 27 | return hasPathSum(root->left, sum - root->val) || 28 | hasPathSum(root->right, sum - root->val); 29 | } 30 | }; 31 | 32 | 33 | int main() { 34 | 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /solutions/203.Remove_Linked_List_Elements/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_n.py 5 | # Create Date: 2015-04-23 22:47:24 6 | # Usage: AC_simulation_n.py 7 | # Descripton: 8 | 9 | 10 | # Definition for singly-linked list. 11 | class ListNode: 12 | def __init__(self, x): 13 | self.val = x 14 | self.next = None 15 | 16 | class Solution: 17 | # @param {ListNode} head 18 | # @param {integer} val 19 | # @return {ListNode} 20 | def removeElements(self, head, val): 21 | dummy = ListNode(0) 22 | dummy.next = head 23 | cur = dummy 24 | while cur.next: 25 | if cur.next.val == val: 26 | cur.next = cur.next.next 27 | else: 28 | cur = cur.next 29 | return dummy.next 30 | -------------------------------------------------------------------------------- /solutions/006.ZigZag_Conversion/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_n.py 5 | # Create Date: 2015-02-27 00:40:10 6 | # Usage: AC_simulation_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @return a string 12 | def convert(self, s, nRows): 13 | if nRows == 1: 14 | return s 15 | step = nRows * 2 - 2 16 | # first row 17 | ret = s[::step] 18 | for i in range(1, nRows - 1): 19 | for j in range(i, len(s), step): 20 | ret += s[j] 21 | if j + (step - i * 2) < len(s): 22 | ret += s[j + (step - i * 2)] 23 | # last row 24 | ret += s[nRows - 1::step] 25 | return ret 26 | 27 | # debug 28 | s = Solution() 29 | print s.convert("PAYPALISHIRING", 3) 30 | -------------------------------------------------------------------------------- /solutions/234.Palindrome_Linked_List/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_n.py 5 | # Create Date: 2015-07-29 13:39:17 6 | # Usage: AC_simulation_n.py 7 | # Descripton: 8 | 9 | 10 | # Definition for singly-linked list. 11 | class ListNode: 12 | def __init__(self, x): 13 | self.val = x 14 | self.next = None 15 | 16 | class Solution: 17 | # @param {ListNode} head 18 | # @return {boolean} 19 | def isPalindrome(self, head): 20 | cur = head 21 | sz = 0 22 | arr = [] 23 | while cur: 24 | arr.append(cur.val) 25 | cur = cur.next 26 | sz += 1 27 | 28 | for i in range(sz // 2): 29 | if arr[i] != arr[sz - i - 1]: 30 | return False 31 | 32 | return True 33 | -------------------------------------------------------------------------------- /solutions/038.Count_and_Say/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_n.py 5 | # Create Date: 2015-07-30 09:41:51 6 | # Usage: AC_simulation_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param {integer} n 12 | # @return {string} 13 | def countAndSay(self, n): 14 | res = '1' 15 | for _ in xrange(n - 1): 16 | res = self.helper(res) 17 | return res 18 | 19 | def helper(self, s): 20 | cnt, res = 1, '' 21 | for i in xrange(len(s) - 1): 22 | if s[i] == s[i + 1]: 23 | cnt += 1 24 | else: 25 | res += str(cnt) + s[i] 26 | cnt = 1 27 | res += str(cnt) + s[-1] 28 | return res 29 | 30 | # test 31 | s = Solution() 32 | print(s.countAndSay(4)) -------------------------------------------------------------------------------- /solutions/239.Sliding_Window_Maximum/AC_multiset_nlogn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_multiset_nlogn.cpp 4 | * Create Date: 2015-08-18 19:20:17 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | vector maxSlidingWindow(vector& nums, int k) { 16 | multiset > win; 17 | vector res; 18 | int n = nums.size(); 19 | for (int i = 0; i < n; ++i) { 20 | win.insert(nums[i]); 21 | if (i >= k - 1) { 22 | res.push_back(*win.begin()); 23 | auto it = win.find(nums[i - k + 1]); 24 | win.erase(it); 25 | } 26 | } 27 | return res; 28 | } 29 | }; 30 | 31 | int main() { 32 | 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/258.Add_Digits/AC_simulation_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_n.cpp 4 | * Create Date: 2015-08-17 00:26:00 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int addDigits(int num) { 16 | int sum = getSum(num); 17 | while (sum >= 10) { 18 | sum = getSum(sum); 19 | } 20 | return sum; 21 | } 22 | private: 23 | int getSum(int num) { 24 | int sum = 0; 25 | while (num) { 26 | sum += num % 10; 27 | num /= 10; 28 | } 29 | return sum; 30 | } 31 | }; 32 | 33 | int main() { 34 | Solution s; 35 | for (int i = 0; i < 100; ++i) { 36 | cout << i << ' ' << s.addDigits(i) << endl; 37 | } 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /solutions/278.First_Bad_Version/AC_dfs_logn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_dfs_logn.py 5 | # Create Date: 2015-09-24 09:55:34 6 | # Usage: AC_dfs_logn.py 7 | # Descripton: https://leetcode.com/problems/first-bad-version/ 8 | 9 | # The isBadVersion API is already defined for you. 10 | # @param version, an integer 11 | # @return a bool 12 | # def isBadVersion(version): 13 | 14 | class Solution(object): 15 | def firstBadVersion(self, n): 16 | """ 17 | :type n: int 18 | :rtype: int 19 | """ 20 | def find(l, r): 21 | if l == r: 22 | return l 23 | mid = (l + r) // 2 24 | if isBadVersion(mid): 25 | return find(l, mid) 26 | else: 27 | return find(mid + 1, r) 28 | return find(1, n) 29 | -------------------------------------------------------------------------------- /solutions/097.Interleaving_String/readme.md: -------------------------------------------------------------------------------- 1 | ## 097. Interleaving String (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/interleaving-string/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 问 s3 是否是 s1 和 s2 交错得到的。 9 | 10 | ### **分析**: 11 | 12 | s3 中的一个字母 s1 和 s2 都有,那这算谁的? 13 | 不同的决策会得到不同的结果,所以这个问题第一眼就感觉要搜索或 DP。 14 | 15 | 1. 搜索,当遇到 s1[i] = s2[j] = s3[i+j] 时,分类讨论,一种判给 s1,再搜索下去,另一种判给 s2 再搜。复杂度是 O(2^n) 16 | 2. 可以考虑对 1 算法进行记忆化,复杂度 O(n*m) 17 | 3. (**C++**)DP。 `dp[i][j]` 表示 s1[i], s2[j] 时是否匹配 s3[i+j],这样两种都会判断到了,公式:`dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s1[j-1] == s3[i+j-1])`。时间复杂度 O(n^2),空间 O(n^2) 18 | 4. (**Java**)对 3 进行优化:使用滚动数组,减小空间复杂度为 O(n) 19 | 5. 在 Discuss 里看到有个大神机智地用 BFS 解决了这题,太形象了!有兴趣可以观摩下:[C++ solution using BFS, with explanation](http://leetcode.com/discuss/19973/8ms-c-solution-using-bfs-with-explanation) 20 | -------------------------------------------------------------------------------- /solutions/228.Summary_Ranges/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_n.py 5 | # Create Date: 2015-07-26 11:35:19 6 | # Usage: AC_simulation_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param {integer[]} nums 12 | # @return {string[]} 13 | def summaryRanges(self, nums): 14 | res = [] 15 | if not nums: 16 | return res 17 | 18 | start = 0 19 | nums.append(nums[-1]) 20 | for i in range(0, len(nums) - 1): 21 | if nums[i] + 1 != nums[i + 1]: 22 | if start == i: 23 | res.append(str(nums[i])) 24 | else: 25 | res.append(str(nums[start]) + '->' + str(nums[i])) 26 | start = i + 1 27 | 28 | nums.pop() 29 | return res 30 | 31 | -------------------------------------------------------------------------------- /solutions/023.Merge_k_Sorted_Lists/readme.md: -------------------------------------------------------------------------------- 1 | ## 023. Merge k Sorted Lists (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/merge-k-sorted-lists/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 和 [021. Merge Two Sorted Lists (Easy)](http://blog.csdn.net/hcbbt/article/details/44064639) 类似,这次要 Merge K 个。 9 | 10 | ### **分析**: 11 | 12 | 很明显可以想到利用已经完成的 Merge Two Sorted Lists 的函数来用。 13 | 这时有两种方法: 14 | 1. (C++) 用二分的思想,把每个 List 和它相邻的 List 进行 Merge,这样规模就缩小了一半了,再重复这样,就可以 O(nklogk) 完成。比如: [1, 2, ..., n] 的第一轮 Merge 是 [1, n/2], [2, n/2+1], ... 15 | 2. (Python) 也是用二分的思想,就是把 Lists 分为两部分,分别递归 Merge k Sorted Lists 后变成两个 List ,然后再对这两 List 进行 Merge Two Sorted Lists 。 16 | 17 | 这两种方法都是递归调用,都可以进行记忆化,用空间换时间,不过我不清楚会不会超空间(Memory Limit Exceed),所以就没试了~ 18 | 19 | 除了用二分的思路,还有更好写的方法,就是用堆(heap),具体就是用优先队列(Priority Queue)。 20 | (Java) 先把每个 List 的第一个节点放进优先队列,每次取出队列中的最大值节点,再把那个节点的 next 放进去。 21 | 22 | -------------------------------------------------------------------------------- /solutions/091.Decode_Ways/AC_dp_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_dp_n.py 5 | # Create Date: 2015-02-26 12:44:05 6 | # Usage: AC_dp_n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param s, a string 12 | # @return an integer 13 | def numDecodings(self, s): 14 | if not s: 15 | return 0 16 | if len(s) == 1: 17 | return 1 if s[0] != '0' else 0 18 | 19 | dp = [1, 1 if s[0] != '0' else 0] 20 | for i in range(2, len(s) + 1): 21 | rec = 0 22 | if s[i - 1] != '0': 23 | rec += dp[(i-1)&1] 24 | if s[i - 2 : i] <= '26' and s[i - 2] != '0': 25 | rec += dp[i&1] 26 | dp[i&1] = rec 27 | return dp[len(s)&1] 28 | 29 | # debug 30 | s = Solution() 31 | print s.numDecodings("12") 32 | -------------------------------------------------------------------------------- /solutions/169.Majority_Element/AC_Bits_n.py: -------------------------------------------------------------------------------- 1 | # Author: illuz 2 | # File: AC_Bits_n.py 3 | # Create Date: 2015-02-05 11:30:25 4 | # Descripton: 5 | 6 | class Solution: 7 | # @param num, a list of integers 8 | # @return an integer 9 | def majorityElement(self, num): 10 | res = 0 11 | for dig in range(32): 12 | app = 0 13 | for n in num: 14 | if (n & (1< len(num): 17 | res |= (1< 3 | * File: AC_brute_force_n2.cpp 4 | * Create Date: 2014-12-24 09:53:51 5 | * Descripton: brute force, O(n*n) 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int strStr(char *haystack, char *needle) { 16 | int hlen = strlen(haystack); 17 | int nlen = strlen(needle); 18 | if (hlen < nlen) 19 | return -1; 20 | for (int i = 0; i <= hlen - nlen; i++) { 21 | if (!strncmp(haystack + i, needle, nlen)) 22 | return i; 23 | } 24 | return -1; 25 | } 26 | }; 27 | 28 | int main() { 29 | char a[100], b[100]; 30 | Solution s; 31 | while (cin >> a >> b) 32 | cout << s.strStr(a, b) << endl; 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /solutions/204.Count_Primes/AC_prime_n2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_prime_n2.cpp 4 | * Create Date: 2015-05-04 23:13:54 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int countPrimes(int n) { 16 | if (n <= 2) 17 | return 0; 18 | vector noprime(n, false); 19 | 20 | int sum = 0; 21 | int bound = sqrt(n); 22 | for (int i = 2; i < n; ++i) { 23 | if (!noprime[i]) { 24 | ++sum; 25 | if (i > bound) 26 | continue; 27 | for (int j = i * i; j < n; j += i) 28 | noprime[j] = true; 29 | } 30 | } 31 | return sum; 32 | } 33 | }; 34 | 35 | int main() { 36 | 37 | return 0; 38 | } 39 | 40 | -------------------------------------------------------------------------------- /solutions/022.Generate_Parentheses/AC_dfs_less2^n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_dfs_less2^n.py 5 | # Create Date: 2015-03-05 10:27:16 6 | # Usage: AC_dfs_less2^n.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param an integer 12 | # @return a list of string 13 | def generateParenthesis(self, n): 14 | dp = {0: [""], 1: ["()"]} 15 | 16 | def memorial_dfs(n): 17 | if n not in dp: 18 | dp[n] = [] 19 | for i in range(n): 20 | for inner in memorial_dfs(i): 21 | for outter in memorial_dfs(n - i - 1): 22 | dp[n].append('(' + inner + ')' + outter) 23 | return dp[n] 24 | 25 | return memorial_dfs(n) 26 | 27 | # debug 28 | s = Solution() 29 | print s.generateParenthesis(3) 30 | -------------------------------------------------------------------------------- /solutions/029.Divide_Two_Integers/AC_binary_nlogn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_binary_nlogn.py 5 | # Create Date: 2015-03-06 15:28:28 6 | # Usage: AC_binary_nlogn.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @return an integer 12 | def divide(self, dividend, divisor): 13 | sign = (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0) 14 | a, b = abs(dividend), abs(divisor) 15 | ret, c = 0, 0 16 | 17 | while a >= b: 18 | c = b 19 | i = 0 20 | while a >= c: 21 | a -= c 22 | ret += (1< 3 | * File: AC_recursive_n.cpp 4 | * Create Date: 2014-12-18 10:51:22 5 | * Descripton: recursive, because f(n) = f(n - 1) + f(n - 2), just like Fibonacci 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int climbStairs(int n) { 16 | if (n == 0) 17 | return 1; 18 | if (n <= 3) 19 | return n; 20 | int pre1 = 1, pre2 = 2, cur; 21 | for (int i = 3; i <= n; i++) { 22 | cur = pre1 + pre2; 23 | pre1 = pre2; 24 | pre2 = cur; 25 | } 26 | return cur; 27 | } 28 | }; 29 | 30 | int main() { 31 | int n; 32 | Solution s; 33 | while (cin >> n) 34 | cout << s.climbStairs(n) << endl; 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /solutions/093.Restore_IP_Addresses/AC_for_27.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_for_27.py 5 | # Create Date: 2015-03-01 20:29:10 6 | # Usage: AC_for_27.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @param s, a string 12 | # @return a list of strings 13 | def restoreIpAddresses(self, s): 14 | ret = [] 15 | isValid = lambda x : str(int(x)) == x and int(x) < 256 16 | for i in range(1, 4): 17 | for j in range(1, 4): 18 | for k in range(1, 4): 19 | sub = [s[0: i], s[i: i + j], s[i + j: i + j + k], s[i + j + k:]] 20 | if '' not in sub and False not in map(isValid, sub): 21 | ret.append('.'.join(sub)) 22 | return ret 23 | 24 | # debug 25 | s = Solution() 26 | print s.restoreIpAddresses('25525511134') 27 | -------------------------------------------------------------------------------- /solutions/226.Invert_Binary_Tree/AC_recursive_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_recursive_n.cpp 4 | * Create Date: 2015-07-26 10:28:58 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | // Definition for a binary tree node. 14 | struct TreeNode { 15 | int val; 16 | TreeNode *left; 17 | TreeNode *right; 18 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | TreeNode* invertTree(TreeNode* root) { 24 | if (root) { 25 | swap(root->left, root->right); 26 | invertTree(root->left); 27 | invertTree(root->right); 28 | } 29 | return root; 30 | } 31 | }; 32 | 33 | int main() { 34 | TreeNode *t(0); 35 | Solution s; 36 | s.invertTree(NULL); 37 | return 0; 38 | } 39 | 40 | -------------------------------------------------------------------------------- /solutions/012.Integer_to_Roman/AC_simulation_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_1.py 5 | # Create Date: 2015-03-02 23:02:51 6 | # Usage: AC_simulation_1.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | # @return a string 12 | def intToRoman(self, num): 13 | val = [ 14 | 1000, 900, 500, 400, 15 | 100, 90, 50, 40, 16 | 10, 9, 5, 4, 17 | 1 18 | ] 19 | syb = [ 20 | "M", "CM", "D", "CD", 21 | "C", "XC", "L", "XL", 22 | "X", "IX", "V", "IV", 23 | "I" 24 | ] 25 | roman = '' 26 | i = 0 27 | while num > 0: 28 | for _ in range(num // val[i]): 29 | roman += syb[i] 30 | num -= val[i] 31 | i += 1 32 | return roman 33 | -------------------------------------------------------------------------------- /solutions/222.Count_Complete_Tree_Nodes/AC_binary_search_lognlogn.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_binary_search_lognlogn.py 5 | # Create Date: 2015-08-07 00:01:49 6 | # Usage: AC_binary_search_lognlogn.py 7 | # Descripton: 8 | 9 | class Solution: 10 | # @param {TreeNode} root 11 | # @return {integer} 12 | def countNodes(self, root): 13 | if not root: 14 | return 0 15 | leftDepth = self.getDepth(root.left) 16 | rightDepth = self.getDepth(root.right) 17 | if leftDepth == rightDepth: 18 | return (1< 3 | * File: AC_binary_logn.java 4 | * Create Date: 2015-02-06 10:27:04 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public int sqrt(int x) { 13 | if (x == 0) 14 | return 0; 15 | int l = 1, r = x / 2 + 1; 16 | while (l <= r) { 17 | int m = (l + r) / 2; 18 | if (m <= x / m && x / (m + 1) < m + 1) 19 | return m; 20 | if (x / m < m) 21 | r = m - 1; 22 | else 23 | l = m + 1; 24 | } 25 | return 0; 26 | } 27 | 28 | // debug 29 | public static void main(String[] args) { 30 | Scanner cin = new Scanner(System.in); 31 | Solution s = new Solution(); 32 | System.out.println("no case"); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /solutions/084.Largest_Rectangle_in_Histogram/AC_bruteforce_less_than_n2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_bruteforce_less_than_n2.cpp 4 | * Create Date: 2015-03-07 15:18:16 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int largestRectangleArea(vector &height) { 16 | int ret = 0; 17 | int len = height.size(); 18 | for (int i = 0; i < len; ++i) 19 | if (i + 1 >= len || height[i] > height[i + 1]) { 20 | int mmin = INT_MAX; 21 | for (int j = i; j >= 0; --j) { 22 | mmin = min(mmin, height[j]); 23 | ret = max(ret, mmin * (i - j + 1)); 24 | } 25 | } 26 | return ret; 27 | } 28 | }; 29 | 30 | int main() { 31 | 32 | return 0; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /solutions/138.Copy_List_with_Random_Pointer/readme.md: -------------------------------------------------------------------------------- 1 | ## 138 Copy List with Random Pointer 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/copy-list-with-random-pointer/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 求一个链表的完全复制。 9 | 10 | ### **分析**: 11 | 12 | 刚开始想,每个节点两个指针,这不跟二叉树一样吗?但是太天真,树是没有环的,这个又没说有没有环,有环也是合法的。 13 | 14 | 1. **(Python)**深复制不是很难,只要把 `` 都保存下来,要用的时候拿来用就可以了。不过这要花上 O(n) 的空间,不是很值。(用 Python 可以用 `collections.defaultdict` 一气呵成) 15 | 2. **(C++)** 递归 + Hash 节点,不过不仅要用到 O(n) 的 Hash 空间,还要有栈的花费,还不知道会不会太深爆栈,不是很好的解。 16 | 3. **(Java)** 不会 O(1) space 解法 QAQ,Discuss 里倒是有不少自称 O(1) space,其实都是用了 O(n) space 的。不过思路是不错,就是在每个旧节点后面插一个新节点,再复制一遍,再去掉旧节点,共三次遍历。(这里用的是 Java,所以去掉旧节点时不用特地去释放旧节点,因为有 GC 机制,不过用的 C/C++ 时,最好手动去 release,不然内存泄露) 17 | 18 | (1) 空间的解法请不要吝啬来教我。 19 | Discuss 上的人说,这个题目要完全复制,所以至少要 O(n) 的空间来放节点,所以可以不去考虑节点的空间。 20 | 这样一来,1,2 的解法还是 O(n) 空间,因为要用到 hash 表,不过 3 的解法就是 O(1) 没错了。 21 | 22 | -------------------------------------------------------------------------------- /solutions/117.Populating_Next_Right_Pointers_in_Each_Node_II/AC_simulation_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_simulation_n.py 5 | # Create Date: 2015-02-22 10:37:20 6 | # Usage: AC_simulation_n.py 7 | # Descripton: The same as vesion I 8 | 9 | 10 | class Solution: 11 | # @param root, a tree node 12 | # @return nothing 13 | def connect(self, root): 14 | header = TreeNode(0) 15 | header.next = root 16 | while header.next: 17 | cur = header.next 18 | prev = header 19 | header.next = None 20 | while cur: 21 | if cur.left: 22 | prev.next = cur.left 23 | prev = prev.next 24 | if cur.right: 25 | prev.next = cur.right 26 | prev = prev.next 27 | cur = cur.next 28 | -------------------------------------------------------------------------------- /solutions/028.Implement_strStr()/readme.md: -------------------------------------------------------------------------------- 1 | ## 028. Implement strStr() (Easy) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/implement-strstr/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 在一个字符串里找另一个字符串在其中的位置。 9 | 10 | ### **分析**: 11 | 这题归在 Easy 类是因为它 O(n*n) 的暴力能过。 12 | 如果数据强点就得 Midium 以上了。 13 | 14 | 1. **(C++)** 这题的暴力 O(n^2) 就是两遍 for 去找 15 | 2. **(C++)** 还有各种高大上的算法,比如 [KMP 算法](http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm),这是经典的了 16 | 3. **(Python)** 另外可以用 hash 去做,叫 rolling hash 算法(见 [Wiki](http://en.wikipedia.org/wiki/Rolling_hash) 和 [StackOverflow](http://stackoverflow.com/questions/711770/fast-implementation-of-rolling-hash)),就是把字符串 hash 出来,按匹配串长度窗口去滚动,再去匹配。hash 字符串有很多种方法,这边的字母好像都是小写,有 26 个,所以就用 29 做基数(本来想像 djb2 算法用 33 做基数,可以直接 `((hash << 5) + hash)` 很快,不过 int 范围只能 hash 6 个字母而且 rolling 的时候还是要 `/33`,还是用 29 算了),超 int 范围的话用 Python 就不用考虑这个问题了。 17 | 18 | 其他还有 Boyer–Moore,Rabin–Karp 算法,具体自己去搜。 19 | -------------------------------------------------------------------------------- /solutions/100.Same_Tree/AC_silulation_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_silulation_n.cpp 4 | * Create Date: 2014-12-19 08:34:19 5 | * Descripton: simulation 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | 14 | // Definition for binary tree 15 | struct TreeNode { 16 | int val; 17 | TreeNode *left; 18 | TreeNode *right; 19 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 20 | }; 21 | 22 | class Solution { 23 | public: 24 | bool isSameTree(TreeNode *p, TreeNode *q) { 25 | if (p == NULL) 26 | return q == NULL; 27 | if (q == NULL) 28 | return p == NULL; 29 | if (p->val != q->val) 30 | return false; 31 | return isSameTree(p->left, q->left) && 32 | isSameTree(p->right, q->right); 33 | } 34 | }; 35 | 36 | int main() { 37 | 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /solutions/151.Reverse_Words_in_a_String/AC_split_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_split_n.java 4 | * Create Date: 2015-03-18 22:30:59 5 | * Descripton: 6 | */ 7 | 8 | import java.util.*; 9 | 10 | public class Solution { 11 | public String reverseWords(String s) { 12 | String[] words = s.trim().split(" +"); 13 | int len = words.length; 14 | if (len == 0) { 15 | return ""; 16 | } 17 | StringBuilder sb = new StringBuilder(words[len - 1]); 18 | for (int i = len - 2; i >= 0; --i) { 19 | sb.append(" " + words[i]); 20 | } 21 | return sb.toString(); 22 | } 23 | 24 | // debug 25 | public static void main(String[] args) { 26 | Scanner cin = new Scanner(System.in); 27 | Solution s = new Solution(); 28 | int[] input = {1, 2, 3, 4}; 29 | System.out.println("no case"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /solutions/225.Implement_Stack_using_Queues/AC_simulation_1.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_1.java 4 | * Create Date: 2015-07-25 12:22:04 5 | * Descripton: 6 | */ 7 | 8 | import java.util.LinkedList; 9 | import java.util.Queue; 10 | 11 | class MyStack { 12 | private Queue queue; 13 | 14 | // Push element x onto stack. 15 | public void push(int x) { 16 | Queue q = new LinkedList(); 17 | q.add(x); 18 | q.add(queue); 19 | queue = q; 20 | } 21 | 22 | // Removes the element on top of the stack. 23 | public void pop() { 24 | queue.remove(); 25 | queue = (Queue)queue.peek(); 26 | } 27 | 28 | // Get the top element. 29 | public int top() { 30 | return (int)queue.peek(); 31 | } 32 | 33 | // Return whether the stack is empty. 34 | public boolean empty() { 35 | return queue == null; 36 | } 37 | } -------------------------------------------------------------------------------- /solutions/278.First_Bad_Version/AC_binary_search_logn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_binary_search_logn.cpp 4 | * Create Date: 2015-09-24 09:33:56 5 | * Descripton: 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | // Forward declaration of isBadVersion API. 14 | bool isBadVersion(int version) { return version >= 1; } 15 | 16 | class Solution { 17 | public: 18 | int firstBadVersion(int n) { 19 | int l = 1, r = n; 20 | while (l < r) { 21 | int mid = l + (r - l) / 2; 22 | if (isBadVersion(mid)) { 23 | r = mid; 24 | } else { 25 | l = mid + 1; 26 | } 27 | } 28 | return l; 29 | } 30 | }; 31 | 32 | int main() { 33 | int n; 34 | Solution s; 35 | cin >> n; 36 | cout << s.firstBadVersion(n) << endl; 37 | return 0; 38 | } 39 | 40 | -------------------------------------------------------------------------------- /solutions/279.Perfect_Squares/MLE_dp_nsqrtn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: MLE_dp_nsqrtn.py 5 | # Create Date: 2015-10-26 11:03:22 6 | 7 | import math 8 | 9 | class Solution(object): 10 | def helper(self, n): 11 | if self.result[n] != 0: 12 | return self.result[n] 13 | if n in self.square: 14 | return 1 15 | self.result[n] = min(1 + self.helper(n - sqr) for sqr in self.square if sqr <= n) 16 | return self.result[n] 17 | 18 | def numSquares(self, n): 19 | """ 20 | :type n: int 21 | :rtype: int 22 | """ 23 | self.result = [0 for _ in xrange(n + 1)] 24 | self.square = [s**2 for s in xrange(1, int(math.sqrt(n))+1)] 25 | 26 | return self.helper(n) 27 | 28 | s = Solution() 29 | print(s.numSquares(12)) 30 | print(s.numSquares(13)) 31 | print(s.numSquares(7168)) 32 | -------------------------------------------------------------------------------- /solutions/328.Odd_Even_Linked_List/AC_double_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_double_n.py 5 | # Create Date: 2016-02-23 19:16:07 6 | # Usage: AC_simulation_n.py 7 | # Descripton: 8 | 9 | 10 | # Definition for singly-linked list. 11 | class ListNode(object): 12 | def __init__(self, x): 13 | self.val = x 14 | self.next = None 15 | 16 | class Solution(object): 17 | def oddEvenList(self, head): 18 | """ 19 | :type head: ListNode 20 | :rtype: ListNode 21 | """ 22 | if not head: 23 | return head 24 | evenhead = head.next 25 | odd, even = head, evenhead 26 | while even and even.next: 27 | odd.next = odd.next.next 28 | even.next = even.next.next 29 | odd, even = odd.next, even.next 30 | odd.next = evenhead 31 | return head 32 | -------------------------------------------------------------------------------- /solutions/041.First_Missing_Positive/AC_array_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_array_n.cpp 4 | * Create Date: 2015-01-28 09:38:55 5 | * Descripton: Brute force. This will use O(n) space && O(n) time. 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int firstMissingPositive(int A[], int n) { 16 | vector rec(n + 2); 17 | for (int i = 0; i < n; i++) { 18 | if (A[i] < n + 2 && A[i] > 0) 19 | rec[A[i]] = true; 20 | } 21 | for (int i = 1; i < n + 2; i++) 22 | if (!rec[i]) 23 | return i; 24 | } 25 | }; 26 | 27 | int main() { 28 | int n, A[100]; 29 | Solution s; 30 | cin >> n; 31 | for (int i = 0; i < n; i++) 32 | cin >> A[i]; 33 | cout << s.firstMissingPositive(A, n) << endl; 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /solutions/058.Length_of_Last_Word/AC_simulation_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_n.cpp 4 | * Create Date: 2014-12-08 15:52:22 5 | * Descripton: simulation, find from back 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int lengthOfLastWord(const char *s) { 16 | int pos = strlen(s); 17 | while (--pos >= 0) { 18 | if (s[pos] != ' ') 19 | break; 20 | } 21 | // not found 22 | if (pos < 0) 23 | return 0; 24 | int ret = 1; 25 | while (--pos >= 0 && s[pos] != ' ') { 26 | ret++; 27 | } 28 | return ret; 29 | } 30 | }; 31 | 32 | int main() { 33 | char str[100]; 34 | Solution s; 35 | while (gets(str)) 36 | cout << s.lengthOfLastWord(str) << endl; 37 | return 0; 38 | } 39 | 40 | -------------------------------------------------------------------------------- /solutions/102.Binary_Tree_Level_Order_Traversal/AC_dfs_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_dfs_n.py 5 | # Create Date: 2015-03-09 09:30:11 6 | # Usage: AC_dfs_n.py 7 | # Descripton: 8 | 9 | 10 | # Definition for a binary tree node 11 | class TreeNode: 12 | def __init__(self, x): 13 | self.val = x 14 | self.left = None 15 | self.right = None 16 | 17 | class Solution: 18 | # @param root, a tree node 19 | # @return a list of lists of integers 20 | def levelOrder(self, root): 21 | ret = [] 22 | def dfs(root, level): 23 | if root: 24 | if level >= len(ret): 25 | ret.append([]) 26 | ret[level].append(root.val) 27 | dfs(root.left, level + 1) 28 | dfs(root.right, level + 1) 29 | 30 | dfs(root, 0) 31 | return ret 32 | 33 | -------------------------------------------------------------------------------- /solutions/111.Minimum_Depth_of_Binary_Tree/AC_recursive_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_recursive_n.cpp 4 | * Create Date: 2014-12-19 08:53:56 5 | * Descripton: recursive 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | // Definition for binary tree 14 | struct TreeNode { 15 | int val; 16 | TreeNode *left; 17 | TreeNode *right; 18 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | int minDepth(TreeNode *root) { 24 | if (root == NULL) 25 | return 0; 26 | int dl = minDepth(root->left); 27 | int dr = minDepth(root->right); 28 | if (dl == 0) 29 | return dr + 1; 30 | if (dr == 0) 31 | return dl + 1; 32 | return min(dr + 1, dl + 1); 33 | } 34 | }; 35 | 36 | int main() { 37 | 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /solutions/146.LRU_Cache/readme.md: -------------------------------------------------------------------------------- 1 | ## 149. LRU Cache (Hard) 2 | 3 | ### **链接**: 4 | 题目:https://leetcode.com/problems/lru-cache/ 5 | 代码(github):https://github.com/illuz/leetcode 6 | 7 | ### **题意**: 8 | 实现一个 LRU 缓冲区的类。 9 | 10 | ### **分析**: 11 | 12 | LRU 不难理解,问题是要怎么高效地去实现它。 13 | LRU 会有频繁的读改操作,所以要有合适的数据结构来让 set 和 get 的复杂度很小,最好近 O(1)。 14 | 已经有人讨论过这个问题了:[What is the best way to Implement a LRU Cache? - Quora](http://www.quora.com/What-is-the-best-way-to-Implement-a-LRU-Cache)。 15 | 16 | 1. 用 Splay 实现,Splay 是棵 BST,同时在查找和修改的时候会让那个节点上浮到根节点,不过操作都是 O(log(n)) 级别的,而且有个问题,就是这棵树可能会变成一条链(正常节点都是按查询频率从上到下,所以很快,均摊小于 O(log(n)))。Splay 太麻烦,这里就不给出。 17 | 2. 用双链表和 HashMap 实现,链表的作用是记录节点的使用顺序。正常情况下 LRU 都是用这种做法的。 18 | 1. HashMap 实现用 key 找到 List 中的节点对象(C++ 中就是迭代器了),找不到就在 List 中增加节点,并插入 HashMap。 19 | 2. 按照要求得到或修改节点的 value。 20 | 3. 修改节点的使用时间,也就是把 List 中的节点拉到 List 头部。 21 | 4. 在第一步时如果节点个数大于可用容量,就将 List 的最后一个节点删去。 22 | 23 | 用 Python 的 OrderedDict 可以一下将 HashMap 和 List 都实现。 24 | 25 | -------------------------------------------------------------------------------- /solutions/019.Remove_Nth_Node_From_End_of_List/AC_two_point_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_two_point_n.py 5 | # Create Date: 2015-03-04 19:16:10 6 | # Usage: AC_two_point_n.py 7 | # Descripton: 8 | 9 | 10 | # Definition for singly-linked list. 11 | class ListNode: 12 | def __init__(self, x): 13 | self.val = x 14 | self.next = None 15 | 16 | class Solution: 17 | # @return a ListNode 18 | def removeNthFromEnd(self, head, n): 19 | dummy = ListNode(0) 20 | dummy.next = head 21 | p, q = dummy, dummy 22 | 23 | # first 'q' go n step 24 | for i in range(n): 25 | q = q.next 26 | 27 | # q & p 28 | while q.next: 29 | p = p.next 30 | q = q.next 31 | 32 | rec = p.next 33 | p.next = rec.next 34 | del rec 35 | return dummy.next 36 | 37 | -------------------------------------------------------------------------------- /solutions/074.Search_a_2D_Matrix/AC_binary_search_log(nm).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_binary_search_log(nm).cpp 4 | * Create Date: 2014-12-28 14:58:07 5 | * Descripton: regard the matrix as an array 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | bool searchMatrix(vector > &matrix, int target) { 16 | if (matrix.empty() || matrix[0].empty()) 17 | return false; 18 | int n = matrix.size(), m = matrix[0].size(); 19 | int l = 0, r = n * m - 1, mid = 0; 20 | while (l < r) { 21 | mid = l + (r - l) / 2; 22 | if (matrix[mid/m][mid%m] < target) 23 | l = mid + 1; 24 | else 25 | r = mid; 26 | } 27 | return matrix[l/m][l%m] == target; 28 | } 29 | }; 30 | 31 | int main() { 32 | return 0; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /solutions/162.Find_Peak_Element/AC_binary_search.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # Author: illuz 4 | # File: AC_binary_search.py 5 | # Create Date: 2015-02-14 09:42:56 6 | # Usage: AC_binary_search.py 7 | # Descripton: 8 | 9 | 10 | class Solution: 11 | def findPeakInRange(self, num, lhs, rhs): 12 | mid = (lhs + rhs) // 2 13 | if (mid == lhs or num[mid] > num[mid - 1]) and \ 14 | (mid == rhs or num[mid] > num[mid + 1]): 15 | return mid 16 | if num[mid] < num[mid + 1]: 17 | return self.findPeakInRange(num, mid + 1, rhs) 18 | else: 19 | return self.findPeakInRange(num, lhs, mid) 20 | # @param num, a list of integer 21 | # @return an integer 22 | def findPeakElement(self, num): 23 | return self.findPeakInRange(num, 0, len(num) - 1) 24 | 25 | 26 | # debug 27 | s = Solution() 28 | print s.findPeakElement([1, 2, 3, 1]) 29 | -------------------------------------------------------------------------------- /solutions/014.Longest_Common_Prefix/AC_bruteforce_n2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_bruteforce_n2.java 4 | * Create Date: 2015-03-03 15:17:18 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public String longestCommonPrefix(String[] strs) { 13 | if (strs.length == 0) 14 | return ""; 15 | for (int i = 0; i < strs[0].length(); i++) { 16 | for (int j = 1; j < strs.length; j++) 17 | if (strs[j].length() <= i || strs[j].charAt(i) != strs[0].charAt(i)) 18 | return strs[0].substring(0, i); 19 | } 20 | return strs[0]; 21 | } 22 | 23 | // debug 24 | public static void main(String[] args) { 25 | Scanner cin = new Scanner(System.in); 26 | Solution s = new Solution(); 27 | int[] input = {1, 2, 3, 1}; 28 | System.out.println("no case"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /solutions/003.Longest_Substring_Without_Repeating_Characters/readme.md: -------------------------------------------------------------------------------- 1 | 2 | ## 003.Longest_Substring_Without_Repeating_Characters 3 | 4 | ### **链接**: 5 | 题目:https://leetcode.com/problems/Longest-Substring-Without-Repeating-Characters/ 6 | 代码(github):https://github.com/illuz/leetcode 7 | 8 | ### **题意**: 9 | 从标题就可以知道题意了,是求一个字符串中最长的不含重复字符的子串。 10 | 11 | ### **分析**: 12 | 开一个数组记录当前字符最近出现的位置,一遍算过去,更新左边界,用它计算最大值就行了。 13 | 需要花费常数的空间。 14 | 15 | 16 | --- 17 | 18 | **(English version)** 19 | 20 | 21 | ## 003.Longest_Substring_Without_Repeating_Characters 22 | 23 | 24 | **Link**: 25 | Problem: https://leetcode.com/problems/Longest-Substring-Without-Repeating-Characters/ 26 | Newest solutions in my Github: https://github.com/illuz/leetcode 27 | 28 | **Analysis**: 29 | Generate an array to record the last position of current character. 30 | Count and update the left bound, and calculate the maximum. 31 | It will just cost constant space. 32 | -------------------------------------------------------------------------------- /solutions/004.Median_of_Two_Sorted_Arrays/readme.md: -------------------------------------------------------------------------------- 1 | 2 | ## 004.Median_of_Two_Sorted_Arrays 3 | 4 | ### **链接**: 5 | 题目:https://leetcode.com/problems/Median-of-Two-Sorted-Arrays/ 6 | 代码(github):https://github.com/illuz/leetcode 7 | 8 | ### **题意**: 9 | 求两个有序数组的中位数。要求复杂度是 O(log(n + m))。 10 | 11 | ### **分析**: 12 | 两种思路: 13 | 1. 直接 merge 两个数组,然后求中位数,能过,不过复杂度是 O(n + m)。 14 | 2. 用二分的思路去做,这不好想,还要考虑到奇偶。可以转化思维,去求两个有序数组中的第 K 大数,这样就比较好想了。 15 | 16 | --- 17 | 18 | **(English version)** 19 | 20 | ## 004.Median_of_Two_Sorted_Arrays 21 | 22 | 23 | **Link**: 24 | Problem: https://leetcode.com/problems/Median-of-Two-Sorted-Arrays/ 25 | Newest solutions in my Github: https://github.com/illuz/leetcode 26 | 27 | **Analysis**: 28 | Two ways to get it. 29 | 1. Merge the two arrays first and solve it. But the time complexity is O(n + m). 30 | 2. Use the method of binary search. This will be hard to think. Just consider to find the k-th biggest number in two sorted arrays and it will help you. 31 | -------------------------------------------------------------------------------- /solutions/007.Reverse_Integer/AC_simulation_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_simulation_n.java 4 | * Create Date: 2015-02-27 10:03:47 5 | * Descripton: 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Solution { 11 | 12 | public int reverse(int x) { 13 | Long res = 0L; 14 | Long tmp = Math.abs((long) x); 15 | while (tmp != 0) { 16 | res = res * 10 + tmp % 10; 17 | tmp = tmp / 10; 18 | if (res > (long)Integer.MAX_VALUE) 19 | return 0; 20 | } 21 | if (x>0) 22 | return res.intValue(); 23 | else 24 | return -res.intValue(); 25 | } 26 | 27 | // debug 28 | public static void main(String[] args) { 29 | Scanner cin = new Scanner(System.in); 30 | Solution s = new Solution(); 31 | int[] input = {1, 2, 3, 1}; 32 | System.out.println("no case"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /solutions/115.Distinct_Subsequences/AC_dp_less_space_n*m.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_dp_less_space_n*m.cpp 4 | * Create Date: 2015-03-11 11:13:04 5 | * Descripton: Use O(m) space. 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | const int N = 0; 12 | 13 | class Solution { 14 | public: 15 | int numDistinct(string S, string T) { 16 | int n = S.length(); 17 | int m = T.length(); 18 | 19 | vector dp(m + 1); 20 | 21 | dp[0] = 1; 22 | for (int i = 0; i < n; ++i) { 23 | for (int j = m - 1; j >= 0; --j) { 24 | if (S[i] == T[j]) 25 | dp[j + 1] += dp[j]; 26 | } 27 | } 28 | 29 | return dp[m]; 30 | } 31 | }; 32 | 33 | int main() { 34 | string a, b; 35 | Solution s; 36 | while (cin >> a >> b) { 37 | cout << s.numDistinct(a, b) << endl; 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /solutions/198.House_Robber/AC_dp_n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: illuz 3 | * File: AC_dp_n.cpp 4 | * Create Date: 2015-03-31 21:12:08 5 | * Descripton: dp[i] = max(dp[i - 1], dp[i - 2] + num[i]) 6 | * dp[i]->cur, dp[i-1]->pre, dp[i-2]->ppre 7 | */ 8 | 9 | #include 10 | 11 | using namespace std; 12 | const int N = 0; 13 | 14 | class Solution { 15 | public: 16 | int rob(vector &num) { 17 | if (num.empty()) 18 | return 0; 19 | 20 | int ppre = 0, pre = 0, cur = 0; 21 | for (auto n : num) { 22 | cur = max(pre, ppre + n); 23 | ppre = pre; 24 | pre = cur; 25 | } 26 | 27 | return max(pre, ppre); 28 | } 29 | }; 30 | 31 | int main() { 32 | int n; 33 | Solution s; 34 | cin >> n; 35 | vector num(n); 36 | for (auto &i : num) 37 | cin >> i; 38 | cout << s.rob(num) << endl; 39 | return 0; 40 | } 41 | 42 | --------------------------------------------------------------------------------