├── leetcode ├── 490_The_Maze_I.java ├── 410_hard_Split_Array_Largest_Sum.java ├── 309_Best_Time_Buy_Sell_Stock_with_Cooldown.java ├── 196_Delete_Duplicate_Emails.sql ├── 182_Duplicate_Emails.sql ├── 595_Big_Countries.java ├── 175_Combine_Two_Tables.sql ├── 237_Delete_Node_Linked_List.java ├── 645_Set_Mismatch.py ├── 193_Valid_Phone_Numbers.sh ├── 171_Excel_Sheet_Column_Number.java ├── 136_Single_Number.java ├── 125_easySolution.java ├── 627_Swap_Salary.sql ├── 080_Remove_Duplicates_From_Sorted_Array_II.java ├── 561_Array_Partition_I.java ├── 191_Number_of_1_Bits.java ├── 176_Second_Highest_Salary.sql ├── 231_Power_of_Two.java ├── 596_Classes_More_5_Students.sql ├── 598_Range_Addition_II.java ├── 754_Reach_a_Number.java ├── 190_Reverse_Bits.java ├── 319_Bulb_Switcher.java ├── 371_Sum_of_Two_Integers.java ├── 009_Palindrome_number.java ├── 096_Unique_Binary_Search_Trees_I.java ├── 195_Tenth_Line.sh ├── 181_Employees_Earning_More.sql ├── 367_Valid_Perfect_Square.java ├── 007_Reverse_Integer.java ├── 258_Add_Digits.java ├── 693_Binary_Number_with_Alternating_Bits.java ├── 338_Counting_Bits.java ├── 183_Customers_Who_Never_Order.sql ├── 011_Container_With_Most_Water.java ├── 217_Contains_Duplicate.java ├── 387_First_Unique_Character.java ├── 172_count_zero.java ├── 557_Reverse_Words_in_String_III.py ├── 201.md ├── 062_Unique_Paths_I.java ├── 120_Triangle.java ├── 263_Ugly_Number.java ├── 405_Convert_a_Number_to_Hexadecimal.java ├── 674_Longest_Continuous_Increasing_Subsequence.java ├── 260_Single_Number_III.java ├── 017_Letter_Combinations_of_a_Phone_Number.py ├── 342_Power_of_Four.java ├── 152_Maximum_Product_Subarray.java ├── 744_Find_Smallest_Letter_Greater_Than_Target.java ├── 051_hard_N-Queens.py ├── 409_Longest_Palindrome.java ├── 645_Set_Mismatch.java ├── 100_Same_tree.java ├── 020_Valid_Parentheses.java ├── 089_Gray_Code.java ├── 112_Path_Sum.java ├── 496_Next_Greater_Element_I.java ├── 058_Length_of_Last_Word.java ├── 012_Integer_to_Romman.java ├── 088_Merge_Sorted_Array.java ├── 495_Teemo_Attaching.java ├── 532_K-diff_Pairs_in_a_Array.py ├── 344_Reverse_String.java ├── 122_Best_Time_Buy_Sell_Stock_II.java ├── 532_K-diff_Pairs_in_a_Array.java ├── 492_Construct_the_Rectangle.java ├── 503_Next_Greater_Element.py ├── 504_Base_7.java ├── 077_Combinations.java ├── 617_Merge_Two_Binary_Trees.java ├── 290_Word_Pattern.java ├── 049_Group_Anagrams.java ├── 240_Search_2D_Matrix_II.java ├── 696_Count_Binary_Substrings.java ├── 141_Linked_List_Cycle.java ├── 728_Self_Dividing_Number.java ├── 026_Remove_Duplicates_from_Sorted_Array.java ├── 071_Simplify_Path.py ├── 235_Lowest_Common_Ancestor_BST.java ├── 581_Shortest_Unsorted_Continuous_Subarray.java ├── 198_House_Robber.java ├── 554_Brick_Wall.java ├── 125_Valid_Palindrome.java ├── 633_Sum_of_Square_Numbers.java ├── 657_Judge_Route_Circle.py ├── 118_Pascal_Triangle.java ├── 412_Fizz_Buzz.java ├── 371_Sum_of_Two_Integers.py ├── 221_Maximal_Square.java ├── 053_Maximum_Subarray.java ├── 064_Minimum_Path_Sum.java ├── 414_Third_Maximum_Number.java ├── 022_Generate_Parentheses.java ├── 069_Sqrt_x.java ├── 389_Find_the_Difference.java ├── 192_Word_Frequency.bash ├── 032_hard_Longest_Valid_Parentheses.java ├── 203_Remove_Linked_List_Elements.java ├── 139_Word_Break.java ├── 322_Coin_Change.java ├── 275_H-Index_II.java ├── 169_Majority_Element.java ├── 437_Path_Sum_III.java ├── 683_hard_K_Empty_Slots.java ├── 753_Cracking_the_Safe.java ├── 421_Maximum_XOR_of_Two_Numbers_in_an_Array.java ├── 757_hard_Set_Intersection_Size_At_Least_Two.java ├── 027_Remove_Element.java ├── 090_Subsets_II.java ├── 383_Ransom_Node.java ├── 552_hard_Student_Attendance_Record_II.java ├── 067_Add_Binary.java ├── 506_Relative_Ranks.java ├── 017_Letter_Combinations_of_a_Phone_Number.java ├── 129_Sum_Root_to_Leaf.java ├── 575_Distribute_Candies.java ├── 682_Baseball_Game.java ├── 070_Climbing_Stairs.java ├── 678_Valid_Parenthesis_String.java ├── 474_Ones_and_Zeroes.java ├── 503_Next_Greater_Element.java ├── 043_Multiply_String.py ├── 146_hard_LRU_Cache.java ├── 261_Graph_Valid_Tree.py ├── 061_Rotate_List.java ├── 150_Evaluate_Reverse_Polish_Notation.java ├── 313_Super_Ugly_Number.java ├── 657_Judge_Route_Circle.java ├── 662_Maximum_Width_of_Binary_Tree.py ├── 664_Strange_Printer.java ├── 038_Count_and_Say.java ├── 086_Partition_List.java ├── 557_Reverse_Words_in_String_III.java ├── 647_Palindromic_Substrings.py ├── 153_Find_Minimum_Rotated_Sorted_Array.java ├── 566_Reshape_the_Matrix.java ├── 142_Linked_List_Cycle_II.java ├── 318_Maximum_Product_of_Word_Lengths.java ├── 620_Not_Boring_Movies.sql ├── 055_Jump_Game.java ├── 044_hard_Wildcard_Matching.java ├── 147_Insertion_Sort_List.java ├── 654_Maximum_Binary_Tree.java ├── 441_Arranging_Coins.java ├── 461_Hamming_Distance.java ├── 640_Solve_the_Equation.java ├── 447_Number_of_Boomeranges.java ├── 116_Populating_Next_Right_Pointers.java ├── 541_Reverse_String_II.java ├── 204_Count_Primes.java ├── 040_Combination_Sum_II.java ├── 111_Minimum_Depth_Binary_Tree.java ├── 283_Move_Zeros.java ├── 467_Unique_Substring_in_Wraparound_String.java ├── 513_Find_Bottom_Left_Tree.java ├── 606_Construct_String_From_Binary_Tree.java ├── 507_Perfect_Number.java ├── 239_Sliding_Window_Maximum.java ├── 667_Beautiful_Arrangement_II.java ├── 151_Reverse_Words_in_String.java ├── 278_First_Bad_Version.java ├── 242_Valid_Anagrame.java ├── 690_Employee_Importance.java ├── 206_Reverse_Linked_List.java ├── 343_Integer_Break.java ├── 656_hard_Coin_Path.py ├── 458_Poor_Pigs.java ├── 039_Combination_Sum.java ├── 268_Missing_Number.java ├── 184_Department_Highest_Salary.sql ├── 036_Valid_Sudoku.java ├── 110_Balanced_Binary_Tree.java ├── 194_Transpose_File.sh ├── 165_Compare_Version_Numbers.java ├── 451_Sort_Characters_By_Frequency.py ├── 031_Next_Permutation.java ├── 033_Search_Rotated_Sorted_Array.java ├── 551_Student_Attenance_Record_I.java ├── 345_Reverse_Vowels_of_a_String.java ├── 054_Spiral_Matrix.java └── 059_Spiral_Matrix_II.java ├── lintcode ├── lintcode_400_hard_Maximum_Gap.java ├── lintcode_139_Subarray_Sum_Closest.java ├── lintcode_404_hard_Subarray_Sum_II.java ├── lintcode_631_Maximal_Square_II.java ├── lintcode_036_Reverse_Linked_List_II.java ├── lintcode_077_Longest_Common_Subsequence.java ├── lintcode_396_hard_Coins_in_a_Line_III.java ├── lintcode_558_hard_Sliding_Window_Matrix_Maximum.java ├── lintcode_366_fibonacci.java ├── 082_Single_Number.java ├── lintcode_394_Coins_in_a_Line_I.java ├── lintcode_413_Reverse_Integer.java ├── 083_Single_Number_II.java ├── lintcode_211_stringPermutation.java ├── lintcode_140_quick_power.java ├── lintcode_517_Ugly_Number.java ├── lintcode_372_Delete_One_Element.java ├── lintcode_046_Majority_Number.java ├── lintocde_075_Find_Peak_Element.java ├── lintcode_375_clone_tree.java ├── 084_Single_Number_III.java ├── lintcode_371_print_n_recursion.java ├── lintcode_008_Rotate_String.java ├── lintcode_076_Longest_Increasing_Subsequence.java ├── lintcode_053_Reverse_Words_String.java ├── lintcode_001_A+B+Problem.java ├── lintcode_009_two_string.java ├── lintcode_365_count_1.java ├── lintcode_068_post_order_tree.java ├── lintcode_056_Two_Sum.java ├── lintcode_039_Recover_Rotated_Sorted_Array.java ├── lintcode_031_Partition_Array.java ├── lintcode_589_Connecting_Graph.java ├── lintcode_040_two_Stack_queue.java └── lintcode_158_Two_Strings_Anagrams.java ├── leetcode_daily ├── temp.md ├── 001.md ├── 973.md ├── 461.md ├── 121.md ├── 976.md ├── 974.md ├── 485.md ├── 055.md ├── 013.md ├── 213.md ├── 647.md ├── 1009.md ├── 263.md ├── 045.md ├── 007.md ├── 1025.md ├── 518.md ├── 315.md ├── 022.md ├── 487.md ├── 470.md ├── 279.md ├── 388.md ├── 946.md ├── 322.md ├── 977.md ├── 999.md ├── 416.md ├── 935.md ├── 621.md ├── 077.md ├── 309.md ├── 043.md ├── 1018.md ├── 141.md ├── 056.md ├── 475.md ├── 629.md ├── 678.md ├── 376.md ├── 347.md ├── 334.md ├── 650.md ├── 978.md ├── 101.md ├── 198.md ├── 473.md ├── 1010.md ├── 290.md ├── 229.md ├── 1016.md ├── 993.md ├── 464.md └── 1014.md ├── img └── leetcode_25.jpg ├── template ├── graph.txt ├── template_TwoPointer.java ├── partition.java ├── template_2sum.java └── 2sumII.java └── codeforces └── Screen_Shot_hightail.png /leetcode/490_The_Maze_I.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lintcode/lintcode_400_hard_Maximum_Gap.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /leetcode/410_hard_Split_Array_Largest_Sum.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lintcode/lintcode_139_Subarray_Sum_Closest.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lintcode/lintcode_404_hard_Subarray_Sum_II.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lintcode/lintcode_631_Maximal_Square_II.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lintcode/lintcode_036_Reverse_Linked_List_II.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lintcode/lintcode_077_Longest_Common_Subsequence.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lintcode/lintcode_396_hard_Coins_in_a_Line_III.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /leetcode/309_Best_Time_Buy_Sell_Stock_with_Cooldown.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /leetcode_daily/temp.md: -------------------------------------------------------------------------------- 1 | []() 2 | 3 | ```python 4 | 5 | ``` -------------------------------------------------------------------------------- /lintcode/lintcode_558_hard_Sliding_Window_Matrix_Maximum.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /img/leetcode_25.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XingxingHuang/Leetcode-for-Fun/HEAD/img/leetcode_25.jpg -------------------------------------------------------------------------------- /template/graph.txt: -------------------------------------------------------------------------------- 1 | directed 2 | 5 3 | A 4 | B 5 | C 6 | D 7 | E 8 | A B 9 | A C 10 | B D 11 | C D 12 | D E -------------------------------------------------------------------------------- /leetcode/196_Delete_Duplicate_Emails.sql: -------------------------------------------------------------------------------- 1 | DELETE p1 2 | FROM Person p1, Person p2 3 | WHERE p1.Email = p2.Email AND 4 | p1.Id > p2.Id -------------------------------------------------------------------------------- /codeforces/Screen_Shot_hightail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XingxingHuang/Leetcode-for-Fun/HEAD/codeforces/Screen_Shot_hightail.png -------------------------------------------------------------------------------- /leetcode/182_Duplicate_Emails.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT Email 3 | FROM Person 4 | GROUP BY Email 5 | having COUNT(Email) > 1 -------------------------------------------------------------------------------- /leetcode/595_Big_Countries.java: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT name, population, area 3 | FROM World 4 | WHERE area > 3000000 OR population > 25000000 -------------------------------------------------------------------------------- /leetcode/175_Combine_Two_Tables.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT FirstName, LastName, City, State 3 | FROM Person 4 | LEFT JOIN Address ON Person.PersonId = Address.PersonId 5 | -------------------------------------------------------------------------------- /leetcode/237_Delete_Node_Linked_List.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void deleteNode(ListNode node) { 3 | node.val = node.next.val; 4 | node.next = node.next.next; 5 | } 6 | } -------------------------------------------------------------------------------- /leetcode/645_Set_Mismatch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findErrorNums(self, nums): 3 | t1 = sum(nums) 4 | t2 = sum(set(nums)) 5 | l = len(nums) 6 | return [t1 - t2, l * (l + 1) / 2 - t2] -------------------------------------------------------------------------------- /leetcode/193_Valid_Phone_Numbers.sh: -------------------------------------------------------------------------------- 1 | Using grep: 2 | 3 | grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt 4 | Using sed: 5 | 6 | sed -n -r '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt 7 | Using awk: 8 | 9 | awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt -------------------------------------------------------------------------------- /leetcode/171_Excel_Sheet_Column_Number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int titleToNumber(String s) { 3 | int n = 0; 4 | for (int i = 0; i < s.length(); i ++) { 5 | n = n * 26 + (s.charAt(i) - 'A'+1); 6 | } 7 | return n; 8 | } 9 | } -------------------------------------------------------------------------------- /leetcode/136_Single_Number.java: -------------------------------------------------------------------------------- 1 | // bit wise method 2 | public class Solution { 3 | public int singleNumber(int[] nums) { 4 | int results = 0; 5 | for (int i:nums){ 6 | results ^=i; 7 | } 8 | return(results); 9 | 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/125_easySolution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPalindrome(String s) { 3 | String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase(); 4 | String rev = new StringBuffer(actual).reverse().toString(); 5 | return actual.equals(rev); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /leetcode/627_Swap_Salary.sql: -------------------------------------------------------------------------------- 1 | 2017.07.23 2 | 3 | UPDATE salary SET sex = IF(sex = 'm', 'f', 'm') 4 | 5 | update salary set sex = CHAR(ASCII('f') ^ ASCII('m') ^ ASCII(sex)); 6 | 7 | UPDATE salary 8 | SET sex = (CASE WHEN sex = 'm' 9 | THEN 'f' 10 | ELSE 'm' 11 | END) -------------------------------------------------------------------------------- /leetcode/080_Remove_Duplicates_From_Sorted_Array_II.java: -------------------------------------------------------------------------------- 1 | // 10.16 2 | class Solution { 3 | public int removeDuplicates(int[] nums) { 4 | int i = 0; 5 | for (int n : nums) 6 | if (i < 2 || n > nums[i-2]) 7 | nums[i++] = n; 8 | return i; 9 | } 10 | } -------------------------------------------------------------------------------- /leetcode/561_Array_Partition_I.java: -------------------------------------------------------------------------------- 1 | // 10.10 math trick 2 | class Solution { 3 | public int arrayPairSum(int[] nums) { 4 | Arrays.sort(nums); 5 | int sum = 0; 6 | for (int i = 0; i < nums.length/2; i++) { 7 | sum += nums[i*2]; 8 | } 9 | return sum; 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/191_Number_of_1_Bits.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // you need to treat n as an unsigned value 3 | public int hammingWeight(int n) { 4 | int m = 0; 5 | while (n != 0){ 6 | if ((n & 1) == 1) m ++; 7 | n = n >>> 1; 8 | } 9 | return m; 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode_daily/001.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ```python 4 | class Solution: 5 | def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]': 6 | m = {} 7 | for i in range(len(nums)): 8 | if target - nums[i] in m: 9 | return [m[target - nums[i]], i] 10 | m[nums[i]] = i 11 | ``` -------------------------------------------------------------------------------- /leetcode/176_Second_Highest_Salary.sql: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/articles/second-highest-salary/ 2 | # Write your MySQL query statement below 3 | SELECT 4 | (SELECT DISTINCT 5 | Salary 6 | FROM 7 | Employee 8 | ORDER BY Salary DESC 9 | LIMIT 1 OFFSET 1) AS SecondHighestSalary 10 | ; -------------------------------------------------------------------------------- /leetcode_daily/973.md: -------------------------------------------------------------------------------- 1 | ```python 2 | class Solution: 3 | def kClosest(self, points, K): 4 | """ 5 | :type points: List[List[int]] 6 | :type K: int 7 | :rtype: List[List[int]] 8 | """ 9 | points = sorted(points, key=lambda x: x[0]**2+x[1]**2) 10 | return points[:K] 11 | ``` -------------------------------------------------------------------------------- /leetcode_daily/461.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ```python 4 | class Solution: 5 | def hammingDistance(self, x: 'int', y: 'int') -> 'int': 6 | diff = x ^ y 7 | count = 0 8 | while diff != 0: 9 | if diff % 2 == 1: 10 | count += 1 11 | diff = diff >> 1 12 | return count 13 | ``` -------------------------------------------------------------------------------- /leetcode/231_Power_of_Two.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPowerOfTwo(int n) { 3 | return n>0 && Integer.bitCount(n) == 1; 4 | } 5 | } 6 | 7 | // four different methods 8 | // https://leetcode.com/problems/power-of-two/discuss/ 9 | // Iterative 10 | // Recursive 11 | // Bit operation 12 | // Math derivation 13 | -------------------------------------------------------------------------------- /leetcode/596_Classes_More_5_Students.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT class 3 | from courses 4 | group by class 5 | having count(DISTINCT student) >= 5 6 | 7 | 8 | 9 | SELECT class 10 | FROM 11 | ( 12 | SELECT class, count(distinct student) AS cnt 13 | FROM 14 | courses 15 | GROUP BY class 16 | ) c 17 | WHERE cnt >= 5 -------------------------------------------------------------------------------- /leetcode/598_Range_Addition_II.java: -------------------------------------------------------------------------------- 1 | // 面积为operation中最小的两个边的乘积。 2 | public class Solution { 3 | public int maxCount(int m, int n, int[][] ops) { 4 | for (int i = 0; i < ops.length; i++) { 5 | m = Math.min(ops[i][0], m); 6 | n = Math.min(ops[i][1], n); 7 | } 8 | return m * n; 9 | } 10 | } -------------------------------------------------------------------------------- /leetcode/754_Reach_a_Number.java: -------------------------------------------------------------------------------- 1 | // 12.30 Math 2 | 3 | class Solution { 4 | public int reachNumber(int target) { 5 | if (target == 0) 6 | return 0; 7 | for (int i = 1;; i++) { 8 | if ( (i + 1)*i/2 - Math.abs(target) >= 0 && ((i + 1)*i/2 - target) % 2 == 0) 9 | return i; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /leetcode/190_Reverse_Bits.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // you need treat n as an unsigned value 3 | public int reverseBits(int n) { 4 | int out = 0; 5 | for (int i = 0; i < 32; i++) { 6 | out <<= 1; 7 | out += n & 1; // add to out 8 | n >>>= 1; // unsign shift 9 | } 10 | return out; 11 | } 12 | } -------------------------------------------------------------------------------- /leetcode/319_Bulb_Switcher.java: -------------------------------------------------------------------------------- 1 | // Divisors come in pairs, like i=12 has divisors 1 and 12, 2 and 6, and 3 and 4. Except when i is a square, like 36 has divisors 1 and 36, 2 and 18, 3 and 12, 4 and 9, and double divisor 6. So bulb i ends up on if and only if i is a square. 2 | 3 | class Solution { 4 | public int bulbSwitch(int n) { 5 | return (int) Math.sqrt(n); 6 | } 7 | } -------------------------------------------------------------------------------- /leetcode/371_Sum_of_Two_Integers.java: -------------------------------------------------------------------------------- 1 | // 2017.8.13 XingxingHuang 2 | public class Solution { 3 | public int getSum(int a, int b) { 4 | while (b != 0) { 5 | int c = (a & b); // 需要进位的位, 1 & 1 ---> 1 6 | a = a ^ b; // 0 ^ 1 ---> 1 1 ^ 0 ---> 1 7 | b = c << 1; // 更新进位 8 | } 9 | return a; 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /leetcode/009_Palindrome_number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPalindrome(int x) { 3 | if (x < 0 || (x!=0 && x%10==0)) { // tricky 4 | return false; 5 | } 6 | int n = 0; 7 | while (x > n) { 8 | n = n*10 + x % 10; 9 | x = x / 10; 10 | } 11 | return n == x || n / 10 == x; // tricky 12 | } 13 | } -------------------------------------------------------------------------------- /leetcode/096_Unique_Binary_Search_Trees_I.java: -------------------------------------------------------------------------------- 1 | // 2017.08.07 2 | public class Solution { 3 | public int numTrees(int n) { 4 | int [] G = new int[n+1]; 5 | G[0] = G[1] = 1; 6 | 7 | for(int i = 2; i <= n; ++i) { 8 | for(int j = 1; j <= i; ++j) { 9 | G[i] += G[j-1] * G[i-j]; 10 | } 11 | } 12 | 13 | return G[n]; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/195_Tenth_Line.sh: -------------------------------------------------------------------------------- 1 | # Solution 1 2 | cnt=0 3 | while read line && [ $cnt -le 10 ]; do 4 | let 'cnt = cnt + 1' 5 | if [ $cnt -eq 10 ]; then 6 | echo $line 7 | exit 0 8 | fi 9 | done < file.txt 10 | 11 | # Solution 2 12 | awk 'FNR == 10 {print }' file.txt 13 | # OR 14 | awk 'NR == 10' file.txt 15 | 16 | # Solution 3 17 | sed -n 10p file.txt 18 | 19 | # Solution 4 20 | tail -n+10 file.txt|head -1 -------------------------------------------------------------------------------- /leetcode_daily/121.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ```python 4 | class Solution(object): 5 | def maxProfit(self, prices): 6 | """ 7 | :type prices: List[int] 8 | :rtype: int 9 | """ 10 | minval = float("inf") 11 | res = 0 12 | for price in prices: 13 | minval = min(price, minval) 14 | res = max(res, price - minval) 15 | return res 16 | 17 | ``` -------------------------------------------------------------------------------- /leetcode/181_Employees_Earning_More.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | 3 | SELECT 4 | a.NAME AS Employee 5 | FROM Employee AS a JOIN Employee AS b 6 | ON a.ManagerId = b.Id 7 | AND a.Salary > b.Salary 8 | ; 9 | 10 | # less efficient 11 | SELECT 12 | a.Name AS 'Employee' 13 | FROM 14 | Employee AS a, 15 | Employee AS b 16 | WHERE 17 | a.ManagerId = b.Id 18 | AND a.Salary > b.Salary 19 | ; -------------------------------------------------------------------------------- /leetcode_daily/976.md: -------------------------------------------------------------------------------- 1 | This one is trick and you need know how to make the loop 2 | 3 | ``` python 4 | class Solution: 5 | def largestPerimeter(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: int 9 | """ 10 | A.sort() 11 | for i in range(len(A) - 3, -1, -1): 12 | if A[i] + A[i+1] > A[i+2]: 13 | return A[i] + A[i+1] + A[i+2] 14 | return 0 15 | ``` -------------------------------------------------------------------------------- /leetcode/367_Valid_Perfect_Square.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPerfectSquare(int num) { 3 | int low = 1; 4 | int high = num; 5 | while (low <= high) { 6 | long m = (low + high) >>> 1; 7 | if (m*m > num) high = (int) m - 1; 8 | if (m*m < num) low = (int) m + 1; 9 | if (m*m == num) return true; 10 | } 11 | return false; 12 | } 13 | } -------------------------------------------------------------------------------- /leetcode/007_Reverse_Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | int result = 0; 4 | 5 | while (x != 0) { 6 | int tail = x % 10; 7 | int newResult = result * 10 + tail; 8 | if ((newResult - tail) / 10 != result) 9 | return 0; 10 | result = newResult; 11 | x = x / 10; 12 | } 13 | 14 | return result; 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode_daily/974.md: -------------------------------------------------------------------------------- 1 | Interesting O(n) solution. Using prefix sum. The tricky is you know that you can count the total by permutation and combination methods. 2 | 3 | ```python 4 | class Solution(object): 5 | def subarraysDivByK(self, A, K): 6 | P = [0] 7 | for x in A: 8 | P.append((P[-1] + x) % K) 9 | 10 | count = collections.Counter(P) 11 | return int(sum(v*(v-1)/2 for v in count.values())) 12 | ``` -------------------------------------------------------------------------------- /leetcode_daily/485.md: -------------------------------------------------------------------------------- 1 | [485](https://leetcode.com/problems/max-consecutive-ones/) Max Consecutive Ones 2 | 3 | ```python 4 | class Solution: 5 | def findMaxConsecutiveOnes(self, nums: List[int]) -> int: 6 | cnt = 0 7 | res = 0 8 | for num in nums: 9 | if num == 1: 10 | cnt += 1 11 | res = max(res, cnt) 12 | else: 13 | cnt = 0 14 | return res 15 | ``` -------------------------------------------------------------------------------- /leetcode/258_Add_Digits.java: -------------------------------------------------------------------------------- 1 | // https://en.wikipedia.org/wiki/Digital_root#Congruence_formula 2 | // 通过输入,来发现规律 3 | // 123456789 10 11 12 13 14 15 4 | // 123456789 1 2 3 4 5 6 5 | public class Solution { 6 | public int addDigits(int num) { 7 | if (num == 0) 8 | return 0; 9 | if (num % 9 == 0) 10 | return 9; 11 | return num % 9; 12 | } 13 | } 14 | 15 | // best solution: 16 | // return 1 + (num - 1) % 9; -------------------------------------------------------------------------------- /leetcode_daily/055.md: -------------------------------------------------------------------------------- 1 | [55](https://leetcode.com/problems/jump-game/) Jump Game 2 | 3 | Check [solutions](https://leetcode.com/problems/jump-game/solution/) for more methods. 4 | 5 | ```python 6 | class Solution: 7 | def canJump(self, nums: 'List[int]') -> 'bool': 8 | m = 0 9 | for i in range(len(nums)): 10 | if i > m: 11 | return False 12 | m = max(m, i + nums[i]) 13 | return True 14 | ``` -------------------------------------------------------------------------------- /leetcode_daily/013.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ```python 4 | class Solution: 5 | def romanToInt(self, s: 'str') -> 'int': 6 | nums = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}; 7 | resault = 0 8 | for i in range(len(s)): 9 | if i > 0 and nums[s[i]] > nums[s[i-1]]: 10 | resault += nums[s[i]] - 2 * nums[s[i-1]] 11 | else: 12 | resault += nums[s[i]] 13 | return resault 14 | 15 | ``` -------------------------------------------------------------------------------- /leetcode_daily/213.md: -------------------------------------------------------------------------------- 1 | 2 | shortest solution 3 | 4 | ```python 5 | class Solution: 6 | def rob(self, nums: 'List[int]') -> 'int': 7 | if not nums: return 0 8 | if len(nums) == 1: 9 | return nums[0] 10 | dp1 = nums[:-1] 11 | dp2 = nums[1:] 12 | for i in range(2, len(nums)-1): 13 | dp1[i] += max(dp1[:i-1]) 14 | dp2[i] += max(dp2[:i-1]) 15 | 16 | return max(dp1 + dp2) 17 | ``` -------------------------------------------------------------------------------- /leetcode_daily/647.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ```python 4 | class Solution: 5 | def countSubstrings(self, s: 'str') -> 'int': 6 | n = len(s) 7 | ans = 0 8 | for center in range(2*n - 1): 9 | left = center // 2 10 | right = left + center % 2 11 | while left >= 0 and right < n and s[left] == s[right]: 12 | ans += 1 13 | left -= 1 14 | right += 1 15 | return ans 16 | ``` -------------------------------------------------------------------------------- /leetcode_daily/1009.md: -------------------------------------------------------------------------------- 1 | [1009](https://leetcode.com/contest/weekly-contest-128/problems/complement-of-base-10-integer/) 2 | 3 | ```python 4 | class Solution: 5 | def bitwiseComplement(self, N: int) -> int: 6 | if N == 0: 7 | return 1 8 | res = 0 9 | count = 0 10 | while N != 0: 11 | if N % 2 == 0: 12 | res += 2**count 13 | count += 1 14 | N = N >> 1 15 | return res 16 | ``` -------------------------------------------------------------------------------- /leetcode/693_Binary_Number_with_Alternating_Bits.java: -------------------------------------------------------------------------------- 1 | // 10.07 2 | class Solution { 3 | public boolean hasAlternatingBits(int n) { 4 | boolean isOne = (n & 1) == 1; 5 | while (n != 0) { 6 | n = n >> 1; 7 | if ((n & 1) == 1 && isOne) 8 | return false; 9 | else if ((n & 1) == 0 && !isOne) 10 | return false; 11 | isOne = !isOne; 12 | } 13 | return !isOne; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/338_Counting_Bits.java: -------------------------------------------------------------------------------- 1 | /** 2 | * DP, 注意位运算符的优先级很低 3 | * @author Xingxing Huang 4 | * @since 2017.04.26 5 | * @Time O(n*size(num)), O(n); 6 | * @param 7 | * @return 8 | */ 9 | public class Solution { 10 | public int[] countBits(int num) { 11 | int[] res = new int[num + 1]; 12 | res[0] = 0; 13 | for (int i = 1; i <= num; i++) { 14 | res[i] = res[i >> 1] + (i & 1); 15 | } 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/183_Customers_Who_Never_Order.sql: -------------------------------------------------------------------------------- 1 | -- SELECT A.Name from Customers A 2 | -- WHERE NOT EXISTS (SELECT 1 FROM Orders B WHERE A.Id = B.CustomerId) 3 | 4 | -- SELECT A.Name from Customers A 5 | -- LEFT JOIN Orders B on a.Id = B.CustomerId 6 | -- WHERE b.CustomerId is NULL 7 | 8 | -- SELECT A.Name from Customers A 9 | -- WHERE A.Id NOT IN (SELECT B.CustomerId from Orders B) 10 | 11 | 12 | select Name as Customers 13 | from Customers 14 | where Id not in 15 | (select CustomerId as Id from Orders); -------------------------------------------------------------------------------- /leetcode/011_Container_With_Most_Water.java: -------------------------------------------------------------------------------- 1 | // 09.15 2 | // two pointer 3 | class Solution { 4 | public int maxArea(int[] height) { 5 | int l = 0; 6 | int r = height.length - 1; 7 | int area = 0; 8 | while (l < r) { 9 | area = Math.max(area, Math.min(height[l], height[r]) * (r - l)); 10 | if (height[l] < height[r]) 11 | l++; 12 | else 13 | r--; 14 | } 15 | return area; 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/217_Contains_Duplicate.java: -------------------------------------------------------------------------------- 1 | // three method 2 | // O(n2) with O(1) 3 | // O(nlogn) with O(1) 4 | // O(n) with O(n) 5 | class Solution { 6 | public boolean containsDuplicate(int[] nums) { 7 | 8 | final Set distinct = new HashSet(); 9 | for(int num : nums) { 10 | if(distinct.contains(num)) { 11 | return true; 12 | } 13 | distinct.add(num); 14 | } 15 | return false; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /leetcode/387_First_Unique_Character.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int firstUniqChar(String s) { 3 | if (s == null || s.equals("")) return -1; 4 | char[] c = s.toCharArray(); 5 | int[] cnt = new int[256]; 6 | 7 | for (int i = 0; i < c.length; i++) { 8 | cnt[c[i]]++; 9 | } 10 | 11 | for (int i = 0; i < c.length; i++) { 12 | if (cnt[c[i]] == 1) return i; 13 | } 14 | return -1; 15 | } 16 | } -------------------------------------------------------------------------------- /lintcode/lintcode_366_fibonacci.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /** 3 | * @param n: an integer 4 | * @return an integer f(n) 5 | */ 6 | public int fibonacci(int n) { 7 | // write your code here 8 | int cur = 0; 9 | int next = 1; 10 | int i = 1; 11 | while (i < n) { 12 | int temp = cur + next; 13 | cur = next; 14 | next = temp; 15 | i++; 16 | } 17 | return cur; 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /leetcode/172_count_zero.java: -------------------------------------------------------------------------------- 1 | // @Author: 黄xing 2 | // 求尾部为0的个数, 等价于乘积中包含5的个数。因为2的个数永远比5多 3 | // 查看阶乘的数列: 1, 2, 3,4, 5, 6, 7, 8, 9, 10 .... 4 | // 可以观察到每隔5个数字就包含一个5的倍数。因此至少有n / 5的0。 5 | // 但这时候我们继续观察,还有25,50,75... 这种情况,他们除以5之后还剩,5,10,25... 6 | // 他们公约数包含更多的5,解决这个问题,我用一个循环即可。 7 | public class Solution { 8 | public int trailingZeroes(int n) { 9 | int res = 0; 10 | while (n >= 5) { 11 | res += n / 5; 12 | n = n / 5; 13 | } 14 | return res; 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode/557_Reverse_Words_in_String_III.py: -------------------------------------------------------------------------------- 1 | /** 2 | * @Athor: Xingxing Huang 3 | * @Date: 2017.04.13 4 | * @Time: 学习python用法 5 | */ 6 | 7 | class Solution(object): 8 | def reverseWords(self, s): 9 | """ 10 | :type s: str 11 | :rtype: str 12 | """ 13 | return " ".join([c[::-1] for c in s.split()]) 14 | 15 | 16 | 17 | # @param {String} s 18 | # @return {String} 19 | def reverse_words(s) 20 | s.split.map(&:reverse).join(' ') 21 | end -------------------------------------------------------------------------------- /template/template_TwoPointer.java: -------------------------------------------------------------------------------- 1 | // 对撞型指针优化算法 2 | if (考虑A[i]和A[j]满足某个条件) 3 | j--; 4 | do something; 5 | else if (考虑A[i]和A[j]不满足某个条件) 6 | i++; 7 | do something; 8 | else 9 | do something; 10 | i++ or j--; 11 | 12 | 13 | // 窗口类指针移动模板 14 | // 通过两层for循环的改进算法,不同于sliding window 15 | for (i = 0; i < n; i++) { 16 | while (j < n) { 17 | if (满足条件) 18 | j++; 19 | 更新j状态; 20 | else (不满足条件) 21 | break; 22 | } 23 | 更新状态; 24 | } -------------------------------------------------------------------------------- /leetcode/201.md: -------------------------------------------------------------------------------- 1 | 从暴力解法开始思考。后来发现最后一个bit的AND结果取决于第二个数比第一数大多少幅度。因此可以通过移动两个数字来得到跨度。 2 | 3 | ```java 4 | // move the two number to the right until they equal. 5 | // all the right bits should be different, the result of AND is 0. 6 | public class Solution { 7 | public int rangeBitwiseAnd(int m, int n) { 8 | int count = 1; 9 | while (m != n) { 10 | m = m >> 1; 11 | n = n >> 1; 12 | count = count << 1; 13 | } 14 | return m * count; 15 | } 16 | } 17 | ``` -------------------------------------------------------------------------------- /leetcode_daily/263.md: -------------------------------------------------------------------------------- 1 | [263](https://leetcode.com/problems/ugly-number/) Ugly Number I 2 | 3 | easy 4 | 5 | ```python 6 | class Solution(object): 7 | def isUgly(self, num): 8 | """ 9 | :type num: int 10 | :rtype: bool 11 | """ 12 | if num == 0: 13 | return False 14 | while num & 1 == 0: 15 | num >>= 1 16 | while num % 3 == 0: 17 | num //= 3 18 | while num % 5 == 0: 19 | num //= 5 20 | return num == 1 21 | ``` -------------------------------------------------------------------------------- /leetcode/062_Unique_Paths_I.java: -------------------------------------------------------------------------------- 1 | // 2017.08.07 2 | public class Solution { 3 | public int uniquePaths(int m, int n) { 4 | int[][] dp = new int[m][n]; 5 | for (int i = 0; i < m; i++) 6 | dp[i][0] = 1; 7 | for (int i = 1; i < n; i++) 8 | dp[0][i] = 1; 9 | for (int i = 1; i < m; i++) { 10 | for (int j = 1; j < n; j++) { 11 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 12 | } 13 | } 14 | return dp[m - 1][n - 1]; 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode_daily/045.md: -------------------------------------------------------------------------------- 1 | [45](https://leetcode.com/problems/jump-game-ii/) Jump Game II 2 | 3 | memorize the maximum reach position, and current count. Use one pass method which is O(N). 4 | 5 | ```python 6 | class Solution: 7 | def jump(self, nums: 'List[int]') -> 'int': 8 | m = 0 9 | end = 0 10 | count = 0 11 | for i in range(len(nums)): 12 | if i > end: 13 | count += 1 14 | end = m 15 | m = max(m, i + nums[i]) 16 | return count 17 | ``` -------------------------------------------------------------------------------- /lintcode/082_Single_Number.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/single-number/ 2 | // 数学技巧 3 | public class Solution { 4 | /** 5 | *@param A : an integer array 6 | *return : a integer 7 | */ 8 | public int singleNumber(int[] A) { 9 | // Write your code here 10 | if (A == null || A.length == 0) { 11 | return 0; 12 | } 13 | int n = A[0]; 14 | for (int i = 1; i < A.length; i++) { 15 | n = n ^ A[i]; 16 | } 17 | return n; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/120_Triangle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minimumTotal(List> triangle) { 3 | if (triangle == null) { 4 | return Integer.MAX_VALUE; 5 | } 6 | int n = triangle.size(); 7 | int[] res = new int[n + 1]; 8 | for (int i = n - 1; i >= 0; i--) { 9 | for (int j = 0; j < triangle.get(i).size(); j++) { 10 | res[j] = Math.min(res[j], res[j + 1]) + triangle.get(i).get(j); 11 | } 12 | } 13 | return res[0]; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/263_Ugly_Number.java: -------------------------------------------------------------------------------- 1 | // @Author 黄Xing 2 | public class Solution { 3 | public boolean isUgly(int num) { 4 | if (num == 0) { 5 | return false; 6 | } 7 | while (num % 2 == 0) { 8 | num >>= 1; 9 | } 10 | while (num % 3 == 0) { 11 | num /= 3; 12 | } 13 | while (num % 5 == 0) { 14 | num /= 5; 15 | } 16 | if (num == 1) { 17 | return true; 18 | } else { 19 | return false; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /leetcode/405_Convert_a_Number_to_Hexadecimal.java: -------------------------------------------------------------------------------- 1 | // attention that the number is stored with binary format, so just deal with 4 bit each time 2 | public class Solution { 3 | 4 | char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 5 | 6 | public String toHex(int num) { 7 | if(num == 0) return "0"; 8 | String result = ""; 9 | while(num != 0){ 10 | result = map[(num & 15)] + result; 11 | num = (num >>> 4); 12 | } 13 | return result; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode_daily/007.md: -------------------------------------------------------------------------------- 1 | ```python 2 | class Solution: 3 | def reverse(self, x): 4 | """ 5 | :type x: int 6 | :rtype: int 7 | """ 8 | n = abs(x) 9 | 10 | reverseint = 0 11 | while n > 0: 12 | reverseint = reverseint * 10 + n % 10 13 | n = n // 10 14 | if x < 0: 15 | reverseint = -reverseint 16 | if reverseint < -(1 << 31) or reverseint > (1 << 31) - 1: 17 | return 0 18 | return reverseint 19 | 20 | 21 | ``` -------------------------------------------------------------------------------- /leetcode_daily/1025.md: -------------------------------------------------------------------------------- 1 | [1025](https://leetcode.com/problems/divisor-game/) Divisor Game 2 | 3 | ```python 4 | class Solution: 5 | def divisorGame(self, N: int) -> bool: 6 | dp = [0 for _ in range(N + 1)] 7 | dp[0] = 1 8 | for i in range(2, N + 1): 9 | flag = 0 10 | for ans in range(1, i): 11 | if i % ans == 0 and dp[i - ans] == 0: 12 | flag = 1 13 | break 14 | dp[i] = flag 15 | return dp[N] == 1 16 | 17 | ``` -------------------------------------------------------------------------------- /leetcode_daily/518.md: -------------------------------------------------------------------------------- 1 | [518](https://leetcode.com/problems/coin-change-2/) Coin Change 2 2 | 3 | DP method. 4 | Think about why we need to loop for the coins firstly and then loop for the amount. 5 | 6 | ```python 7 | class Solution: 8 | def change(self, amount: int, coins: List[int]) -> int: 9 | dp = [0 for i in range(amount + 1)] 10 | dp[0] = 1 11 | for coin in coins: 12 | for m in range(1, amount + 1): 13 | if m >= coin: 14 | dp[m] += dp[m - coin] 15 | return dp[amount] 16 | ``` -------------------------------------------------------------------------------- /lintcode/lintcode_394_Coins_in_a_Line_I.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/coins-in-a-line/ 2 | public class Solution { 3 | /** 4 | * @param n: an integer 5 | * @return: a boolean which equals to true if the first player will win 6 | */ 7 | public boolean firstWillWin(int n) { 8 | // write your code here 9 | n = n % 3; 10 | if (n == 0) { 11 | return false; 12 | } 13 | return true; 14 | } 15 | } 16 | 17 | // 九章的不同算法解析 18 | // http://www.jiuzhang.com/solution/coins-in-a-line/ -------------------------------------------------------------------------------- /leetcode_daily/315.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ```python 4 | class Solution: 5 | def countSmaller(self, nums: 'List[int]') -> 'List[int]': 6 | res = [] 7 | ans = [] 8 | for i in range(len(nums)-1, -1, -1): 9 | l, r = 0, len(ans) 10 | while l < r: 11 | m = l + (r - l) // 2 12 | if ans[m] >= nums[i]: 13 | r = m 14 | else: 15 | l = m + 1 16 | res.append(r) 17 | ans.insert(r, nums[i]) 18 | return res[::-1] 19 | ``` -------------------------------------------------------------------------------- /leetcode/674_Longest_Continuous_Increasing_Subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findLengthOfLCIS(int[] nums) { 3 | if (nums == null || nums.length < 1) { 4 | return 0; 5 | } 6 | int max = 1; 7 | int count = 1; 8 | for (int i = 1; i < nums.length; i++) { 9 | if (nums[i] > nums[i - 1]) { 10 | count++; 11 | max = Math.max(count, max); 12 | } else { 13 | count = 1; 14 | } 15 | } 16 | return max; 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/260_Single_Number_III.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] singleNumber(int[] nums) { 3 | int diff = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | diff ^= nums[i]; 6 | } 7 | int[] res = new int[]{0, 0}; 8 | // Get its last set bit 9 | diff &= -diff; 10 | for (int i = 0; i < nums.length; i++) { 11 | if ((nums[i] & diff) == 0) 12 | res[0] ^= nums[i]; 13 | else 14 | res[1] ^= nums[i]; 15 | } 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/017_Letter_Combinations_of_a_Phone_Number.py: -------------------------------------------------------------------------------- 1 | # lambda 2 | # reduce 3 | class Solution: 4 | # @return a list of strings, [s1, s2] 5 | def letterCombinations(self, digits): 6 | if '' == digits: return [] 7 | kvmaps = { 8 | '2': 'abc', 9 | '3': 'def', 10 | '4': 'ghi', 11 | '5': 'jkl', 12 | '6': 'mno', 13 | '7': 'pqrs', 14 | '8': 'tuv', 15 | '9': 'wxyz' 16 | } 17 | return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, ['']) -------------------------------------------------------------------------------- /leetcode_daily/022.md: -------------------------------------------------------------------------------- 1 | [22](https://leetcode.com/problems/generate-parentheses/) Generate Parentheses 2 | 3 | ```python 4 | class Solution: 5 | def generateParenthesis(self, n: 'int') -> 'List[str]': 6 | res = [] 7 | def generate(cur, left, right): 8 | if left == 0 and right == 0: 9 | res.append(cur) 10 | if left > 0: 11 | generate(cur+"(", left-1, right) 12 | if right > 0 and left < right: 13 | generate(cur+")", left, right-1) 14 | generate("", n, n) 15 | return res 16 | ``` -------------------------------------------------------------------------------- /leetcode_daily/487.md: -------------------------------------------------------------------------------- 1 | [487](https://leetcode.com/problems/max-consecutive-ones-ii/) Max Consecutive Ones II 2 | 3 | ```python 4 | class Solution: 5 | def findMaxConsecutiveOnes(self, nums: List[int]) -> int: 6 | maxConsecutive = 0 7 | zeroLeft = 0 8 | zeroRight = 0 9 | for i in range(len(nums)): 10 | zeroRight += 1 11 | if nums[i] == 0: 12 | zeroLeft = zeroRight 13 | zeroRight = 0 14 | maxConsecutive = max(maxConsecutive, zeroLeft+zeroRight) 15 | return maxConsecutive 16 | 17 | ``` -------------------------------------------------------------------------------- /leetcode/342_Power_of_Four.java: -------------------------------------------------------------------------------- 1 | // 2017.09.07 2 | 3 | // The basic idea is from power of 2, We can use "n&(n-1) == 0" to determine if n is power of 2. For power of 4, the additional restriction is that in binary form, the only "1" should always located at the odd position. For example, 4^0 = 1, 4^1 = 100, 4^2 = 10000. 4 | // So we can use "num & 0x55555555==num" to check if "1" is located at the odd position. 5 | 6 | public class Solution { 7 | public boolean isPowerOfFour(int num) { 8 | return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num); 9 | } 10 | } -------------------------------------------------------------------------------- /leetcode/152_Maximum_Product_Subarray.java: -------------------------------------------------------------------------------- 1 | // 12.21 注意正负号 和 0 2 | class Solution { 3 | public int maxProduct(int[] nums) { 4 | int res = nums[0]; 5 | for (int i = 1, imax = res, imin = res; i < nums.length; i++) { 6 | if (nums[i] < 0) { 7 | int temp = imin; 8 | imin = imax; 9 | imax = temp; 10 | } 11 | imax = Math.max(nums[i]*imax, nums[i]); 12 | imin = Math.min(nums[i]*imin, nums[i]); 13 | res = Math.max(res, imax); 14 | } 15 | return res; 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode_daily/470.md: -------------------------------------------------------------------------------- 1 | [470](https://leetcode.com/problems/implement-rand10-using-rand7/) 2 | 3 | There are interesting solutions in the discussion. 4 | 5 | 6 | ```python 7 | # The rand7() API is already defined for you. 8 | # def rand7(): 9 | # @return a random integer in the range 1 to 7 10 | 11 | class Solution: 12 | def rand10(self): 13 | """ 14 | :rtype: int 15 | """ 16 | n1 = rand7() - 1 17 | n2 = rand7() - 1 18 | while n1*7+n2 >= 40: 19 | n1 = rand7() - 1 20 | n2 = rand7() - 1 21 | return (n1*7 + n2)%10 + 1 22 | ``` -------------------------------------------------------------------------------- /leetcode/744_Find_Smallest_Letter_Greater_Than_Target.java: -------------------------------------------------------------------------------- 1 | // 12.09 contest 62 2 | // easy 题目二分法练习 3 | class Solution { 4 | public char nextGreatestLetter(char[] letters, char target) { 5 | int l = 0; 6 | int r = letters.length; 7 | while (l < r) { 8 | int m = l + (r - l) / 2; 9 | if (letters[m] - target <= 0) { 10 | l = m + 1; 11 | } else { 12 | r = m; 13 | } 14 | if (l == letters.length) 15 | return letters[0]; 16 | } 17 | return letters[l]; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/051_hard_N-Queens.py: -------------------------------------------------------------------------------- 1 | # https://discuss.leetcode.com/topic/20217/fast-short-and-easy-to-understand-python-solution-11-lines-76ms 2 | def solveNQueens(self, n): 3 | def DFS(queens, xy_dif, xy_sum): 4 | p = len(queens) 5 | if p==n: 6 | result.append(queens) 7 | return None 8 | for q in range(n): 9 | if q not in queens and p-q not in xy_dif and p+q not in xy_sum: 10 | DFS(queens+[q], xy_dif+[p-q], xy_sum+[p+q]) 11 | result = [] 12 | DFS([],[],[]) 13 | return [ ["."*i + "Q" + "."*(n-i-1) for i in sol] for sol in result] -------------------------------------------------------------------------------- /leetcode/409_Longest_Palindrome.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestPalindrome(String s) { 3 | if (s == null || s.length() == 0) 4 | return 0; 5 | Set set = new HashSet<>(); 6 | int count = 0; 7 | for (char c : s.toCharArray()) { 8 | if (set.contains(c)) { 9 | count++; 10 | set.remove(c); 11 | } else { 12 | set.add(c); 13 | } 14 | } 15 | if (!set.isEmpty()) 16 | return 2 * count + 1; 17 | return 2 * count; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/645_Set_Mismatch.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] findErrorNums(int[] nums) { 3 | int[] res = new int[2]; 4 | int n = nums.length; 5 | int[] ans = new int[n + 1]; 6 | for (int i = 0; i < n; i++) { 7 | if (ans[nums[i]] == 1) { 8 | res[0] = nums[i]; 9 | } else { 10 | ans[nums[i]] = 1; 11 | } 12 | } 13 | for (int i = 1; i <= n; i++) { 14 | if (ans[i] == 0) { 15 | res[1] = i; 16 | } 17 | } 18 | return res; 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode_daily/279.md: -------------------------------------------------------------------------------- 1 | Interesting DP 2 | 3 | ```python 4 | # DP problem, if you know the best solution for 1 ~ n-1, then you can find the best solution for n is the min(1 + dp[n-1], 4 + dp[n-4], ...) 5 | class Solution: 6 | def numSquares(self, n): 7 | """ 8 | :type n: int 9 | :rtype: int 10 | """ 11 | dp = [i for i in range(n + 1)] 12 | for i in range(1, n + 1): 13 | m = 1 14 | while m*m <= i: 15 | dp[i] = min(dp[i], dp[i - m*m] + 1) 16 | m += 1 17 | return dp[n] 18 | 19 | 20 | 21 | ``` -------------------------------------------------------------------------------- /leetcode_daily/388.md: -------------------------------------------------------------------------------- 1 | [388](https://leetcode.com/problems/longest-absolute-file-path/) Longest Absolute File Path 2 | 3 | 4 | 5 | ```python 6 | class Solution: 7 | def lengthLongestPath(self, input: str) -> int: 8 | res = 0 9 | pathlen = {0: 0} 10 | for line in input.splitlines(): 11 | name = line.lstrip("\t") 12 | depth = len(line) - len(name) 13 | if "." in name: 14 | res = max(res, pathlen[depth] + len(name)) 15 | else: 16 | pathlen[depth+1] = pathlen[depth] + len(name) + 1 17 | return res 18 | ``` -------------------------------------------------------------------------------- /leetcode/100_Same_tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isSameTree(TreeNode p, TreeNode q) { 12 | if (p == null && q == null) return true; 13 | if (p == null || q == null) return false; 14 | if (p.val == q.val) { 15 | if (isSameTree(p.left, q.left) && isSameTree(p.right, q.right)) return true; 16 | } 17 | return false; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/020_Valid_Parentheses.java: -------------------------------------------------------------------------------- 1 | // 09.15 2 | // attention: "([)]" is false; 3 | class Solution { 4 | public boolean isValid(String s) { 5 | Stack stack = new Stack(); 6 | for (char c : s.toCharArray()) { 7 | if (c == '(') 8 | stack.push(')'); 9 | else if (c == '{') 10 | stack.push('}'); 11 | else if (c == '[') 12 | stack.push(']'); 13 | else if (stack.isEmpty() || stack.pop() != c) 14 | return false; 15 | } 16 | return stack.isEmpty(); 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode_daily/946.md: -------------------------------------------------------------------------------- 1 | [946](https://leetcode.com/problems/validate-stack-sequences/) Validate Stack Sequences. 2 | 3 | Use stack. 4 | 5 | ```python 6 | class Solution: 7 | def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: 8 | count = 0 9 | stack = [] 10 | for n in pushed: 11 | stack.append(n) 12 | # there is one value in stack equal to popped list. 13 | while stack and count < len(popped) and stack[-1] == popped[count]: 14 | stack.pop() 15 | count += 1 16 | return count == len(popped) 17 | ``` -------------------------------------------------------------------------------- /leetcode/089_Gray_Code.java: -------------------------------------------------------------------------------- 1 | // 12.12 2 | // The idea is simple. G(i) = i^ (i/2). 3 | class Solution { 4 | public List grayCode(int n) { 5 | List result = new LinkedList<>(); 6 | for (int i = 0; i < 1<> 1); 8 | return result; 9 | } 10 | } 11 | 12 | 13 | public List grayCode(int n) { 14 | List rs=new ArrayList(); 15 | rs.add(0); 16 | for(int i=0;i=0;k--) 19 | rs.add(rs.get(k) | 1< map = new HashMap<>(); 6 | Stack stack = new Stack<>(); 7 | for (int num: nums2) { 8 | while (!stack.isEmpty() && stack.peek() < num) 9 | map.put(stack.pop(), num); 10 | stack.push(num); 11 | } 12 | for (int i = 0; i < nums1.length; i++) { 13 | nums1[i] = map.getOrDefault(nums1[i], -1); 14 | } 15 | return nums1; 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/058_Length_of_Last_Word.java: -------------------------------------------------------------------------------- 1 | // 09.20 2 | class Solution { 3 | public int lengthOfLastWord(String s) { 4 | int len = 0; 5 | int pre = 0; 6 | for (int i = 0; i < s.length(); i++) { 7 | if (s.charAt(i) != ' ') { 8 | len++; 9 | pre = len; 10 | } else { 11 | pre = Math.max(pre, len); 12 | len = 0; 13 | } 14 | } 15 | return pre; 16 | } 17 | } 18 | 19 | // java single line 20 | // public int lengthOfLastWord(String s) { 21 | // return s.trim().length()-s.trim().lastIndexOf(" ")-1; 22 | // } -------------------------------------------------------------------------------- /leetcode/012_Integer_to_Romman.java: -------------------------------------------------------------------------------- 1 | // 2017.08.07 2 | // https://my.oschina.net/Tsybius2014/blog/487325 3 | public class Solution { 4 | public String intToRoman(int num) { 5 | int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; 6 | String[] strs = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 7 | 8 | StringBuilder sb = new StringBuilder(); 9 | 10 | for(int i = 0;i < values.length; i++) { 11 | while(num >= values[i]) { 12 | num -= values[i]; 13 | sb.append(strs[i]); 14 | } 15 | } 16 | return sb.toString(); 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/088_Merge_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void merge(int[] nums1, int m, int[] nums2, int n) { 3 | int i = m - 1; 4 | int j = n - 1; 5 | while (i >= 0 && j >= 0) { 6 | if (nums1[i] >= nums2[j]) { 7 | nums1[i + j + 1] = nums1[i]; 8 | i--; 9 | } else { 10 | nums1[i + j + 1] = nums2[j]; 11 | j--; 12 | } 13 | } 14 | // only need to consider the residual of num2 15 | while (j >= 0) { 16 | nums1[j] = nums2[j]; 17 | j--; 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode/495_Teemo_Attaching.java: -------------------------------------------------------------------------------- 1 | // 2017.07.31 2 | public class Solution { 3 | public int findPoisonedDuration(int[] timeSeries, int duration) { 4 | if (timeSeries.length == 0) 5 | return 0; 6 | int total = 0; 7 | int cur = timeSeries[0]; 8 | for (int i = 1; i < timeSeries.length; i++) { 9 | if (timeSeries[i] >= cur + duration) { 10 | total += duration; 11 | } else { 12 | total += timeSeries[i] - cur; 13 | } 14 | cur = timeSeries[i]; 15 | } 16 | total += duration; 17 | return total; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/532_K-diff_Pairs_in_a_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findPairs(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | if k == 0: 9 | return sum(v>1 for v in collections.Counter(nums).values()) 10 | elif k > 0: 11 | return len(set(nums)&set(n+k for n in nums)) 12 | else: 13 | return 0 14 | # nums_set = set(nums) 15 | # count = 0 16 | # for n in nums_set: 17 | # if n + k in nums_set: 18 | # count += 1 19 | # return count 20 | -------------------------------------------------------------------------------- /leetcode/344_Reverse_String.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Athor: Xingxing Huang 3 | * @Date: 2017.04.13 4 | * @Time: O(n), 请查看solution 的详细分析: 5 | * https://discuss.leetcode.com/topic/43296/java-simple-and-clean-with-explanations-6-solutions 6 | */ 7 | public class Solution { 8 | public String reverseString(String s) { 9 | char[] chs = s.toCharArray(); 10 | int i = 0; 11 | int j = chs.length - 1; 12 | while (i < j) { 13 | char ch = chs[i]; 14 | chs[i] = chs[j]; 15 | chs[j] = ch; 16 | i++; 17 | j--; 18 | } 19 | return String.valueOf(chs); 20 | } 21 | } -------------------------------------------------------------------------------- /leetcode/122_Best_Time_Buy_Sell_Stock_II.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Author: Xingxing Huang 3 | @Time: O(N) 4 | @Date: 2017/03/27 5 | @思路: 比较相邻的值,如果减小,那么这个profit我们肯定能够获得。 6 | 对于递减的序列,由于只能买卖一次,获得的最大收益就是头尾的价格差 7 | @相关链接: 股票系列题的分析 https://sophiesongge.github.io/leetcode/2017/02/15/buy-sell-stock.html 8 | */ 9 | public class Solution { 10 | public int maxProfit(int[] prices) { 11 | int profit = 0; 12 | for (int i = 1; i < prices.length; i++) { 13 | if (prices[i] - prices[i - 1] > 0) { 14 | profit += prices[i] - prices[i - 1]; 15 | } 16 | } 17 | return profit; 18 | } 19 | } -------------------------------------------------------------------------------- /template/partition.java: -------------------------------------------------------------------------------- 1 | // two pointer 2 | // quick sort 3 | public int partition(int[] nums, int l, int r) { 4 | // 初始双指针 和 pivot 5 | int left = l; 6 | int right = r; 7 | int pivot = nums[left]; 8 | while (left < right) { 9 | // 右边小与的移动到左边 10 | while (left < right && num[right] >= pivot) { 11 | right--; 12 | } 13 | nums[left] = nums[right]; 14 | // 左边小于的移动到右边 15 | while (left < right && nums[left] <= pivot) { 16 | left++; 17 | } 18 | nums[right] = nums[left]; 19 | } 20 | // 注意这一句!! pivot归位。 21 | nums[left] = pivot; 22 | return left 23 | } -------------------------------------------------------------------------------- /leetcode/532_K-diff_Pairs_in_a_Array.java: -------------------------------------------------------------------------------- 1 | // 注意考虑k = 0 的情况 2 | public class Solution { 3 | public int findPairs(int[] nums, int k) { 4 | Map map = new HashMap<>(); 5 | for (int n: nums) { 6 | map.put(n, map.getOrDefault(n, 0) + 1); 7 | } 8 | int count = 0; 9 | for (int key : map.keySet()) { 10 | if (k == 0) { 11 | if (map.get(key) > 1) 12 | count++; 13 | } else if (k > 0) { 14 | if (map.containsKey(key + k)) 15 | count++; 16 | } 17 | } 18 | return count; 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode/492_Construct_the_Rectangle.java: -------------------------------------------------------------------------------- 1 | // 2017.07.29 2 | public class Solution { 3 | public int[] constructRectangle(int area) { 4 | if (area == 0) 5 | return new int[] {0, 0}; 6 | for (int i = (int) Math.sqrt(area); i <= area; i++) { 7 | if (area % i == 0 && i >= area / i) 8 | return new int[]{i, area / i}; 9 | } 10 | return new int[]{1, area}; 11 | } 12 | } 13 | 14 | public class Solution { 15 | public int[] constructRectangle(int area) { 16 | int w = (int) Math.sqrt(area); 17 | while (area%w!=0) w--; 18 | return new int[]{area/w, w}; 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode/503_Next_Greater_Element.py: -------------------------------------------------------------------------------- 1 | # 超时,平方复杂度 2 | # @Author 黄xing 3 | class Solution(object): 4 | def nextGreaterElements(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: List[int] 8 | """ 9 | n = len(nums) 10 | out = []; 11 | for i in range(n): 12 | for j in range(n - 1): 13 | index = (i + j + 1) % n; 14 | if nums[index] > nums[i]: 15 | out.append(nums[index]) 16 | break 17 | if len(out) < i + 1: 18 | out.append(-1) 19 | return out 20 | 21 | -------------------------------------------------------------------------------- /leetcode/504_Base_7.java: -------------------------------------------------------------------------------- 1 | // 0929 2 | class Solution { 3 | public String convertToBase7(int num) { 4 | int sign = num >= 0 ? 1 : -1; 5 | num = Math.abs(num); 6 | int level = 1; 7 | int m = 0; 8 | while (num > 0) { 9 | m += level * (num % 7); 10 | level *= 10; 11 | num = num/7; 12 | } 13 | return sign == 1 ? ""+m : "-"+m; 14 | } 15 | } 16 | 17 | 18 | // recursive 19 | public String convertTo7(int num) { 20 | if (num < 0) 21 | return '-' + convertTo7(-num); 22 | if (num < 7) 23 | return num + ""; 24 | return convertTo7(num / 7) + num % 7; 25 | } -------------------------------------------------------------------------------- /leetcode_daily/322.md: -------------------------------------------------------------------------------- 1 | [322](https://leetcode.com/problems/coin-change/) Coin Change 2 | 3 | DP very standard question. Check the [solutions](https://leetcode.com/problems/coin-change/solution/) for well described top-down and bottom up methods. 4 | 5 | ```python 6 | class Solution: 7 | def coinChange(self, coins: List[int], amount: int) -> int: 8 | dp = [float("inf") for i in range(amount + 1)] 9 | dp[0] = 0 10 | for m in range(1, amount + 1): 11 | for c in coins: 12 | if m >= c: 13 | dp[m] = min(dp[m - c] + 1, dp[m]) 14 | return dp[amount] if dp[amount] != float("inf") else -1 15 | ``` -------------------------------------------------------------------------------- /leetcode/077_Combinations.java: -------------------------------------------------------------------------------- 1 | // 12.12 2 | // 经典backtrack 练手题 3 | class Solution { 4 | public List> combine(int n, int k) { 5 | List> res = new ArrayList<>(); 6 | search(res, n, 1, new ArrayList(), k); 7 | return res; 8 | } 9 | private void search(List> res, int n, int idx, List cur, int k) { 10 | if (cur.size() == k) 11 | res.add(new ArrayList(cur)); 12 | for (int i = idx; i <= n; i++) { 13 | cur.add(i); 14 | search(res, n, i + 1, cur, k); 15 | cur.remove(cur.size() - 1); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/617_Merge_Two_Binary_Trees.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | // 10.10 11 | // tree tranverse 12 | class Solution { 13 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 14 | if (t1 == null && t2 == null) return null; 15 | if (t1 == null) return t2; 16 | if (t2 == null) return t1; 17 | t1.val += t2.val; 18 | t1.left = mergeTrees(t1.left, t2.left); 19 | t1.right = mergeTrees(t1.right, t2.right); 20 | return t1; 21 | } 22 | } -------------------------------------------------------------------------------- /template/template_2sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Two sum 模板 3 | * 这一类通过对撞型指针优化算法,根本上其实要证明就是不用扫描多余状态 4 | * 算法复杂度下降到 O(n) 5 | * 相会型指针的题目: 6 | * 2 sum 7 | * 3 sum closest 8 | * 3 sum 9 | * 4 sum 10 | * Two sum II 11 | * Triangle Count 12 | * Trapping Rain Water 13 | * Container With Most Water 14 | */ 15 | 16 | int left = 0, right = nums.length - 1; 17 | while (left < right) { 18 | if (A[left] 和 A[right] 满足某一条件) { 19 | //做一些事情 20 | right--; // 不用考虑[left + 1, right - 1] 和 right组成的pair; 21 | } else if (A[left] 和 A[right] 不满足某一条件) { 22 | left++; // 不用考虑[left + 1, right - 1] 和 left 组成的pair 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /leetcode/290_Word_Pattern.java: -------------------------------------------------------------------------------- 1 | // @Author: Xingxing Huang 2 | // @Date: 2017/03/24 3 | public class Solution { 4 | public boolean wordPattern(String pattern, String str) { 5 | String[] words = str.split(" "); 6 | if (pattern.length() != words.length) { 7 | return false; 8 | } 9 | Map map = new HashMap(); 10 | for (int i = 0; i < words.length; i++) { 11 | // map.put will return 'value' if 'key' exists, else it will return null 12 | if (map.put(pattern.charAt(i), i) != map.put(words[i], i)) { 13 | return false; 14 | } 15 | } 16 | return true; 17 | } 18 | } -------------------------------------------------------------------------------- /template/2sumII.java: -------------------------------------------------------------------------------- 1 | // 本代码在旧的网站上才有. 2 | // Given an array of integers, find how many pairs in the array such that their sum is bigger than a specific target number. Please return the number of pairs. 3 | public class Solution { 4 | public int twoSum2(int[], nums, int target) { 5 | Arrays.sort(nums); 6 | int left = 0, right = nums.length - 1; 7 | int ans = 0; 8 | while (left < right) { 9 | if (nums[left] + nums[right] > target) { 10 | ans = ans + (right - left); 11 | right--; 12 | } else { 13 | left++; 14 | } 15 | } 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/049_Group_Anagrams.java: -------------------------------------------------------------------------------- 1 | // 黄xing 2 | // hash思想 3 | public class Solution { 4 | public List> groupAnagrams(String[] strs) { 5 | Map> map = new HashMap>(); 6 | for (String s: strs) { 7 | char[] ss = s.toCharArray(); 8 | Arrays.sort(ss); // Arrays.sort() 9 | String key = String.valueOf(ss); // String.valueOf(char array) 10 | if (!map.containsKey(key)) { 11 | map.put(key, new ArrayList()); 12 | } 13 | map.get(key).add(s); 14 | } 15 | return new ArrayList>(map.values()); 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/240_Search_2D_Matrix_II.java: -------------------------------------------------------------------------------- 1 | // @Author: Xingxing Huang 2 | // Time: O(m) + O(n) 3 | public class Solution { 4 | public boolean searchMatrix(int[][] matrix, int target) { 5 | if (matrix.length == 0 || matrix[0].length == 0) { 6 | return false; 7 | } 8 | int i = 0; 9 | int j = matrix[0].length - 1; 10 | while (i < matrix.length && j >= 0) { 11 | if (target < matrix[i][j]) { 12 | j--; 13 | } else if (target > matrix[i][j]) { 14 | i++; 15 | } else { 16 | return true; 17 | } 18 | } 19 | return false; 20 | } 21 | } -------------------------------------------------------------------------------- /lintcode/lintcode_413_Reverse_Integer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * http://www.lintcode.com/en/problem/reverse-integer/?favoriteListName=bit# 3 | * 注意考虑一下情况: 4 | * overflow,0, 5 | */ 6 | public class Solution { 7 | /** 8 | * @param n the integer to be reversed 9 | * @return the reversed integer 10 | */ 11 | public int reverseInteger(int n) { 12 | // Write your code here 13 | int res = 0; 14 | while (n != 0) { 15 | int tmp = res*10 + n % 10; 16 | n = n / 10; 17 | if (tmp/10 != res) { 18 | return 0; 19 | } 20 | res = tmp; 21 | } 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/696_Count_Binary_Substrings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countBinarySubstrings(String s) { 3 | if (s == null || s.length() < 2) 4 | return 0; 5 | int count = 0; 6 | for (int i = 0; i < s.length() - 1; i++) { 7 | if (s.charAt(i) != s.charAt(i + 1)) { 8 | int l = i; 9 | int r = i + 1; 10 | while (l >= 0 && r < s.length() && s.charAt(i) == s.charAt(l) && s.charAt(i + 1) == s.charAt(r)) { 11 | count++; 12 | l--; 13 | r++; 14 | } 15 | } 16 | } 17 | return count; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode_daily/977.md: -------------------------------------------------------------------------------- 1 | too easy 2 | 3 | ```python 4 | class Solution: 5 | def sortedSquares(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: List[int] 9 | """ 10 | B = [i**2 for i in A] 11 | return sorted(B) 12 | ``` 13 | 14 | two pointer 15 | 16 | ```python 17 | class Solution(object): 18 | def maxTurbulenceSize(self, A): 19 | N = len(A) 20 | ans = 1 21 | anchor = 0 22 | 23 | for i in xrange(1, N): 24 | c = cmp(A[i-1], A[i]) 25 | if i == N-1 or c * cmp(A[i], A[i+1]) != -1: 26 | ans = max(ans, i - anchor + 1) 27 | anchor = i 28 | return ans 29 | ``` -------------------------------------------------------------------------------- /leetcode/141_Linked_List_Cycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean hasCycle(ListNode head) { 14 | if(head==null) return false; 15 | ListNode walker = head; 16 | ListNode runner = head; 17 | while(runner.next!=null && runner.next.next!=null) { 18 | walker = walker.next; 19 | runner = runner.next.next; 20 | if(walker==runner) return true; 21 | } 22 | return false; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/728_Self_Dividing_Number.java: -------------------------------------------------------------------------------- 1 | // 11.19 2 | // easy, brute force 3 | class Solution { 4 | public List selfDividingNumbers(int left, int right) { 5 | List res = new ArrayList<>(); 6 | for (int num = left; num <= right; num++) { 7 | boolean flag = true; 8 | int orig = num; 9 | while (orig > 0) { 10 | int n = orig % 10; 11 | if (n == 0 || num % n != 0) { 12 | flag = false; 13 | break; 14 | } 15 | orig = orig / 10; 16 | } 17 | if (flag) res.add(num); 18 | } 19 | return res; 20 | } 21 | } -------------------------------------------------------------------------------- /leetcode/026_Remove_Duplicates_from_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | // 09.15 2 | class Solution { 3 | public int removeDuplicates(int[] nums) { 4 | if (nums == null || nums.length == 0) 5 | return 0; 6 | int idx = 0; 7 | for (int i = 1; i < nums.length; i++) { 8 | if (nums[i] != nums[i - 1]) { 9 | nums[++idx] = nums[i]; 10 | } 11 | } 12 | return idx + 1; 13 | } 14 | } 15 | 16 | 17 | class Solution { 18 | public int removeDuplicates(int[] nums) { 19 | int i = 0; 20 | for (int n : nums) 21 | if (i == 0 || n > nums[i-1]) 22 | nums[i++] = n; 23 | return i; 24 | } 25 | } -------------------------------------------------------------------------------- /leetcode/071_Simplify_Path.py: -------------------------------------------------------------------------------- 1 | # 黄xing 2 | class Solution(object): 3 | def simplifyPath(self, path): 4 | """ 5 | :type path: str 6 | :rtype: str 7 | """ 8 | newArray = ["/"] 9 | for s in path.split('/'): 10 | if s == '.' or s == '': 11 | continue 12 | if s == '..': 13 | if len(newArray) == 1: 14 | continue 15 | else: 16 | newArray = newArray[:-1] 17 | continue 18 | newArray.append(s) 19 | #print newArray 20 | return '/'.join(newArray).replace('//','/') 21 | 22 | 23 | -------------------------------------------------------------------------------- /leetcode/235_Lowest_Common_Ancestor_BST.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 | while (root != null) { 13 | if (root.val > Math.max(p.val, q.val) ) { 14 | root = root.left; 15 | } else if (root.val < Math.min(p.val, q.val) ) { 16 | root = root.right; 17 | } else { 18 | return root; 19 | } 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /leetcode/581_Shortest_Unsorted_Continuous_Subarray.java: -------------------------------------------------------------------------------- 1 | // 10.10 2 | // check the solution for many methods 3 | public class Solution { 4 | public int findUnsortedSubarray(int[] nums) { 5 | int[] snums = nums.clone(); 6 | Arrays.sort(snums); 7 | int start = snums.length, end = 0; 8 | for (int i = 0; i < snums.length; i++) { 9 | if (snums[i] != nums[i]) { 10 | start = Math.min(start, i); 11 | end = Math.max(end, i); 12 | } 13 | } 14 | return (end - start >= 0 ? end - start + 1 : 0); 15 | } 16 | } 17 | 18 | // many methods 19 | // https://leetcode.com/problems/shortest-unsorted-continuous-subarray/solution/ -------------------------------------------------------------------------------- /leetcode/198_House_Robber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * DP问题,每次结果可以分解为 (i-2最优结果+i), 或者 (i - 1最优结果) 3 | * @athor Xingxing Huang 4 | * @since 2017.04.14 5 | * @Time O(n), 6 | * @param array 7 | * @return int, maximum money 8 | */ 9 | public class Solution { 10 | public int rob(int[] nums) { 11 | if (nums == null || nums.length == 0) { 12 | return 0; 13 | } 14 | if (nums.length == 1) { 15 | return nums[0]; 16 | } 17 | nums[1] = Math.max(nums[0], nums[1]); 18 | for (int i = 2; i < nums.length; i++) { 19 | nums[i] = Math.max(nums[i - 2] + nums[i], nums[i - 1]); 20 | } 21 | return nums[nums.length - 1]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/554_Brick_Wall.java: -------------------------------------------------------------------------------- 1 | // 2017.07.31 XingxingHuang 2 | // 用hashmap记录每个位置的空隙的个数,墙壁厚度减去最大空隙个数既得。 3 | public class Solution { 4 | public int leastBricks(List> wall) { 5 | if (wall.size() == 0) 6 | return 0; 7 | Map map = new HashMap<>(); 8 | int count = 0; 9 | for (List list : wall) { 10 | int len = 0; 11 | for (int i = 0; i < list.size() - 1; i++) { 12 | len += list.get(i); 13 | map.put(len, map.getOrDefault(len, 0) + 1); 14 | count = Math.max(count, map.get(len)); 15 | } 16 | } 17 | return wall.size() - count; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode_daily/999.md: -------------------------------------------------------------------------------- 1 | [999](https://leetcode.com/problems/available-captures-for-rook/) Available Captures for Rook 2 | 3 | 4 | ```python 5 | class Solution: 6 | def numRookCaptures(self, board: List[List[str]]) -> int: 7 | for i in range(8): 8 | for j in range(8): 9 | if board[i][j] == 'R': 10 | x0, y0 = i, j 11 | res = 0 12 | for i, j in [[1, 0], [0, 1], [-1, 0], [0, -1]]: 13 | x, y = x0 + i, y0 + j 14 | while 0 <= x < 8 and 0 <= y < 8: 15 | if board[x][y] == 'p': res += 1 16 | if board[x][y] != '.': break 17 | x, y = x + i, y + j 18 | return res 19 | 20 | ``` -------------------------------------------------------------------------------- /leetcode/125_Valid_Palindrome.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPalindrome(String s) { 3 | if (s == null || s.isEmpty == 0) {return true;} 4 | s = s.toLowerCase(); 5 | int i = 0; 6 | int j = s.length() - 1; 7 | while (i <= j) { 8 | if (!Character.isLetterOrDigit(s.charAt(i))) { 9 | i++; 10 | continue; 11 | } 12 | if (!Character.isLetterOrDigit(s.charAt(j))) { 13 | j--; 14 | continue; 15 | } 16 | if (s.charAt(i) != s.charAt(j)) {return false;} 17 | i++; 18 | j--; 19 | } 20 | return true; 21 | } 22 | } -------------------------------------------------------------------------------- /leetcode/633_Sum_of_Square_Numbers.java: -------------------------------------------------------------------------------- 1 | // 注意溢出的情况, 2 | // 记忆化的思想 3 | public class Solution { 4 | public boolean judgeSquareSum(int c) { 5 | if (c == 0 || c == 1) { 6 | return true; 7 | } 8 | Set set = new HashSet(); 9 | int max = (int) Math.sqrt(2000000000); 10 | for (int i = 0; i < c && i < max; i++) { 11 | if (i * i > c) 12 | break; 13 | set.add(i * i); 14 | } 15 | for (int i : set) { 16 | if (i > c) 17 | break; 18 | if (set.contains(c - i)) { 19 | return true; 20 | } 21 | } 22 | return false; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/657_Judge_Route_Circle.py: -------------------------------------------------------------------------------- 1 | # easy 2 | class Solution(object): 3 | def judgeCircle(self, moves): 4 | """ 5 | :type moves: str 6 | :rtype: bool 7 | """ 8 | if len(moves) == 0: 9 | return True 10 | i = 0 11 | j = 0 12 | for move in moves: 13 | if move == "R": i += 1 14 | if move == "L": i -= 1 15 | if move == "U": j += 1 16 | if move == "D": j -= 1 17 | if (i == 0 and j == 0): return True 18 | return False 19 | 20 | # collections counter 21 | def judgeCircle(self, moves): 22 | c = collections.Counter(moves) 23 | return c['L'] == c['R'] and c['U'] == c['D'] -------------------------------------------------------------------------------- /leetcode/118_Pascal_Triangle.java: -------------------------------------------------------------------------------- 1 | //2017.08.27 XingxingHuang 2 | // easy, two loop 3 | class Solution { 4 | public List> generate(int numRows) { 5 | List> res = new ArrayList<>(); 6 | if (numRows < 1) { 7 | return res; 8 | } 9 | res.add(new ArrayList(Arrays.asList(1))); 10 | for (int i = 1; i < numRows; i++) { 11 | res.add(new ArrayList()); 12 | res.get(i).add(1); 13 | for (int j = 0; j < res.get(i - 1).size() - 1; j++) 14 | res.get(i).add(res.get(i - 1).get(j) + res.get(i - 1).get(j + 1)); 15 | res.get(i).add(1); 16 | } 17 | return res; 18 | } 19 | } -------------------------------------------------------------------------------- /lintcode/083_Single_Number_II.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/single-number-ii/ 2 | // http://www.jiuzhang.com/solutions/single-number-ii/ 3 | 4 | public class Solution { 5 | public int singleNumber(int[] A) { 6 | if (A == null || A.length == 0) { 7 | return -1; 8 | } 9 | int result=0; 10 | int[] bits=new int[32]; 11 | for (int i = 0; i < 32; i++) { 12 | // 计算出结果数字上每一位的数字 13 | for(int j = 0; j < A.length; j++) { 14 | bits[i] += A[j] >> i & 1; 15 | bits[i] %= 3; 16 | } 17 | // 添加每一位的数字 18 | result |= (bits[i] << i); 19 | } 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /leetcode/412_Fizz_Buzz.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public List fizzBuzz(int n) { 4 | List ret = new ArrayList(n); 5 | for(int i=1,fizz=0,buzz=0;i<=n ;i++){ 6 | fizz++; 7 | buzz++; 8 | if(fizz==3 && buzz==5){ 9 | ret.add("FizzBuzz"); 10 | fizz=0; 11 | buzz=0; 12 | }else if(fizz==3){ 13 | ret.add("Fizz"); 14 | fizz=0; 15 | }else if(buzz==5){ 16 | ret.add("Buzz"); 17 | buzz=0; 18 | }else{ 19 | ret.add(String.valueOf(i)); 20 | } 21 | } 22 | return ret; 23 | } 24 | } -------------------------------------------------------------------------------- /lintcode/lintcode_211_stringPermutation.java: -------------------------------------------------------------------------------- 1 | // @Author: Xingxing Huang 2 | public class Solution { 3 | /** 4 | * @param A a string 5 | * @param B a string 6 | * @return a boolean 7 | */ 8 | public boolean stringPermutation(String A, String B) { 9 | // Write your code here 10 | int[] helper = new int[128]; 11 | for (char i : A.toCharArray()) { 12 | helper[i - ' ']++; 13 | } 14 | for (char i : B.toCharArray()) { 15 | helper[i - ' ']--; 16 | } 17 | for (int i = 0; i < helper.length; i++) { 18 | if (helper[i] != 0) { 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/371_Sum_of_Two_Integers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getSum(self, a, b): 3 | """ 4 | :type a: int 5 | :type b: int 6 | :rtype: int 7 | """ 8 | # 32 bits integer max 9 | MAX = 0x7FFFFFFF 10 | # 32 bits interger min 11 | MIN = 0x80000000 12 | # mask to get last 32 bits 13 | mask = 0xFFFFFFFF 14 | while b != 0: 15 | # ^ get different bits and & gets double 1s, << moves carry 16 | a, b = (a ^ b) & mask, ((a & b) << 1) & mask 17 | # if a is negative, get a's 32 bits complement positive first 18 | # then get 32-bit positive's Python complement negative 19 | return a if a <= MAX else ~(a ^ mask) -------------------------------------------------------------------------------- /lintcode/lintcode_140_quick_power.java: -------------------------------------------------------------------------------- 1 | // @Author: Xingxing Huang 2 | // 数论内容 3 | // a^b % c = (a^2)^(b/2) %c 4 | // a^b % c = (a^2)^(b/2)*a %c 5 | // 注意用long 变量,否则数字相乘会溢出 6 | class Solution { 7 | /* 8 | * @param a, b, n: 32bit integers 9 | * @return: An integer 10 | */ 11 | public int fastPower(int a, int b, int n) { 12 | // write your code here 13 | if (n == 0) { 14 | return 1 % b; 15 | } 16 | if (n == 1) { 17 | return a % b; 18 | } 19 | long temp = fastPower(a, b, n >> 1); 20 | temp = temp * temp % b; 21 | if ((n & 0x1) == 1) { 22 | temp = temp * (a % b) % b; 23 | } 24 | return (int) temp; 25 | } 26 | } -------------------------------------------------------------------------------- /lintcode/lintcode_517_Ugly_Number.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/ugly-number/ 2 | // 相关题目 518, 4 3 | public class Solution { 4 | /** 5 | * @param num an integer 6 | * @return true if num is an ugly number or false 7 | */ 8 | public boolean isUgly(int num) { 9 | // Write your code here 10 | if (num == 0) { 11 | return false; 12 | } 13 | if (num == 1) { 14 | return true; 15 | } 16 | while (num % 2 == 0) { 17 | num /= 2; 18 | } 19 | while (num % 3 == 0) { 20 | num /= 3; 21 | } 22 | while (num % 5 == 0) { 23 | num /= 5; 24 | } 25 | return num == 1; 26 | } 27 | } -------------------------------------------------------------------------------- /leetcode/221_Maximal_Square.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maximalSquare(char[][] matrix) { 3 | if (matrix.length == 0) {return 0;} 4 | int m = matrix.length; 5 | int n = matrix[0].length; 6 | int[][] dp = new int[m + 1][n + 1]; // attention 7 | int results = 0; 8 | for (int i = 1; i <= m; i++) { 9 | for (int j = 1; j <= n; j++) { 10 | if(matrix[i - 1][j - 1] == '1') { 11 | dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j - 1]), dp[i - 1][j]) + 1; // attention 12 | results = Math.max(results, dp[i][j]); 13 | } 14 | } 15 | } 16 | return results * results; 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode_daily/416.md: -------------------------------------------------------------------------------- 1 | [416](https://leetcode.com/problems/partition-equal-subset-sum/) Partition equal subset sum. 2 | 3 | 4 | There is a simple recusive method. But here the DP solution is still the best one. 5 | 6 | ```python 7 | class Solution: 8 | def canPartition(self, nums: List[int]) -> bool: 9 | if len(nums) < 2: 10 | return False 11 | SUM = sum(nums) 12 | if SUM % 2 != 0: 13 | return False 14 | dp = [False for i in range(SUM//2 + 1)] 15 | dp[0] = True 16 | for i in range(len(nums)): 17 | for j in range(SUM//2, nums[i] - 1, -1): 18 | dp[j] = dp[j] or dp[j - nums[i]] 19 | return dp[SUM//2] 20 | 21 | 22 | ``` -------------------------------------------------------------------------------- /lintcode/lintcode_372_Delete_One_Element.java: -------------------------------------------------------------------------------- 1 | // @Author: Xingxing Huang 2 | /** 3 | * Definition for ListNode. 4 | * public class ListNode { 5 | * int val; 6 | * ListNode next; 7 | * ListNode(int val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | * } 12 | */ 13 | public class Solution { 14 | /** 15 | * @param node: the node in the list should be deleted 16 | * @return: nothing 17 | */ 18 | public void deleteNode(ListNode node) { 19 | // write your code here 20 | if (node.next == null) { 21 | node = null; 22 | } else { 23 | node.val = node.next.val; 24 | node.next = node.next.next; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /leetcode/053_Maximum_Subarray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 简单DP 思想,先求和,并同时找最大最小值。 3 | * 注意参数顺序,需要画图分析出来,然后再谢代码 4 | * @athor Xingxing Huang 5 | * @since 2017.04.14 6 | * @Time O(n), 7 | * @param 8 | * @return 9 | */ 10 | public class Solution { 11 | public int maxSubArray(int[] nums) { 12 | if (nums == null) { 13 | return 0; 14 | } 15 | // 定义初始状态 16 | int min = 0; 17 | int max = nums[0]; 18 | int sum = nums[0]; 19 | // 递归求解 20 | for (int i = 1; i < nums.length; i++) { 21 | min = Math.min(sum, min); 22 | sum += nums[i]; 23 | // 分解为小问题 24 | max = Math.max(sum - min, max); 25 | } 26 | return max; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/064_Minimum_Path_Sum.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minPathSum(int[][] grid) { 3 | int m = grid.length; 4 | int n = grid[0].length; 5 | for (int i = 0; i < m; i++) { 6 | for (int j = 0; j < n; j++) { 7 | if (i == 0 && j == 0) { 8 | continue; 9 | } else if (i == 0) { 10 | grid[i][j] += grid[i][j - 1]; 11 | } else if (j == 0) { 12 | grid[i][j] += grid[i - 1][j]; 13 | } else { 14 | grid[i][j] = Math.min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j]; 15 | } 16 | } 17 | } 18 | return grid[m - 1][n - 1]; 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode/414_Third_Maximum_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int thirdMax(int[] nums) { 3 | Integer max1 = null; 4 | Integer max2 = null; 5 | Integer max3 = null; 6 | for (Integer n : nums) { 7 | if (n.equals(max1) || n.equals(max2) || n.equals(max3)) continue; 8 | if (max1 == null || n > max1) { 9 | max3 = max2; 10 | max2 = max1; 11 | max1 = n; 12 | } else if (max2 == null || n > max2) { 13 | max3 = max2; 14 | max2 = n; 15 | } else if (max3 == null || n > max3) { 16 | max3 = n; 17 | } 18 | } 19 | return max3 == null ? max1 : max3; 20 | } 21 | } -------------------------------------------------------------------------------- /leetcode/022_Generate_Parentheses.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public List generateParenthesis(int n) { 4 | List s = new ArrayList(); 5 | backtrack(s, "", 0, 0, n); 6 | return s; 7 | } 8 | 9 | public void backtrack(List s, String str, int left, int right, int n) { 10 | // 如果字符串已经使用n个括号 11 | if (str.length() == 2 * n) { 12 | s.add(str); 13 | return; 14 | } 15 | // 如果可以添加左括号 16 | if (left < n) { 17 | backtrack(s, str + '(', left + 1, right, n); 18 | } 19 | // 如果可以添加右括号 20 | if (right < left) { 21 | backtrack(s, str + ')', left, right + 1, n); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/069_Sqrt_x.java: -------------------------------------------------------------------------------- 1 | // 09/20 2 | class Solution { 3 | public int mySqrt(int x) { 4 | if (x == 0) 5 | return 0; 6 | int left = 1, right = x; 7 | while (true) { 8 | int mid = left + (right - left)/2; 9 | if (mid > x/mid) { 10 | right = mid - 1; 11 | } else if (mid + 1 > x/(mid + 1)) { 12 | return mid; 13 | } else { 14 | left = mid + 1; 15 | } 16 | } 17 | } 18 | } 19 | 20 | // Newton method 21 | // https://discuss.leetcode.com/topic/24532/3-4-short-lines-integer-newton-every-language 22 | long r = x; 23 | while (r*r > x) 24 | r = (r + x/r) / 2; 25 | return (int) r; -------------------------------------------------------------------------------- /leetcode_daily/935.md: -------------------------------------------------------------------------------- 1 | A good practice for DP 2 | 3 | ```python 4 | class Solution: 5 | def knightDialer(self, N): 6 | """ 7 | :type N: int 8 | :rtype: int 9 | """ 10 | moves = [[4,6],[6,8],[7,9],[4,8],[3,9,0],[], 11 | [1,7,0],[2,6],[1,3],[2,4]] 12 | # dp[i][j] presents the methods of number i with j moves 13 | dp = [[1 for i in range(10)]] 14 | for i in range(N - 1): 15 | dp.append([0 for i in range(10)]) 16 | for n, c in enumerate(dp[i]): 17 | for neighbour in moves[n]: 18 | dp[i + 1][neighbour] += c 19 | dp[i + 1][neighbour] %= 10**9 + 7 20 | return sum(dp[N - 1]) % (10**9 + 7) 21 | ``` -------------------------------------------------------------------------------- /leetcode_daily/621.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ```python 4 | class Solution: 5 | def leastInterval(self, tasks: 'List[str]', n: 'int') -> 'int': 6 | m = [0] * 26 7 | for task in tasks: 8 | m[ord(task) - ord("A")] += 1 9 | m = sorted(m) 10 | 11 | max_val = m[-1] - 1 12 | idle = max_val * n 13 | for i in range(24, -1, -1): 14 | if m[i] > 0: 15 | # filling the rest task into the slots, 16 | # if the number is equal to the max_val, we need to add one elements in the end of the sequences. 17 | idle -= min(m[i], max_val) 18 | if idle > 0: 19 | return idle + len(tasks) 20 | else: 21 | return len(tasks) 22 | 23 | ``` -------------------------------------------------------------------------------- /leetcode/389_Find_the_Difference.java: -------------------------------------------------------------------------------- 1 | // hashmap 2 | public class Solution { 3 | public char findTheDifference(String s, String t) { 4 | int[] map = new int[26]; 5 | for (int i = 0; i < s.length(); i++) map[s.charAt(i) - 'a']++; 6 | for (int i = 0; i < t.length(); i++) { 7 | map[t.charAt(i) - 'a']--; 8 | if (map[t.charAt(i) - 'a'] < 0) return t.charAt(i); 9 | } 10 | return ' '; 11 | } 12 | } 13 | 14 | // bit manipulation 15 | public char findTheDifference(String s, String t) { 16 | char c = 0; 17 | for (int i = 0; i < s.length(); ++i) { 18 | c ^= s.charAt(i); 19 | } 20 | for (int i = 0; i < t.length(); ++i) { 21 | c ^= t.charAt(i); 22 | } 23 | return c; 24 | } -------------------------------------------------------------------------------- /leetcode/192_Word_Frequency.bash: -------------------------------------------------------------------------------- 1 | # Read from the file words.txt and output the word frequency list to stdout. 2 | cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{ print $2, $1 }' 3 | 4 | # tr -s: truncate the string with target string, but only remaining one instance (e.g. multiple whitespaces) 5 | # sort: To make the same string successive so that uniq could count the same string fully and correctly. 6 | # uniq -c: uniq is used to filter out the repeated lines which are successive, -c means counting 7 | # sort -r: -r means sorting in descending order 8 | # awk '{ print $2, $1 }': To format the output, see here. 9 | 10 | 11 | 12 | awk '\ 13 | { for (i=1; i<=NF; i++) { ++D[$i]; } }\ 14 | END { for (i in D) { print i, D[i] } }\ 15 | ' words.txt | sort -nr -k 2 -------------------------------------------------------------------------------- /lintcode/lintcode_046_Majority_Number.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/majority-number/ 2 | // 技巧 3 | public class Solution { 4 | /** 5 | * @param nums: a list of integers 6 | * @return: find a majority number 7 | */ 8 | public int majorityNumber(ArrayList nums) { 9 | // write your code 10 | int count = 0; 11 | int candidate = -1; 12 | for (int i = 0; i < nums.size(); i++) { 13 | if (count == 0) { 14 | count++; 15 | candidate = nums.get(i); 16 | } else if (candidate == nums.get(i)) { 17 | count++; 18 | } else { 19 | count--; 20 | } 21 | } 22 | return candidate; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/032_hard_Longest_Valid_Parentheses.java: -------------------------------------------------------------------------------- 1 | // 09.16 2 | // https://leetcode.com/problems/longest-valid-parentheses/solution/ 3 | class Solution { 4 | public int longestValidParentheses(String s) { 5 | int maxans = 0; 6 | Stack stack = new Stack<>(); 7 | stack.push(-1); 8 | for (int i = 0; i < s.length(); i++) { 9 | if (s.charAt(i) == '(') { 10 | stack.push(i); 11 | } else { 12 | stack.pop(); 13 | if (stack.empty()) { 14 | stack.push(i); 15 | } else { 16 | maxans = Math.max(maxans, i - stack.peek()); 17 | } 18 | } 19 | } 20 | return maxans; 21 | } 22 | } -------------------------------------------------------------------------------- /leetcode/203_Remove_Linked_List_Elements.java: -------------------------------------------------------------------------------- 1 | // non recursive 2 | class Solution { 3 | public ListNode removeElements(ListNode head, int val) { 4 | ListNode dummy = new ListNode(0); 5 | dummy.next = head; 6 | ListNode cur = dummy; 7 | while (cur.next != null) { 8 | if (cur.next.val == val) 9 | cur.next = cur.next.next; 10 | else 11 | cur = cur.next; 12 | } 13 | return dummy.next; 14 | } 15 | } 16 | 17 | // recursive 18 | class Solution { 19 | public ListNode removeElements(ListNode head, int val) { 20 | if (head == null) return head; 21 | head.next = removeElements(head.next, val); 22 | return head.val == val ? head.next : head; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/139_Word_Break.java: -------------------------------------------------------------------------------- 1 | // @Author: Xingxing Huang 2 | // @Time: substring方法的时间复杂度为O(N),因此该DP方法复杂度高 3 | // @Date: 2017/03/26 4 | // 动态规划求解,从第一个元素开始,如果包含该元素的之前字符串能分割成word,该位置设置为true。如果最后一位为true,那么返回true 5 | public class Solution { 6 | public boolean wordBreak(String s, List wordDict) { 7 | Boolean[] f = new Boolean[s.length() + 1]; // 长度+1 8 | f[0] = true; 9 | for (int i = 0; i <= s.length(); i++) { 10 | // 对i位置前面的字符串进行扫描 11 | for (int j = 0; j < i; j++) { 12 | if (f[j] && wordDict.containskey(s.substring(j, i))) { 13 | f[i] = true; 14 | break; 15 | } 16 | } 17 | } 18 | return f[s.length()]; 19 | } 20 | } 21 | 22 | 23 | -------------------------------------------------------------------------------- /leetcode/322_Coin_Change.java: -------------------------------------------------------------------------------- 1 | // 09.19 DP问题 2 | // corner case: amount = 0; 3 | class Solution { 4 | public int coinChange(int[] coins, int amount) { 5 | if (amount == 0) return 0; 6 | int[] dp = new int[amount + 1]; 7 | Arrays.sort(coins); 8 | for (int i = 1; i <= amount; i++) { 9 | for (int j = 0; j < coins.length; j++) { 10 | if (i - coins[j] >= 0 && (dp[i - coins[j]] > 0 || i - coins[j] == 0)) { 11 | if (dp[i] == 0) 12 | dp[i] = dp[i - coins[j]] + 1; 13 | else 14 | dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1); 15 | } 16 | } 17 | } 18 | return dp[amount] > 0 ? dp[amount] : -1; 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode_daily/077.md: -------------------------------------------------------------------------------- 1 | [77](https://leetcode.com/problems/combinations/) Practice the Permutation. 2 | 3 | ```python 4 | class Solution: 5 | def __init__(self): 6 | self.result = [] 7 | def combine(self, n, k): 8 | """ 9 | :type n: int 10 | :type k: int 11 | :rtype: List[List[int]] 12 | """ 13 | self.dfs([], n, k, 1) 14 | return self.result 15 | 16 | def dfs(self, cur, n, k, start): 17 | if len(cur) > k: 18 | return 19 | if len(cur) == k: 20 | self.result.append(cur) 21 | return 22 | for i in range(start, n + 1): 23 | cur.append(i) 24 | self.dfs(cur.copy(), n, k, i + 1) 25 | cur = cur[0:-1] 26 | return 27 | ``` -------------------------------------------------------------------------------- /leetcode_daily/309.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ```python 4 | class Solution(object): 5 | def maxProfit(self, prices): 6 | """ 7 | :type prices: List[int] 8 | :rtype: int 9 | """ 10 | # free is the maximum profit I can have while being free to buy. 11 | # have is the maximum profit I can have while having stock. 12 | # cool is the maximum profit I can have while cooling down. 13 | free = 0 14 | have = cool = float('-inf') 15 | for p in prices: 16 | free, have, cool = max(free, cool), max(have, free - p), have + p 17 | ## this doesn't work 18 | # free = max(free, cool) 19 | # have = max(have, free - p) 20 | # cool = have + p 21 | return max(free, cool) 22 | ``` -------------------------------------------------------------------------------- /leetcode/275_H-Index_II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * binary search。边界条件非常注意 3 | * @author Xingxing Huang 4 | * @since 2017.05.23 5 | * @Time O(n) 6 | * @param int[] 7 | * @return int 8 | */ 9 | public class Solution { 10 | public int hIndex(int[] citations) { 11 | int len = citations.length; 12 | int lo = 0; 13 | int hi = len - 1; 14 | while (lo <= hi) { 15 | int mid = lo + (hi - lo) / 2; 16 | // 左边的引用一定小于排名 17 | if (citations[mid] == len - mid) { 18 | return len - mid; 19 | } else if (citations[mid] > len - mid) { 20 | hi = mid - 1; 21 | } else { 22 | lo = mid + 1; 23 | } 24 | } 25 | return len - lo; 26 | } 27 | } -------------------------------------------------------------------------------- /leetcode_daily/043.md: -------------------------------------------------------------------------------- 1 | [043](https://leetcode.com/problems/rotate-image/) Rotate Image 2 | 3 | ```python 4 | class Solution: 5 | def rotate(self, matrix: List[List[int]]) -> None: 6 | """ 7 | Do not return anything, modify matrix in-place instead. 8 | """ 9 | n = len(matrix[0]) 10 | for i in range(n // 2 + n % 2): 11 | for j in range(n // 2): 12 | temp = matrix[n-1-j][i] 13 | matrix[n-1-j][i] = matrix[n-1-i][n-j-1] 14 | matrix[n-1-i][n-j-1] = matrix[j][n-1-i] 15 | matrix[j][n-1-i] = matrix[i][j] 16 | matrix[i][j] = temp 17 | ``` 18 | 19 | There is one interesting [solution](https://leetcode.com/problems/rotate-image/solution/) with a Transpose followed by a reverse -------------------------------------------------------------------------------- /leetcode/169_Majority_Element.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 方法巧妙。 3 | * 有多重解法,并且有进阶问题 229 4 | * https://discuss.leetcode.com/topic/28601/java-solutions-sorting-hashmap-moore-voting-bit-manipulation 5 | * @author Xingxing Huang 6 | * @since 2017.05.04 7 | * @Time 排序方法 O(NlogN), 快速方法O(N) 8 | * @param int[] 9 | * @return int 10 | */ 11 | public class Solution { 12 | public int majorityElement(int[] nums) { 13 | int count = 0; 14 | int num = 0; 15 | for (int i = 0; i < nums.length; i++) { 16 | if (count == 0) { 17 | num = nums[i]; 18 | } 19 | if (nums[i] == num) { 20 | count++; 21 | } else { 22 | count--; 23 | } 24 | } 25 | return num; 26 | } 27 | } -------------------------------------------------------------------------------- /leetcode/437_Path_Sum_III.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int pathSum(TreeNode root, int sum) { 12 | if (root == null) return 0; 13 | times = pathSumFrom(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); 14 | return times; 15 | } 16 | 17 | // sum start from current node 18 | public int pathSumFrom(TreeNode node, int sum){ 19 | if (node == null) return 0; 20 | return (node.val == sum ? 1 : 0) 21 | + pathSumFrom(node.left, sum - node.val) + pathSumFrom(node.right, sum - node.val); 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode/683_hard_K_Empty_Slots.java: -------------------------------------------------------------------------------- 1 | // Key constrain: the number of flowers between them is k and these flowers are not blooming. 2 | class Solution { 3 | public int kEmptySlots(int[] flowers, int k) { 4 | int n = flowers.length, ans = -1; 5 | int [] le = new int [n + 2]; 6 | int [] ri = new int [n + 2]; 7 | for(int i = 0; i <= n + 1; i++){ 8 | le[i] = i - 1; 9 | ri[i] = i + 1; 10 | } 11 | for(int i = flowers.length - 1; i >= 0; i--){ 12 | int p = flowers[i]; 13 | int l = le[p], r = ri[p]; 14 | if((p - l - 1 == k && l != 0) || (r - p - 1 == k && r != n + 1)) 15 | ans = i + 1; 16 | ri[l] = r; le[r] = l; 17 | } 18 | return ans; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/753_Cracking_the_Safe.java: -------------------------------------------------------------------------------- 1 | // k^n 2 | class Solution { 3 | public String crackSafe(int n, int k) { 4 | int M = (int) Math.pow(k, n-1); 5 | int[] P = new int[M * k]; 6 | for (int i = 0; i < k; ++i) 7 | for (int q = 0; q < M; ++q) 8 | P[i*M + q] = q*k + i; 9 | 10 | StringBuilder ans = new StringBuilder(); 11 | for (int i = 0; i < M*k; ++i) { 12 | int j = i; 13 | while (P[j] >= 0) { 14 | ans.append(String.valueOf(j / M)); 15 | int v = P[j]; 16 | P[j] = -1; 17 | j = v; 18 | } 19 | } 20 | 21 | for (int i = 0; i < n-1; ++i) 22 | ans.append("0"); 23 | return new String(ans); 24 | } 25 | } -------------------------------------------------------------------------------- /leetcode/421_Maximum_XOR_of_Two_Numbers_in_an_Array.java: -------------------------------------------------------------------------------- 1 | // 10.02 2 | // bit位从左往右依次确定, 最大数在该位是多少。 3 | class Solution { 4 | public int findMaximumXOR(int[] nums) { 5 | int max = 0; 6 | int mask = 0; 7 | for (int i = 31; i >= 0; i--) { 8 | mask = mask | (1 << i); // 修改mask的第i位,用于获取第31位到第i位的数 9 | Set set = new HashSet<>(); 10 | // 判断当前数中是否有该位为1的数 11 | for (int num : nums) 12 | set.add(num & mask); 13 | int tmp = max | (1 << i); // 修改当前最大值的第i位; 14 | for (int prefix : set) { 15 | if (set.contains(tmp ^ prefix)) { 16 | max = tmp; 17 | break; 18 | } 19 | } 20 | } 21 | return max; 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode/757_hard_Set_Intersection_Size_At_Least_Two.java: -------------------------------------------------------------------------------- 1 | // 12.30 hard 2 | class Solution { 3 | public int intersectionSizeTwo(int[][] rs) { 4 | Arrays.sort(rs, new Comparator() { 5 | public int compare(int[] a, int[] b) { 6 | return a[1] - b[1]; 7 | } 8 | }); 9 | int n = rs.length; 10 | int p = 0; 11 | int[] xs = new int[n*2+5]; 12 | for(int[] r : rs){ 13 | int rem = 2; 14 | for(int i = 0;i < p;i++){ 15 | if(r[0] <= xs[i] && xs[i] <= r[1]){ 16 | rem--; 17 | } 18 | } 19 | for(int i = 0;i < rem;i++){ 20 | xs[p++] = r[1] - i; 21 | } 22 | } 23 | return p; 24 | } 25 | } -------------------------------------------------------------------------------- /leetcode_daily/1018.md: -------------------------------------------------------------------------------- 1 | [1018](https://leetcode.com/problems/binary-prefix-divisible-by-5/) Binary Prefix Divisible By 5 2 | 3 | Easy 4 | 5 | ```python 6 | class Solution(object): 7 | def prefixesDivBy5(self, A): 8 | """ 9 | :type A: List[int] 10 | :rtype: List[bool] 11 | """ 12 | res = [] 13 | num = 0 14 | for a in A: 15 | num = num * 2 + a 16 | if num % 5 == 0: 17 | res.append(True) 18 | else: 19 | res.append(False) 20 | return res 21 | ``` 22 | 23 | Better solution using prefix mod 24 | 25 | ```python 26 | def prefixesDivBy5(self, A): 27 | for i in xrange(1, len(A)): 28 | A[i] += A[i - 1] * 2 % 5 29 | return [a % 5 == 0 for a in A] 30 | ``` -------------------------------------------------------------------------------- /lintcode/lintocde_075_Find_Peak_Element.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/find-peak-element/ 2 | // 边界条件很容易出错,方向不要弄反了 3 | class Solution { 4 | /** 5 | * @param A: An integers array. 6 | * @return: return any of peek positions. 7 | */ 8 | public int findPeak(int[] A) { 9 | // write your code here 10 | int l = 1; 11 | int r = A.length - 2; 12 | while (l + 1 < r) { 13 | int m = l + (r - l) / 2; 14 | if (A[m] < A[m - 1]) { 15 | r = m; 16 | } else if (A[m] < A[m + 1]) { 17 | l = m; 18 | } else { 19 | return m; 20 | } 21 | } 22 | if (A[l] > A[r]) { 23 | return l; 24 | } 25 | return r; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/027_Remove_Element.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeElement(int[] nums, int val) { 3 | int i = 0; 4 | int j = nums.length-1; 5 | while (i <= j) { 6 | while (i <= j && nums[j] == val) j--; 7 | while (i <= j && nums[i] != val) i++; 8 | if (i < j) { 9 | nums[i] = nums[j]; 10 | nums[j] = val; 11 | } 12 | } 13 | //if (j == -1) return 0; 14 | return j + 1; 15 | 16 | } 17 | } 18 | 19 | 20 | public int removeElement(int[] A, int elem) { 21 | int m = 0; 22 | for(int i = 0; i < A.length; i++){ 23 | 24 | if(A[i] != elem){ 25 | A[m] = A[i]; 26 | m++; 27 | } 28 | } 29 | 30 | return m; 31 | } -------------------------------------------------------------------------------- /lintcode/lintcode_375_clone_tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition of TreeNode: 3 | * public class TreeNode { 4 | * public int val; 5 | * public TreeNode left, right; 6 | * public TreeNode(int val) { 7 | * this.val = val; 8 | * this.left = this.right = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | /** 14 | * @param root: The root of binary tree 15 | * @return root of new tree 16 | */ 17 | public TreeNode cloneTree(TreeNode root) { 18 | // Write your code here 19 | if (root == null) { 20 | return null; 21 | } 22 | TreeNode newRoot = new TreeNode(root.val); 23 | newRoot.left = cloneTree(root.left); 24 | newRoot.right = cloneTree(root.right); 25 | return newRoot; 26 | } 27 | } -------------------------------------------------------------------------------- /leetcode/090_Subsets_II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsetsWithDup(int[] nums) { 3 | Arrays.sort(nums); 4 | List> res = new ArrayList<>(); 5 | List each = new ArrayList<>(); 6 | helper(res, each, 0, nums); 7 | return res; 8 | } 9 | public void helper(List> res, List each, int pos, int[] n) { 10 | if (pos <= n.length) { 11 | res.add(each); 12 | } 13 | int i = pos; 14 | while (i < n.length) { 15 | each.add(n[i]); 16 | helper(res, new ArrayList<>(each), i + 1, n); 17 | each.remove(each.size() - 1); 18 | i++; 19 | while (i < n.length && n[i] == n[i - 1]) {i++;} 20 | } 21 | return; 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode/383_Ransom_Node.java: -------------------------------------------------------------------------------- 1 | ## python 2 | class Solution(object): 3 | def canConstruct(self, ransomNote, magazine): 4 | """ 5 | :type ransomNote: str 6 | :type magazine: str 7 | :rtype: bool 8 | """ 9 | return not collections.Counter(ransomNote) - collections.Counter(magazine) 10 | 11 | 12 | public class Solution { 13 | public boolean canConstruct(String ransomNote, String magazine) { 14 | int[] arr = new int[26]; 15 | for (int i = 0; i < magazine.length(); i++) { 16 | arr[magazine.charAt(i) - 'a']++; 17 | } 18 | for (int i = 0; i < ransomNote.length(); i++) { 19 | if(--arr[ransomNote.charAt(i)-'a'] < 0) { 20 | return false; 21 | } 22 | } 23 | return true; 24 | } 25 | } -------------------------------------------------------------------------------- /leetcode/552_hard_Student_Attendance_Record_II.java: -------------------------------------------------------------------------------- 1 | // 10.10 DP 2 | // https://discuss.leetcode.com/topic/86526/improving-the-runtime-from-o-n-to-o-log-n 3 | class Solution { 4 | public int checkRecord(int n) { 5 | final int MOD = 1000000007; 6 | int[][][] f = new int[n + 1][2][3]; 7 | 8 | f[0] = new int[][]{{1, 1, 1}, {1, 1, 1}}; 9 | for (int i = 1; i <= n; i++) 10 | for (int j = 0; j < 2; j++) 11 | for (int k = 0; k < 3; k++) { 12 | int val = f[i - 1][j][2]; // ...P 13 | if (j > 0) val = (val + f[i - 1][j - 1][2]) % MOD; // ...A 14 | if (k > 0) val = (val + f[i - 1][j][k - 1]) % MOD; // ...L 15 | f[i][j][k] = val; 16 | } 17 | return f[n][1][2]; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/067_Add_Binary.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String addBinary(String a, String b) { 3 | StringBuilder s = new StringBuilder(); 4 | int la = a.length() - 1; 5 | int lb = b.length() - 1; 6 | int sign = 0; 7 | while(la >=0 || lb >=0) { 8 | // get the value 9 | if (la >= 0) { 10 | sign += a.charAt(la) - '0'; 11 | la--; 12 | } 13 | if (lb >= 0) { 14 | sign += b.charAt(lb) - '0'; 15 | lb--; 16 | } 17 | // add to the string 18 | s.append(sign % 2); 19 | sign = sign >> 1; 20 | } 21 | if (sign != 0) { 22 | s.append(sign); 23 | } 24 | return s.reverse().toString(); 25 | } 26 | } -------------------------------------------------------------------------------- /leetcode/506_Relative_Ranks.java: -------------------------------------------------------------------------------- 1 | // 2017.08.08 XingxingHuang 2 | // All the scores of athletes are guaranteed to be **unique**. 3 | public class Solution { 4 | public String[] findRelativeRanks(int[] nums) { 5 | PriorityQueue pq = new PriorityQueue<>((i, j) -> (-nums[i] + nums[j])); 6 | for (int i = 0; i < nums.length; i++) 7 | pq.offer(i); 8 | String[] res = new String[nums.length]; 9 | if (!pq.isEmpty()) 10 | res[pq.poll()] = "Gold Medal"; 11 | if (!pq.isEmpty()) 12 | res[pq.poll()] = "Silver Medal"; 13 | if (!pq.isEmpty()) 14 | res[pq.poll()] = "Bronze Medal"; 15 | for (int i = 4; i <= nums.length; i++) { 16 | res[pq.poll()] = String.valueOf(i); 17 | } 18 | return res; 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode_daily/141.md: -------------------------------------------------------------------------------- 1 | [141](https://leetcode.com/problems/linked-list-cycle/) Linked List Cycle 2 | 3 | ```python 4 | # Definition for singly-linked list. 5 | # class ListNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution(object): 11 | def hasCycle(self, head): 12 | """ 13 | :type head: ListNode 14 | :rtype: bool 15 | """ 16 | if head is None or head.next is None: 17 | return False 18 | slow = head 19 | fast = head.next.next 20 | while slow != fast: 21 | if fast is None or fast.next is None: 22 | return False 23 | slow = slow.next 24 | fast = fast.next.next 25 | return True 26 | 27 | 28 | 29 | ``` -------------------------------------------------------------------------------- /leetcode/017_Letter_Combinations_of_a_Phone_Number.java: -------------------------------------------------------------------------------- 1 | // 09.15 2 | class Solution { 3 | private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; 4 | 5 | public List letterCombinations(String digits) { 6 | List res = new ArrayList<>(); 7 | helper(digits, 0, res, ""); 8 | return res; 9 | } 10 | private void helper(String digits, int idx, List res, String str) { 11 | if (idx == digits.length()) { 12 | if (str.length() == 0) return; 13 | res.add(str); 14 | return; 15 | } 16 | String key = KEYS[digits.charAt(idx) - '0']; 17 | for (int i = 0; i < key.length(); i++) { 18 | helper(digits, idx + 1, res, str + key.charAt(i)); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /leetcode/129_Sum_Root_to_Leaf.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | // 12.12 全局变量help 11 | class Solution { 12 | public int sum = 0; 13 | public int sumNumbers(TreeNode root) { 14 | if (root == null) 15 | return 0; 16 | helper(root, root.val); 17 | return sum; 18 | } 19 | private void helper(TreeNode root, int pre) { 20 | if (root.left == null && root.right == null) 21 | sum = sum + pre; 22 | if (root.left != null) 23 | helper(root.left, pre * 10 + root.left.val); 24 | if (root.right != null) 25 | helper(root.right, pre * 10 + root.right.val); 26 | } 27 | } -------------------------------------------------------------------------------- /leetcode/575_Distribute_Candies.java: -------------------------------------------------------------------------------- 1 | // 10.10 2 | // using set 3 | public class Solution { 4 | public int distributeCandies(int[] candies) { 5 | HashSet < Integer > set = new HashSet < > (); 6 | for (int candy: candies) { 7 | set.add(candy); 8 | } 9 | return Math.min(set.size(), candies.length / 2); 10 | } 11 | } 12 | 13 | // using sort 14 | public class Solution { 15 | public int distributeCandies(int[] candies) { 16 | Arrays.sort(candies); 17 | int count = 1; 18 | for (int i = 1; i < candies.length && count < candies.length / 2; i++) 19 | if (candies[i] > candies[i - 1]) 20 | count++; 21 | return count; 22 | } 23 | } 24 | 25 | 26 | // solutions in the leetcode 27 | // https://leetcode.com/problems/distribute-candies/solution/ -------------------------------------------------------------------------------- /lintcode/084_Single_Number_III.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param A : An integer array 4 | * @return : Two integers 5 | */ 6 | public List singleNumberIII(int[] A) { 7 | int xor = 0; 8 | for (int i = 0; i < A.length; i++) { 9 | xor ^= A[i]; 10 | } 11 | 12 | int lastBit = xor - (xor & (xor - 1)); 13 | int group0 = 0, group1 = 0; 14 | for (int i = 0; i < A.length; i++) { 15 | if ((lastBit & A[i]) == 0) { 16 | group0 ^= A[i]; 17 | } else { 18 | group1 ^= A[i]; 19 | } 20 | } 21 | 22 | ArrayList result = new ArrayList(); 23 | result.add(group0); 24 | result.add(group1); 25 | return result; 26 | } 27 | } -------------------------------------------------------------------------------- /lintcode/lintcode_371_print_n_recursion.java: -------------------------------------------------------------------------------- 1 | // @Author: Xingxing Huang 2 | public class Solution { 3 | /** 4 | * @param n: An integer. 5 | * return : An array storing 1 to the largest number with n digits. 6 | */ 7 | public List numbersByRecursion(int n) { 8 | // write your code here 9 | List result = new ArrayList(); 10 | if (n == 0) { 11 | return result; 12 | } 13 | for (int i = 1; i <= 9; i++) { 14 | result.add(i); 15 | } 16 | if (n == 1) { 17 | return result; 18 | } 19 | for (int i : numbersByRecursion(n - 1)) { 20 | for (int j = 0; j <= 9; j++) { 21 | result.add(i * 10 + j); 22 | } 23 | } 24 | return result; 25 | } 26 | } -------------------------------------------------------------------------------- /leetcode/682_Baseball_Game.java: -------------------------------------------------------------------------------- 1 | // 0923 2 | class Solution { 3 | public int calPoints(String[] ops) { 4 | Stack stack = new Stack<>(); 5 | for (String s: ops) { 6 | if (s.equals("C")) { 7 | stack.pop(); 8 | } else if (s.equals("D")) { 9 | stack.push(stack.peek()*2); 10 | } else if (s.equals("+")) { 11 | int n = stack.pop(); 12 | int m = stack.pop(); 13 | stack.push(m); 14 | stack.push(n); 15 | stack.push(m + n); 16 | } else { 17 | stack.push(Integer.valueOf(s)); 18 | } 19 | } 20 | int sum = 0; 21 | while (!stack.isEmpty()) { 22 | sum += stack.pop(); 23 | } 24 | return sum; 25 | } 26 | } -------------------------------------------------------------------------------- /leetcode/070_Climbing_Stairs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Fibonacci 问题 3 | * @athor Xingxing Huang 4 | * @since 2017.04.14 5 | * @Time O(n), 6 | * @param int 7 | * @return int 8 | */ 9 | 10 | // public class Solution { 11 | // public int climbStairs(int n) { 12 | // if (n == 0) return 0; 13 | // if (n == 2) return 2; 14 | // if (n == 1) return 1; 15 | // return climbStairs(n - 2) + climbStairs(n - 1); 16 | // } 17 | // } 18 | 19 | public class Solution { 20 | public int climbStairs(int n) { 21 | //if (n <= 2) return n; 22 | 23 | int one = 1; 24 | int two = 0; 25 | int total = 0; 26 | for (int i = 0; i < n; i ++){ 27 | total = one + two; 28 | two = one; 29 | one = total; 30 | } 31 | return total; 32 | } 33 | } -------------------------------------------------------------------------------- /leetcode/678_Valid_Parenthesis_String.java: -------------------------------------------------------------------------------- 1 | // 09.16 brute force, recursive 2 | 3 | class Solution { 4 | public boolean checkValidString(String s) { 5 | if (s == null || s.length() == 0) 6 | return true; 7 | return check(s, 0, 0); 8 | } 9 | public boolean check(String s, int sum, int idx) { 10 | if (sum < 0) 11 | return false; 12 | if (idx == s.length()) 13 | return sum == 0; 14 | // 15 | if (s.charAt(idx) == '(') { 16 | sum++; 17 | return check(s, sum, idx + 1); 18 | } else if (s.charAt(idx) == ')') { 19 | sum--; 20 | return check(s, sum, idx + 1); 21 | } else { 22 | return check(s, sum + 1, idx + 1) || check(s, sum, idx + 1) || check(s, sum - 1, idx + 1); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /leetcode/474_Ones_and_Zeroes.java: -------------------------------------------------------------------------------- 1 | // 2017.08.11 XingxingHuang 2 | // dp, dp[i][j]记录i,j个0和1的数字可以构成多少个字符串。依次添加字符串,并更新所有dp[i][j]的值 3 | public class Solution { 4 | public int findMaxForm(String[] strs, int m, int n) { 5 | int[][] dp = new int[m + 1][n + 1]; 6 | for (String s: strs) { 7 | int[] count = count(s); 8 | for (int i = m; i >= count[0]; i--) { 9 | for (int j = n; j >= count[1]; j--) { 10 | dp[i][j] = Math.max(1 + dp[i - count[0]][j - count[1]], dp[i][j]); 11 | } 12 | } 13 | } 14 | return dp[m][n]; 15 | } 16 | public int[] count(String str) { 17 | int[] res = new int[2]; 18 | for (int i = 0; i < str.length(); i++) { 19 | res[str.charAt(i) - '0']++; 20 | } 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode/503_Next_Greater_Element.java: -------------------------------------------------------------------------------- 1 | // @Author 黄xing 2 | public class Solution { 3 | public int[] nextGreaterElements(int[] nums) { 4 | int[] next = new int[nums.length]; 5 | Stack stack = new Stack(); 6 | // 维护一个栈结构存储已经遍历过的index, 7 | for (int i = 0; i < nums.length * 2 ; i++) { 8 | // 当前元素比栈顶对应元素大的时候找到目标,pop 9 | while (!stack.isEmpty() && nums[stack.peek()] < nums[i % nums.length]) { 10 | next[stack.pop()] = nums[i % nums.length]; 11 | } 12 | // 当前元素进栈, push, 栈结构中的数组元素始终是递减的。 13 | if (i < nums.length) { 14 | stack.push(i); 15 | } 16 | } 17 | // 栈中还剩最大值 18 | while (!stack.isEmpty()) { 19 | next[stack.pop()] = -1; 20 | } 21 | return next; 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode_daily/056.md: -------------------------------------------------------------------------------- 1 | ```python 2 | # Definition for an interval. 3 | # class Interval: 4 | # def __init__(self, s=0, e=0): 5 | # self.start = s 6 | # self.end = e 7 | 8 | class Solution: 9 | def merge(self, intervals: 'List[Interval]') -> 'List[Interval]': 10 | res = [] 11 | if len(intervals) == 0: 12 | return res 13 | intervals = sorted(intervals, key = lambda x: x.start) 14 | left = intervals[0].start 15 | right = intervals[0].end 16 | for interval in intervals: 17 | if interval.start <= right: 18 | right = max(interval.end, right) 19 | else: 20 | res.append([left, right]) 21 | left = interval.start 22 | right = interval.end 23 | res.append([left, right]) 24 | return res 25 | ``` -------------------------------------------------------------------------------- /leetcode/043_Multiply_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def multiply(self, num1, num2): 3 | """ 4 | :type num1: str 5 | :type num2: str 6 | :rtype: str 7 | """ 8 | s = [0] * (len(num1) + len(num2)) 9 | for i in range(len(num1) - 1, -1, -1): 10 | for j in range(len(num2) - 1, -1, -1): 11 | num = s[i + j + 1] + int(num1[i]) * int(num2[j]) 12 | s[i + j + 1] = num % 10 13 | # 注意这个地方的值可以大于10,但是会在下一轮中变成小于10 14 | s[i + j] += num / 10 15 | #print s 16 | # add to string 17 | out = '' 18 | for temp in s: 19 | # 注意第一个元素是空的情况 20 | if not (out == '' and temp == 0): 21 | out += str(temp) 22 | if out == '': 23 | return "0" 24 | return out -------------------------------------------------------------------------------- /leetcode/146_hard_LRU_Cache.java: -------------------------------------------------------------------------------- 1 | class LRUCache { 2 | 3 | private LinkedHashMap map; 4 | private final int CAPACITY; 5 | 6 | public LRUCache(int capacity) { 7 | CAPACITY = capacity; 8 | map = new LinkedHashMap(capacity, 0.75f, true){ 9 | protected boolean removeEldestEntry(Map.Entry eldest) { 10 | return size() > CAPACITY; 11 | } 12 | }; 13 | } 14 | 15 | public int get(int key) { 16 | return map.getOrDefault(key, -1); 17 | } 18 | 19 | public void put(int key, int value) { 20 | map.put(key, value); 21 | } 22 | } 23 | 24 | /** 25 | * Your LRUCache object will be instantiated and called as such: 26 | * LRUCache obj = new LRUCache(capacity); 27 | * int param_1 = obj.get(key); 28 | * obj.put(key,value); 29 | */ -------------------------------------------------------------------------------- /leetcode/261_Graph_Valid_Tree.py: -------------------------------------------------------------------------------- 1 | # http://www.jiuzhang.com/solutions/graph-valid-tree/ 2 | class Solution: 3 | # @param {int} n an integer 4 | # @param {int[][]} edges a list of undirected edges 5 | # @return {boolean} true if it's a valid tree, or false 6 | def validTree(self, n, edges): 7 | # Write your code here 8 | root = [i for i in range(n)] 9 | for i in edges: 10 | root1 = self.find(root, i[0]) 11 | root2 = self.find(root, i[1]) 12 | if root1 == root2: 13 | return False 14 | else: 15 | root[root1] = root2 16 | return len(edges) == n - 1 17 | 18 | def find(self, root, e): 19 | if root[e] == e: 20 | return e 21 | else: 22 | root[e] = self.find(root, root[e]) 23 | return root[e] -------------------------------------------------------------------------------- /leetcode/061_Rotate_List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode rotateRight(ListNode head, int k) { 11 | if (head == null) {return head;} 12 | // get the size, get the cycle linklist 13 | int n = 1; 14 | ListNode test = head; 15 | while (test.next != null) { 16 | n++; 17 | test = test.next; 18 | } 19 | test.next = head; 20 | 21 | // move the linklist 22 | for (int i = 1; i < n - k % n ; i++) { 23 | head = head.next; 24 | } 25 | ListNode last = head; 26 | head = head.next; 27 | last.next = null; 28 | return head; 29 | } 30 | } -------------------------------------------------------------------------------- /leetcode/150_Evaluate_Reverse_Polish_Notation.java: -------------------------------------------------------------------------------- 1 | // @Author: 黄xing 2 | // 利用stack 解决 3 | public class Solution { 4 | public int evalRPN(String[] tokens) { 5 | Stack stack = new Stack(); 6 | for (int i = 0; i < tokens.length; i++) { 7 | if (tokens[i].equals("+")) { 8 | stack.push(stack.pop() + stack.pop()); 9 | } else if (tokens[i].equals("-")) { 10 | stack.push(- stack.pop() + stack.pop()); 11 | } else if (tokens[i].equals("*")) { 12 | stack.push(stack.pop() * stack.pop()); 13 | } else if (tokens[i].equals("/")) { 14 | stack.push(1 / stack.pop() * stack.pop()); 15 | } else { 16 | stack.push(Integer.parseInt(tokens[i])); 17 | } 18 | } 19 | return stack.pop(); 20 | } 21 | } -------------------------------------------------------------------------------- /leetcode/313_Super_Ugly_Number.java: -------------------------------------------------------------------------------- 1 | // check : https://discuss.leetcode.com/topic/34841/java-three-methods-23ms-36-ms-58ms-with-heap-performance-explained 2 | class Solution { 3 | public int nthSuperUglyNumber(int n, int[] primes) { 4 | int[] ugly = new int[n]; 5 | int[] idx = new int[primes.length]; 6 | 7 | ugly[0] = 1; 8 | for (int i = 1; i < n; i++) { 9 | //find next 10 | ugly[i] = Integer.MAX_VALUE; 11 | for (int j = 0; j < primes.length; j++) 12 | ugly[i] = Math.min(ugly[i], primes[j] * ugly[idx[j]]); 13 | 14 | //slip duplicate 15 | for (int j = 0; j < primes.length; j++) { 16 | while (primes[j] * ugly[idx[j]] == ugly[i]) 17 | idx[j]++; 18 | } 19 | } 20 | 21 | return ugly[n - 1]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/657_Judge_Route_Circle.java: -------------------------------------------------------------------------------- 1 | public boolean judgeCircle(String moves) { 2 | int x = 0, y = 0; 3 | for(char c: moves.toCharArray()){ 4 | x += (c=='R'?1:0) + (c=='L'?-1:0); y += (c=='U'?1:0) + (c=='D'?-1:0); 5 | } 6 | return x == 0 && y == 0; 7 | } 8 | 9 | class Solution { 10 | public boolean judgeCircle(String moves) { 11 | if (moves == null || moves.length() == 0) 12 | return true; 13 | int[] count = new int[2]; 14 | for (char c : moves.toCharArray()) { 15 | if (c == 'U') count[0]++; 16 | if (c == 'D') count[0]--; 17 | if (c == 'L') count[1]++; 18 | if (c == 'R') count[1]--; 19 | } 20 | for (int i = 0; i < count.length; i++) 21 | if (count[i] != 0) return false; 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/662_Maximum_Width_of_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def dfs(self, r, dep, no): 10 | if r is None: 11 | return 12 | if dep not in self.d: 13 | self.d[dep] = [] 14 | self.d[dep].append(no) 15 | self.dfs(r.left, dep + 1, no * 2) 16 | self.dfs(r.right, dep + 1, no * 2 + 1) 17 | def widthOfBinaryTree(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: int 21 | """ 22 | self.d = dict() 23 | self.dfs(root, 0, 1) 24 | ans = 0 25 | for x in self.d: 26 | ans = max(ans, self.d[x][-1] - self.d[x][0] + 1) 27 | return ans -------------------------------------------------------------------------------- /leetcode/664_Strange_Printer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int strangePrinter(String s) { 3 | int n = s.length(); 4 | if (n == 0) 5 | return 0; 6 | int[][] dp = new int[n][n]; 7 | for (int i = 0; i < n; ++i) 8 | dp[i][i] = 1; 9 | for (int i = 1; i < n; ++i) { // 表示间隔,从1开始到间隔n-1. 10 | for (int j = 0; j < n - i; ++j) { // 依次遍历每个元素 11 | dp[j][j + i] = i + 1; 12 | for (int k = j + 1; k <= j + i; ++k) { // 从该间隔中任意一点断开字符串。 13 | int t = dp[j][k - 1] + dp[k][j + i]; 14 | if (s.charAt(k - 1) == s.charAt(j + i)) // 相同就可以省略依次打印次数。 15 | --t; 16 | dp[j][j + i] = Math.min(dp[j][j + i], t); 17 | } 18 | } 19 | } 20 | return dp[0][n - 1]; 21 | } 22 | } -------------------------------------------------------------------------------- /leetcode/038_Count_and_Say.java: -------------------------------------------------------------------------------- 1 | // 09.20 easy string program 2 | class Solution { 3 | public String countAndSay(int n) { 4 | StringBuilder sb = new StringBuilder("1"); 5 | StringBuilder prev; 6 | int count; 7 | char say; 8 | for (int i = 1; i < n; i++) { 9 | prev = sb; 10 | sb = new StringBuilder(); 11 | count = 1; 12 | say = prev.charAt(0); 13 | for (int j = 1; j < prev.length(); j++) { 14 | if (prev.charAt(j) != say) { 15 | sb.append(count).append(say); 16 | count = 1; 17 | say = prev.charAt(j); 18 | } else { 19 | count++; 20 | } 21 | } 22 | sb.append(count).append(say); 23 | } 24 | return sb.toString(); 25 | } 26 | } -------------------------------------------------------------------------------- /leetcode/086_Partition_List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | // 10.15 easy linkedlist 10 | class Solution { 11 | public ListNode partition(ListNode head, int x) { 12 | ListNode lower = new ListNode(0); 13 | ListNode higher = new ListNode(0); 14 | ListNode l = lower; 15 | ListNode r = higher; 16 | while (head != null) { 17 | if (head.val < x) { 18 | l.next = head; 19 | l = l.next; 20 | } else { 21 | r.next = head; 22 | r = r.next; 23 | } 24 | head = head.next; 25 | } 26 | l.next = higher.next; 27 | r.next = null; 28 | return lower.next; 29 | } 30 | } -------------------------------------------------------------------------------- /leetcode/557_Reverse_Words_in_String_III.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Athor: Xingxing Huang 3 | * @Date: 2017.04.13 4 | * @Time: 学习 char[] chars = s.toCharArray(); 和 String.valueOf(chars); 5 | */ 6 | public class Solution { 7 | public String reverseWords(String s) { 8 | char[] chars = s.toCharArray(); 9 | for (int i = 0; i < s.length();) { 10 | int end = i; 11 | while (end < s.length() && chars[end] != ' ') { 12 | end++; 13 | } 14 | reverse(chars, i, end - 1); 15 | i = end + 1; 16 | } 17 | return String.valueOf(chars); 18 | } 19 | private void reverse(char[] chars, int start, int end) { 20 | for (int i = start, j = end; i < j; i++, j--) { 21 | char ch = chars[i]; 22 | chars[i] = chars[j]; 23 | chars[j] = ch; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /leetcode/647_Palindromic_Substrings.py: -------------------------------------------------------------------------------- 1 | # XingxingHuang 暴力解法,分解成偶数和奇数情况从当前字符展开计算palindromic的计数 2 | class Solution(object): 3 | def countSubstrings(self, s): 4 | """ 5 | :type s: str 6 | :rtype: int 7 | """ 8 | count = 0; 9 | for i in range(len(s)): 10 | # # itself 11 | # 2n + 1 12 | for j in range(len(s)): 13 | if (i - j >= 0 and i + j < len(s) and s[i - j] == s[i + j]): 14 | count += 1 15 | else: 16 | break 17 | # 2n 18 | if (i + 1 < len(s) and s[i] == s[i + 1]): 19 | m = i 20 | n = i + 1 21 | while (m >= 0 and n < len(s) and s[m] == s[n]): 22 | count += 1 23 | m -= 1 24 | n += 1 25 | return count -------------------------------------------------------------------------------- /leetcode_daily/475.md: -------------------------------------------------------------------------------- 1 | [475](https://leetcode.com/problems/heaters/) Heaters 2 | 3 | 4 | Be careful for one corner case that. For some heater, you can just jump over it. 5 | 6 | 7 | ```python 8 | class Solution: 9 | def findRadius(self, houses: List[int], heaters: List[int]) -> int: 10 | houses = sorted(houses) 11 | heaters = sorted(heaters) 12 | i = 0 13 | l = 0 14 | res = 0 15 | while i < len(houses): 16 | r = l + 1 17 | while r < len(heaters) and abs(heaters[l]-houses[i]) >= abs(heaters[r]-houses[i]): 18 | l = r 19 | r += 1 20 | res = max(res, abs(heaters[l] - houses[i])) 21 | # print(heaters[l], houses[i], res) 22 | i += 1 23 | return res 24 | ``` 25 | 26 | There are other methods to solve the problem, such as DP, binary search. -------------------------------------------------------------------------------- /leetcode/153_Find_Minimum_Rotated_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | // @Author: 黄xing 2 | // https://github.com/XingxingHuang 3 | // Time: 套用标准二分法模板求解,O(log N) 4 | public class Solution { 5 | public int findMin(int[] nums) { 6 | if (nums.length == 0) { 7 | return Integer.MAX_VALUE; 8 | } 9 | int start = 0; 10 | int end = nums.length - 1; 11 | while (start + 1 < end) { 12 | int mid = start + (end - start) / 2; 13 | if (nums[start] < nums[end]) { 14 | return nums[start]; 15 | } else if (nums[start] > nums[mid]) { 16 | end = mid; 17 | } else { 18 | start = mid; 19 | } 20 | } 21 | if (nums[start] > nums[end]) { 22 | return nums[end]; 23 | } else { 24 | return nums[start]; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /leetcode_daily/629.md: -------------------------------------------------------------------------------- 1 | [629](https://leetcode.com/problems/k-inverse-pairs-array/) K inverse Pairs Array 2 | 3 | Check the [solutions](https://leetcode.com/problems/k-inverse-pairs-array/solution/) for many detail explanations. 4 | 5 | ```python 6 | class Solution: 7 | def kInversePairs(self, n: int, k: int) -> int: 8 | MOD = 1000000007 9 | dp = [[0] * (k+1) for _ in range(n+1)] 10 | # dp = [[0 for i in range(k+1)] for _ in range(n+1)] 11 | 12 | for i in range(0, n + 1, 1): 13 | dp[i][0] = 1 14 | 15 | for i in range(1, n + 1, 1): 16 | for j in range(1, k + 1, 1): 17 | if j - i >= 0: 18 | dp[i][j] = (dp[i][j-1] + (dp[i-1][j] - dp[i-1][j-i])) % MOD; 19 | else: 20 | dp[i][j] = (dp[i][j-1] + dp[i-1][j]) % MOD 21 | return dp[n][k] 22 | ``` -------------------------------------------------------------------------------- /leetcode_daily/678.md: -------------------------------------------------------------------------------- 1 | [678](https://leetcode.com/problems/valid-parenthesis-string/) Valid Parenthesis String 2 | 3 | 4 | The [solutions](https://leetcode.com/problems/valid-parenthesis-string/solution/) provides the Brute force, DP, greedy methods. 5 | 6 | lee215 solution is [here](https://leetcode.com/problems/valid-parenthesis-string/discuss/107570/JavaC%2B%2BPython-One-Pass-Count-the-Open-Parenthesis) 7 | 8 | 9 | ```python 10 | class Solution: 11 | def checkValidString(self, s: str) -> bool: 12 | x = 0 13 | y = 0 14 | for char in s: 15 | if char == "(": 16 | x += 1 17 | else: 18 | x = max(x - 1, 0) 19 | if char == ")": 20 | y -= 1 21 | else: 22 | y += 1 23 | if y < 0: 24 | return False 25 | return x == 0 26 | 27 | ``` -------------------------------------------------------------------------------- /leetcode/566_Reshape_the_Matrix.java: -------------------------------------------------------------------------------- 1 | // 2017.07.26 2 | // @Author: Xingxing Huang 3 | public class Solution { 4 | public int[][] matrixReshape(int[][] nums, int r, int c) { 5 | if (nums == null || nums.length == 0 || nums[0].length == 0) 6 | return nums; 7 | int m = nums.length; 8 | int n = nums[0].length; 9 | if (m * n != r * c) 10 | return nums; 11 | int[][] res = new int[r][c]; 12 | for (int i = 0; i < m * n; i++) { 13 | res[i / c][i % c] = nums[i / n][i % n]; 14 | } 15 | return res; 16 | } 17 | } 18 | 19 | // Three solutions: // https://leetcode.com/problems/reshape-the-matrix/tabs/solution 20 | // Using queue: take all elements out and then put them into new array. 21 | // Without using extra Space, two loops for the origin array 22 | // Using division and modulus, like what I have done -------------------------------------------------------------------------------- /leetcode_daily/376.md: -------------------------------------------------------------------------------- 1 | [376](https://leetcode.com/problems/wiggle-subsequence/) 2 | 3 | check the [solutions](https://leetcode.com/problems/wiggle-subsequence/) 4 | 5 | ```python 6 | class Solution: 7 | def wiggleMaxLength(self, nums: List[int]) -> int: 8 | n = len(nums) 9 | if n < 2: 10 | return n 11 | up = [0 for i in range(n)] 12 | down = [0 for i in range(n)] 13 | up[0] = 1 14 | down[0] = 1 15 | for i in range(1, n): 16 | if nums[i] > nums[i - 1]: 17 | up[i] = down[i - 1] + 1 18 | down[i] = down[i - 1] 19 | elif nums[i] < nums[i - 1]: 20 | up[i] = up[i - 1] 21 | down[i] = up[i - 1] + 1 22 | else: 23 | down[i] = down[i - 1] 24 | up[i] = up[i - 1] 25 | return max(up[n - 1], down[n - 1]) 26 | ``` -------------------------------------------------------------------------------- /leetcode/142_Linked_List_Cycle_II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | // 10.15 13 | public class Solution { 14 | public ListNode detectCycle(ListNode head) { 15 | ListNode slow = head; 16 | ListNode fast = head; 17 | 18 | while (fast!=null && fast.next!=null){ 19 | fast = fast.next.next; 20 | slow = slow.next; 21 | 22 | if (fast == slow){ 23 | ListNode slow2 = head; 24 | while (slow2 != slow){ 25 | slow = slow.next; 26 | slow2 = slow2.next; 27 | } 28 | return slow; 29 | } 30 | } 31 | return null; 32 | } 33 | } -------------------------------------------------------------------------------- /leetcode/318_Maximum_Product_of_Word_Lengths.java: -------------------------------------------------------------------------------- 1 | // 2017.08.20 XingxingHuang 2 | class Solution { 3 | public static int maxProduct(String[] words) { 4 | if (words == null || words.length <= 1) 5 | return 0; 6 | int m = words.length; 7 | // convert to binary 8 | int[] nums = new int[m]; 9 | for (int i = 0; i < m; i++) { 10 | for (int j = 0; j < words[i].length(); j++) { 11 | nums[i] = nums[i] | (1 << (words[i].charAt(j) - 'a')); 12 | } 13 | } 14 | // compare with O(n^2); 15 | int max = 0; 16 | for (int i = 0; i < m; i++) { 17 | for (int j = i + 1; j < m; j++) { 18 | if ((nums[i] & nums[j]) == 0) 19 | max = Math.max(max, words[i].length() * words[j].length()); 20 | } 21 | } 22 | return max; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/620_Not_Boring_Movies.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT * 3 | FROM cinema 4 | WHERE id MOD 2 = 1 AND description != 'boring' 5 | ORDER BY rating desc 6 | 7 | 8 | SELECT * FROM cinema WHERE (id % 2 = 1) AND (description <> 'boring') ORDER BY rating DESC 9 | 10 | select * 11 | from cinema 12 | where mod(id, 2) = 1 and description != 'boring' 13 | order by rating DESC 14 | 15 | 16 | # 10.18 17 | Select * 18 | from cinema 19 | where 20 | id % 2 = 1 and 21 | description not like "%boring%" 22 | order by rating desc 23 | 24 | 25 | # https://www.postgresql.org/docs/9.5/static/functions-matching.html 26 | 'abc' LIKE 'abc' true 27 | 'abc' LIKE 'a%' true 28 | 'abc' LIKE '_b_' true 29 | 'abc' LIKE 'c' false 30 | 31 | 'abc' SIMILAR TO 'abc' true 32 | 'abc' SIMILAR TO 'a' false 33 | 'abc' SIMILAR TO '%(b|d)%' true 34 | 'abc' SIMILAR TO '(b|c)%' false -------------------------------------------------------------------------------- /leetcode_daily/347.md: -------------------------------------------------------------------------------- 1 | [347](https://leetcode.com/problems/top-k-frequent-elements/) Top K Frequent Elements 2 | 3 | use heap 4 | 5 | ```python 6 | class Solution: 7 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 8 | count = collections.Counter(nums) 9 | return heapq.nlargest(k, count.keys(), key=count.get) 10 | ``` 11 | 12 | use bucket sort 13 | 14 | ```python 15 | class Solution: 16 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 17 | count = collections.Counter(nums) 18 | bucket = [[] for i in range(len(nums) + 1)] 19 | for key, val in count.items(): 20 | bucket[val].append(key) 21 | res = [] 22 | for i in range(len(nums), 0, -1): 23 | for j in bucket[i]: 24 | if len(res) == k: 25 | break 26 | res.append(j) 27 | return res 28 | ``` -------------------------------------------------------------------------------- /lintcode/lintcode_008_Rotate_String.java: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/en/problem/rotate-string/ 2 | public class Solution { 3 | /** 4 | * @param str: an array of char 5 | * @param offset: an integer 6 | * @return: nothing 7 | */ 8 | public void rotateString(char[] str, int offset) { 9 | // write your code here 10 | if (str == null || str.length == 0) 11 | return; 12 | 13 | offset = offset % str.length; 14 | reverse(str, 0, str.length - offset - 1); 15 | reverse(str, str.length - offset, str.length - 1); 16 | reverse(str, 0, str.length - 1); 17 | } 18 | 19 | private void reverse(char[] str, int start, int end) { 20 | for (int i = start, j = end; i < j; i++, j--) { 21 | char temp = str[i]; 22 | str[i] = str[j]; 23 | str[j] = temp; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /leetcode/055_Jump_Game.java: -------------------------------------------------------------------------------- 1 | // 12.12 DP 简单 2 | class Solution { 3 | public boolean canJump(int[] nums) { 4 | int max = 0; 5 | for(int i = 0; i< nums.length; i++){ 6 | if(i > max) 7 | return false; 8 | max = Math.max(nums[i] + i, max); 9 | } 10 | return true; 11 | } 12 | } 13 | 14 | 15 | // 超时 16 | class Solution { 17 | public boolean canJump(int[] nums) { 18 | if (nums == null || nums.length == 0) 19 | return false; 20 | int[] dp = new int[nums.length]; 21 | dp[0] = 1; 22 | for (int i = 0; i < nums.length; i++) { 23 | if (dp[i] == 1) { 24 | // 注意循环条件判断 25 | for (int j = 1; j <= nums[i] && i + j < nums.length; j++) 26 | dp[i + j] = 1; 27 | } 28 | } 29 | return dp[nums.length - 1] == 1; 30 | } 31 | } -------------------------------------------------------------------------------- /leetcode/044_hard_Wildcard_Matching.java: -------------------------------------------------------------------------------- 1 | // 09.16 2 | public class Solution { 3 | public boolean isMatch(String s, String p) { 4 | boolean[][] match=new boolean[s.length()+1][p.length()+1]; 5 | match[s.length()][p.length()]=true; 6 | for(int i=p.length()-1;i>=0;i--){ 7 | if(p.charAt(i)!='*') 8 | break; 9 | else 10 | match[s.length()][i]=true; 11 | } 12 | for(int i=s.length()-1;i>=0;i--){ 13 | for(int j=p.length()-1;j>=0;j--){ 14 | if(s.charAt(i)==p.charAt(j)||p.charAt(j)=='?') 15 | match[i][j]=match[i+1][j+1]; 16 | else if(p.charAt(j)=='*') 17 | match[i][j]=match[i+1][j]||match[i][j+1]; 18 | else 19 | match[i][j]=false; 20 | } 21 | } 22 | return match[0][0]; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/147_Insertion_Sort_List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode insertionSortList(ListNode head) { 11 | if (head == null || head.next == null) {return head;} 12 | ListNode result = new ListNode(0); 13 | while (head != null) { 14 | ListNode cur = result; 15 | // define the location of head.val 16 | while (cur.next != null && cur.next.val < head.val) {cur = cur.next;} 17 | // insert the head.val to the node cur. Pay atention for the sequence 18 | ListNode help = cur.next; 19 | cur.next = head; 20 | head = head.next; 21 | cur.next.next = help; 22 | } 23 | return result.next; 24 | } 25 | } -------------------------------------------------------------------------------- /leetcode/654_Maximum_Binary_Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode constructMaximumBinaryTree(int[] nums) { 12 | if (nums == null) 13 | return null; 14 | return helper(nums, 0, nums.length - 1); 15 | } 16 | private TreeNode helper(int[] nums, int m, int n) { 17 | if (m > n) 18 | return null; 19 | int idx = m; 20 | for (int i = m + 1; i <= n; i++) { 21 | if (nums[idx] < nums[i]) 22 | idx = i; 23 | } 24 | TreeNode root = new TreeNode(nums[idx]); 25 | root.left = helper(nums, m, idx - 1); 26 | root.right = helper(nums, idx + 1, n); 27 | return root; 28 | } 29 | } -------------------------------------------------------------------------------- /leetcode/441_Arranging_Coins.java: -------------------------------------------------------------------------------- 1 | // binary search 2 | public class Solution { 3 | public int arrangeCoins(int n) { 4 | int start = 0; 5 | int end = n; 6 | int mid = 0; 7 | while (start <= end){ 8 | mid = (start + end) >>> 1; 9 | if ((0.5 * mid * mid + 0.5 * mid ) <= n){ 10 | start = mid + 1; 11 | }else{ 12 | end = mid - 1; 13 | } 14 | } 15 | return start - 1; 16 | } 17 | } 18 | 19 | 20 | // Math 21 | public class Solution { 22 | public int arrangeCoins(int n) { 23 | return (int) ((Math.sqrt(1 + 8.0 * n) - 1) / 2); 24 | } 25 | } 26 | 27 | 28 | // O(n) 29 | class Solution { 30 | public int arrangeCoins(int n) { 31 | for (int i = 0; i <= n + 1; i++) { 32 | if (n < (i*(i+1) / 2)) return i - 1; 33 | } 34 | return 0; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /leetcode/461_Hamming_Distance.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int hammingDistance(int x, int y) { 3 | return Integer.bitCount(x ^ y); 4 | } 5 | } 6 | 7 | 8 | public int hammingDistance(int x, int y) { 9 | int xor = x ^ y, count = 0; 10 | for (int i=0;i<32;i++) count += (xor >> i) & 1; 11 | return count; 12 | } 13 | 14 | 15 | class Solution { 16 | public int hammingDistance(int x, int y) { 17 | int n = x ^ y; 18 | int count = 0; 19 | while (n != 0) { 20 | count += n & 1; 21 | n = n >> 1; 22 | } 23 | return count; 24 | } 25 | } 26 | 27 | 28 | 29 | 30 | # python 31 | class Solution(object): 32 | def hammingDistance(self, x, y): 33 | """ 34 | :type x: int 35 | :type y: int 36 | :rtype: int 37 | """ 38 | num = bin(x^y).count('1') 39 | return(num) 40 | -------------------------------------------------------------------------------- /leetcode/640_Solve_the_Equation.java: -------------------------------------------------------------------------------- 1 | // 使用正则表达式 2 | public String solveEquation(String equation) { 3 | int[] res = evaluateExpression(equation.split("=")[0]), 4 | res2 = evaluateExpression(equation.split("=")[1]); 5 | res[0] -= res2[0]; 6 | res[1] = res2[1] - res[1]; 7 | if (res[0] == 0 && res[1] == 0) return "Infinite solutions"; 8 | if (res[0] == 0) return "No solution"; 9 | return "x=" + res[1]/res[0]; 10 | } 11 | 12 | public int[] evaluateExpression(String exp) { 13 | String[] tokens = exp.split("(?=[-+])"); 14 | int[] res = new int[2]; 15 | for (String token : tokens) { 16 | if (token.equals("+x") || token.equals("x")) res[0] += 1; 17 | else if (token.equals("-x")) res[0] -= 1; 18 | else if (token.contains("x")) res[0] += Integer.parseInt(token.substring(0, token.indexOf("x"))); 19 | else res[1] += Integer.parseInt(token); 20 | } 21 | return res; 22 | } -------------------------------------------------------------------------------- /leetcode_daily/334.md: -------------------------------------------------------------------------------- 1 | [334](https://leetcode.com/problems/increasing-triplet-subsequence/) Increasing Triplet Subsequence 2 | 3 | Interesting `DP` solution. Need to think about how to get the best solution. 4 | 5 | ```python 6 | # brute force is O(n3) 7 | # you will notice that if you already found a small number, you can always use it as the first number. Then you can save the minimum when passing through the list. The same idea for the second and the third numbers. Time complexity O(n) 8 | class Solution: 9 | def increasingTriplet(self, nums: 'List[int]') -> 'bool': 10 | one = float("inf") 11 | two = float("inf") 12 | three = float("inf") 13 | for n in nums: 14 | if n <= one: 15 | one = n 16 | elif n <= two: 17 | two = n 18 | elif n <= three: 19 | return True 20 | return False 21 | 22 | 23 | ``` -------------------------------------------------------------------------------- /leetcode/447_Number_of_Boomeranges.java: -------------------------------------------------------------------------------- 1 | // 2017.08.20 2 | class Solution { 3 | public int numberOfBoomerangs(int[][] points) { 4 | int res = 0; 5 | 6 | Map map = new HashMap<>(); 7 | for(int i = 0; i < points.length; i++) { 8 | for(int j = 0; j < points.length; j++) { 9 | if(i == j) 10 | continue; 11 | int d = getDistance(points[i], points[j]); 12 | map.put(d, map.getOrDefault(d, 0) + 1); 13 | } 14 | 15 | for(int val : map.values()) { 16 | res += val * (val-1); 17 | } 18 | map.clear(); 19 | } 20 | 21 | return res; 22 | } 23 | 24 | private int getDistance(int[] a, int[] b) { 25 | int dx = a[0] - b[0]; 26 | int dy = a[1] - b[1]; 27 | return dx * dx + dy * dy; 28 | } 29 | } -------------------------------------------------------------------------------- /lintcode/lintcode_076_Longest_Increasing_Subsequence.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/longest-increasing-subsequence/ 2 | // 九章算法,包含一个二分法思路 3 | // http://www.jiuzhang.com/solution/longest-increasing-subsequence/ 4 | public class Solution { 5 | /** 6 | * @param nums: The integer array 7 | * @return: The length of LIS (longest increasing subsequence) 8 | */ 9 | public int longestIncreasingSubsequence(int[] nums) { 10 | int []f = new int[nums.length]; 11 | int max = 0; 12 | for (int i = 0; i < nums.length; i++) { 13 | f[i] = 1; 14 | for (int j = 0; j < i; j++) { 15 | if (nums[j] < nums[i]) { 16 | f[i] = f[i] > f[j] + 1 ? f[i] : f[j] + 1; 17 | } 18 | } 19 | if (f[i] > max) { 20 | max = f[i]; 21 | } 22 | } 23 | return max; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/116_Populating_Next_Right_Pointers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree with next pointer. 3 | * public class TreeLinkNode { 4 | * int val; 5 | * TreeLinkNode left, right, next; 6 | * TreeLinkNode(int x) { val = x; } 7 | * } 8 | */ 9 | // 12.12 重新练习 10 | public class Solution { 11 | public void connect(TreeLinkNode root) { 12 | TreeLinkNode level_start = root; 13 | while (level_start != null){ 14 | TreeLinkNode cur = level_start; 15 | while (cur != null){ 16 | // 连接左右子树 17 | if(cur.left != null) 18 | cur.left.next = cur.right; 19 | // 连接右子树和顺延的下一个 20 | if(cur.right != null && cur.next != null) 21 | cur.right.next = cur.next.left; 22 | cur = cur.next; 23 | } 24 | level_start = level_start.left; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /leetcode/541_Reverse_String_II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Athor: Xingxing Huang 3 | * @Date: 2017.04.13 4 | * @Time: 注意String的操作方法, 5 | * s.length() 6 | * char[] chars = s.toCharArray(); 7 | * String.valueOf(chars); 8 | */ 9 | public class Solution { 10 | public String reverseStr(String s, int k) { 11 | if (s == null || s.length() <= 1) { 12 | return s; 13 | } 14 | char[] chars = s.toCharArray(); 15 | for (int i = 0; i < chars.length;) { 16 | int end = Math.min(i + k - 1, chars.length - 1); 17 | reverse(chars, i, end); 18 | i += 2 * k; 19 | } 20 | return String.valueOf(chars); 21 | } 22 | public void reverse(char[] chars, int start, int end) { 23 | for (int i = start, j = end; i < j; i++, j--) { 24 | char ch = chars[i]; 25 | chars[i] = chars[j]; 26 | chars[j] = ch; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /lintcode/lintcode_053_Reverse_Words_String.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 注意空格的处理,可以参照leetcode 151 用stack方法逆序 3 | * @author Xingxing Huang 4 | * @since 2017.04.30 5 | * @Time O(n), 6 | * @param 7 | * @return 8 | */ 9 | 10 | public class Solution { 11 | /** 12 | * @param s : A string 13 | * @return : A string 14 | */ 15 | public String reverseWords(String s) { 16 | // write your code 17 | if (s == null || s.length() == 0) { 18 | return ""; 19 | } 20 | 21 | String[] array = s.split(" "); 22 | StringBuilder sb = new StringBuilder(); 23 | 24 | for (int i = array.length - 1; i >= 0; --i) { 25 | if (!array[i].equals("")) { 26 | sb.append(array[i]).append(" "); 27 | } 28 | } 29 | 30 | //remove the last " " 31 | return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/204_Count_Primes.java: -------------------------------------------------------------------------------- 1 | // 9.20 2 | // 1 is not a prime number, 质数 3 | class Solution { 4 | public int countPrimes(int n) { 5 | int count = 0; 6 | boolean[] dp = new boolean[n + 1]; 7 | for (int i = 2; i < n; i++) { 8 | if (dp[i]) continue; 9 | count++; 10 | for (int j = 2; j*i < n; j++) { 11 | dp[i*j] = true; 12 | } 13 | } 14 | return count; 15 | } 16 | } 17 | 18 | 19 | public class Solution { 20 | public int countPrimes(int n) { 21 | boolean[] notPrime = new boolean[n]; 22 | int count = 0; 23 | for (int i = 2; i < n; i++) { 24 | if (notPrime[i] == false) { 25 | count++; 26 | for (int j = 2; i*j < n; j++) { 27 | notPrime[i*j] = true; 28 | } 29 | } 30 | } 31 | 32 | return count; 33 | } 34 | } -------------------------------------------------------------------------------- /leetcode/040_Combination_Sum_II.java: -------------------------------------------------------------------------------- 1 | // 10.24 DFS 2 | // 注意相同元素的情况 3 | class Solution { 4 | public List> combinationSum2(int[] cand, int target) { 5 | Arrays.sort(cand); 6 | List> res = new ArrayList>(); 7 | List path = new ArrayList(); 8 | dfs_com(cand, 0, target, path, res); 9 | return res; 10 | } 11 | void dfs_com(int[] cand, int cur, int target, List path, List> res) { 12 | if (target == 0) { 13 | res.add(new ArrayList(path)); 14 | return ; 15 | } 16 | if (target < 0) return; 17 | for (int i = cur; i < cand.length; i++){ 18 | if (i > cur && cand[i] == cand[i-1]) continue; 19 | path.add(path.size(), cand[i]); 20 | dfs_com(cand, i+1, target - cand[i], path, res); 21 | path.remove(path.size()-1); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/111_Minimum_Depth_Binary_Tree.java: -------------------------------------------------------------------------------- 1 | // Author: Xingxing Huang 2 | // Data: 2017/03/24 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode(int x) { val = x; } 10 | * } 11 | */ 12 | public class Solution { 13 | public int minDepth(TreeNode root) { 14 | if (root == null) { 15 | return 0; 16 | } 17 | // This calculate the min depth 18 | // if (root.left == null || root.right == null) { 19 | // return 1; 20 | // } 21 | // return Math.min(minDepth(root.left), minDepth(root.right)) + 1; 22 | int left = minDepth(root.left); 23 | int right = minDepth(root.right); 24 | if (left == 0 || right == 0) { 25 | return left + right + 1; 26 | } else { 27 | return Math.min(left, right) + 1; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /leetcode/283_Move_Zeros.java: -------------------------------------------------------------------------------- 1 | // 2017.07.29 2 | public class Solution { 3 | public void moveZeroes(int[] nums) { 4 | if (nums == null || nums.length <= 1) { 5 | return; 6 | } 7 | int i = 0; 8 | for (int j = 0; j < nums.length; j++) { 9 | if (nums[j] != 0) { 10 | nums[i] = nums[j]; 11 | if (j > i) { 12 | nums[j] = 0; 13 | } 14 | i++; 15 | } 16 | } 17 | } 18 | } 19 | 20 | // you can just swap the numbers in position of i and j. 21 | public class Solution{ 22 | public void moveZeroes(int[] nums) { 23 | int j = 0; 24 | for(int i = 0; i < nums.length; i++) { 25 | if(nums[i] != 0) { 26 | int temp = nums[j]; 27 | nums[j] = nums[i]; 28 | nums[i] = temp; 29 | j++; 30 | } 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /leetcode/467_Unique_Substring_in_Wraparound_String.java: -------------------------------------------------------------------------------- 1 | // 10.05 2 | // @Xingxing 3 | // 很容易想到暴力方法,找出所有连续的子串,然后统计子串的个数。但是不同的连续子串会有重复的子串出现,不能直接用数学的方法快速计算结果。 4 | // 这里用了一个很巧妙的方法,对于每个连续子串,我们只需要标记以某个元素结尾的最长连续子串。这样我们就可以记录所有连续子串的情形。 5 | // 有了这个存储方式就可以很容易计算不一样子串的数量,即将记录的以某一字母结尾子串长度相加求和即可。 6 | class Solution { 7 | public int findSubstringInWraproundString(String p) { 8 | int count = 0; 9 | Map map = new HashMap<>(); 10 | for (int i = 0; i < p.length(); i++) { 11 | if (count == 0 || p.charAt(i) == p.charAt(i-1) + 1 || (p.charAt(i) == 'a' && p.charAt(i-1) == 'z')) { 12 | count++; 13 | } else { 14 | count = 1; 15 | } 16 | map.put(p.charAt(i), Math.max(map.getOrDefault(p.charAt(i), 0), count)); 17 | } 18 | int res = 0; 19 | for (char c: map.keySet()) 20 | res += map.get(c); 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode/513_Find_Bottom_Left_Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Author: Xingxing Huang 3 | * @Date: 2017.04.13 4 | * @Time: O(n), BFS遍历,但是遍历的时候注意进出栈顺序即可。 5 | * 每次只需要记录一个节点即可,出队列的最后一个元素即为最左元素 6 | */ 7 | /** 8 | * Definition for a binary tree node. 9 | * public class TreeNode { 10 | * int val; 11 | * TreeNode left; 12 | * TreeNode right; 13 | * TreeNode(int x) { val = x; } 14 | * } 15 | */ 16 | public class Solution { 17 | public int findBottomLeftValue(TreeNode root) { 18 | Queue queue = new LinkedList(); 19 | TreeNode node = root; 20 | queue.offer(root); 21 | while (!queue.isEmpty()) { 22 | node = queue.poll(); 23 | if (node.right != null) { 24 | queue.offer(node.right); 25 | } 26 | if (node.left != null) { 27 | queue.offer(node.left); 28 | } 29 | } 30 | return node.val; 31 | } 32 | } -------------------------------------------------------------------------------- /leetcode/606_Construct_String_From_Binary_Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | // 10.10 11 | // Tree tranverse 12 | class Solution { 13 | public String tree2str(TreeNode t) { 14 | if (t == null) return ""; 15 | StringBuilder sb = new StringBuilder(""); 16 | sb.append("" + t.val); 17 | if (t.left == null && t.right == null) { 18 | return sb.toString(); 19 | } 20 | // if (t.left != null) { 21 | sb.append("("); 22 | sb.append(tree2str(t.left)); 23 | sb.append(")"); 24 | // } 25 | if (t.right != null) { 26 | sb.append("("); 27 | sb.append(tree2str(t.right)); 28 | sb.append(")"); 29 | } 30 | return sb.toString(); 31 | } 32 | } -------------------------------------------------------------------------------- /leetcode_daily/650.md: -------------------------------------------------------------------------------- 1 | [650](https://leetcode.com/problems/2-keys-keyboard/) 2 keys keyboard 2 | 3 | 4 | 5 | ```python 6 | class Solution(object): 7 | def minSteps(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | ans = 0 13 | d = 2 14 | while n > 1: 15 | while n % d == 0: 16 | ans += d 17 | n /= d 18 | d += 1 19 | return ans 20 | ``` 21 | 22 | 23 | DP method 24 | 25 | ```python 26 | class Solution(object): 27 | def minSteps(self, n): 28 | """ 29 | :type n: int 30 | :rtype: int 31 | """ 32 | dp = [0 for i in range(n + 1)] 33 | for i in range(2, n + 1): 34 | dp[i] = i 35 | for j in range(i - 1, 1, -1): 36 | if i % j == 0: 37 | dp[i] = dp[j] + i //j 38 | break 39 | return dp[n] 40 | ``` -------------------------------------------------------------------------------- /leetcode_daily/978.md: -------------------------------------------------------------------------------- 1 | ```python 2 | class Solution: 3 | def maxTurbulenceSize(self, A): 4 | """ 5 | :type A: List[int] 6 | :rtype: int 7 | """ 8 | if len(A) == 1: 9 | return 1 10 | pre = None 11 | res = -1 12 | count = 1 13 | for i in range(1, len(A)): 14 | if A[i] > A[i - 1]: 15 | sign = 1 16 | elif A[i] == A[i - 1]: 17 | sign = 0 18 | else: 19 | sign = -1 20 | 21 | if (pre == None and sign != 0) or (pre is not None and pre*sign == -1): 22 | count += 1 23 | res = max(res, count) 24 | elif sign == 0: 25 | count = 1 26 | else: 27 | count = 2 28 | # print(res, count, sign) 29 | pre = sign 30 | return res 31 | 32 | 33 | ``` 34 | -------------------------------------------------------------------------------- /lintcode/lintcode_001_A+B+Problem.java: -------------------------------------------------------------------------------- 1 | //https://www.lintcode.com/en/problem/a-b-problem/ 2 | //http://www.jiuzhang.com/solutions/a-b-problem/ 3 | class Solution { 4 | /* 5 | * param a: The first integer 6 | * param b: The second integer 7 | * return: The sum of a and b 8 | */ 9 | public int aplusb(int a, int b) { 10 | // 主要利用异或运算来完成 11 | // 异或运算有一个别名叫做:不进位加法 12 | // 那么a ^ b就是a和b相加之后,该进位的地方不进位的结果 13 | // 然后下面考虑哪些地方要进位,自然是a和b里都是1的地方 14 | // a & b就是a和b里都是1的那些位置,a & b << 1 就是进位 15 | // 之后的结果。所以:a + b = (a ^ b) + (a & b << 1) 16 | // 令a' = a ^ b, b' = (a & b) << 1 17 | // 可以知道,这个过程是在模拟加法的运算过程,进位不可能 18 | // 一直持续,所以b最终会变为0。因此重复做上述操作就可以 19 | // 求得a + b的值。 20 | while (b != 0) { 21 | int _a = a ^ b; 22 | int _b = (a & b) << 1; 23 | a = _a; 24 | b = _b; 25 | } 26 | return a; 27 | } 28 | }; -------------------------------------------------------------------------------- /leetcode/507_Perfect_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean checkPerfectNumber(int num) { 3 | if (num <= 0) return false; 4 | int sum = 0; 5 | for (int i = 1; i*i <= num; i++) { 6 | if (num % i == 0) { 7 | sum += i; 8 | if (i*i != num) 9 | sum += num / i; 10 | } 11 | } 12 | return sum - num == num; 13 | } 14 | } 15 | 16 | // Euclid proved that 2p−1(2p−1)2p−1(2p−1) is an even perfect number whenever 2p−12p−1 is prime, where pp is prime. 17 | public class Solution { 18 | public int pn(int p) { 19 | return (1 << (p - 1)) * ((1 << p) - 1); 20 | } 21 | public boolean checkPerfectNumber(int num) { 22 | int[] primes=new int[]{2,3,5,7,13,17,19,31}; 23 | for (int prime: primes) { 24 | if (pn(prime) == num) 25 | return true; 26 | } 27 | return false; 28 | } 29 | } -------------------------------------------------------------------------------- /leetcode_daily/101.md: -------------------------------------------------------------------------------- 1 | [101](https://leetcode.com/problems/symmetric-tree/) Symmetric Tree 2 | 3 | ```python 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def isSymmetric(self, root: TreeNode) -> bool: 13 | if root is None: 14 | return True 15 | return self.check(root.left, root.right) 16 | 17 | def check(self, node1, node2): 18 | if node1 is None and node2 is None: 19 | return True 20 | elif node1 is None or node2 is None: 21 | return False 22 | elif node1.val != node2.val: 23 | return False 24 | if not self.check(node1.left, node2.right): 25 | return False 26 | if not self.check(node1.right, node2.left): 27 | return False 28 | return True 29 | ``` -------------------------------------------------------------------------------- /leetcode/239_Sliding_Window_Maximum.java: -------------------------------------------------------------------------------- 1 | // 09.22 2 | // the best solution has O(n) 3 | // Use deque to store the index, but should be clever how to input and output number 4 | class Solution { 5 | public int[] maxSlidingWindow(int[] nums, int k) { 6 | if (nums == null || nums.length == 0 || k <= 0) 7 | return new int[0]; 8 | int len = nums.length; 9 | int[] res = new int[len - k + 1]; 10 | Deque dq = new ArrayDeque<>(); 11 | int idx = 0; 12 | for (int i = 0; i < len; i++) { 13 | while (!dq.isEmpty() && dq.peek() < i - k + 1) // poll n out of range 14 | dq.poll(); 15 | while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) // poll n lower than current 16 | dq.pollLast(); 17 | dq.offer(i); 18 | if (i >= k - 1) 19 | res[idx++] = nums[dq.peek()]; 20 | } 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode/667_Beautiful_Arrangement_II.java: -------------------------------------------------------------------------------- 1 | // python 2 | class Solution: 3 | def constructArray(self, n, k): 4 | """ 5 | :type n: int 6 | :type k: int 7 | :rtype: List[int] 8 | """ 9 | from functools import reduce 10 | return list(reduce(lambda x, y: x + y, [[i, k+2-i] for i in range(1, (k+1) // 2 + 1)])) + ([] if k % 2 != 0 else [k // 2 + 1]) + list(range(k+2, n+1)) 11 | 12 | // python 13 | class Solution: 14 | def constructArray(self, n, k): 15 | l, r, res = 2, n, [1] 16 | for _ in range(k - 1): 17 | if len(res) & 1: 18 | res.append(r) 19 | r -= 1 20 | else: 21 | res.append(l) 22 | l += 1 23 | if len(res) & 1: 24 | res.extend(range(l, r + 1)) 25 | else: 26 | res.extend(range(r, l - 1, -1)) 27 | return res 28 | 29 | 30 | // java 31 | -------------------------------------------------------------------------------- /leetcode/151_Reverse_Words_in_String.java: -------------------------------------------------------------------------------- 1 | // 黄xing 2 | public class Solution { 3 | public String reverseWords(String s) { 4 | // 用栈存储字符串,空格分割 5 | Stack stack = new Stack(); 6 | for (int i = 0; i < s.length(); i++) { 7 | if (s.charAt(i) == ' ') { 8 | continue; 9 | } else { 10 | while (s.charAt(i) == " ") {i++;} 11 | int j = i; 12 | while (i < s.length() && s.charAt(i) != ' ') {i++;} 13 | stack.push(" " ); 14 | stack.push(s.substring(j, i)); 15 | } 16 | } 17 | // 从栈中取出字符串达到reverse的目的 18 | if (stack.isEmpty()) { 19 | return ""; 20 | } 21 | StringBuilder out = new StringBuilder(); 22 | while (!stack.isEmpty()) { 23 | out.append(stack.pop()); 24 | } 25 | return out.deleteCharAt(out.length() - 1).toString(); 26 | } 27 | } -------------------------------------------------------------------------------- /lintcode/lintcode_009_two_string.java: -------------------------------------------------------------------------------- 1 | // @Author 黄xing 2 | // O(n), O(1) 3 | // ASCII http://images2015.cnblogs.com/blog/822124/201608/822124-20160819180928718-882826750.jpg 4 | public class Solution { 5 | /** 6 | * @param s: The first string 7 | * @param b: The second string 8 | * @return true or false 9 | */ 10 | public boolean anagram(String s, String t) { 11 | // write your code here 12 | if (s.length() != t.length()) { 13 | return false; 14 | } 15 | int[] helper = new int[128]; 16 | for (int i = 0; i < s.length(); i++) { 17 | helper[s.charAt(i) - ' ']++; 18 | } 19 | for (int j = 0; j < t.length(); j++) { 20 | helper[t.charAt(j) - ' ']--; 21 | } 22 | for (int i = 0; i < helper.length; i++) { 23 | if (helper[i] != 0) { 24 | return false; 25 | } 26 | } 27 | return true; 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/278_First_Bad_Version.java: -------------------------------------------------------------------------------- 1 | // @Author: 黄xing 2 | // Time: O(log N) 3 | 4 | /* The isBadVersion API is defined in the parent class VersionControl. 5 | boolean isBadVersion(int version); */ 6 | 7 | public class Solution extends VersionControl { 8 | public int firstBadVersion(int n) { 9 | if (!isBadVersion(n)) { 10 | return -1; 11 | } 12 | int i = 1; 13 | int j = n; 14 | while (i < j) { 15 | //int mid = i + (j - i) / 2; // yes 16 | //int mid = (i + j) / 2; // no 溢出 17 | //int mid = (i + j) >>> 1; // yes 18 | //int mid = (i + j) >> 1; // no 溢出 19 | int mid = i + ((j - i) >> 1); // yes 位移优先级低于加减 20 | //int mid = i + (j - i) >>> 1; // no 21 | if (isBadVersion(mid)) { 22 | j = mid; 23 | } else { 24 | i = mid + 1; 25 | } 26 | } 27 | return i; 28 | } 29 | } -------------------------------------------------------------------------------- /leetcode_daily/198.md: -------------------------------------------------------------------------------- 1 | [198](https://leetcode.com/problems/house-robber/) 2 | 3 | Easy dp, but good for practice. Need to pass with bug free 4 | 5 | ```python 6 | class Solution(object): 7 | def rob(self, nums): 8 | """ 9 | :type nums: List[int] 10 | :rtype: int 11 | """ 12 | n = len(nums) 13 | dp = [0 for i in range(n + 1)] 14 | for i in range(n): 15 | if i == 0: 16 | dp[i + 1] = nums[0] 17 | if i - 1 >= 0: 18 | dp[i + 1] = max(dp[i], dp[i - 1] + nums[i]) 19 | if i - 2 >= 0: 20 | dp[i + 1] = max(dp[i + 1], dp[i - 2] + nums[i]) 21 | res = max(dp[n], dp[n - 1]) 22 | return res 23 | ``` 24 | 25 | 26 | Very short python solution 27 | 28 | ```python 29 | class Solution: 30 | def rob(self, nums): 31 | last, now = 0, 0 32 | for i in nums: last, now = now, max(last + i, now) 33 | return now 34 | ``` -------------------------------------------------------------------------------- /leetcode_daily/473.md: -------------------------------------------------------------------------------- 1 | [473](https://leetcode.com/problems/matchsticks-to-square/) Matchsticks to Square 2 | 3 | 4 | Depth First Search 5 | 6 | ```python 7 | class Solution: 8 | def makesquare(self, nums: List[int]) -> bool: 9 | if len(nums) < 4: 10 | return False 11 | total = sum(nums) 12 | if total % 4 != 0: 13 | return False 14 | nums = sorted(nums, reverse=True) 15 | return dfs(nums, [0]*4, 0, total//4) 16 | 17 | def dfs(nums, sums, idx, total): 18 | if idx == len(nums): 19 | return sums[0] == total and sums[1] == total and sums[2] == total 20 | for i in range(4): 21 | if sums[i] + nums[idx] > total: 22 | continue 23 | sums[i] += nums[idx] 24 | if dfs(nums, sums, idx + 1, total): 25 | return True 26 | sums[i] -= nums[idx] 27 | return False 28 | 29 | 30 | ``` 31 | 32 | DP 33 | 34 | ```python 35 | ``` 36 | -------------------------------------------------------------------------------- /leetcode/242_Valid_Anagrame.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isAnagram(String s, String t) { 3 | if (s.length() != t.length()) 4 | return false; 5 | Map map = new HashMap<>(); 6 | for (int i = 0; i < s.length(); i++) { 7 | char a = s.charAt(i); 8 | char b = t.charAt(i); 9 | map.put(a, map.getOrDefault(a, 0) + 1); 10 | map.put(b, map.getOrDefault(b, 0) - 1); 11 | } 12 | for (Character key : map.keySet()) 13 | if (map.get(key) != 0) return false; 14 | return true; 15 | } 16 | } 17 | 18 | // use sort method, only O(1) space 19 | public boolean isAnagram(String s, String t) { 20 | if (s.length() != t.length()) { 21 | return false; 22 | } 23 | char[] str1 = s.toCharArray(); 24 | char[] str2 = t.toCharArray(); 25 | Arrays.sort(str1); 26 | Arrays.sort(str2); 27 | return Arrays.equals(str1, str2); 28 | } -------------------------------------------------------------------------------- /leetcode/690_Employee_Importance.java: -------------------------------------------------------------------------------- 1 | /* 2 | // Employee info 3 | class Employee { 4 | // It's the unique id of each node; 5 | // unique id of this employee 6 | public int id; 7 | // the importance value of this employee 8 | public int importance; 9 | // the id of direct subordinates 10 | public List subordinates; 11 | }; 12 | */ 13 | 14 | // 0929 15 | // recursive DFS 16 | class Solution { 17 | private Set set = new HashSet<>(); 18 | public int getImportance(List employees, int id) { 19 | int val = 0; 20 | if (set.contains(id)) return 0; 21 | for (Employee em : employees) { 22 | if (em.id == id) { 23 | val += em.importance; 24 | for (int subid : em.subordinates) { 25 | val += getImportance(employees, subid); 26 | } 27 | return val; 28 | } 29 | } 30 | return val; 31 | } 32 | } -------------------------------------------------------------------------------- /lintcode/lintcode_365_count_1.java: -------------------------------------------------------------------------------- 1 | // @Author: Xingxing Huang 2 | // O(m) 3 | public class Solution { 4 | /** 5 | * @param num: an integer 6 | * @return: an integer, the number of ones in num 7 | */ 8 | public int countOnes(int num) { 9 | // write your code here 10 | int count = 0; 11 | while (num != 0) { 12 | num = num & (num - 1); 13 | count++; 14 | } 15 | return count; 16 | } 17 | }; 18 | 19 | 20 | // @Author: Xingxing Huang 21 | // O(n) 22 | public class Solution { 23 | /** 24 | * @param num: an integer 25 | * @return: an integer, the number of ones in num 26 | */ 27 | public int countOnes(int num) { 28 | // write your code here 29 | int count = 0; 30 | while (num != 0) { 31 | if ((num & 1) == 1) { 32 | count++; 33 | } 34 | num >>>= 1; 35 | } 36 | return count; 37 | } 38 | }; -------------------------------------------------------------------------------- /leetcode/206_Reverse_Linked_List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode reverseList(ListNode head) { 11 | ListNode dummy = new ListNode(0); 12 | while (head != null) { 13 | ListNode node = dummy.next; 14 | dummy.next = head; 15 | head = head.next; 16 | dummy.next.next = node; 17 | } 18 | return dummy.next; 19 | } 20 | } 21 | 22 | //recursive 23 | public ListNode reverseList(ListNode head) { 24 | /* recursive solution */ 25 | return reverseListInt(head, null); 26 | } 27 | 28 | private ListNode reverseListInt(ListNode head, ListNode newHead) { 29 | if (head == null) 30 | return newHead; 31 | ListNode next = head.next; 32 | head.next = newHead; 33 | return reverseListInt(next, head); 34 | } -------------------------------------------------------------------------------- /leetcode/343_Integer_Break.java: -------------------------------------------------------------------------------- 1 | // 2017.08.07 @XingxingHuang 2 | // Attention for the state transfer method. 3 | public class Solution { 4 | public int integerBreak(int n) { 5 | int[] dp = new int[n + 1]; 6 | dp[1] = 1; 7 | for (int i = 2; i <= n; i++) { 8 | for (int j = 1; j <= (i + 1) / 2; j++) { 9 | dp[i] = Math.max(dp[i], Math.max(dp[j], j) * Math.max(dp[i - j], i - j)); 10 | } 11 | } 12 | return dp[n]; 13 | } 14 | } 15 | 16 | // can also use math 17 | 18 | public class Solution { 19 | public int integerBreak(int n) { 20 | if(n == 2) 21 | return 1; 22 | else if(n == 3) 23 | return 2; 24 | else if(n%3 == 0) 25 | return (int)Math.pow(3, n/3); 26 | else if(n%3 == 1) 27 | return 2 * 2 * (int) Math.pow(3, (n - 4) / 3); 28 | else 29 | return 2 * (int) Math.pow(3, n/3); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /leetcode/656_hard_Coin_Path.py: -------------------------------------------------------------------------------- 1 | # lee215 2 | class Solution(object): 3 | def cheapestJump(self, A, B): 4 | """ 5 | :type A: List[int] 6 | :type B: int 7 | :rtype: List[int] 8 | """ 9 | if not A or A[0] == -1: 10 | return [] 11 | dp = [[float('inf')] for i in A] 12 | dp[0] = [A[0], 1] 13 | N = len(A) 14 | 15 | for i in range(N): 16 | if A[i] == -1: 17 | continue 18 | for j in range(i + 1, min(N, i + B + 1)): 19 | if A[j] == -1: 20 | continue 21 | if dp[i][0] + A[j] < dp[j][0]: 22 | dp[j] = [dp[i][0] + A[j]] + dp[i][1:] + [j + 1] 23 | if dp[i][0] + A[j] == dp[j][0]: 24 | path = dp[i][1:] + [j + 1] 25 | if path < dp[j][1:]: 26 | dp[j] = [dp[i][0] + A[j]] + dp[i][1:] + [j + 1] 27 | return dp[-1][1:] -------------------------------------------------------------------------------- /lintcode/lintcode_068_post_order_tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition of TreeNode: 3 | * public class TreeNode { 4 | * public int val; 5 | * public TreeNode left, right; 6 | * public TreeNode(int val) { 7 | * this.val = val; 8 | * this.left = this.right = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | /** 14 | * @param root: The root of binary tree. 15 | * @return: Postorder in ArrayList which contains node values. 16 | */ 17 | public ArrayList postorderTraversal(TreeNode root) { 18 | // write your code here 19 | ArrayList res = new ArrayList(); 20 | postTravel(root, res); 21 | return res; 22 | } 23 | public void postTravel(TreeNode root, ArrayList res) { 24 | if (root != null) { 25 | postTravel(root.left, res); 26 | postTravel(root.right, res); 27 | res.add(root.val); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /leetcode/458_Poor_Pigs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 3 | int status = minutesToTest/minutesToDie + 1; 4 | int num_of_pig = 0; 5 | while(Math.pow(status, num_of_pig) < buckets) {num_of_pig++;} 6 | return num_of_pig; 7 | } 8 | } 9 | 10 | // 09.24 11 | // buckets: number of buckets 12 | // minutesToDie: time for each test 13 | // minutesToTest: total time. 14 | // Then, we can only test limited round, n = minutesToTest / minutesToDie. 15 | //In general, we can solve up to (⌊minutesToTest / minutesToDie⌋ + 1)^pigs buckets 16 | 17 | //// This is WRONG !!!! 18 | // 1st round we can use m pig to test m + 1 groups of buckets, we left 1 group with poison and m - 1 pigs. 19 | // 2st round, m - 1 pigs to test m groups, and left m - 2 pigs. 20 | // ... 21 | // last round, 1 pig to test 2 bucket, got the poison one. 22 | // We can think in reversed order. Then total bucket we can check is 23 | 24 | -------------------------------------------------------------------------------- /lintcode/lintcode_056_Two_Sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 注意hashmap的使用 3 | * @author Xingxing Huang 4 | * @since 2017.04.30 5 | * @Time O(n), 6 | * @param 7 | * @return 8 | */ 9 | public class Solution { 10 | /* 11 | * @param numbers : An array of Integer 12 | * @param target : target = numbers[index1] + numbers[index2] 13 | * @return : [index1 + 1, index2 + 1] (index1 < index2) 14 | numbers=[2, 7, 11, 15], target=9 15 | return [1, 2] 16 | */ 17 | public int[] twoSum(int[] numbers, int target) { 18 | HashMap map = new HashMap<>(); 19 | 20 | for (int i = 0; i < numbers.length; i++) { 21 | if (map.get(numbers[i]) != null) { 22 | int[] result = {map.get(numbers[i]) + 1, i + 1}; 23 | return result; 24 | } 25 | map.put(target - numbers[i], i); 26 | } 27 | 28 | int[] result = {}; 29 | return result; 30 | } 31 | } -------------------------------------------------------------------------------- /leetcode/039_Combination_Sum.java: -------------------------------------------------------------------------------- 1 | // 10.20 backtracking 2 | 3 | public class Solution { 4 | public List> combinationSum(int[] candidates, int target) { 5 | Arrays.sort(candidates); 6 | List> result = new ArrayList>(); 7 | getResult(result, new ArrayList(), candidates, target, 0); 8 | 9 | return result; 10 | } 11 | 12 | private void getResult(List> result, List cur, int candidates[], int target, int start){ 13 | if(target > 0){ 14 | for(int i = start; i < candidates.length && target >= candidates[i]; i++){ 15 | cur.add(candidates[i]); 16 | getResult(result, cur, candidates, target - candidates[i], i); 17 | cur.remove(cur.size() - 1); 18 | }//for 19 | }//if 20 | else if(target == 0 ){ 21 | result.add(new ArrayList(cur)); 22 | }//else if 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/268_Missing_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int missingNumber(int[] nums) { //sum 3 | int len = nums.length; 4 | int sum = (0+len)*(len+1)/2; 5 | for(int i=0; imid) right = mid; 31 | else left = mid+1; 32 | } 33 | return left; 34 | } -------------------------------------------------------------------------------- /leetcode_daily/1010.md: -------------------------------------------------------------------------------- 1 | [1010](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/) Pairs of Songs With Total Durations Divisible by 60 2 | 3 | ```python 4 | class Solution: 5 | def numPairsDivisibleBy60(self, time: List[int]) -> int: 6 | mem = {} 7 | res = 0 8 | for t in time: 9 | ans = t % 60 10 | if ans == 0: 11 | res += mem.get(0, 0) 12 | elif 60 - ans in mem: 13 | res += mem[60 - ans] 14 | mem[ans] = mem.get(ans, 0) + 1 15 | return res 16 | ``` 17 | 18 | lee215 [solution](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/256738/JavaC%2B%2BPython-Two-Sum-with-K-60) 19 | 20 | ```python 21 | def numPairsDivisibleBy60(self, time): 22 | c = collections.Counter() 23 | res = 0 24 | for t in time: 25 | res += c[-t % 60] 26 | c[t % 60] += 1 27 | return res 28 | ``` -------------------------------------------------------------------------------- /leetcode_daily/290.md: -------------------------------------------------------------------------------- 1 | [290](https://leetcode.com/problems/word-pattern/) word pattern 2 | 3 | ```python 4 | class Solution(object): 5 | def wordPattern(self, pattern, str): 6 | """ 7 | :type pattern: str 8 | :type str: str 9 | :rtype: bool 10 | """ 11 | str_map = {} 12 | pat_map = {} 13 | str_array = str.split() 14 | if len(str_array) != len(pattern): 15 | return False 16 | for i, s in enumerate(str_array): 17 | if str_map.get(s, -1) != pat_map.get(pattern[i], -1): 18 | return False 19 | str_map[s] = pat_map[pattern[i]] = i 20 | return True 21 | ``` 22 | 23 | Very short python [solution](https://leetcode.com/problems/word-pattern/discuss/73433/Short-in-Python) 24 | 25 | ```python 26 | def wordPattern(self, pattern, str): 27 | s = pattern 28 | t = str.split() 29 | return len(set(zip(s, t))) == len(set(s)) == len(set(t)) and len(s) == len(t) 30 | ``` -------------------------------------------------------------------------------- /leetcode/184_Department_Highest_Salary.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT d.Name as Department, e.Name as Employee, e.salary as Salary 3 | FROM Employee as e 4 | JOIN Department as d on e.DepartmentId = d.Id 5 | where e.salary >= ALL(Select e2.salary from Employee as e2 where e.DepartmentId = e2.DepartmentId) 6 | # WHERE e.salary >= (SELECT MAX(salary) from Employee as e2 where e.DepartmentId = e2.DepartmentId) 7 | 8 | 9 | # # wrong anwser 10 | # SELECT d.Name as 'Department', e.Name as Employee, e.salary as Salary 11 | # FROM Employee as e 12 | # JOIN Department as d on e.DepartmentId = d.Id 13 | # JOIN Employee as e2 on e.DepartmentId = e2.DepartmentId 14 | # where (e.salary >= e2.salary) 15 | 16 | 17 | # 1 1000 5 1 * 18 | # 2 19 | # 3 20 | # 2 2000 5 1 * 21 | # 2 * 22 | # 3 23 | # 3 3000 5 1 * 24 | # 2 * 25 | # 3 * 26 | -------------------------------------------------------------------------------- /leetcode_daily/229.md: -------------------------------------------------------------------------------- 1 | [229](https://leetcode.com/problems/majority-element-ii/) Majority Element II 2 | 3 | classic algorithm called `Boyer-Moore Majority Vote algorithm`. Check the discussions to understand how it works. 4 | 5 | ```python 6 | # Boyer-Moore Majority Vote algorithm 7 | class Solution: 8 | def majorityElement(self, nums: 'List[int]') -> 'List[int]': 9 | c1, c2, num1, num2 = 0, 0, 0, 1 10 | for n in nums: 11 | if n == num1: 12 | c1 += 1 13 | elif n == num2: 14 | c2 += 1 15 | elif c1 == 0: 16 | num1, c1 = n, 1 17 | elif c2 == 0: 18 | num2, c2 = n, 1 19 | else: 20 | c1 -= 1 21 | c2 -= 1 22 | res = [] 23 | if nums.count(num1) > len(nums) // 3: 24 | res.append(num1) 25 | if nums.count(num2) > len(nums) // 3: 26 | res.append(num2) 27 | return res 28 | 29 | ``` -------------------------------------------------------------------------------- /leetcode_daily/1016.md: -------------------------------------------------------------------------------- 1 | [1016](https://leetcode.com/contest/weekly-contest-129/problems/binary-string-with-substrings-representing-1-to-n/) Binary String With Substrings Representing 1 To N 2 | 3 | 4 | 5 | ```python 6 | class Solution: 7 | def queryString(self, S: str, N: int) -> bool: 8 | mem = set([]) 9 | for n in range(N, 0, -1): 10 | s = bin(n)[2:] 11 | num1 = int(s+"0", 2) 12 | if num1 in mem: 13 | continue 14 | num2 = int(s+"1", 2) 15 | if num2 in mem: 16 | continue 17 | if not s in S: 18 | return False 19 | # print(s) 20 | mem.add(n) 21 | return True 22 | ``` 23 | 24 | From [lee215](https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/260847/JavaC%2B%2BPython-O(S2)) 25 | 26 | ```python 27 | def queryString(self, S, N): 28 | return all(bin(i)[2:] in S for i in xrange(N, N / 2, -1)) 29 | ``` -------------------------------------------------------------------------------- /leetcode/036_Valid_Sudoku.java: -------------------------------------------------------------------------------- 1 | // 10.24 2 | // 注意看题目意思: A valid Sudoku board (partially filled) is not necessarily solvable. 3 | class Solution { 4 | public boolean isValidSudoku(char[][] board) { 5 | for(int i = 0; i<9; i++){ 6 | HashSet rows = new HashSet(); 7 | HashSet columns = new HashSet(); 8 | HashSet cube = new HashSet(); 9 | for (int j = 0; j < 9;j++){ 10 | if(board[i][j]!='.' && !rows.add(board[i][j])) 11 | return false; 12 | if(board[j][i]!='.' && !columns.add(board[j][i])) 13 | return false; 14 | int RowIndex = 3*(i/3); 15 | int ColIndex = 3*(i%3); 16 | if(board[RowIndex + j/3][ColIndex + j%3]!='.' && !cube.add(board[RowIndex + j/3][ColIndex + j%3])) 17 | return false; 18 | } 19 | } 20 | return true; 21 | } 22 | } -------------------------------------------------------------------------------- /leetcode_daily/993.md: -------------------------------------------------------------------------------- 1 | [993](https://leetcode.com/problems/cousins-in-binary-tree/) 2 | 3 | ```python 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution(object): 12 | def isCousins(self, root, x, y): 13 | """ 14 | :type root: TreeNode 15 | :type x: int 16 | :type y: int 17 | :rtype: bool 18 | """ 19 | level1, parent1 = traverse(root, 0, x, None) 20 | level2, parent2 = traverse(root, 0, y, None) 21 | return level1 == level2 and parent1 != parent2 22 | 23 | def traverse(root, level, x, parent): 24 | if root is None: 25 | return None, None 26 | if root.val == x: 27 | return level, parent 28 | l, p = traverse(root.left, level+1, x, root) 29 | if l is None: 30 | l, p = traverse(root.right, level+1, x, root) 31 | return l, p 32 | ``` -------------------------------------------------------------------------------- /lintcode/lintcode_039_Recover_Rotated_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/recover-rotated-sorted-array/ 2 | public class Solution { 3 | /** 4 | * @param nums: The rotated sorted array 5 | * @return: void 6 | */ 7 | public void recoverRotatedSortedArray(ArrayList nums) { 8 | // write your code here 9 | for (int index = 0; index < nums.size() - 1; index++) { 10 | if (nums.get(index) > nums.get(index + 1)) { 11 | reverse(nums, 0, index); 12 | reverse(nums, index + 1, nums.size() - 1); 13 | reverse(nums, 0, nums.size() - 1); 14 | return; 15 | } 16 | } 17 | } 18 | 19 | private void reverse(ArrayList nums, int start, int end) { 20 | for (int i = start, j = end; i < j; i++, j--) { 21 | int temp = nums.get(i); 22 | nums.set(i, nums.get(j)); 23 | nums.set(j, temp); 24 | } 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /leetcode/110_Balanced_Binary_Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 注意分治的思想,分析tree的性质确定状态要求。分治的时候使用了递归方法。 3 | * @author Xingxing Huang 4 | * @since 2017.04.18 5 | * @Time O(n) 6 | * @param 7 | * @return 8 | */ 9 | /** 10 | * Definition for a binary tree node. 11 | * public class TreeNode { 12 | * int val; 13 | * TreeNode left; 14 | * TreeNode right; 15 | * TreeNode(int x) { val = x; } 16 | * } 17 | */ 18 | public class Solution { 19 | public boolean isBalanced(TreeNode root) { 20 | return maxDepth(root) != -1; 21 | } 22 | public int maxDepth(TreeNode root) { 23 | // return -1: not balanced 24 | // return depth if balanced 25 | if (root == null) { 26 | return 0; 27 | } 28 | int left = maxDepth(root.left); 29 | int right = maxDepth(root.right); 30 | if (left == -1 || right == -1 || Math.abs(left - right) > 1) { 31 | return -1; 32 | } 33 | return Math.max(left, right) + 1; 34 | } 35 | } -------------------------------------------------------------------------------- /leetcode/194_Transpose_File.sh: -------------------------------------------------------------------------------- 1 | # Read from the file file.txt and print its transposed content to stdout. 2 | # awk 3 | awk ' 4 | { 5 | for (i = 1; i <= NF; i++) { 6 | if(NR == 1) { 7 | s[i] = $i; 8 | } else { 9 | s[i] = s[i] " " $i; 10 | } 11 | } 12 | } 13 | END { 14 | for (i = 1; s[i] != ""; i++) { 15 | print s[i]; 16 | } 17 | }' file.txt 18 | 19 | 20 | 21 | #BASH 22 | ncol=`head -n1 file.txt | wc -w` 23 | 24 | for i in `seq 1 $ncol` 25 | do 26 | echo `cut -d' ' -f$i file.txt` 27 | done 28 | 29 | 30 | # 31 | #!/bin/bash 32 | 33 | declare -A matrix 34 | col=1 35 | row=1 36 | 37 | while read line; do 38 | col=1 39 | for word in $line; do 40 | matrix[$row,$col]=$word 41 | ((col++)) 42 | done 43 | ((row++)) 44 | done < file.txt 45 | 46 | for ((i=1;i 'bool': 6 | if maxChoosableInteger * (maxChoosableInteger + 1) // 2 < desiredTotal: 7 | return False 8 | 9 | # memorization 10 | mem = {} 11 | def helper(nums, desiredTotal): 12 | if str(nums) in mem: 13 | return mem[str(nums)] 14 | if nums[-1] >= desiredTotal: 15 | return True 16 | for i in range(len(nums)): 17 | left = nums[:i] + nums[(i+1):] 18 | if not helper(left, desiredTotal - nums[i]): 19 | mem[str(nums)] = True 20 | return True 21 | mem[str(nums)] = False 22 | return False 23 | 24 | nums = list(range(1, maxChoosableInteger + 1, 1)) 25 | return helper(nums, desiredTotal) 26 | ``` -------------------------------------------------------------------------------- /leetcode/165_Compare_Version_Numbers.java: -------------------------------------------------------------------------------- 1 | // 2017.07.29 string s1.compareTo(string s2) 2 | public class Solution { 3 | public int compareVersion(String version1, String version2) { 4 | String[] s1 = version1.split("\\."); 5 | String[] s2 = version2.split("\\."); 6 | int maxlen = Math.max(s1.length, s2.length); 7 | for (int i = 0; i < maxlen; i++) { 8 | int v1 = s1.length <= i ? 0 : value(s1[i]); 9 | int v2 = s2.length <= i ? 0 : value(s2[i]); 10 | // if (v1.compareTo(v2) != 0) { 11 | // return v1.compareTo(v2); 12 | // } 13 | if (v1 > v2) { 14 | return 1; 15 | } else if (v1 < v2) { 16 | return -1; 17 | } 18 | } 19 | return 0; 20 | } 21 | private int value(String s) { 22 | int num = 0; 23 | for (char c : s.toCharArray()) { 24 | num = num * 10 + (c - '0'); 25 | } 26 | return num; 27 | } 28 | } -------------------------------------------------------------------------------- /leetcode/451_Sort_Characters_By_Frequency.py: -------------------------------------------------------------------------------- 1 | # @Author 黄xing 利用dictionary类型和bucket方法完成 2 | class Solution(object): 3 | def frequencySort(self, s): 4 | """ 5 | :type s: str 6 | :rtype: str 7 | """ 8 | # save the number counts into a dictionary 9 | scount = {} 10 | maxValue = 0 11 | for char in s: 12 | scount[char] = scount.get(char, 0) + 1 13 | if scount[char] > maxValue: 14 | maxValue = scount[char] 15 | 16 | # use a bucket to save the order 17 | bucket = [] 18 | for i in range(maxValue + 1): 19 | bucket.append([]) 20 | for key, value in scount.iteritems(): 21 | bucket[value].append(key) 22 | 23 | # join the string 24 | out = "" 25 | for i in range(len(bucket) - 1, 0, -1): 26 | if bucket[i] == []: 27 | continue 28 | for char in bucket[i]: 29 | out += char * i 30 | return out -------------------------------------------------------------------------------- /lintcode/lintcode_031_Partition_Array.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/partition-array/ 2 | public class Solution { 3 | /* 4 | * @param : The integer array you should partition 5 | * @param : An integer 6 | * @return: The index after partition 7 | */ 8 | public int partitionArray(int[] nums, int k) { 9 | // write your code here 10 | if (nums == null || nums.length <= 1) { 11 | return 0; 12 | } 13 | int i = 0; 14 | int j = nums.length - 1; 15 | while (i < j) { 16 | if (nums[i] >= k) { 17 | swap(nums, i, j); 18 | j--; 19 | } else { 20 | i++; 21 | } 22 | } 23 | // 注意终止的判断。 24 | if (nums[i] >= k) { 25 | return i; 26 | } 27 | return i + 1; 28 | } 29 | public void swap(int[] nums, int i, int j) { 30 | int temp = nums[i]; 31 | nums[i] = nums[j]; 32 | nums[j] = temp; 33 | } 34 | }; -------------------------------------------------------------------------------- /leetcode/031_Next_Permutation.java: -------------------------------------------------------------------------------- 1 | // 10.13 注意置换的顺序,然后array操作即可 2 | // 123 > 132 > 213 > 231 > 312 > 321 3 | class Solution { 4 | public void nextPermutation(int[] nums) { 5 | if (nums == null || nums.length == 1) 6 | return; 7 | int i = nums.length - 2; 8 | while (i >= 0 && nums[i] >= nums[i + 1]) 9 | i--; 10 | if (i < 0) { 11 | reverse(nums, 0, nums.length - 1); 12 | return; 13 | } 14 | // example: 127654 > 142567 15 | int j = nums.length - 1; 16 | while (j >= 0 && nums[j] <= nums[i]) 17 | j--; 18 | swap(nums, i, j); 19 | reverse(nums, i + 1, nums.length - 1); 20 | } 21 | private void reverse(int[] nums, int start, int end) { 22 | while (start < end) 23 | swap(nums, start++, end--); 24 | } 25 | private void swap(int[] nums, int i, int j) { 26 | int temp = nums[i]; 27 | nums[i] = nums[j]; 28 | nums[j] = temp; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /lintcode/lintcode_589_Connecting_Graph.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/connecting-graph/ 2 | // union find 典型题目 3 | public class ConnectingGraph { 4 | private int[] father; 5 | private int find(int x) { 6 | if (father[x] == x) { 7 | return x; 8 | } 9 | father[x] = find(father[x]); 10 | return father[x]; 11 | } 12 | public ConnectingGraph(int n) { 13 | // initialize your data structure here. 14 | father = new int[n + 1]; 15 | for (int i = 1; i <= n; i++) { 16 | father[i] = i; 17 | } 18 | } 19 | 20 | public void connect(int a, int b) { 21 | // Write your code here 22 | int fa = find(a); 23 | int fb = find(b); 24 | if (fa != fb) { 25 | father[fa] = fb; 26 | } 27 | } 28 | 29 | public boolean query(int a, int b) { 30 | // Write your code here 31 | int fa = find(a); 32 | int fb = find(b); 33 | return fa == fb; 34 | } 35 | } -------------------------------------------------------------------------------- /lintcode/lintcode_040_two_Stack_queue.java: -------------------------------------------------------------------------------- 1 | // @Author Xingxing Huang 2 | public class MyQueue { 3 | private Stack stack1; 4 | private Stack stack2; 5 | 6 | public MyQueue() { 7 | // do initialization if necessary 8 | // push only 9 | stack1 = new Stack(); 10 | // pop only 11 | stack2 = new Stack(); 12 | } 13 | 14 | public void push(int element) { 15 | // write your code here 16 | while (!stack2.isEmpty()) { 17 | stack1.push(stack2.pop()); 18 | } 19 | stack1.push(element); 20 | } 21 | 22 | public int pop() { 23 | // write your code here 24 | while (!stack1.isEmpty()) { 25 | stack2.push(stack1.pop()); 26 | } 27 | return stack2.pop(); 28 | } 29 | 30 | public int top() { 31 | // write your code here 32 | while (!stack1.isEmpty()) { 33 | stack2.push(stack1.pop()); 34 | } 35 | return stack2.peek(); 36 | } 37 | } -------------------------------------------------------------------------------- /leetcode/033_Search_Rotated_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | // 二分查找,注意与在循环数组中查找最小值的区别。 2 | public class Solution { 3 | public int search(int[] nums, int target) { 4 | if (nums == null || nums.length == 0) { 5 | return -1; 6 | } 7 | int start = 0; 8 | int end = nums.length - 1; 9 | 10 | while (start <= end) { 11 | int mid = start + (end - start) / 2; 12 | if (nums[mid] == target) 13 | return mid; 14 | 15 | if (nums[start] <= nums[mid]){ 16 | if (target < nums[mid] && target >= nums[start]) 17 | end = mid - 1; 18 | else 19 | start = mid + 1; 20 | } 21 | 22 | if (nums[mid] <= nums[end]){ 23 | if (target > nums[mid] && target <= nums[end]) 24 | start = mid + 1; 25 | else 26 | end = mid - 1; 27 | } 28 | } 29 | return -1; 30 | } 31 | } -------------------------------------------------------------------------------- /leetcode/551_Student_Attenance_Record_I.java: -------------------------------------------------------------------------------- 1 | // String manipulation 2 | // 10.10 3 | class Solution { 4 | public boolean checkRecord(String s) { 5 | int a = 0; 6 | int l = 0; 7 | for (int i = 0; i < s.length(); i++) { 8 | if (s.charAt(i) == 'A') { 9 | a++; 10 | if (a > 1) return false; 11 | } 12 | if (s.charAt(i) == 'L') { 13 | if ( l == 0 || (i > 0 && s.charAt(i - 1) == 'L')) l++; 14 | if (l > 2) return false; 15 | } else { 16 | l = 0; 17 | } 18 | } 19 | return true; 20 | } 21 | } 22 | 23 | 24 | // one line 25 | public boolean checkRecord(String s) { 26 | return !s.matches(".*LLL.*|.*A.*A.*"); 27 | } 28 | 29 | 30 | // 3 line without reg 31 | public class Solution { 32 | public boolean checkRecord(String s) { 33 | if(s.indexOf("A") != s.lastIndexOf("A") || s.contains("LLL")) 34 | return false; 35 | return true; 36 | } 37 | } -------------------------------------------------------------------------------- /leetcode/345_Reverse_Vowels_of_a_String.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String reverseVowels(String s) { 3 | if (s == null || s.length() ==0) return s; 4 | String vowels = "aeiouAEIOU"; 5 | int i = 0; 6 | int j = s.length() - 1; 7 | char[] chars = s.toCharArray(); 8 | while (i <= j) { 9 | // while (i <= j && !vowels.contains(""+chars[j])) j --; 10 | // while (i <= j && !vowels.contains(""+chars[i])) i ++; 11 | // if (vowels.contains(""+chars[i]) && vowels.contains(""+chars[j])) { 12 | while (i <= j && vowels.indexOf(chars[j]) == -1) j --; 13 | while (i <= j && vowels.indexOf(chars[i]) == -1) i ++; 14 | if (vowels.indexOf(chars[i]) != -1 && vowels.indexOf(chars[j]) != -1) { 15 | char t = chars[i]; 16 | chars[i] = chars[j]; 17 | chars[j] = t; 18 | i ++; 19 | j --; 20 | } 21 | } 22 | return new String(chars); 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode_daily/1014.md: -------------------------------------------------------------------------------- 1 | [1014](https://leetcode.com/problems/best-sightseeing-pair/) Best Sightseeing Pair 2 | 3 | Use a heap to store the passed numbers. Not the best solution. 4 | 5 | ```python 6 | class Solution: 7 | def maxScoreSightseeingPair(self, A: List[int]) -> int: 8 | heap = [] 9 | heapq.heapify(heap) 10 | res = 0 11 | count = 0 12 | for a in A: 13 | # print(heap) 14 | if len(heap) != 0: 15 | temp = a + (-heap[0]) - count 16 | res = max(res, temp) 17 | heapq.heappush(heap, -a-count) 18 | count += 1 19 | return res 20 | ``` 21 | 22 | 23 | Better solution from [discussion](https://leetcode.com/problems/best-sightseeing-pair/discuss/260850/JavaC%2B%2BPython-One-Pass) with only one pass. 24 | 25 | ```python 26 | def maxScoreSightseeingPair(self, A): 27 | cur = res = 0 28 | for a in A: 29 | res = max(res, cur + a) 30 | cur = max(cur, a) - 1 31 | return res 32 | ``` -------------------------------------------------------------------------------- /lintcode/lintcode_158_Two_Strings_Anagrams.java: -------------------------------------------------------------------------------- 1 | // http://www.lintcode.com/en/problem/two-strings-are-anagrams/ 2 | // @Author 黄xing 3 | // O(n), O(1) 4 | // ASCII http://images2015.cnblogs.com/blog/822124/201608/822124-20160819180928718-882826750.jpg 5 | public class Solution { 6 | /** 7 | * @param s: The first string 8 | * @param b: The second string 9 | * @return true or false 10 | */ 11 | public boolean anagram(String s, String t) { 12 | // write your code here 13 | if (s.length() != t.length()) { 14 | return false; 15 | } 16 | int[] helper = new int[128]; 17 | for (int i = 0; i < s.length(); i++) { 18 | helper[s.charAt(i) - ' ']++; 19 | } 20 | for (int j = 0; j < t.length(); j++) { 21 | helper[t.charAt(j) - ' ']--; 22 | } 23 | for (int i = 0; i < helper.length; i++) { 24 | if (helper[i] != 0) { 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | }; -------------------------------------------------------------------------------- /leetcode/054_Spiral_Matrix.java: -------------------------------------------------------------------------------- 1 | // 09.23 2 | // 注意中间只有一个元素的情况。 3 | class Solution { 4 | public List spiralOrder(int[][] matrix) { 5 | List list = new ArrayList<>(); 6 | if (matrix == null || matrix.length == 0 || matrix[0].length == 0) 7 | return list; 8 | int m = matrix.length; 9 | int n = matrix[0].length; 10 | int i = 0; 11 | int j = 0; 12 | int p = m - 1; 13 | int q = n - 1; 14 | while (i <= p && j <= q) { 15 | for (int k = j; k <= q; k++) list.add(matrix[i][k]); 16 | i++; 17 | for (int k = i; k <= p; k++) list.add(matrix[k][q]); 18 | q--; 19 | if (i <= p) { // attention 20 | for (int k = q; k >= j; k--) list.add(matrix[p][k]); 21 | p--; 22 | } 23 | if (j <= q) { 24 | for (int k = p; k >= i; k--) list.add(matrix[k][j]); 25 | j++; 26 | } 27 | } 28 | return list; 29 | } 30 | } -------------------------------------------------------------------------------- /leetcode/059_Spiral_Matrix_II.java: -------------------------------------------------------------------------------- 1 | // same as spiral matrix I 2 | public class Solution { 3 | public static int[][] generateMatrix(int n) { 4 | int[][] ret = new int[n][n]; 5 | int left = 0,top = 0; 6 | int right = n -1,down = n - 1; 7 | int count = 1; 8 | while (left <= right) { 9 | for (int j = left; j <= right; j ++) { 10 | ret[top][j] = count++; 11 | } 12 | top ++; 13 | for (int i = top; i <= down; i ++) { 14 | ret[i][right] = count ++; 15 | } 16 | right --; 17 | for (int j = right; j >= left; j --) { 18 | ret[down][j] = count ++; 19 | } 20 | down --; 21 | for (int i = down; i >= top; i --) { 22 | ret[i][left] = count ++; 23 | } 24 | left ++; 25 | } 26 | return ret; 27 | } 28 | } 29 | 30 | 31 | // python solution 32 | // https://discuss.leetcode.com/topic/19130/4-9-lines-python-solutions --------------------------------------------------------------------------------