├── README.md ├── cpp ├── 3Sum.cc ├── 3Sum_Closest.cc ├── 4Sum.cc ├── Add_Binary.cc ├── Add_Digits.cc ├── Add_Strings.cc ├── Add_Two_Numbers.cc ├── Anagrams.cc ├── Balanced_Binary_Tree.cc ├── Best_Time_to_Buy_and_Sell_Stock.cc ├── Best_Time_to_Buy_and_Sell_Stock_II.cc ├── Best_Time_to_Buy_and_Sell_Stock_III.cc ├── Binary_Search_Tree_Iterator.cc ├── Binary_Tree_Inorder_Traversal.cc ├── Binary_Tree_Level_Order_Traversal.cc ├── Binary_Tree_Level_Order_Traversal_II.cc ├── Binary_Tree_Postorder_Traversal.cc ├── Binary_Tree_Preorder_Traversal.cc ├── Binary_Watch.cc ├── Combination_Sum.cc ├── Combination_Sum_II.cc ├── Container_With_Most_Water.cc ├── Contains_Duplicate.cc ├── Contains_Duplicate_II.cc ├── Convert_a_Number_to_Hexadecimal.cc ├── Count_and_Say.cc ├── Delete_Node_in_a_Linked_List.cc ├── Divide_Two_Integers.cc ├── Excel_Sheet_Column_Number.cc ├── Excel_Sheet_Column_Title.cc ├── Factorial_Trailing_Zeroes.cc ├── Find_Minimum_in_Rotated_Sorted_Array.cc ├── Find_Minimum_in_Rotated_Sorted_Array_II.cc ├── Find_Peak_Element.cc ├── Find_the_Difference.cc ├── First_Unique_Character_in_a_String.cc ├── Fizz_Buzz.cc ├── Gas_Station.cc ├── Generate_Parentheses.cc ├── Gray_Code.cc ├── Happy_Number.cc ├── House_Robber.cc ├── Implement_Queue_using_Stacks.cc ├── Implement_Stack_using_Queues.cc ├── Implement_strStr().cc ├── Integer_to_Roman.cc ├── Intersection_of_Two_Arrays.cc ├── Intersection_of_Two_Arrays_II.cc ├── Intersection_of_Two_Linked_Lists.cc ├── Invert_Binary_Tree.cc ├── Kth_Largest_Element_in_an_Array.cc ├── Length_of_Last_Word.cc ├── Letter_Combinations_of_a_Phone_Number.cc ├── Linked_List_Cycle_II.cc ├── Linked_List_Random_Node.cc ├── Longest_Common_Prefix.cc ├── Longest_Consecutivec_Sequence.cc ├── Longest_Palindrome.cc ├── Longest_Palindromic_Substring.cc ├── Majority_Element.cc ├── Maximum_Subarray.cc ├── Merge_Sorted_Array.cc ├── Min_Stack.cc ├── Minimum_Moves_to_Equal_Array_Elements.cc ├── Minimum_Path_Sum.cc ├── Move_Zeroes.cc ├── Nim_Game.cc ├── Number_of_1_Bits.cc ├── Number_of_Boomerangs.cc ├── Palindrome_Number.cc ├── Palindrome_Partitioning.cc ├── Partition_List.cc ├── Pascal's_Triangle.cc ├── Pascal's_Triangle_II.cc ├── Permutations.cc ├── Plus_One.cc ├── Power_of_Four.cc ├── Power_of_Three.cc ├── Power_of_Two.cc ├── Ransom_Note.cc ├── Remove_Duplicates_from_Sorted_Array.cc ├── Remove_Duplicates_from_Sorted_List.cc ├── Remove_Duplicates_from_Sorted_List_II.cc ├── Remove_Element.cc ├── Remove_Nth_Node_From_End_of_List.cc ├── Reverse_Bits.cc ├── Reverse_Integer.cc ├── Reverse_Linked_List _II.cc ├── Reverse_Linked_List.cc ├── Reverse_String.cc ├── Reverse_Vowels_of_a_String.cc ├── Roman_to_Integer.cc ├── Rotate_Array.cc ├── Rotate_Image.cc ├── Rotate_List.cc ├── Same_Tree.cc ├── Search_Insert_Position.cc ├── Search_a_2D_Matrix.cc ├── Set_Matrix_Zeroes.cc ├── Single_Number.cc ├── Single_Number_II.cc ├── String_to_Integer.cc ├── Subsets.cc ├── Subsets_II.cc ├── Sum_of_Left_Leaves.cc ├── Swap_Nodes_in_Pairs.cc ├── Symmetric_Tree.cc ├── Top_K_Frequent_Elements.cc ├── Triangle.cc ├── Two_Sum.cc ├── Two_Sum_II-Input_array_is_sorted.cc ├── Ugly_Number.cc ├── Ugly_Number_II.cc ├── Unique_Binary_Search_Trees.cc ├── Unique_Paths.cc ├── Valid_Anagram.cc ├── Valid_Parentheses.cc ├── Valid_Sudoku.cc └── ZigZag_Conversion.cc ├── go ├── add-binary │ ├── add-binary.go │ └── add-binary_test.go ├── add-two-numbers │ └── add-two-numbers.go ├── balanced-binary-tree │ └── balanced-binary-tree.go ├── best-time-to-buy-and-sell-stock-ii │ └── best-time-to-buy-and-sell-stock-ii.go ├── best-time-to-buy-and-sell-stock │ └── best-time-to-buy-and-sell-stock.go ├── binary-tree-level-order-traversal-ii │ └── binary-tree-level-order-traversal-ii.go ├── binary-tree-level-order-traversal │ └── binary-tree-level-order-traversal.go ├── climbing-stairs │ └── climbing-stairs.go ├── contains-duplicate-ii │ └── contains-duplicate-ii.go ├── contains-duplicate │ └── contains-duplicate.go ├── convert-bst-to-greater-tree │ └── convert-bst-to-greater-tree.go ├── convert-sorted-array-to-binary-search-tree │ └── convert-sorted-array-to-binary-search-tree.go ├── convert-sorted-list-to-binary-search-tree │ └── convert-sorted-list-to-binary-search-tree.go ├── count-and-say │ └── count-and-say.go ├── count-primes │ └── count-primes.go ├── delete-node-in-a-linked-list │ └── delete-node-in-a-linked-list.go ├── detect-capital │ └── detect-capital.go ├── diameter-of-binary-tree │ └── diameter-of-binary-tree.go ├── excel-sheet-column-number │ ├── excel-sheet-column-number.go │ └── excel-sheet-column-number_test.go ├── find-all-anagrams-in-a-string │ └── find-all-anagrams-in-a-string.go ├── find-all-duplicates-in-an-array │ ├── find-all-duplicates-in-an-array.go │ └── find-all-duplicates-in-an-array_test.go ├── find-all-numbers-disappeared-in-an-array │ └── find-all-numbers-disappeared-in-an-array.go ├── first-unique-character-in-a-string │ └── first-unique-character-in-a-string.go ├── fizz-buzz │ ├── fizz-buzz.go │ └── fizz-buzz_test.go ├── hamming-distance │ ├── hamming-distance.go │ └── hamming-distance_test.go ├── happy-number │ └── happy-number.go ├── house-robber │ └── house-robber.go ├── implement-strstr │ └── implement-strstr.go ├── intersection-of-two-arrays │ └── intersection-of-two-arrays.go ├── invert-binary-tree │ └── invert-binary-tree.go ├── length-of-last-word │ └── length-of-last-word.go ├── longest-common-prefix │ └── longest-common-prefix.go ├── longest-increasing-subsequence │ └── longest-increasing-subsequence.go ├── longest-substring-without-repeating-characters │ └── longest-substring-without-repeating-characters.go ├── majority-element-ii │ └── majority-element-ii.go ├── majority-element │ └── majority-element.go ├── maximum-depth-of-binary-tree │ └── maximum-depth-of-binary-tree.go ├── maximum-subarray │ └── maximum-subarray.go ├── merge-sorted-array │ └── merge-sorted-array.go ├── merge-two-binary-trees │ └── merge-two-binary-trees.go ├── merge-two-sorted-lists │ └── merge-two-sorted-lists.go ├── min-stack │ └── min-stack.go ├── minimum-depth-of-binary-tree │ └── minimum-depth-of-binary-tree.go ├── minimum-moves-to-equal-array-elements │ └── minimum-moves-to-equal-array-elements.go ├── minimum-path-sum │ └── minimum-path-sum.go ├── missing-number │ └── missing-number.go ├── move-zeroes │ └── move-zeroes.go ├── palindrome-linked-list │ └── palindrome-linked-list.go ├── palindrome-number │ ├── palindrome-number.go │ └── palindrome-number_test.go ├── path-sum-ii │ └── path-sum-ii.go ├── path-sum-iii │ └── path-sum-iii.go ├── path-sum │ └── path-sum.go ├── plus-one │ └── plus-one.go ├── product-of-array-except-self │ └── product-of-array-except-self.go ├── ransom-note │ └── ransom-note.go ├── remove-duplicates-from-sorted-array │ └── remove-duplicates-from-sorted-array.go ├── remove-duplicates-from-sorted-list │ └── remove-duplicates-from-sorted-list.go ├── remove-element │ └── remove-element.go ├── remove-linked-list-elements │ └── remove-linked-list-elements.go ├── reverse-linked-list │ ├── reverse-linked-list.go │ └── reverse-linked-list_test.go ├── reverse-string │ ├── reverse-string.go │ └── reverse-string_test.go ├── roman-to-integer │ └── roman-to-integer.go ├── same-tree │ └── same-tree.go ├── search-insert-position │ └── search-insert-position.go ├── single-number-ii │ └── single-number-ii.go ├── single-number │ └── single-number.go ├── sort-colors │ └── sort-colors.go ├── sqrtx │ └── sqrtx.go ├── string-to-integer-atoi │ └── string-to-integer-atoi.go ├── subtree-of-another-tree │ └── subtree-of-another-tree.go ├── sum-of-left-leaves │ └── sum-of-left-leaves.go ├── symmetric-tree │ └── symmetric-tree.go ├── two-sum │ ├── two-sum.go │ └── two-sum_test.go ├── util │ └── util.go ├── valid-anagram │ └── valid-anagram.go ├── valid-parentheses │ └── valid-parentheses.go └── valid-perfect-square │ └── valid-perfect-square.go ├── mysql ├── big-countries.sql ├── combine-two-tables.sql ├── consecutive-numbers.sql ├── customers-who-never-order.sql ├── delete-duplicate-emails.sql ├── department-highest-salary.sql ├── department-top-three-salaries.sql ├── duplicate-emails.sql ├── employees-earning-more-than-their-managers.sql ├── not-boring-movies.sql ├── rank-scores.sql ├── rising-temperature.sql ├── second-highest-salary.sql └── swap-salary.sql ├── python ├── Fizz_Buzz.py ├── Nim_Game.py ├── Reverse_String.py └── Single_Number.py └── shell ├── Tenth_Line.sh ├── Transpose_File.sh ├── Valid_Phone_Numbers.sh └── Word_Frequency.sh /README.md: -------------------------------------------------------------------------------- 1 | leetcode 2 | ======== 3 | 4 | Solutions of LeetCode 5 | -------------------------------------------------------------------------------- /cpp/3Sum_Closest.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 3 | 4 | For example, given array S = {-1 2 1 -4}, and target = 1. 5 | 6 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 7 | */ 8 | 9 | class Solution { 10 | public: 11 | int threeSumClosest(vector &num, int target) 12 | { 13 | int len = num.size(); 14 | if (len < 3) 15 | return 0; 16 | 17 | sort(num.begin(), num.end()); 18 | int result = num[0] + num[1] + num[2]; 19 | for (int i = 0; i < len-2; i++) 20 | { 21 | int left = i + 1, right = len - 1; 22 | while (left < right) 23 | { 24 | int tmp = num[i] + num[left] + num[right]; 25 | if (tmp < target) 26 | { 27 | left++; 28 | } 29 | else if (tmp > target) 30 | { 31 | right--; 32 | } 33 | else 34 | { 35 | return target; 36 | } 37 | 38 | if (abs(tmp - target) < abs(result - target)) 39 | result = tmp; 40 | } 41 | } 42 | 43 | return result; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /cpp/Add_Binary.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given two binary strings, return their sum (also a binary string). 3 | 4 | For example, 5 | a = "11" 6 | b = "1" 7 | Return "100". 8 | */ 9 | 10 | class Solution 11 | { 12 | public: 13 | string addBinary(string a, string b) 14 | { 15 | string result; 16 | 17 | int len1 = a.size(); 18 | int len2 = b.size(); 19 | int carry = 0; 20 | 21 | int i = len1 - 1; 22 | int j = len2 - 1; 23 | 24 | for ( ; i >= 0 && j >= 0; i--, j--) 25 | { 26 | result.push_back((a[i] - '0' + b[j] - '0' + carry) % 2 + '0'); 27 | carry = (a[i] - '0' + b[j] - '0' + carry) / 2; 28 | } 29 | 30 | if (i > j) 31 | { 32 | for ( ; i >= 0; i--) 33 | { 34 | result.push_back((a[i] - '0' + 0 + carry) % 2 + '0'); 35 | carry = (a[i] - '0' + 0 + carry) / 2; 36 | } 37 | } 38 | else if (i < j) 39 | { 40 | for ( ; j >= 0; j--) 41 | { 42 | result.push_back((0 + b[j] - '0' + carry) % 2 + '0'); 43 | carry = (0 + b[j] - '0' + carry) / 2; 44 | } 45 | } 46 | 47 | if (carry == 1) 48 | result.push_back('0' + carry); 49 | 50 | reverse(result.begin(), result.end()); 51 | 52 | return result; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /cpp/Add_Digits.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 3 | For example: 4 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | int addDigits(int num) 11 | { 12 | while (num >= 10) 13 | { 14 | int digit_sum = 0; 15 | while (num > 0) 16 | { 17 | digit_sum += (num % 10); 18 | num /= 10; 19 | } 20 | num = digit_sum; 21 | } 22 | 23 | return num; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /cpp/Add_Strings.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given two non-negative numbers num1 and num2 represented as string, 3 | return the sum of num1 and num2. 4 | 5 | Note: 6 | 7 | 1.The length of both num1 and num2 is < 5100. 8 | 2.Both num1 and num2 contains only digits 0-9. 9 | 3.Both num1 and num2 does not contain any leading zero. 10 | 4.You must not use any built-in BigInteger library or convert the inputs to integer directly. 11 | */ 12 | class Solution 13 | { 14 | public: 15 | string addStrings(string num1, string num2) 16 | { 17 | string result; 18 | 19 | for (int i = num1.size() - 1, j = num2.size() - 1, carry = 0; 20 | i >= 0 || j >= 0 || carry; 21 | --i, --j, carry /= 10) 22 | { 23 | if (i >= 0) 24 | { 25 | carry += num1[i] - '0'; 26 | } 27 | if (j >= 0) 28 | { 29 | carry += num2[j] - '0'; 30 | } 31 | result += to_string(carry % 10); 32 | } 33 | reverse(result.begin(), result.end()); 34 | 35 | return result; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /cpp/Anagrams.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of strings, return all groups of strings that are anagrams. 3 | 4 | Note: All inputs will be in lower-case. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | vector anagrams(vector &strs) 11 | { 12 | vector result; 13 | map mapping; // 每个字符串及其在vector中的位置 14 | 15 | for (int i = 0; i < strs.size(); i++) 16 | { 17 | string tmp = strs[i]; 18 | std::sort(tmp.begin(), tmp.end()); 19 | 20 | map::iterator it = mapping.find(tmp); 21 | if (it == mapping.end()) // 没有 22 | { 23 | mapping[tmp] = i; 24 | } 25 | else // 已有 26 | { 27 | if (mapping[tmp] == -1) 28 | { 29 | result.push_back(strs[i]); 30 | } 31 | else 32 | { 33 | result.push_back(strs[mapping[tmp]]); // 原来那个 34 | mapping[tmp] = -1; // -1(正常都是>=0的)作为一个标识,表示以后直接添加入result中即可 35 | result.push_back(strs[i]); // 这个 36 | } 37 | } 38 | } 39 | 40 | return result; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /cpp/Balanced_Binary_Tree.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, determine if it is height-balanced. 3 | 4 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | */ 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution 17 | { 18 | public: 19 | bool isBalanced(TreeNode *root) 20 | { 21 | if (root == NULL) 22 | return true; 23 | 24 | int left = treeHeight(root->left); 25 | int right = treeHeight(root->right); 26 | 27 | if (left - right > 1 || left - right < -1) 28 | { 29 | return false; 30 | } 31 | 32 | return isBalanced(root->left) && isBalanced(root->right); 33 | } 34 | private: 35 | int treeHeight(TreeNode* root) 36 | { 37 | if (root == NULL) 38 | return 0; 39 | 40 | int left = treeHeight(root->left) + 1; 41 | int right = treeHeight(root->right) + 1; 42 | 43 | return left > right ? left : right; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /cpp/Best_Time_to_Buy_and_Sell_Stock.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | int maxProfit(vector &prices) 11 | { 12 | if (prices.size() == 0) 13 | return 0; 14 | 15 | int max = 0, delta = 0; 16 | int low = prices[0]; 17 | 18 | for (int i = 1; i < prices.size(); i++) 19 | { 20 | delta = prices[i] - low; 21 | if (delta <= 0) 22 | low = prices[i]; 23 | if (delta > max) 24 | max = delta; 25 | } 26 | 27 | return max; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /cpp/Best_Time_to_Buy_and_Sell_Stock_II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like 5 | (ie, buy one and sell one share of the stock multiple times). However, you may not engage in 6 | multiple transactions at the same time (ie, you must sell the stock before you buy again). 7 | */ 8 | 9 | class Solution 10 | { 11 | public: 12 | int maxProfit(vector &prices) 13 | { 14 | int max_profit = 0; 15 | 16 | for (int i = 1; i < prices.size(); i++) 17 | { 18 | if (prices[i] > prices[i-1]) 19 | max_profit += prices[i] - prices[i-1]; 20 | } 21 | 22 | return max_profit; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /cpp/Best_Time_to_Buy_and_Sell_Stock_III.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 5 | 6 | Note: 7 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 8 | */ 9 | 10 | class Solution 11 | { 12 | public: 13 | int maxProfit(vector &prices) 14 | { 15 | if (prices.size() <= 1) 16 | return 0; 17 | 18 | const int n = prices.size(); 19 | vector f(n); // 0...i的最大利润 20 | vector g(n); // i...n-1的最大利润 21 | 22 | int min_price = prices[0]; 23 | for (int i = 1; i < n; i++) 24 | { 25 | min_price = min(min_price, prices[i]); 26 | f[i] = max(f[i-1], prices[i] - min_price); 27 | } 28 | 29 | int max_price = prices[n-1]; 30 | for (int i = n-2; i >= 0; i--) 31 | { 32 | max_price = max(max_price, prices[i]); 33 | g[i] = max(g[i+1], max_price - prices[i]); 34 | } 35 | 36 | int max_profit = 0; 37 | for (int i = 0; i < n; i++) 38 | max_profit = max(max_profit, f[i] + g[i]); 39 | 40 | return max_profit; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /cpp/Binary_Search_Tree_Iterator.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 3 | 4 | Calling next() will return the next smallest number in the BST. 5 | 6 | Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 7 | */ 8 | 9 | /** 10 | * Definition for binary tree 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 | * }; 17 | */ 18 | class BSTIterator 19 | { 20 | private: 21 | stack stk; 22 | public: 23 | BSTIterator(TreeNode *root) 24 | { 25 | while (root != NULL) 26 | { 27 | stk.push(root); 28 | root = root->left; 29 | } 30 | } 31 | 32 | /** @return whether we have a next smallest number */ 33 | bool hasNext() 34 | { 35 | return !stk.empty(); 36 | } 37 | 38 | /** @return the next smallest number */ 39 | int next() 40 | { 41 | TreeNode* node = stk.top(); 42 | stk.pop(); 43 | int ret = node->val; 44 | node = node->right; 45 | while (node != NULL) 46 | { 47 | stk.push(node); 48 | node = node->left; 49 | } 50 | 51 | return ret; 52 | } 53 | }; 54 | 55 | /** 56 | * Your BSTIterator will be called like this: 57 | * BSTIterator i = BSTIterator(root); 58 | * while (i.hasNext()) cout << i.next(); 59 | */ 60 | -------------------------------------------------------------------------------- /cpp/Binary_Tree_Level_Order_Traversal.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | 4 | For example: 5 | Given binary tree {3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its level order traversal as: 12 | [ 13 | [3], 14 | [9,20], 15 | [15,7] 16 | ] 17 | confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 18 | */ 19 | 20 | /** 21 | * Definition for binary tree 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | class Solution 30 | { 31 | public: 32 | vector > levelOrder(TreeNode *root) 33 | { 34 | vector > result; 35 | if (root == NULL) 36 | return result; 37 | 38 | queue current, next; 39 | vector level; 40 | 41 | current.push(root); 42 | while (!current.empty()) 43 | { 44 | while (!current.empty()) 45 | { 46 | TreeNode* node = current.front(); 47 | current.pop(); 48 | 49 | level.push_back(node->val); 50 | 51 | if (node->left != NULL) 52 | next.push(node->left); 53 | 54 | if (node->right != NULL) 55 | next.push(node->right); 56 | } 57 | 58 | result.push_back(level); 59 | level.clear(); 60 | swap(next, current); 61 | } 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /cpp/Combination_Sum.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 3 | 4 | The same repeated number may be chosen from C unlimited number of times. 5 | 6 | Note: 7 | All numbers (including target) will be positive integers. 8 | Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 9 | The solution set must not contain duplicate combinations. 10 | For example, given candidate set 2,3,6,7 and target 7, 11 | A solution set is: 12 | [7] 13 | [2, 2, 3] 14 | */ 15 | 16 | class Solution 17 | { 18 | public: 19 | vector > combinationSum(vector& candidates, int target) 20 | { 21 | sort(candidates.begin(), candidates.end()); 22 | 23 | vector > result; 24 | vector item; 25 | 26 | dfs(candidates, target, 0, item, result); 27 | 28 | return result; 29 | } 30 | 31 | void dfs(vector& candidates, int gap, int start, vector& item, vector >& result) 32 | { 33 | if (gap == 0) // 找个一个解 34 | { 35 | result.push_back(item); 36 | return; 37 | } 38 | 39 | for (int i = start; i < candidates.size(); i++) 40 | { 41 | if (candidates[i] > gap) 42 | return; // 剪枝 43 | 44 | item.push_back(candidates[i]); 45 | dfs(candidates, gap - candidates[i], i, item, result);// 由于可重复选择,那么继续从i 46 | item.pop_back(); 47 | } 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /cpp/Container_With_Most_Water.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). 3 | n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 4 | Find two lines, which together with x-axis forms a container, such that the container contains the most water. 5 | 6 | Note: You may not slant the container. 7 | */ 8 | 9 | class Solution { 10 | public: 11 | int maxArea(vector& height) 12 | { 13 | int left = 0, right = height.size() - 1; 14 | int result = 0; 15 | 16 | while (left < right) 17 | { 18 | int area = (right - left) * (height[left] < height[right] ? height[left] : height[right]); 19 | 20 | if (area > result) 21 | result = area; 22 | 23 | (height[left] <= height[right]) ? left++ : right--; 24 | } 25 | 26 | return result; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /cpp/Contains_Duplicate.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, find if the array contains any duplicates. 3 | Your function should return true if any value appears at least twice in the array, 4 | and it should return false if every element is distinct. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | bool containsDuplicate(vector& nums) 11 | { 12 | unordered_map mapping; 13 | 14 | for (int i = 0; i < nums.size(); i++) 15 | { 16 | if (mapping.find(nums[i]) != mapping.end()) 17 | return true; 18 | 19 | mapping[nums[i]] = i; 20 | } 21 | 22 | return false; 23 | } 24 | /* 25 | bool containsDuplicate(vector& nums) 26 | { 27 | if (nums.size() <= 0) 28 | return false; 29 | 30 | unordered_map mapping; 31 | 32 | for (int i = 0; i < nums.size(); i++) 33 | { 34 | mapping[nums[i]] = i; 35 | } 36 | 37 | if (mapping.size() < nums.size()) 38 | { 39 | return true; 40 | } 41 | 42 | return false; 43 | } 44 | */ 45 | }; 46 | -------------------------------------------------------------------------------- /cpp/Contains_Duplicate_II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers and an integer k, 3 | find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] 4 | and the difference between i and j is at most k. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | bool containsNearbyDuplicate(vector& nums, int k) 11 | { 12 | unordered_map mapping; 13 | for (int i = 0; i < nums.size(); i++) 14 | { 15 | if (mapping.find(nums[i]) != mapping.end() && i - mapping[nums[i]] <= k){ 16 | return true; 17 | } 18 | mapping[nums[i]] = i; 19 | } 20 | 21 | return false; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /cpp/Convert_a_Number_to_Hexadecimal.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer, write an algorithm to convert it to hexadecimal. 3 | For negative integer, two’s complement method is used. 4 | 5 | Note: 6 | 7 | 1.All letters in hexadecimal (a-f) must be in lowercase. 8 | 2.The hexadecimal string must not contain extra leading 0s. 9 | If the number is zero, it is represented by a single zero character '0'; 10 | otherwise, the first character in the hexadecimal string will not be the zero character. 11 | 3.The given number is guaranteed to fit within the range of a 32-bit signed integer. 12 | 4. You must not use any method provided by the library which converts/formats the number to hex directly. 13 | Example 1: 14 | 15 | Input: 16 | 26 17 | 18 | Output: 19 | "1a" 20 | Example 2: 21 | 22 | Input: 23 | -1 24 | 25 | Output: 26 | "ffffffff" 27 | */ 28 | 29 | class Solution 30 | { 31 | public: 32 | string toHex(int num) 33 | { 34 | if (num == 0) return "0"; 35 | std::string result; 36 | 37 | int step = 2 * sizeof(num); 38 | for (int i = 0; i < step; ++i, num >>= 4) 39 | { 40 | int n = num & 0xf; 41 | if (n < 0xa) 42 | { 43 | result.push_back('0' + n); 44 | } 45 | else 46 | { 47 | result.push_back('a' + n - 10); 48 | } 49 | } 50 | reverse(result.begin(), result.end()); 51 | auto pos = result.find_first_not_of('0'); 52 | result = result.substr(pos); 53 | 54 | return result; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /cpp/Count_and_Say.cc: -------------------------------------------------------------------------------- 1 | /* 2 | The count-and-say sequence is the sequence of integers beginning as follows: 3 | 1, 11, 21, 1211, 111221, ... 4 | 5 | 1 is read off as "one 1" or 11. 6 | 11 is read off as "two 1s" or 21. 7 | 21 is read off as "one 2, then one 1" or 1211. 8 | Given an integer n, generate the nth sequence. 9 | 10 | Note: The sequence of integers will be represented as a string. 11 | */ 12 | 13 | class Solution 14 | { 15 | public: 16 | string countAndSay(int n) 17 | { 18 | string ret = "1"; 19 | 20 | for (int i = 2; i <= n; i++) 21 | { 22 | ret = iteration(ret); 23 | } 24 | 25 | return ret; 26 | } 27 | private: 28 | string iteration(string s) 29 | { 30 | string ret; 31 | char pre = s[0]; 32 | int count = 1; 33 | 34 | for (int i = 1; i < s.size(); i++) 35 | { 36 | if (s[i] == pre) 37 | { 38 | count++; 39 | } 40 | else 41 | { 42 | char tmp = count + '0'; 43 | ret.push_back(tmp); 44 | ret.push_back(pre); 45 | //ret = ret + tmp + pre; 46 | pre = s[i]; 47 | count = 1; 48 | } 49 | } 50 | 51 | // 少了最后的保存 收尾 52 | char tmp = count + '0'; 53 | ret = ret + tmp + pre; 54 | 55 | return ret; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /cpp/Delete_Node_in_a_Linked_List.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 3 | 4 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, 5 | the linked list should become 1 -> 2 -> 4 after calling your function. 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode(int x) : val(x), next(NULL) {} 14 | * }; 15 | */ 16 | class Solution 17 | { 18 | public: 19 | void deleteNode(ListNode* node) 20 | { 21 | ListNode* tmp = node->next; 22 | node->val = node->next->val; 23 | node->next = node->next->next; 24 | delete tmp; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /cpp/Divide_Two_Integers.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Divide two integers without using multiplication, division and mod operator. 3 | 4 | If it is overflow, return MAX_INT. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | int divide(int dividend, int divisor) 11 | { 12 | assert(divisor != 0); 13 | bool flag = true; 14 | if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) 15 | { 16 | flag = false; 17 | } 18 | 19 | // 当 dividend = INT_MIN 时, -dividend 会溢出,所以用 long long 20 | long long left = abs((long long)dividend); 21 | long long right = abs((long long)divisor); 22 | // 当 dividend = INT_MIN 时, divisor = -1 时,结果会溢出,所以用 long long 23 | long long result = 0; 24 | 25 | while (left >= right) 26 | { 27 | long long tmpDivisor = right; 28 | for (int i = 0; (tmpDivisor << i) <= left; i++) 29 | { 30 | left -= (tmpDivisor << i); 31 | result += (1 << i); 32 | } 33 | } 34 | 35 | if (flag == false) 36 | result *= -1; 37 | if (result > INT_MAX) 38 | return INT_MAX; 39 | 40 | return result; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /cpp/Excel_Sheet_Column_Number.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Related to question Excel Sheet Column Title 3 | 4 | Given a column title as appear in an Excel sheet, return its corresponding column number. 5 | 6 | For example: 7 | 8 | A -> 1 9 | B -> 2 10 | C -> 3 11 | ... 12 | Z -> 26 13 | AA -> 27 14 | AB -> 28 15 | */ 16 | 17 | class Solution 18 | { 19 | public: 20 | int titleToNumber(string s) 21 | { 22 | if (s.size() == 0) 23 | return 0; 24 | 25 | int result = 0; 26 | for (int i = 0; i < s.size(); i++) 27 | { 28 | result = result * 26 + s[i] - 'A' + 1; 29 | } 30 | 31 | return result; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /cpp/Excel_Sheet_Column_Title.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 3 | 4 | For example: 5 | 6 | 1 -> A 7 | 2 -> B 8 | 3 -> C 9 | ... 10 | 26 -> Z 11 | 27 -> AA 12 | 28 -> AB 13 | */ 14 | 15 | class Solution 16 | { 17 | public: 18 | //进制26 但是从1 到 26 而不是0 到 25 19 | string convertToTitle(int n) 20 | { 21 | string result; 22 | while (n > 0) 23 | { 24 | char c = (n - 1) % 26 + 'A'; 25 | result.insert(result.begin(), c); 26 | n = (n - 1) / 26; 27 | } 28 | 29 | return result; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /cpp/Factorial_Trailing_Zeroes.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return the number of trailing zeroes in n!. 3 | 4 | Note: Your solution should be in logarithmic time complexity. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | // 只要查5的个数就可以了。有足够的偶数和5结合成为10 11 | // 仅为5的倍数,贡献1个;为25的倍数,贡献2个;..... 12 | // |_N/5_|+|_N/25_|+|_N/5^3_|+... 13 | // 1~n之间5的倍数+1~n之间25的倍数+... 14 | int trailingZeroes(int n) 15 | { 16 | int result = 0; 17 | while (n) 18 | { 19 | result += n / 5; 20 | n /= 5; 21 | } 22 | 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /cpp/Find_Minimum_in_Rotated_Sorted_Array_II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Follow up for "Find Minimum in Rotated Sorted Array": 3 | What if duplicates are allowed? 4 | 5 | Would this affect the run-time complexity? How and why? 6 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 7 | 8 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 9 | 10 | Find the minimum element. 11 | 12 | The array may contain duplicates. 13 | */ 14 | 15 | class Solution 16 | { 17 | public: 18 | 19 | int findMin(vector &nums) 20 | { 21 | if (nums.empty()) 22 | return 0; 23 | 24 | int size = nums.size(); 25 | int left = 0; 26 | int right = size - 1; 27 | int mid; 28 | 29 | while (left < right && nums[left] >= nums[right]) 30 | { 31 | mid = (left + right) / 2; 32 | if (nums[mid] > nums[right]) 33 | { 34 | left = mid + 1; // mid不可能为最小了,所以+1 35 | } 36 | else if (nums[mid] < nums[right]) 37 | { 38 | right = mid; 39 | } 40 | else 41 | { 42 | left++; 43 | } 44 | } 45 | 46 | return nums[left]; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /cpp/Find_Peak_Element.cc: -------------------------------------------------------------------------------- 1 | /* 2 | A peak element is an element that is greater than its neighbors. 3 | 4 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 5 | 6 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 7 | 8 | You may imagine that num[-1] = num[n] = -∞. 9 | 10 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 11 | 12 | click to show spoilers. 13 | */ 14 | 15 | class Solution 16 | { 17 | public: 18 | int findPeakElement(const vector &num) 19 | { 20 | // 找驼峰。走到i-1这个位置,那么之前肯定没有返回,也就比左边的大。只需要比右边大即可 21 | for (int i = 1; i < num.size(); i++) 22 | { 23 | if (num[i-1] > num[i]) 24 | return i-1; 25 | } 26 | 27 | return num.size() - 1; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /cpp/Find_the_Difference.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings s and t which consist of only lowercase letters. 3 | 4 | String t is generated by random shuffling string s 5 | and then add one more letter at a random position. 6 | 7 | Find the letter that was added in t. 8 | 9 | Example: 10 | 11 | Input: 12 | s = "abcd" 13 | t = "abcde" 14 | 15 | Output: 16 | e 17 | 18 | Explanation: 19 | 'e' is the letter that was added. 20 | */ 21 | class Solution 22 | { 23 | public: 24 | char findTheDifference(string s, string t) 25 | { 26 | string tmp = t; 27 | for (auto c : s) 28 | { 29 | auto pos = tmp.find_first_of(c); 30 | assert(pos != string::npos); 31 | tmp.erase(pos, 1); 32 | } 33 | 34 | return tmp[0]; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /cpp/First_Unique_Character_in_a_String.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, find the first non-repeating character in it and return it's index. 3 | If it doesn't exist, return -1. 4 | 5 | Examples: 6 | 7 | s = "leetcode" 8 | return 0. 9 | 10 | s = "loveleetcode", 11 | return 2. 12 | Note: You may assume the string contain only lowercase letters 13 | */ 14 | 15 | class Solution 16 | { 17 | public: 18 | int firstUniqChar(string s) 19 | { 20 | map mapping; 21 | 22 | for (auto& c : s) 23 | { 24 | mapping[c]++; 25 | } 26 | for (int i = 0; i < s.size(); ++i) 27 | { 28 | if (mapping[s[i]] == 1) 29 | return i; 30 | } 31 | return -1; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /cpp/Fizz_Buzz.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that outputs the string representation of numbers from 1 to n. 3 | 4 | But for multiples of three it should output “Fizz” instead of the number 5 | and for the multiples of five output “Buzz”. 6 | For numbers which are multiples of both three and five output “FizzBuzz”. 7 | 8 | Example: 9 | 10 | n = 15, 11 | 12 | Return: 13 | [ 14 | "1", 15 | "2", 16 | "Fizz", 17 | "4", 18 | "Buzz", 19 | "Fizz", 20 | "7", 21 | "8", 22 | "Fizz", 23 | "Buzz", 24 | "11", 25 | "Fizz", 26 | "13", 27 | "14", 28 | "FizzBuzz" 29 | ] 30 | */ 31 | 32 | class Solution 33 | { 34 | public: 35 | vector fizzBuzz(int n) 36 | { 37 | vector result; 38 | 39 | for (int i = 1; i <= n; ++i) 40 | { 41 | if (i % (3 * 5) == 0) 42 | { 43 | result.emplace_back("FizzBuzz"); 44 | } 45 | else if (i % 3 == 0) 46 | { 47 | result.emplace_back("Fizz"); 48 | } 49 | else if (i % 5 == 0) 50 | { 51 | result.emplace_back("Buzz"); 52 | } 53 | else 54 | { 55 | result.emplace_back(to_string(i)); 56 | } 57 | } 58 | 59 | return result; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /cpp/Gas_Station.cc: -------------------------------------------------------------------------------- 1 | /* 2 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 3 | 4 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 5 | 6 | Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. 7 | 8 | Note: 9 | The solution is guaranteed to be unique. 10 | */ 11 | 12 | class Solution 13 | { 14 | public: 15 | int canCompleteCircuit(vector &gas, vector &cost) 16 | { 17 | const int n = gas.size(); 18 | int ret = 0, total = 0, tmp = 0; 19 | for (int i = 0; i < n; ++i) 20 | { 21 | total += gas[i] - cost[i]; 22 | tmp += gas[i] - cost[i]; 23 | if (tmp < 0) // 当入不敷出时 调整,重新开始 24 | { 25 | ret = i + 1; 26 | tmp = 0; 27 | } 28 | } 29 | return total >= 0 ? ret : -1; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /cpp/Generate_Parentheses.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | For example, given n = 3, a solution set is: 5 | 6 | "((()))", "(()())", "(())()", "()(())", "()()()" 7 | */ 8 | 9 | class Solution 10 | { 11 | public: 12 | vector generateParenthesis(int n) 13 | { 14 | vector result; 15 | string str; 16 | 17 | generator(result, n, n, str); 18 | 19 | return result; 20 | } 21 | private: 22 | void generator(vector& result, int left, int right, string str) 23 | { 24 | if (left == 0 && right == 0) 25 | { 26 | result.push_back(str); 27 | return; 28 | } 29 | 30 | if (left > 0) 31 | { 32 | generator(result, left - 1, right, str + "("); 33 | } 34 | if (right > 0 && right > left) 35 | { 36 | generator(result, left, right - 1, str + ")"); 37 | } 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /cpp/Gray_Code.cc: -------------------------------------------------------------------------------- 1 | /* 2 | The gray code is a binary numeral system where two successive values differ in only one bit. 3 | 4 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 5 | 6 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 7 | 8 | 00 - 0 9 | 01 - 1 10 | 11 - 3 11 | 10 - 2 12 | Note: 13 | For a given n, a gray code sequence is not uniquely defined. 14 | 15 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. 16 | 17 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. 18 | */ 19 | 20 | class Solution 21 | { 22 | public: 23 | vector grayCode(int n) 24 | { 25 | vector result(1 << n, 0); 26 | 27 | for (int i = 0; i < 1<> 1) ^ i; // http://en.wikipedia.org/wiki/Gray_code 30 | } 31 | 32 | return result; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /cpp/Happy_Number.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Write an algorithm to determine if a number is "happy". 3 | 4 | A happy number is a number defined by the following process: 5 | Starting with any positive integer, replace the number by the sum of the squares of its digits, 6 | and repeat the process until the number equals 1 (where it will stay), 7 | or it loops endlessly in a cycle which does not include 1. 8 | Those numbers for which this process ends in 1 are happy numbers. 9 | 10 | Example: 19 is a happy number 11 | 12 | 12 + 92 = 82 13 | 82 + 22 = 68 14 | 62 + 82 = 100 15 | 12 + 02 + 02 = 1 16 | */ 17 | 18 | class Solution 19 | { 20 | public: 21 | bool isHappy(int n) 22 | { 23 | unordered_map mapping; 24 | 25 | while (1) 26 | { 27 | if (n == 1) 28 | return true; 29 | 30 | if (mapping.find(n) == mapping.end()) // or mapping[n] == false 31 | mapping[n] = true; 32 | else 33 | return false; 34 | 35 | int sum = 0; 36 | while (n) 37 | { 38 | sum += (n % 10) * (n % 10); 39 | n /= 10; 40 | } 41 | n = sum; 42 | } 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /cpp/House_Robber.cc: -------------------------------------------------------------------------------- 1 | /* 2 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, 3 | the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and 4 | it will automatically contact the police if two adjacent houses were broken into on the same night. 5 | 6 | Given a list of non-negative integers representing the amount of money of each house, 7 | determine the maximum amount of money you can rob tonight without alerting the police. 8 | */ 9 | 10 | class Solution 11 | { 12 | public: 13 | int rob(vector& num) 14 | { 15 | const int n = num.size(); 16 | if (n <= 0) 17 | return 0; 18 | 19 | vector dp(n, 0); 20 | if (n >= 1) 21 | dp[0] = num[0]; 22 | if (n >= 2) 23 | dp[1] = std::max(num[0], num[1]); 24 | 25 | for (int i = 2; i < n; i++) 26 | { 27 | dp[i] = std::max(dp[i-1], dp[i-2] + num[i]); 28 | } 29 | 30 | return dp[n-1]; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /cpp/Implement_Queue_using_Stacks.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Implement the following operations of a queue using stacks. 3 | 4 | push(x) -- Push element x to the back of queue. 5 | pop() -- Removes the element from in front of queue. 6 | peek() -- Get the front element. 7 | empty() -- Return whether the queue is empty. 8 | Notes: 9 | You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, 10 | and is empty operations are valid. 11 | Depending on your language, stack may not be supported natively. 12 | You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. 13 | You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). 14 | */ 15 | 16 | class Queue 17 | { 18 | public: 19 | // Push element x to the back of queue. 20 | void push(int x) 21 | { 22 | s1_.push(x); 23 | } 24 | 25 | // Removes the element from in front of queue. 26 | void pop(void) 27 | { 28 | helper(s1_, s2_); 29 | s2_.pop(); 30 | helper(s2_, s1_); 31 | } 32 | 33 | // Get the front element. 34 | int peek(void) 35 | { 36 | helper(s1_, s2_); 37 | int ret = s2_.top(); 38 | helper(s2_, s1_); 39 | return ret; 40 | } 41 | 42 | // Return whether the queue is empty. 43 | bool empty(void) 44 | { 45 | return s1_.empty(); 46 | } 47 | private: 48 | void helper(stack& lhs, stack& rhs) 49 | { 50 | while (!lhs.empty()) 51 | { 52 | rhs.push(lhs.top()); 53 | lhs.pop(); 54 | } 55 | } 56 | stack s1_; 57 | stack s2_; 58 | }; 59 | -------------------------------------------------------------------------------- /cpp/Implement_Stack_using_Queues.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Implement the following operations of a stack using queues. 3 | 4 | push(x) -- Push element x onto stack. 5 | pop() -- Removes the element on top of the stack. 6 | top() -- Get the top element. 7 | empty() -- Return whether the stack is empty. 8 | Notes: 9 | You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. 10 | Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. 11 | You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). 12 | */ 13 | 14 | class Stack 15 | { 16 | public: 17 | // Push element x onto stack. 18 | void push(int x) 19 | { 20 | q_.push(x); 21 | } 22 | 23 | // Removes the element on top of the stack. 24 | void pop() 25 | { 26 | if (!empty()) 27 | { 28 | for (int i = 0; i < q_.size() - 1; i++) 29 | { 30 | q_.push(q_.front()); 31 | q_.pop(); 32 | } 33 | q_.pop(); 34 | } 35 | } 36 | 37 | // Get the top element. 38 | int top() 39 | { 40 | return q_.back(); 41 | } 42 | 43 | // Return whether the stack is empty. 44 | bool empty() 45 | { 46 | return q_.empty(); 47 | } 48 | private: 49 | queue q_; 50 | }; 51 | -------------------------------------------------------------------------------- /cpp/Implement_strStr().cc: -------------------------------------------------------------------------------- 1 | /* 2 | Implement strStr(). 3 | 4 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | int strStr(char *haystack, char *needle) 11 | { 12 | if (haystack == NULL || needle == NULL) 13 | return -1; 14 | 15 | int hLen = strlen(haystack); 16 | int nLen = strlen(needle); 17 | 18 | if (nLen == 0) 19 | return 0; 20 | 21 | if (hLen == 0) 22 | return -1; 23 | 24 | if (hLen < nLen) 25 | return -1; 26 | 27 | int i = 0, j = 0, k = -1; 28 | for ( ; i < hLen; i++) 29 | { 30 | j = 0; 31 | if (haystack[i] == needle[j] && j < nLen) 32 | { 33 | k = i; 34 | while (haystack[i] == needle[j] && j < nLen) 35 | { 36 | i++; 37 | j++; 38 | } 39 | 40 | if (needle[j] == '\0') 41 | return k; 42 | else 43 | i = k; 44 | } 45 | } 46 | 47 | return -1; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /cpp/Integer_to_Roman.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer, convert it to a roman numeral. 3 | 4 | Input is guaranteed to be within the range from 1 to 3999. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | string intToRoman(int num) 11 | { 12 | string symbol[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 13 | int value[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 14 | 15 | string result; 16 | 17 | // 贪心 18 | int i = 0; 19 | while (num > 0) 20 | { 21 | while (num >= value[i]) 22 | { 23 | result += symbol[i]; 24 | num -= value[i]; 25 | } 26 | i++; 27 | } 28 | 29 | return result; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /cpp/Intersection_of_Two_Arrays.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given two arrays, write a function to compute their intersection. 3 | 4 | Example: 5 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 6 | 7 | Note: 8 | Each element in the result must be unique. 9 | The result can be in any order. 10 | */ 11 | 12 | class Solution 13 | { 14 | public: 15 | vector intersection(vector& nums1, vector& nums2) 16 | { 17 | vector result; 18 | 19 | set tmp; 20 | for (const auto& i : nums1) 21 | { 22 | tmp.insert(i); 23 | } 24 | 25 | for (const auto& i : nums2) 26 | { 27 | if (tmp.count(i)) 28 | { 29 | result.push_back(i); 30 | tmp.erase(i); 31 | } 32 | } 33 | 34 | return result; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /cpp/Intersection_of_Two_Arrays_II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given two arrays, write a function to compute their intersection. 3 | 4 | Example: 5 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. 6 | 7 | Note: 8 | Each element in the result should appear as many times as it shows in both arrays. 9 | The result can be in any order. 10 | Follow up: 11 | What if the given array is already sorted? How would you optimize your algorithm? 12 | What if nums1's size is small compared to num2's size? Which algorithm is better? 13 | What if elements of nums2 are stored on disk, and the memory is limited 14 | such that you cannot load all elements into the memory at once? 15 | */ 16 | 17 | class Solution { 18 | public: 19 | vector intersect(vector& nums1, vector& nums2) 20 | { 21 | vector result; 22 | 23 | map tmp; 24 | for (const auto& i : nums1) 25 | { 26 | ++tmp[i]; 27 | } 28 | 29 | for (const auto& i : nums2) 30 | { 31 | if (tmp[i] > 0) 32 | { 33 | result.push_back(i); 34 | --tmp[i]; 35 | } 36 | } 37 | 38 | return result; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /cpp/Invert_Binary_Tree.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Invert a binary tree. 3 | 4 | 4 5 | / \ 6 | 2 7 7 | / \ / \ 8 | 1 3 6 9 9 | to 10 | 4 11 | / \ 12 | 7 2 13 | / \ / \ 14 | 9 6 3 1 15 | Trivia: 16 | Google: 90% of our engineers use the software you wrote (Homebrew), 17 | but you can’t invert a binary tree on a whiteboard so fuck off. 18 | */ 19 | 20 | /** 21 | * Definition for a binary tree node. 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | class Solution 30 | { 31 | public: 32 | TreeNode* invertTree(TreeNode* root) 33 | { 34 | if (root == NULL) 35 | return root; 36 | 37 | TreeNode* tmp = invertTree(root->left); 38 | root->left = invertTree(root->right); 39 | root->right = tmp; 40 | 41 | return root; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /cpp/Kth_Largest_Element_in_an_Array.cc: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | // quick sort 5 | int findKthLargest(vector& nums, int k) 6 | { 7 | int L = 0, R = nums.size() - 1; 8 | while (L < R) 9 | { 10 | int left = L, right = R; 11 | int key = nums[left]; 12 | while (left < right) 13 | { 14 | while (left < right && nums[right] < key) --right; 15 | nums[left] = nums[right]; 16 | while (left < right && nums[left] >= key) ++left; 17 | nums[right] = nums[left]; 18 | } 19 | nums[left] = key; 20 | if (left == k - 1) 21 | return nums[k - 1]; 22 | else if (left > k - 1) 23 | R = left - 1; 24 | else 25 | L = left + 1; 26 | } 27 | return nums[k - 1]; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /cpp/Length_of_Last_Word.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 3 | 4 | If the last word does not exist, return 0. 5 | 6 | Note: A word is defined as a character sequence consists of non-space characters only. 7 | 8 | For example, 9 | Given s = "Hello World", 10 | return 5. 11 | */ 12 | 13 | class Solution 14 | { 15 | public: 16 | int lengthOfLastWord(const char *s) 17 | { 18 | if (s == NULL) 19 | return 0; 20 | 21 | const char* p = s; 22 | while (*p != '\0') 23 | p++; 24 | 25 | p--; 26 | while (*p == ' ' && p >= s) 27 | p--; 28 | const char* end = p; 29 | 30 | while (isalpha(*p) && p >= s) 31 | p--; 32 | const char* begin = p + 1; 33 | 34 | return end - begin + 1; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /cpp/Letter_Combinations_of_a_Phone_Number.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a digit string, return all possible letter combinations that the number could represent. 3 | 4 | A mapping of digit to letters (just like on the telephone buttons) is given below. 5 | 6 | 7 | 8 | Input:Digit string "23" 9 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 10 | Note: 11 | Although the above answer is in lexicographical order, your answer could be in any order you want. 12 | */ 13 | 14 | class Solution 15 | { 16 | public: 17 | vector letterCombinations(string digits) 18 | { 19 | vector keyboard = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; // 0~9 20 | vector result; 21 | string path; 22 | 23 | dfs(keyboard, result, digits, path, 0); 24 | 25 | return result; 26 | } 27 | 28 | void dfs(vector& keyboard, vector& result, string& digits, string& path, int dIndex) 29 | { 30 | if (dIndex == digits.length()) 31 | { 32 | result.push_back(path); 33 | return; 34 | } 35 | int num = digits[dIndex] - '0'; 36 | for (int i = 0; i < keyboard[num].length(); i++) 37 | { 38 | //tmp.append(1, keyboard[num][i]); 39 | path.push_back(keyboard[num][i]); 40 | dfs(keyboard, result, digits, path, dIndex + 1); 41 | path.pop_back(); 42 | } 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /cpp/Linked_List_Cycle_II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 3 | 4 | Follow up: 5 | Can you solve it without using extra space? 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode(int x) : val(x), next(NULL) {} 14 | * }; 15 | */ 16 | class Solution 17 | { 18 | public: 19 | ListNode *detectCycle(ListNode *head) 20 | { 21 | ListNode* slow = head, *fast = head; 22 | ListNode* tmp = NULL; 23 | 24 | while (fast != NULL && fast->next != NULL) 25 | { 26 | slow = slow->next; 27 | fast = fast->next->next; 28 | 29 | if (slow == fast) 30 | { 31 | tmp = head; // 出发,相遇时在交点处 32 | while (tmp != slow) 33 | { 34 | tmp = tmp->next; 35 | slow = slow->next; 36 | } 37 | return tmp; 38 | } 39 | } 40 | 41 | return NULL; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /cpp/Longest_Common_Prefix.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | */ 4 | 5 | class Solution 6 | { 7 | public: 8 | string longestCommonPrefix(vector &strs) 9 | { 10 | if (strs.empty()) 11 | return ""; 12 | 13 | for (int i = 0; i < strs[0].size(); i++) 14 | { 15 | for (int j = 1; j < strs.size(); j++) 16 | { 17 | if (strs[0][i] != strs[j][i]) 18 | { 19 | //return strs[0].substr(0, i); 20 | //return string(strs[0].c_str(), i); 21 | return string(strs[0], 0, i); 22 | } 23 | } 24 | } 25 | 26 | return strs[0]; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /cpp/Longest_Consecutivec_Sequence.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 3 | 4 | For example, 5 | Given [100, 4, 200, 1, 3, 2], 6 | The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 7 | 8 | Your algorithm should run in O(n) complexity. 9 | */ 10 | 11 | class Solution 12 | { 13 | public: 14 | int longestConsecutive(vector &num) 15 | { 16 | map mapping; 17 | 18 | for(int i = 0; i < num.size(); i++) 19 | { 20 | mapping[num[i]] = i; 21 | } 22 | 23 | int longest = 0; 24 | for (int i = 0; i < num.size(); i++) 25 | { 26 | int cnt = 1; 27 | 28 | for(int n = num[i]+1; mapping.find(n) != mapping.end(); n++) 29 | { 30 | mapping.erase(mapping.find(n)); 31 | cnt++; 32 | } 33 | 34 | for(int n = num[i]-1; mapping.find(n) != mapping.end(); n--) 35 | { 36 | mapping.erase(mapping.find(n)); 37 | cnt++; 38 | } 39 | 40 | if (longest < cnt) 41 | longest = cnt; 42 | 43 | if(mapping.size() == 0) 44 | break; 45 | } 46 | 47 | return longest; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /cpp/Longest_Palindrome.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string which consists of lowercase or uppercase letters, 3 | find the length of the longest palindromes that can be built with those letters. 4 | 5 | This is case sensitive, for example "Aa" is not considered a palindrome here. 6 | 7 | Note: 8 | Assume the length of given string will not exceed 1,010. 9 | 10 | Example: 11 | 12 | Input: 13 | "abccccdd" 14 | 15 | Output: 16 | 7 17 | 18 | Explanation: 19 | One longest palindrome that can be built is "dccaccd", whose length is 7. 20 | */ 21 | class Solution 22 | { 23 | public: 24 | int longestPalindrome(string s) 25 | { 26 | int odds = 0; 27 | for (char c = 'A'; c <= 'z'; ++c) 28 | { 29 | odds += count(s.cbegin(), s.cend(), c) & 1; 30 | } 31 | 32 | return s.size() - odds + (odds > 0); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /cpp/Longest_Palindromic_Substring.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, find the longest palindromic substring in S. 3 | You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | string findPalindrome(string s, int left, int right) 10 | { 11 | const int len = s.size(); 12 | while (left >= 0 && right <= len-1 && s[left] == s[right]) 13 | { 14 | left--; 15 | right++; 16 | } 17 | return s.substr(left+1, right-left-1); 18 | } 19 | 20 | string longestPalindrome(string s) 21 | { 22 | const int len = s.size(); 23 | if (len <= 1) 24 | return s; 25 | 26 | string longest; 27 | string str; 28 | 29 | for (int i = 0; i < len-1; ++i) 30 | { 31 | str = findPalindrome(s, i, i); 32 | if (str.size() > longest.size()) 33 | longest = str; 34 | 35 | str = findPalindrome(s, i, i+1); 36 | if (str.size() > longest.size()) 37 | longest = str; 38 | } 39 | 40 | return longest; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /cpp/Majority_Element.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 3 | 4 | You may assume that the array is non-empty and the majority element always exist in the array. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | /* 11 | 每两个不同的,则一块删除。最后剩下就是所求的。 12 | 可扩展到n/k的情况,每k个不同的一块删除。 13 | */ 14 | int majorityElement(vector &num) 15 | { 16 | if (num.size() == 0) 17 | return 0; 18 | 19 | int result = num[0]; 20 | int cnt = 1; 21 | for (int i = 1; i < num.size(); i++) 22 | { 23 | if (cnt == 0) 24 | { 25 | result = num[i]; 26 | cnt = 1; 27 | } 28 | else 29 | { 30 | if (result == num[i]) 31 | cnt++; 32 | else 33 | cnt--; 34 | } 35 | } 36 | 37 | return result; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /cpp/Maximum_Subarray.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 3 | 4 | For example, given the array [−2,1,−3,4,−1,2,1,−5,4], 5 | the contiguous subarray [4,−1,2,1] has the largest sum = 6. 6 | */ 7 | 8 | class Solution 9 | { 10 | public: 11 | int maxSubArray(int A[], int n) 12 | { 13 | int sum = A[0], maxSum = A[0]; 14 | 15 | for (int i = 1; i < n; i++) 16 | { 17 | if (sum < 0) 18 | sum = 0; // 重新开始 19 | 20 | sum += A[i]; 21 | maxSum = std::max(maxSum, sum); 22 | } 23 | 24 | return maxSum; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /cpp/Merge_Sorted_Array.cc: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void merge(int A[], int m, int B[], int n) 5 | { 6 | int ia = m - 1, ib = n -1, icur = m + n - 1; 7 | while (ia >= 0 && ib >= 0) 8 | { 9 | // 从后向前! 10 | if (B[ib] >= A[ia]) 11 | { 12 | A[icur--] = B[ib--]; 13 | } 14 | else 15 | { 16 | A[icur--] = A[ia--]; 17 | } 18 | } 19 | 20 | while (ib >= 0) 21 | { 22 | A[icur--] = B[ib--]; 23 | } 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /cpp/Min_Stack.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 3 | 4 | push(x) -- Push element x onto stack. 5 | pop() -- Removes the element on top of the stack. 6 | top() -- Get the top element. 7 | getMin() -- Retrieve the minimum element in the stack. 8 | */ 9 | 10 | class MinStack 11 | { 12 | public: 13 | void push(int x) 14 | { 15 | stack_.push(x); 16 | if (x <= getMin()) 17 | { 18 | minStack_.push(x); 19 | } 20 | } 21 | 22 | void pop() 23 | { 24 | if (!stack_.empty()) 25 | { 26 | if (stack_.top() == minStack_.top()) 27 | { 28 | minStack_.pop(); 29 | } 30 | stack_.pop(); 31 | } 32 | } 33 | 34 | int top() 35 | { 36 | return stack_.top(); 37 | } 38 | 39 | int getMin() 40 | { 41 | if (!minStack_.empty()) 42 | { 43 | return minStack_.top(); 44 | } 45 | return INT_MAX; 46 | } 47 | private: 48 | stack stack_; 49 | stack minStack_; 50 | }; 51 | -------------------------------------------------------------------------------- /cpp/Minimum_Moves_to_Equal_Array_Elements.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty integer array of size n, 3 | find the minimum number of moves required to make all array elements equal, 4 | where a move is incrementing n - 1 elements by 1. 5 | 6 | Example: 7 | 8 | Input: 9 | [1,2,3] 10 | 11 | Output: 12 | 3 13 | 14 | Explanation: 15 | Only three moves are needed (remember each move increments two elements): 16 | 17 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 18 | */ 19 | class Solution 20 | { 21 | public: 22 | // 相当于每次最大的值减一;所有数字必然减少到最小值 23 | int minMoves(vector& nums) 24 | { 25 | return accumulate(nums.cbegin(), nums.cend(), 0) - 26 | nums.size() * *min_element(nums.cbegin(), nums.cend()); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /cpp/Minimum_Path_Sum.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 3 | 4 | Note: You can only move either down or right at any point in time. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | int minPathSum(vector >& grid) 11 | { 12 | if(grid.size() == 0 || grid[0].size() == 0) 13 | return 0; 14 | 15 | const int row = grid.size(), col = grid[0].size(); 16 | vector > dp(row, vector(col)); 17 | 18 | dp[0][0] = grid[0][0]; 19 | for (int i = 1; i < col; i++) 20 | { 21 | dp[0][i] = dp[0][i-1] + grid[0][i]; 22 | } 23 | for (int j = 1; j < row; j++) 24 | { 25 | dp[j][0] = dp[j-1][0] + grid[j][0]; 26 | } 27 | 28 | for (int i = 1; i < row; i++) 29 | { 30 | for (int j = 1; j < col; j++) 31 | { 32 | dp[i][j] = (dp[i-1][j] < dp[i][j-1] ? dp[i-1][j] : dp[i][j-1]) + grid[i][j]; 33 | } 34 | } 35 | 36 | return dp[row-1][col-1]; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /cpp/Move_Zeroes.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 4 | Note: 5 | You must do this in-place without making a copy of the array. 6 | Minimize the total number of operations. 7 | */ 8 | 9 | class Solution 10 | { 11 | public: 12 | void moveZeroes(vector& nums) 13 | { 14 | int first = 0; 15 | int second = 0; 16 | int size = nums.size(); 17 | 18 | while (first < size && second < size) 19 | { 20 | while (nums[second] != 0 && second < size) second++; // zero 21 | while (nums[first] == 0 && first < size) first++; // non-zero 22 | 23 | if (first < size && second < first) // need swap 24 | { 25 | int tmp = nums[first]; 26 | nums[first] = nums[second]; 27 | nums[second] = tmp; 28 | 29 | second++; 30 | first++; 31 | } 32 | else // don't need, move first 33 | first++; 34 | } 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /cpp/Nim_Game.cc: -------------------------------------------------------------------------------- 1 | /* 2 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, 3 | each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. 4 | You will take the first turn to remove the stones. 5 | 6 | Both of you are very clever and have optimal strategies for the game. 7 | Write a function to determine whether you can win the game given the number of stones in the heap. 8 | 9 | For example, if there are 4 stones in the heap, then you will never win the game: 10 | no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 11 | */ 12 | class Solution 13 | { 14 | public: 15 | bool canWinNim(int n) 16 | { 17 | return n % 4 != 0; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /cpp/Number_of_1_Bits.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 3 | 4 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | int hammingWeight(uint32_t n) 11 | { 12 | int cnt = 0; 13 | for (int i = 0; i < sizeof(n)*8; i++) 14 | { 15 | if ((n >> i) & 0x01) 16 | cnt++; 17 | } 18 | 19 | return cnt; 20 | } 21 | 22 | // n & (n-1)的作用:将n的二进制数中的低位的1改为0 23 | int hammingWeight2(uint32_t n) 24 | { 25 | int cnt = 0; 26 | while (n != 0) 27 | { 28 | n &= (n - 1); 29 | cnt++; 30 | } 31 | 32 | return cnt; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /cpp/Number_of_Boomerangs.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given n points in the plane that are all pairwise distinct, 3 | a "boomerang" is a tuple of points (i, j, k) such that the distance 4 | between i and j equals the distance between i and k (the order of the tuple matters). 5 | 6 | Find the number of boomerangs. 7 | You may assume that n will be at most 500 and 8 | coordinates of points are all in the range [-10000, 10000] (inclusive). 9 | 10 | Example: 11 | Input: 12 | [[0,0],[1,0],[2,0]] 13 | 14 | Output: 15 | 2 16 | 17 | Explanation: 18 | The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]] 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | int numberOfBoomerangs(vector>& points) 25 | { 26 | int result = 0; 27 | 28 | for (int i = 0; i < points.size(); ++i) 29 | { 30 | unordered_map group; 31 | for (int j = 0; j < points.size(); ++j) 32 | { 33 | if (j == i) continue; 34 | 35 | int dx = points[i].first - points[j].first; 36 | int dy = points[i].second - points[j].second; 37 | ++group[dx * dx + dy * dy]; 38 | } 39 | 40 | for (const auto& item : group) 41 | { 42 | if (item.second > 1) 43 | { 44 | result += item.second * (item.second - 1); 45 | } 46 | } 47 | } 48 | 49 | return result; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /cpp/Palindrome_Number.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Determine whether an integer is a palindrome. Do this without extra space. 3 | */ 4 | class Solution 5 | { 6 | public: 7 | bool isPalindrome(int x) 8 | { 9 | if (x < 0) 10 | return false; 11 | 12 | int d = 1; 13 | while (x / d >= 10) 14 | d *= 10; // 直接到最高位数 15 | 16 | while (x > 0) 17 | { 18 | int high = x / d; // 最高位 19 | int low = x % 10; // 最低位 20 | 21 | if (high != low) 22 | return false; 23 | 24 | x = x % d / 10; // 去掉最高位 和 最低位 25 | d /= 100; 26 | } 27 | 28 | return true; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /cpp/Palindrome_Partitioning.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return all possible palindrome partitioning of s. 5 | 6 | For example, given s = "aab", 7 | Return 8 | 9 | [ 10 | ["aa","b"], 11 | ["a","a","b"] 12 | ] 13 | */ 14 | 15 | class Solution 16 | { 17 | public: 18 | vector> partition(string s) 19 | { 20 | vector > result; 21 | vector item; 22 | 23 | dfs(s, 0, item, result); 24 | 25 | return result; 26 | } 27 | 28 | void dfs(string& s, int begin, vector& item, vector >& result) 29 | { 30 | if (begin == s.size()) 31 | { 32 | result.push_back(item); 33 | return; 34 | } 35 | for (int i = begin; i < s.size(); i++) 36 | { 37 | if (isPalindrome(s, begin, i)) 38 | { 39 | item.push_back(s.substr(begin, i-begin+1)); 40 | dfs(s, i+1, item, result); 41 | item.pop_back(); 42 | } 43 | } 44 | } 45 | 46 | bool isPalindrome(string& s, int begin, int end) 47 | { 48 | while (begin < end) 49 | { 50 | if (s[begin++] != s[end--]) 51 | return false; 52 | } 53 | return true; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /cpp/Partition_List.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 3 | 4 | You should preserve the original relative order of the nodes in each of the two partitions. 5 | 6 | For example, 7 | Given 1->4->3->2->5->2 and x = 3, 8 | return 1->2->2->4->3->5. 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | class Solution 20 | { 21 | public: 22 | ListNode *partition(ListNode *head, int x) 23 | { 24 | ListNode dummy(0), *ins = &dummy, *cur = &dummy; 25 | dummy.next = head; 26 | 27 | while (cur->next != NULL) // 终止循环:cur指向最后结点 28 | { 29 | if (cur->next->val >= x) 30 | { 31 | cur = cur->next; // ins不动,只cur移动 32 | } 33 | else 34 | { 35 | if (cur == ins) 36 | { 37 | cur = cur->next; 38 | ins = ins->next; 39 | } 40 | else 41 | { 42 | ListNode *tmp = cur->next; 43 | cur->next = tmp->next; 44 | tmp->next = ins->next; 45 | ins->next = tmp; 46 | ins = tmp; 47 | } 48 | } 49 | } 50 | 51 | return dummy.next; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /cpp/Pascal's_Triangle.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given numRows, generate the first numRows of Pascal's triangle. 3 | 4 | For example, given numRows = 5, 5 | Return 6 | 7 | [ 8 | [1], 9 | [1,1], 10 | [1,2,1], 11 | [1,3,3,1], 12 | [1,4,6,4,1] 13 | ] 14 | */ 15 | 16 | class Solution 17 | { 18 | public: 19 | vector > generate(int numRows) 20 | { 21 | vector > result; 22 | if (numRows == 0) 23 | return result; 24 | 25 | result.push_back(vector(1, 1)); // 第一行 1个1 26 | 27 | for (int i = 2; i <= numRows; i++) 28 | { 29 | const vector& prev = result[i-2]; // 上一行 30 | 31 | vector current; 32 | current.push_back(1); // 开头 33 | for (int j = 1; j < i - 1; j++) // 中间 34 | { 35 | current.push_back(prev[j-1] + prev[j]); 36 | } 37 | current.push_back(1); // 结尾 38 | 39 | result.push_back(current); 40 | } 41 | 42 | return result; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /cpp/Pascal's_Triangle_II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an index k, return the kth row of the Pascal's triangle. 3 | 4 | For example, given k = 3, 5 | Return [1,3,3,1]. 6 | 7 | Note: 8 | Could you optimize your algorithm to use only O(k) extra space? 9 | */ 10 | 11 | class Solution 12 | { 13 | public: 14 | // use only O(k) extra space 15 | vector getRow(int rowIndex) 16 | { 17 | vector result; 18 | 19 | for (int i = 0; i <= rowIndex; i++) 20 | { 21 | for (int j = i - 1; j > 0; j--) 22 | { 23 | result[j] = result[j-1] + result[j]; 24 | } 25 | result.push_back(1); 26 | } 27 | 28 | return result; 29 | } 30 | /* 31 | vector getRow(int rowIndex) 32 | { 33 | if (rowIndex < 0) 34 | return vector(); 35 | if (rowIndex == 0) 36 | return vector(1,1); 37 | 38 | vector prev = vector(1, 1); 39 | for (int i = 1; i <= rowIndex; i++) 40 | { 41 | vector result; 42 | result.push_back(1); 43 | for (int j = 1; j < i; j++) 44 | { 45 | result.push_back(prev[j-1] + prev[j]); 46 | } 47 | result.push_back(1); 48 | 49 | prev = result; 50 | } 51 | 52 | return prev; 53 | } 54 | */ 55 | }; 56 | -------------------------------------------------------------------------------- /cpp/Permutations.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of numbers, return all possible permutations. 3 | 4 | For example, 5 | [1,2,3] have the following permutations: 6 | [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. 7 | */ 8 | 9 | class Solution 10 | { 11 | public: 12 | /* 13 | 1 2 3 14 | 1 3 2 15 | 2 1 3 16 | 2 3 1 17 | 3 1 2 18 | 3 2 1 19 | */ 20 | vector > permute(vector& num) 21 | { 22 | vector > result; 23 | vector available(num.size(), true); 24 | 25 | vector item; 26 | dfs(num, available, item, result); 27 | 28 | return result; 29 | } 30 | 31 | void dfs(const vector& num, vector& available, vector& item, vector >& result) 32 | { 33 | if (item.size() == num.size()) 34 | { 35 | result.push_back(item); 36 | return; 37 | } 38 | for (int i = 0; i < num.size(); ++i) 39 | { 40 | if (available[i]) 41 | { 42 | available[i] = false; 43 | item.push_back(num[i]); 44 | dfs(num, available, item, result); 45 | item.pop_back(); 46 | available[i] = true; 47 | } 48 | } 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /cpp/Plus_One.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-negative number represented as an array of digits, plus one to the number. 3 | 4 | The digits are stored such that the most significant digit is at the head of the list. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | vector plusOne(vector &digits) 11 | { 12 | typedef vector::reverse_iterator r_iter; 13 | int carry = 0; 14 | 15 | r_iter it = digits.rbegin(); 16 | *it += 1; 17 | for (r_iter it = digits.rbegin(); it != digits.rend(); it++) 18 | { 19 | *it += carry; 20 | if (*it == 10) 21 | { 22 | carry = 1; 23 | *it %= 10; 24 | } 25 | else 26 | { 27 | carry = 0; 28 | } 29 | } 30 | 31 | if (carry == 1) 32 | digits.insert(digits.begin(), 1); 33 | 34 | return digits; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /cpp/Power_of_Four.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 3 | 4 | Example: 5 | Given num = 16, return true. Given num = 5, return false. 6 | 7 | Follow up: Could you solve it without loops/recursion? 8 | */ 9 | class Solution 10 | { 11 | public: 12 | bool isPowerOfFour(int num) 13 | { 14 | while (num && !(num & 0b11)) 15 | { 16 | num >>= 2; 17 | } 18 | 19 | return num == 1; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /cpp/Power_of_Three.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer, write a function to determine if it is a power of three. 3 | 4 | Follow up: 5 | Could you do it without using any loop / recursion? 6 | */ 7 | class Solution 8 | { 9 | public: 10 | bool isPowerOfThree(int n) 11 | { 12 | for (; n > 1; n /= 3) 13 | { 14 | if (n % 3 != 0) return false; 15 | } 16 | 17 | return n == 1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /cpp/Power_of_Two.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer, write a function to determine if it is a power of two. 3 | */ 4 | 5 | class Solution 6 | { 7 | public: 8 | bool isPowerOfTwo(int n) 9 | { 10 | return n > 0 && (n & (n - 1)) == 0; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /cpp/Ransom_Note.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 3 | write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
 4 | otherwise, 
it 
will 
return 
false. 

 5 | 6 | Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note. 7 | 8 | Note: 9 | You may assume that both strings contain only lowercase letters. 10 | 11 | canConstruct("a", "b") -> false 12 | canConstruct("aa", "ab") -> false 13 | canConstruct("aa", "aab") -> true 14 | */ 15 | 16 | class Solution 17 | { 18 | public: 19 | bool canConstruct(string ransomNote, string magazine) 20 | { 21 | vector counts(26); 22 | int letters = 0; 23 | for (const auto& c : ransomNote) 24 | { 25 | if (counts[c-'a']++ == 0) 26 | { 27 | ++letters; 28 | } 29 | } 30 | 31 | for (const auto& c : magazine) 32 | { 33 | if (--counts[c-'a'] == 0 && --letters == 0) 34 | { 35 | // 如果满足了,那么可以提早退出循环 36 | break; 37 | } 38 | } 39 | return letters == 0; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /cpp/Remove_Duplicates_from_Sorted_Array.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 3 | 4 | Do not allocate extra space for another array, you must do this in place with constant memory. 5 | 6 | For example, 7 | Given input array A = [1,1,2], 8 | 9 | Your function should return length = 2, and A is now [1,2]. 10 | */ 11 | 12 | class Solution 13 | { 14 | public: 15 | int removeDuplicates(int A[], int n) 16 | { 17 | if (n == 0) 18 | return 0; 19 | 20 | int index = 0; // 新数组索引 21 | for (int i = 1; i < n; i++) 22 | { 23 | if (A[index] != A[i]) 24 | { 25 | A[++index] = A[i]; 26 | } 27 | } 28 | 29 | return index + 1; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /cpp/Remove_Duplicates_from_Sorted_List.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted linked list, delete all duplicates such that each element appear only once. 3 | 4 | For example, 5 | Given 1->1->2, return 1->2. 6 | Given 1->1->2->3->3, return 1->2->3. 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * struct ListNode { 12 | * int val; 13 | * ListNode *next; 14 | * ListNode(int x) : val(x), next(NULL) {} 15 | * }; 16 | */ 17 | class Solution 18 | { 19 | public: 20 | ListNode *deleteDuplicates(ListNode *head) 21 | { 22 | if (head == NULL || head->next == NULL) 23 | return head; 24 | 25 | ListNode* pPre = head; 26 | ListNode* pCur = head->next; 27 | while (pCur != NULL) 28 | { 29 | if (pPre->val == pCur->val) 30 | { 31 | pPre->next = pCur->next; 32 | delete pCur; 33 | } 34 | else 35 | { 36 | pPre->next = pCur; 37 | pPre = pPre->next; 38 | } 39 | 40 | pCur = pCur->next; 41 | } 42 | 43 | return head; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /cpp/Remove_Element.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array and a value, remove all instances of that value in place and return the new length. 3 | 4 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | int removeElement(int A[], int n, int elem) 11 | { 12 | int num = 0; 13 | for(int i = 0; i < n-num; i++) 14 | { 15 | if (A[i] == elem) 16 | { 17 | A[i] = A[n-1-num]; // 把最后的元素放到这个'坑' 18 | num++; 19 | i--; 20 | } 21 | } 22 | return n-num; 23 | } 24 | /*更简单点的 25 | int removeElement(int A[], int n, int elem) 26 | { 27 | int index = 0; 28 | for (int i = 0; i < n; ++i) 29 | { 30 | if (A[i] != elem) 31 | { 32 | A[index++] = A[i]; 33 | } 34 | } 35 | return index; 36 | } 37 | */ 38 | }; 39 | -------------------------------------------------------------------------------- /cpp/Reverse_Bits.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse bits of a given 32 bits unsigned integer. 3 | 4 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), 5 | return 964176192 (represented in binary as 00111001011110000010100101000000). 6 | 7 | Follow up: 8 | If this function is called many times, how would you optimize it? 9 | 10 | Related problem: Reverse Integer 11 | */ 12 | 13 | class Solution 14 | { 15 | public: 16 | uint32_t reverseBits(uint32_t n) 17 | { 18 | uint32_t ret = 0; 19 | 20 | for (int i = 0; i < 8*sizeof(uint32_t); i++) 21 | { 22 | if ((n >> i) & 0x1) 23 | { 24 | ret = (ret << 1) | 0x1; 25 | } 26 | else 27 | { 28 | ret <<= 1; 29 | } 30 | } 31 | 32 | return ret; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /cpp/Reverse_Integer.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse digits of an integer. 3 | Example1: x = 123, return 321 4 | Example2: x = -123, return -321 5 | */ 6 | class Solution 7 | { 8 | public: 9 | int reverse(int x) 10 | { 11 | // 不用单独处理正负 12 | //int ret = 0; // 错 无法保存 ret INT_MAX 13 | long long ret = 0; 14 | while (x) 15 | { 16 | ret = ret * 10 + (x % 10); 17 | x /= 10; 18 | } 19 | 20 | if (ret < INT_MIN || ret > INT_MAX) 21 | return 0; 22 | 23 | return ret; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /cpp/Reverse_Linked_List _II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 3 | 4 | For example: 5 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 6 | 7 | return 1->4->3->2->5->NULL. 8 | 9 | Note: 10 | Given m, n satisfy the following condition: 11 | 1 ≤ m ≤ n ≤ length of list. 12 | */ 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * struct ListNode { 17 | * int val; 18 | * ListNode *next; 19 | * ListNode(int x) : val(x), next(NULL) {} 20 | * }; 21 | */ 22 | class Solution 23 | { 24 | public: 25 | // 画图推倒,一目了然 26 | ListNode *reverseBetween(ListNode *head, int m, int n) 27 | { 28 | if (head == NULL || m >= n) 29 | return head; 30 | 31 | ListNode dummy(0); 32 | dummy.next = head; 33 | ListNode* pPrev = &dummy; 34 | 35 | for (int i = 0; i < m-1; i++) 36 | pPrev = pPrev->next; 37 | 38 | ListNode* pCur = pPrev->next; 39 | for (int i = 0; i < n-m; i++) 40 | { 41 | ListNode* pNext = pCur->next; 42 | 43 | pCur->next = pNext->next; 44 | pNext->next = pPrev->next; 45 | pPrev->next = pNext; 46 | 47 | } 48 | 49 | return dummy.next; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /cpp/Reverse_Linked_List.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a singly linked list. 3 | 4 | click to show more hints. 5 | 6 | Hint: 7 | A linked list can be reversed either iteratively or recursively. Could you implement both? 8 | */ 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * struct ListNode { 13 | * int val; 14 | * ListNode *next; 15 | * ListNode(int x) : val(x), next(NULL) {} 16 | * }; 17 | */ 18 | class Solution 19 | { 20 | public: 21 | ListNode* reverseList(ListNode* head) 22 | { 23 | if (head == NULL || head->next == NULL) 24 | return head; 25 | 26 | ListNode* pPre = NULL; 27 | ListNode* pCur = head; 28 | ListNode* pNext = pCur->next; 29 | 30 | while (pCur != NULL) 31 | { 32 | pNext = pCur->next; 33 | pCur->next = pPre; 34 | pPre = pCur; 35 | pCur = pNext; 36 | } 37 | head = pPre; 38 | 39 | return head; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /cpp/Reverse_String.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that takes a string as input and returns the string reversed. 3 | 4 | Example: 5 | Given s = "hello", return "olleh". 6 | */ 7 | 8 | class Solution 9 | { 10 | public: 11 | string reverseString(string s) 12 | { 13 | if (s.size() == 0) 14 | return s; 15 | 16 | int left = 0, right = s.size() - 1; 17 | while (left < right) 18 | { 19 | char tmp = s[left]; 20 | s[left] = s[right]; 21 | s[right] = tmp; 22 | left++; 23 | right--; 24 | } 25 | 26 | return s; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /cpp/Reverse_Vowels_of_a_String.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that takes a string as input and reverse only the vowels of a string. 3 | 4 | Example 1: 5 | Given s = "hello", return "holle". 6 | 7 | Example 2: 8 | Given s = "leetcode", return "leotcede". 9 | */ 10 | 11 | class Solution 12 | { 13 | public: 14 | string reverseVowels(string s) 15 | { 16 | if (s.size() == 0) 17 | return s; 18 | 19 | int left = 0, right = s.size() - 1; 20 | while (left < right) 21 | { 22 | if (!isVowel(tolower(s[left]))) 23 | ++left; 24 | else if (!isVowel(tolower(s[right]))) 25 | --right; 26 | else 27 | { 28 | char tmp = s[left]; 29 | s[left] = s[right]; 30 | s[right] = tmp; 31 | left++; 32 | right--; 33 | } 34 | } 35 | 36 | return s; 37 | } 38 | 39 | private: 40 | const string vowels_ = "aeiou"; 41 | bool isVowel(char c) 42 | { 43 | return vowels_.find(c) != string::npos; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /cpp/Rotate_Array.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Rotate an array of n elements to the right by k steps. 3 | 4 | For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. 5 | 6 | Note: 7 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 8 | 9 | [show hint] 10 | 11 | Related problem: Reverse Words in a String II 12 | */ 13 | 14 | class Solution 15 | { 16 | public: 17 | void rotate(int nums[], int n, int k) 18 | { 19 | if (k <= 0) 20 | return; 21 | 22 | k %= n; // don't forget this 23 | 24 | _reverse(nums, n-k, n-1); 25 | _reverse(nums, 0, n-k-1); 26 | _reverse(nums, 0, n-1); 27 | } 28 | 29 | void _reverse(int num[], int left, int right) 30 | { 31 | int tmp; 32 | while (left < right) 33 | { 34 | tmp = num[left]; 35 | num[left++] = num[right]; 36 | num[right--] = tmp; 37 | } 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /cpp/Rotate_Image.cc: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an n x n 2D matrix representing an image. 3 | 4 | Rotate the image by 90 degrees (clockwise). 5 | 6 | Follow up: 7 | Could you do this in-place? 8 | */ 9 | 10 | class Solution 11 | { 12 | public: 13 | // 对角线分成四部分 14 | void rotate(vector>& matrix) 15 | { 16 | int n = matrix.size(); 17 | 18 | for (int i = 0; i < n / 2; i++) 19 | { 20 | for (int j = i; j < n - i - 1; j++) 21 | { 22 | int tmp = matrix[i][j]; 23 | 24 | matrix[i][j] = matrix[n-j-1][i]; 25 | matrix[n-j-1][i] = matrix[n-i-1][n-j-1]; 26 | matrix[n-i-1][n-j-1] = matrix[j][n-i-1]; 27 | matrix[j][n-i-1] = tmp; 28 | } 29 | } 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /cpp/Rotate_List.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a list, rotate the list to the right by k places, where k is non-negative. 3 | 4 | For example: 5 | Given 1->2->3->4->5->NULL and k = 2, 6 | return 4->5->1->2->3->NULL. 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * struct ListNode { 12 | * int val; 13 | * ListNode *next; 14 | * ListNode(int x) : val(x), next(NULL) {} 15 | * }; 16 | */ 17 | class Solution 18 | { 19 | public: 20 | ListNode *rotateRight(ListNode *head, int k) 21 | { 22 | if (head == NULL || k <= 0) 23 | return head; 24 | 25 | // 得到链表长度 26 | int len = 1; 27 | ListNode* p1 = head; 28 | while (p1->next != NULL) 29 | { 30 | p1 = p1->next; 31 | len++; 32 | } 33 | 34 | k = k % len; // 这里排除了一种k==len时会造成 形成了环 的情况。k==len,k=0; 35 | 36 | // 这里想要到达 前一结点。就要想到是否存在前一结点。那么设一dummy结点。 37 | ListNode dummy(0), *p2 = &dummy; 38 | dummy.next = head; 39 | 40 | for (int i = 0; i < len-k; i++) 41 | p2 = p2->next; 42 | 43 | p1->next = head; 44 | head = p2->next; 45 | p2->next = NULL; 46 | 47 | return head; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /cpp/Same_Tree.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given two binary trees, write a function to check if they are equal or not. 3 | 4 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 5 | */ 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution 17 | { 18 | public: 19 | bool isSameTree(TreeNode *p, TreeNode *q) 20 | { 21 | if (p == NULL && q == NULL) 22 | return true; 23 | if (p == NULL || q == NULL) 24 | return false; 25 | if (p->val != q->val) 26 | return false; 27 | 28 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /cpp/Search_Insert_Position.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 3 | 4 | You may assume no duplicates in the array. 5 | 6 | Here are few examples. 7 | [1,3,5,6], 5 → 2 8 | [1,3,5,6], 2 → 1 9 | [1,3,5,6], 7 → 4 10 | [1,3,5,6], 0 → 0 11 | */ 12 | 13 | class Solution 14 | { 15 | public: 16 | int searchInsert(int A[], int n, int target) 17 | { 18 | int left = 0, right = n - 1; 19 | int mid; 20 | 21 | while (left <= right) 22 | { 23 | mid = left + (right - left) / 2; 24 | 25 | if (A[mid] == target) 26 | return mid; 27 | if (A[mid] < target) 28 | left = mid + 1; 29 | else 30 | right = mid - 1; 31 | } 32 | 33 | return left; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /cpp/Set_Matrix_Zeroes.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 3 | */ 4 | 5 | class Solution 6 | { 7 | public: 8 | void setZeroes(vector>& matrix) 9 | { 10 | bool rArray[matrix.size()] = {false}; 11 | bool cArray[matrix[0].size()] = {false}; 12 | for (int row = 0; row < matrix.size(); row++) 13 | { 14 | for (int col = 0; col < matrix[row].size(); col++) 15 | { 16 | if (matrix[row][col] == 0) 17 | { 18 | rArray[row] = true; 19 | cArray[col] = true; 20 | } 21 | } 22 | } 23 | 24 | for (int row = 0; row < matrix.size(); row++) 25 | { 26 | for (int col = 0; col < matrix[0].size(); col++) 27 | { 28 | if (rArray[row] || cArray[col]) 29 | matrix[row][col] = 0; 30 | } 31 | } 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /cpp/Single_Number.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, every element appears twice except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | */ 7 | 8 | class Solution 9 | { 10 | public: 11 | //偶数次,异或为零 12 | int singleNumber(int A[], int n) 13 | { 14 | int result = 0; 15 | for (int i = 0; i < n; i++) 16 | { 17 | result ^= A[i]; 18 | } 19 | return result; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /cpp/Single_Number_II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, every element appears three times except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | */ 7 | 8 | class Solution 9 | { 10 | public: 11 | // 这种方法可以拓展为 every element appears k times except for one 12 | int singleNumber(int A[], int n) 13 | { 14 | int result = 0; 15 | int count[32] = {0}; // 保存每个位的次数 16 | 17 | for (int bit = 0; bit < 32; bit++) 18 | { 19 | for (int index = 0; index < n; index ++) 20 | { 21 | if ((A[index] >> bit) & 1) 22 | { 23 | count[bit]++; 24 | } 25 | } 26 | result |= ((count[bit] % 3) << bit); // 拼出the single one 27 | } 28 | 29 | return result; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /cpp/String_to_Integer.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Implement atoi to convert a string to an integer. 3 | 4 | Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. 5 | 6 | Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. 7 | */ 8 | 9 | class Solution 10 | { 11 | public: 12 | int atoi(const char *str) 13 | { 14 | int num = 0; 15 | int sign = 1; // 默认正 16 | const int n = strlen(str); 17 | int i = 0; 18 | 19 | // 空格处理 20 | while (str[i] == ' ' && i < n) 21 | i++; 22 | 23 | // 符号处理 24 | if (str[i] == '+') 25 | { 26 | i++; 27 | } 28 | else if (str[i] == '-') 29 | { 30 | sign = -1; 31 | i++; 32 | } // 没有else哦 33 | 34 | // 处理数字部分 35 | for (; i < n; i++) 36 | { 37 | if (str[i] < '0' || str[i] > '9') 38 | break; 39 | if (num > INT_MAX / 10 || 40 | (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10)) 41 | { 42 | return sign == -1 ? INT_MIN : INT_MAX; 43 | } 44 | 45 | num = num * 10 + str[i] - '0'; // 核心 46 | } 47 | 48 | return num * sign; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /cpp/Subsets_II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of integers that might contain duplicates, S, return all possible subsets. 3 | 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | For example, 8 | If S = [1,2,2], a solution is: 9 | 10 | [ 11 | [2], 12 | [1], 13 | [1,2,2], 14 | [2,2], 15 | [1,2], 16 | [] 17 | ] 18 | */ 19 | 20 | class Solution 21 | { 22 | public: 23 | vector > subsetsWithDup(vector &S) 24 | { 25 | sort(S.begin(),S.end()); 26 | vector > result; 27 | vector path; 28 | 29 | dfs(S, result, path, 0); 30 | 31 | return result; 32 | } 33 | private: 34 | void dfs(vector& S, vector >& result, vector& path, int step) 35 | { 36 | result.push_back(path); 37 | for (int i = step; i < S.size(); i++) 38 | { 39 | if (i != step && S[i] == S[i-1]) 40 | continue; 41 | path.push_back(S[i]); 42 | dfs(S, result, path, i+1); 43 | path.pop_back(); 44 | } 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /cpp/Sum_of_Left_Leaves.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Find the sum of all left leaves in a given binary tree. 3 | 4 | Example: 5 | 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | 12 | There are two left leaves in the binary tree, 13 | with values 9 and 15 respectively. Return 24. 14 | */ 15 | class Solution 16 | { 17 | public: 18 | int sumOfLeftLeaves(TreeNode* root) 19 | { 20 | int result = 0; 21 | 22 | if (root != NULL) 23 | { 24 | sumOfLeftLeaves(root, result, false); 25 | } 26 | return result; 27 | } 28 | 29 | private: 30 | void sumOfLeftLeaves(TreeNode* root, int& result, bool isleft) 31 | { 32 | if (root->left == NULL && root->right == NULL && isleft) 33 | { 34 | result += root->val; 35 | } 36 | 37 | if (root->left != NULL) 38 | { 39 | sumOfLeftLeaves(root->left, result, true); 40 | } 41 | 42 | if (root->right != NULL) 43 | { 44 | sumOfLeftLeaves(root->right, result, false); 45 | } 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /cpp/Swap_Nodes_in_Pairs.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, swap every two adjacent nodes and return its head. 3 | 4 | For example, 5 | Given 1->2->3->4, you should return the list as 2->1->4->3. 6 | 7 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 8 | */ 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * struct ListNode { 13 | * int val; 14 | * ListNode *next; 15 | * ListNode(int x) : val(x), next(NULL) {} 16 | * }; 17 | */ 18 | class Solution 19 | { 20 | public: 21 | ListNode *swapPairs(ListNode *head) 22 | { 23 | ListNode dummy(0), *cur = &dummy; 24 | dummy.next = head; 25 | 26 | while (cur->next != NULL && cur->next->next != NULL) 27 | { 28 | ListNode* tmp = cur->next->next; 29 | cur->next->next = tmp->next; 30 | tmp->next = cur->next; 31 | cur->next = tmp; 32 | 33 | cur = tmp->next; 34 | } 35 | 36 | return dummy.next; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /cpp/Symmetric_Tree.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 3 | 4 | For example, this binary tree is symmetric: 5 | 6 | 1 7 | / \ 8 | 2 2 9 | / \ / \ 10 | 3 4 4 3 11 | But the following is not: 12 | 1 13 | / \ 14 | 2 2 15 | \ \ 16 | 3 3 17 | */ 18 | 19 | /** 20 | * Definition for binary tree 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | class Solution 29 | { 30 | public: 31 | bool isSymmetric(TreeNode* root) 32 | { 33 | if (root == NULL) 34 | return true; 35 | 36 | return isSymmetric(root->left, root->right); 37 | } 38 | private: 39 | bool isSymmetric(TreeNode* left, TreeNode* right) 40 | { 41 | if (left == NULL) 42 | return right == NULL; 43 | 44 | if (right == NULL) 45 | return false; 46 | 47 | if (left->val != right->val) 48 | return false; 49 | 50 | return (isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left)); 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /cpp/Top_K_Frequent_Elements.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty array of integers, return the k most frequent elements. 3 | 4 | For example, 5 | Given [1,1,1,2,2,3] and k = 2, return [1,2]. 6 | 7 | Note: 8 | You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 9 | Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 10 | */ 11 | 12 | class Solution 13 | { 14 | public: 15 | vector topKFrequent(vector& nums, int k) 16 | { 17 | vector result; 18 | 19 | map counts; 20 | for (const auto& i : nums) 21 | { 22 | ++counts[i]; 23 | } 24 | 25 | vector> tmp; 26 | for (auto it = counts.begin(); it != counts.end(); ++it) 27 | { 28 | tmp.emplace_back(it->second, it->first); 29 | } 30 | nth_element(tmp.begin(), tmp.begin() + k - 1, tmp.end(), compareFunc); 31 | 32 | for (int i = 0; i < k; i++) 33 | { 34 | result.push_back(tmp[i].second); 35 | } 36 | 37 | return result; 38 | } 39 | 40 | static bool compareFunc(const pair& lhs, const pair& rhs) 41 | { 42 | return lhs.first > rhs.first; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /cpp/Triangle.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 3 | 4 | For example, given the following triangle 5 | [ 6 | [2], 7 | [3,4], 8 | [6,5,7], 9 | [4,1,8,3] 10 | ] 11 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 12 | 13 | Note: 14 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 15 | */ 16 | 17 | class Solution 18 | { 19 | public: 20 | /* 21 | int minimumTotal(vector>& triangle) 22 | { 23 | int result = INT_MAX; 24 | 25 | dfs(triangle, 0, 0, 0, result); 26 | 27 | return result; 28 | } 29 | void dfs(vector >& triangle, int pathSum, int level, int position, int& result) 30 | { 31 | if (level == triangle.size()) 32 | { 33 | result = std::min(result, pathSum); 34 | return; 35 | } 36 | 37 | for (int i = position; i <= position+1 && i < triangle[level].size(); i++) 38 | { 39 | dfs(triangle, pathSum + triangle[level][i], level+1, i, result); 40 | } 41 | } 42 | */ 43 | int minimumTotal(vector>& triangle) 44 | { 45 | for (int i = triangle.size() - 2; i >= 0; --i) 46 | { 47 | for (int j = 0; j < i + 1; ++j) 48 | triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]); 49 | } 50 | 51 | return triangle[0][0]; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /cpp/Two_Sum_II-Input_array_is_sorted.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers that is already sorted in ascending order, 3 | find two numbers such that they add up to a specific target number. 4 | 5 | The function twoSum should return indices of the two numbers such that they add up to the target, 6 | where index1 must be less than index2. 7 | Please note that your returned answers (both index1 and index2) are not zero-based. 8 | 9 | You may assume that each input would have exactly one solution. 10 | 11 | Input: numbers={2, 7, 11, 15}, target=9 12 | Output: index1=1, index2=2 13 | */ 14 | 15 | class Solution 16 | { 17 | public: 18 | vector twoSum(vector& numbers, int target) 19 | { 20 | vector result; 21 | int left = 0; 22 | int right = numbers.size() - 1; 23 | 24 | while (left < right) 25 | { 26 | if (numbers[left] + numbers[right] > target) 27 | { 28 | right--; 29 | } 30 | else if (numbers[left] + numbers[right] < target) 31 | { 32 | left++; 33 | } 34 | else 35 | { 36 | result.push_back(left+1); 37 | result.push_back(right+1); 38 | return result; 39 | } 40 | } 41 | 42 | return result; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /cpp/Ugly_Number.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to check whether a given number is an ugly number. 3 | 4 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 5 | For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 6 | 7 | Note that 1 is typically treated as an ugly number. 8 | */ 9 | 10 | class Solution 11 | { 12 | public: 13 | bool isUgly(int num) 14 | { 15 | if (num <= 0) return false; 16 | if (num == 1) return true; 17 | 18 | while (num % 2 == 0) num /= 2; 19 | while (num % 3 == 0) num /= 3; 20 | while (num % 5 == 0) num /= 5; 21 | 22 | return num == 1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /cpp/Ugly_Number_II.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to find the n-th ugly number. 3 | 4 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 5 | For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 6 | 7 | Note that 1 is typically treated as an ugly number. 8 | */ 9 | 10 | class Solution 11 | { 12 | public: 13 | int nthUglyNumber(int n) 14 | { 15 | int i = 0, j = 0, k = 0; 16 | vector v{1}; 17 | 18 | while (v.size() < n) 19 | { 20 | int nextUgly = min(min(v[i]*2, v[j]*3), v[k]*5); 21 | v.push_back(nextUgly); 22 | if (nextUgly == v[i]*2) i++; 23 | if (nextUgly == v[j]*3) j++; 24 | if (nextUgly == v[k]*5) k++; 25 | } 26 | 27 | return v[n-1]; 28 | } 29 | 30 | /* Time Limit Exceeded 31 | 32 | int nthUglyNumber(int n) 33 | { 34 | int cnt = 0; 35 | int i = 1; 36 | for (; cnt < n; ++i) 37 | { 38 | if (isUgly(i)) cnt++; 39 | } 40 | 41 | return i-1; 42 | } 43 | 44 | bool isUgly(int num) 45 | { 46 | if (num <= 0) return false; 47 | if (num == 1) return true; 48 | 49 | while (num % 2 == 0) num /= 2; 50 | while (num % 3 == 0) num /= 3; 51 | while (num % 5 == 0) num /= 5; 52 | 53 | return num == 1; 54 | } 55 | */ 56 | }; 57 | -------------------------------------------------------------------------------- /cpp/Unique_Binary_Search_Trees.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 3 | 4 | For example, 5 | Given n = 3, there are a total of 5 unique BST's. 6 | 7 | 1 3 3 2 1 8 | \ / / / \ \ 9 | 3 2 1 1 3 2 10 | / / \ \ 11 | 2 1 2 3 12 | */ 13 | 14 | class Solution 15 | { 16 | public: 17 | int numTrees(int n) 18 | { 19 | int f[n+1]; 20 | memset(f, 0, sizeof(int) * (n + 1)); 21 | f[0] = 1; 22 | 23 | for (int i = 1; i <= n; i++) 24 | { 25 | for (int j = 0; j < i; j++) 26 | { 27 | f[i] += f[j] * f[i-1-j]; 28 | } 29 | } 30 | 31 | return f[n]; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /cpp/Unique_Paths.cc: -------------------------------------------------------------------------------- 1 | /* 2 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 3 | 4 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 5 | 6 | How many possible unique paths are there? 7 | 8 | 9 | Above is a 3 x 7 grid. How many possible unique paths are there? 10 | 11 | Note: m and n will be at most 100. 12 | */ 13 | 14 | class Solution 15 | { 16 | public: 17 | // f[i, j] = f[i - 1, j] + f[i, j - 1] 18 | int uniquePaths(int m, int n) 19 | { 20 | int f[m][n]; 21 | memset(f, 0, sizeof(int) * m * n); 22 | for (int i = 0; i < m; i++) 23 | { 24 | f[i][0] = 1; 25 | } 26 | for (int j = 0; j < n; j++) 27 | { 28 | f[0][j] = 1; 29 | } 30 | 31 | for (int i = 1; i < m; i++) 32 | { 33 | for (int j = 1; j < n; j++) 34 | { 35 | f[i][j] = f[i-1][j] + f[i][j-1]; 36 | } 37 | } 38 | 39 | return f[m-1][n-1]; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /cpp/Valid_Anagram.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings s and t, write a function to determine if t is an anagram of s. 3 | 4 | For example, 5 | s = "anagram", t = "nagaram", return true. 6 | s = "rat", t = "car", return false. 7 | 8 | Note: 9 | You may assume the string contains only lowercase alphabets. 10 | */ 11 | 12 | class Solution 13 | { 14 | public: 15 | bool isAnagram(string s, string t) 16 | { 17 | if (s.size() != t.size()) 18 | return false; 19 | 20 | map mapping1; 21 | for (auto c : s) 22 | mapping1[c]++; 23 | 24 | map mapping2; 25 | for (auto c : t) 26 | mapping2[c]++; 27 | 28 | for (auto it1 = mapping1.begin(), it2 = mapping2.begin(); it1 != mapping1.end(); it1++, it2++) 29 | { 30 | if (it1->first != it2->first || it1->second != it2->second) 31 | return false; 32 | } 33 | 34 | return true; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /cpp/Valid_Parentheses.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 5 | */ 6 | class Solution 7 | { 8 | public: 9 | /* 经典的压栈 10 | 左括号,直接压栈。右括号,判断栈是否为空和栈顶是否与此右括号匹配,弹出栈顶 11 | 元素全部遍历后,栈应为空,判断之。 12 | class Solution 13 | { 14 | public: 15 | bool isValid(string s) 16 | { 17 | if (s.length() == 0) 18 | return true; 19 | 20 | stack st; 21 | 22 | for (int i = 0; i < s.length(); i++) 23 | { 24 | if (s[i] == '(' || s[i] == '{' || s[i] == '[') 25 | st.push(s[i]); 26 | else 27 | { 28 | if (st.empty() || (st.top() == '(' && s[i] != ')') || 29 | (st.top() == '{' && s[i] != '}') || 30 | (st.top() == '[' && s[i] != ']')) 31 | { 32 | return false; 33 | } 34 | else 35 | { 36 | st.pop(); 37 | } 38 | } 39 | } 40 | 41 | return st.empty(); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /cpp/ZigZag_Conversion.cc: -------------------------------------------------------------------------------- 1 | /* 2 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 3 | 4 | P A H N 5 | A P L S I I G 6 | Y I R 7 | And then read line by line: "PAHNAPLSIIGYIR" 8 | Write the code that will take a string and make this conversion given a number of rows: 9 | 10 | string convert(string text, int nRows); 11 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 12 | */ 13 | 14 | class Solution 15 | { 16 | public: 17 | string convert(string s, int nRows) 18 | { 19 | int len = s.size(); 20 | if (nRows <= 1 || nRows >= len) 21 | return s; 22 | 23 | vector lines(nRows); 24 | int row = 0; // 所在行 25 | int step = 1; // 行的步长 1或-1 从上到下 从下到上 26 | // 扫描string s,将字符填到适当的行 27 | for (int i = 0; i < len; i++) 28 | { 29 | if (row == nRows - 1) 30 | step = -1; 31 | if (row == 0) 32 | step = 1; 33 | 34 | lines[row].push_back(s[i]); 35 | row += step; 36 | } 37 | 38 | string ret; 39 | for (int i = 0; i < nRows; i++) 40 | { 41 | ret += lines[i]; 42 | } 43 | 44 | return ret; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /go/add-binary/add-binary.go: -------------------------------------------------------------------------------- 1 | package add_binary 2 | 3 | /* 4 | 67. 二进制求和 5 | 6 | 给定两个二进制字符串,返回他们的和(用二进制表示)。 7 | 8 | 输入为非空字符串且只包含数字 1 和 0。 9 | 10 | 示例 1: 11 | 12 | 输入: a = "11", b = "1" 13 | 输出: "100" 14 | 示例 2: 15 | 16 | 输入: a = "1010", b = "1011" 17 | 输出: "10101" 18 | */ 19 | 20 | func addBinary(a string, b string) string { 21 | la, lb := len(a), len(b) 22 | l := la 23 | if lb > la { 24 | l = lb 25 | } 26 | result := make([]byte, l) 27 | 28 | carry := byte(0) 29 | for i, j, k := la-1, lb-1, l-1; i >= 0 || j >= 0; i, j, k = i-1, j-1, k-1 { 30 | num := carry 31 | if i >= 0 { 32 | num += a[i] - '0' 33 | } 34 | if j >= 0 { 35 | num += b[j] - '0' 36 | } 37 | 38 | carry = num / 2 39 | result[k] = num%2 + '0' 40 | } 41 | 42 | if carry > 0 { 43 | result = append([]byte{carry + '0'}, result...) 44 | } 45 | return string(result) 46 | } 47 | -------------------------------------------------------------------------------- /go/add-binary/add-binary_test.go: -------------------------------------------------------------------------------- 1 | package add_binary 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestAddBinary(t *testing.T) { 8 | tt := []struct { 9 | name string 10 | a string 11 | b string 12 | expect string 13 | }{ 14 | { 15 | "如题", 16 | "11", 17 | "1", 18 | "100", 19 | }, 20 | { 21 | "如题", 22 | "1010", 23 | "1011", 24 | "10101", 25 | }, 26 | } 27 | for _, tc := range tt { 28 | t.Run(tc.name, func(t *testing.T) { 29 | if got := addBinary(tc.a, tc.b); got != tc.expect { 30 | t.Fatalf("addBinary(%v, %v) got %v, expect %v", tc.a, tc.b, got, tc.expect) 31 | } 32 | }) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /go/add-two-numbers/add-two-numbers.go: -------------------------------------------------------------------------------- 1 | package add_two_numbers 2 | 3 | import "../util" 4 | 5 | /* 6 | 2. 两数相加 7 | 8 | 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。 9 | 10 | 你可以假设除了数字 0 之外,这两个数字都不会以零开头。 11 | 12 | 示例: 13 | 14 | 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 15 | 输出:7 -> 0 -> 8 16 | 原因:342 + 465 = 807 17 | */ 18 | 19 | type ListNode = util.ListNode 20 | 21 | func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { 22 | dummy := &ListNode{-1, nil} 23 | cur := dummy 24 | 25 | carry := 0 26 | for l1 != nil || l2 != nil || carry > 0 { 27 | num := carry 28 | 29 | if l1 != nil { 30 | num += l1.Val 31 | l1 = l1.Next 32 | } 33 | 34 | if l2 != nil { 35 | num += l2.Val 36 | l2 = l2.Next 37 | } 38 | 39 | carry = num / 10 40 | 41 | cur.Next = &ListNode{Val: num % 10} 42 | cur = cur.Next 43 | } 44 | 45 | return dummy.Next 46 | } 47 | -------------------------------------------------------------------------------- /go/best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.go: -------------------------------------------------------------------------------- 1 | package best_time_to_buy_and_sell_stock_ii 2 | 3 | /* 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | Design an algorithm to find the maximum profit. 7 | You may complete as many transactions as you like 8 | (ie, buy one and sell one share of the stock multiple times). 9 | However, you may not engage in multiple transactions at the same time 10 | (ie, you must sell the stock before you buy again). 11 | */ 12 | 13 | func maxProfit(prices []int) int { 14 | result := 0 15 | 16 | for i := 1; i < len(prices); i++ { 17 | if prices[i]-prices[i-1] > 0 { 18 | result += prices[i] - prices[i-1] 19 | } 20 | } 21 | 22 | return result 23 | } 24 | -------------------------------------------------------------------------------- /go/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.go: -------------------------------------------------------------------------------- 1 | package best_time_to_buy_and_sell_stock 2 | 3 | /* 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | If you were only permitted to complete at most one transaction 7 | (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 8 | 9 | Example 1: 10 | Input: [7, 1, 5, 3, 6, 4] 11 | Output: 5 12 | 13 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 14 | Example 2: 15 | Input: [7, 6, 4, 3, 1] 16 | Output: 0 17 | 18 | In this case, no transaction is done, i.e. max profit = 0. 19 | */ 20 | 21 | func maxProfit(prices []int) int { 22 | if len(prices) == 0 { 23 | return 0 24 | } 25 | 26 | max, delta, low := 0, 0, prices[0] 27 | 28 | for i := 1; i < len(prices); i++ { 29 | delta = prices[i] - low 30 | if delta <= 0 { // 说明prices[i]比low小,那么由于要在i后面卖出,则在i处买入更划算 31 | low = prices[i] // 重新开始 32 | } 33 | 34 | if delta > max { 35 | max = delta 36 | } 37 | } 38 | 39 | return max 40 | } 41 | -------------------------------------------------------------------------------- /go/binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii.go: -------------------------------------------------------------------------------- 1 | package binary_tree_level_order_traversal_ii 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | 107. 二叉树的层次遍历 II 9 | 10 | 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) 11 | 12 | 例如: 13 | 给定二叉树 [3,9,20,null,null,15,7], 14 | 15 | 3 16 | / \ 17 | 9 20 18 | / \ 19 | 15 7 20 | 返回其自底向上的层次遍历为: 21 | 22 | [ 23 | [15,7], 24 | [9,20], 25 | [3] 26 | ] 27 | */ 28 | 29 | type TreeNode = util.TreeNode 30 | 31 | func levelOrderBottom(root *TreeNode) [][]int { 32 | if root == nil { 33 | return [][]int{} 34 | } 35 | 36 | result := make([][]int, 0) 37 | queue := make([]*TreeNode, 0) 38 | queue = append(queue, root) 39 | 40 | for len(queue) > 0 { 41 | level := make([]int, 0) 42 | 43 | l := len(queue) 44 | for i := 0; i < l; i++ { 45 | cur := queue[0] 46 | queue = queue[1:] 47 | level = append(level, cur.Val) 48 | 49 | if cur.Left != nil { 50 | queue = append(queue, cur.Left) 51 | } 52 | if cur.Right != nil { 53 | queue = append(queue, cur.Right) 54 | } 55 | } 56 | result = append([][]int{level}, result...) 57 | } 58 | 59 | return result 60 | } 61 | -------------------------------------------------------------------------------- /go/binary-tree-level-order-traversal/binary-tree-level-order-traversal.go: -------------------------------------------------------------------------------- 1 | package binary_tree_level_order_traversal 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 9 | 10 | 例如: 11 | 给定二叉树: [3,9,20,null,null,15,7], 12 | 13 | 3 14 | / \ 15 | 9 20 16 | / \ 17 | 15 7 18 | 返回其层次遍历结果: 19 | 20 | [ 21 | [3], 22 | [9,20], 23 | [15,7] 24 | ] 25 | */ 26 | 27 | type TreeNode = util.TreeNode 28 | 29 | func levelOrder(root *TreeNode) [][]int { 30 | if root == nil { 31 | return [][]int{} 32 | } 33 | 34 | result := make([][]int, 0) 35 | queue := make([]*TreeNode, 0) 36 | queue = append(queue, root) 37 | 38 | for len(queue) > 0 { 39 | level := make([]int, 0) 40 | 41 | l := len(queue) 42 | for i := 0; i < l; i++ { 43 | cur := queue[0] 44 | queue = queue[1:] 45 | level = append(level, cur.Val) 46 | 47 | if cur.Left != nil { 48 | queue = append(queue, cur.Left) 49 | } 50 | if cur.Right != nil { 51 | queue = append(queue, cur.Right) 52 | } 53 | } 54 | result = append(result, level) 55 | } 56 | 57 | return result 58 | } 59 | -------------------------------------------------------------------------------- /go/climbing-stairs/climbing-stairs.go: -------------------------------------------------------------------------------- 1 | package climbing_stairs 2 | 3 | /* 4 | You are climbing a stair case. It takes n steps to reach to the top. 5 | 6 | Each time you can either climb 1 or 2 steps. 7 | In how many distinct ways can you climb to the top? 8 | 9 | Note: Given n will be a positive integer. 10 | 11 | 12 | Example 1: 13 | 14 | Input: 2 15 | Output: 2 16 | Explanation: There are two ways to climb to the top. 17 | 18 | 1. 1 step + 1 step 19 | 2. 2 steps 20 | Example 2: 21 | 22 | Input: 3 23 | Output: 3 24 | Explanation: There are three ways to climb to the top. 25 | 26 | 1. 1 step + 1 step + 1 step 27 | 2. 1 step + 2 steps 28 | 3. 2 steps + 1 step 29 | */ 30 | 31 | // 直观,但超时了。不推荐 32 | func climbStairs(n int) int { 33 | if n == 1 { 34 | return 1 35 | } else if n == 2 { 36 | return 2 37 | } 38 | 39 | return climbStairs(n) + climbStairs(n-1) 40 | } 41 | 42 | // 利用了中间计算结果 43 | func climbStairs2(n int) int { 44 | if n == 1 { 45 | return 1 46 | } 47 | 48 | ways := make([]int, n+1) 49 | ways[0], ways[1] = 1, 1 50 | 51 | for i := 2; i <= n; i++ { 52 | ways[i] = ways[i-1] + ways[i-2] 53 | } 54 | 55 | return ways[n] 56 | } 57 | -------------------------------------------------------------------------------- /go/contains-duplicate-ii/contains-duplicate-ii.go: -------------------------------------------------------------------------------- 1 | package contains_duplicate_ii 2 | 3 | /* 4 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array 5 | such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 6 | */ 7 | 8 | func containsNearbyDuplicate(nums []int, k int) bool { 9 | m := make(map[int]int) // 值->索引 10 | 11 | for i, n := range nums { 12 | if _, ok := m[n]; ok { 13 | if i-m[n] <= k { 14 | return true 15 | } 16 | } 17 | m[n] = i // 不是else分支 18 | } 19 | 20 | return false 21 | } 22 | -------------------------------------------------------------------------------- /go/contains-duplicate/contains-duplicate.go: -------------------------------------------------------------------------------- 1 | package contains_duplicate 2 | 3 | /* 4 | Given an array of integers, find if the array contains any duplicates. Your function should return true if any value 5 | appears at least twice in the array, and it should return false if every element is distinct. 6 | */ 7 | 8 | func containsDuplicate(nums []int) bool { 9 | m := make(map[int]bool, len(nums)) 10 | 11 | for _, n := range nums { 12 | if m[n] { 13 | return true 14 | } 15 | m[n] = true 16 | } 17 | 18 | return false 19 | } 20 | -------------------------------------------------------------------------------- /go/convert-bst-to-greater-tree/convert-bst-to-greater-tree.go: -------------------------------------------------------------------------------- 1 | package convert_bst_to_greater_tree 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | Given a Binary Search Tree (BST), convert it to a Greater Tree 9 | such that every key of the original BST is changed to the original key 10 | plus sum of all keys greater than the original key in BST. 11 | 12 | Example: 13 | 14 | Input: The root of a Binary Search Tree like this: 15 | 5 16 | / \ 17 | 2 13 18 | 19 | Output: The root of a Greater Tree like this: 20 | 18 21 | / \ 22 | 20 13 23 | */ 24 | 25 | type TreeNode = util.TreeNode 26 | 27 | func convertBST(root *TreeNode) *TreeNode { 28 | sum := 0 29 | 30 | travel(root, &sum) 31 | return root 32 | } 33 | 34 | // 右-中-左 遍历 35 | func travel(root *TreeNode, sum *int) { 36 | if root == nil { 37 | return 38 | } 39 | 40 | travel(root.Right, sum) 41 | root.Val += *sum 42 | *sum = root.Val 43 | travel(root.Left, sum) 44 | } 45 | -------------------------------------------------------------------------------- /go/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.go: -------------------------------------------------------------------------------- 1 | package convert_sorted_array_to_binary_search_tree 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 9 | 10 | For this problem, a height-balanced binary tree is defined as a binary tree 11 | in which the depth of the two subtrees of every node never differ by more than 1. 12 | 13 | 14 | Example: 15 | 16 | Given the sorted array: [-10,-3,0,5,9], 17 | 18 | One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 19 | 20 | 0 21 | / \ 22 | -3 9 23 | / / 24 | -10 5 25 | */ 26 | 27 | type TreeNode = util.TreeNode 28 | 29 | func SortedArrayToBST(nums []int) *TreeNode { 30 | if len(nums) == 0 { 31 | return nil 32 | } 33 | 34 | mid := len(nums) / 2 35 | return &TreeNode{ 36 | nums[mid], 37 | SortedArrayToBST(nums[:mid]), 38 | SortedArrayToBST(nums[mid+1:]), 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /go/convert-sorted-list-to-binary-search-tree/convert-sorted-list-to-binary-search-tree.go: -------------------------------------------------------------------------------- 1 | package convert_sorted_list_to_binary_search_tree 2 | 3 | import ( 4 | "../convert-sorted-array-to-binary-search-tree" 5 | "../util" 6 | ) 7 | 8 | /* 9 | Given a singly linked list where elements are sorted in ascending order, 10 | convert it to a height balanced BST. 11 | 12 | For this problem, a height-balanced binary tree is defined as a binary tree 13 | in which the depth of the two subtrees of every node never differ by more than 1. 14 | 15 | 16 | Example: 17 | 18 | Given the sorted linked list: [-10,-3,0,5,9], 19 | 20 | One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 21 | 22 | 0 23 | / \ 24 | -3 9 25 | / / 26 | -10 5 27 | */ 28 | 29 | type ListNode = util.ListNode 30 | type TreeNode = util.TreeNode 31 | 32 | // 一种方法直接链表变数组,然后利用convert-sorted-array-to-binary-search-tree.go 33 | func sortedListToBST(head *ListNode) *TreeNode { 34 | arr := []int{} 35 | for head != nil { 36 | arr = append(arr, head.Val) 37 | head = head.Next 38 | } 39 | 40 | return convert_sorted_array_to_binary_search_tree.SortedArrayToBST(arr) 41 | } 42 | 43 | // 方法2: 找到中间位置,一个slow,一个fast, slow走一步,fast走两步 44 | -------------------------------------------------------------------------------- /go/count-and-say/count-and-say.go: -------------------------------------------------------------------------------- 1 | package count_and_say 2 | 3 | import "fmt" 4 | 5 | /* 6 | 38. 报数 7 | 8 | 报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 9 | 10 | 1. 1 11 | 2. 11 12 | 3. 21 13 | 4. 1211 14 | 5. 111221 15 | 1 被读作 "one 1" ("一个一") , 即 11。 16 | 11 被读作 "two 1s" ("两个一"), 即 21。 17 | 21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。 18 | 19 | 给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。 20 | 21 | 注意:整数顺序将表示为一个字符串。 22 | 23 | 24 | 25 | 示例 1: 26 | 27 | 输入: 1 28 | 输出: "1" 29 | 示例 2: 30 | 31 | 输入: 4 32 | 输出: "1211" 33 | */ 34 | 35 | func countAndSay(n int) string { 36 | 37 | if n == 1 { 38 | return "1" 39 | } 40 | 41 | // 先找到n-1是多少 42 | str := countAndSay(n - 1) 43 | 44 | result := "" 45 | num := 1 46 | 47 | i := 0 48 | for ; i < len(str)-1; i++ { 49 | if str[i] != str[i+1] { // 不等时,输出 50 | result += fmt.Sprintf("%d%c", num, str[i]) 51 | num = 1 52 | } else { 53 | num++ 54 | } 55 | } 56 | result += fmt.Sprintf("%d%c", num, str[i]) 57 | 58 | return result 59 | } 60 | -------------------------------------------------------------------------------- /go/count-primes/count-primes.go: -------------------------------------------------------------------------------- 1 | package count_primes 2 | 3 | /* 4 | Description: 5 | 6 | Count the number of prime numbers less than a non-negative number, n. 7 | */ 8 | 9 | // 最直观判断质数的方法:判断能不能被 2 ~ 根号n 整除 10 | 11 | // 此题用 埃拉托斯特尼筛法 更好 12 | // https://zh.wikipedia.org/wiki/%E5%9F%83%E6%8B%89%E6%89%98%E6%96%AF%E7%89%B9%E5%B0%BC%E7%AD%9B%E6%B3%95 13 | 14 | func countPrimes(n int) int { 15 | if n <= 2 { 16 | return 0 17 | } 18 | 19 | composite := make([]bool, n) 20 | num := n / 2 21 | 22 | for i := 3; i*i < n; i += 2 { 23 | if composite[i] { 24 | continue 25 | } 26 | 27 | for j := i * i; j < n; j += 2 * i { 28 | if !composite[j] { 29 | num-- 30 | composite[j] = true 31 | } 32 | } 33 | } 34 | 35 | return num 36 | } 37 | -------------------------------------------------------------------------------- /go/delete-node-in-a-linked-list/delete-node-in-a-linked-list.go: -------------------------------------------------------------------------------- 1 | package delete_node_in_a_linked_list 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | Write a function to delete a node (except the tail) in a singly linked list, 9 | given only access to that node. 10 | 11 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, 12 | the linked list should become 1 -> 2 -> 4 after calling your function. 13 | */ 14 | 15 | type ListNode = util.ListNode 16 | 17 | func deleteNode(node *ListNode) { 18 | node.Val = node.Next.Val 19 | node.Next = node.Next.Next 20 | } 21 | -------------------------------------------------------------------------------- /go/detect-capital/detect-capital.go: -------------------------------------------------------------------------------- 1 | package detect_capital 2 | 3 | /* 4 | Given a word, you need to judge whether the usage of capitals in it is right or not. 5 | 6 | We define the usage of capitals in a word to be right when one of the following cases holds: 7 | 8 | All letters in this word are capitals, like "USA". 9 | All letters in this word are not capitals, like "leetcode". 10 | Only the first letter in this word is capital if it has more than one letter, like "Google". 11 | Otherwise, we define that this word doesn't use capitals in a right way. 12 | Example 1: 13 | Input: "USA" 14 | Output: True 15 | Example 2: 16 | Input: "FlaG" 17 | Output: False 18 | Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters. 19 | */ 20 | 21 | func detectCapitalUse(word string) bool { 22 | head := word[:1] 23 | tail := word[1:] 24 | if isIn(head, 'A', 'Z') { 25 | return isIn(tail, 'A', 'Z') || isIn(tail, 'a', 'z') 26 | } 27 | return isIn(tail, 'a', 'z') 28 | } 29 | 30 | func isIn(s string, first, last byte) bool { 31 | for i := range s { 32 | if !(first <= s[i] && s[i] <= last) { 33 | return false 34 | } 35 | } 36 | return true 37 | } 38 | -------------------------------------------------------------------------------- /go/diameter-of-binary-tree/diameter-of-binary-tree.go: -------------------------------------------------------------------------------- 1 | package diameter_of_binary_tree 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | Given a binary tree, you need to compute the length of the diameter of the tree. 9 | The diameter of a binary tree is the length of the longest path between any two nodes in a tree. 10 | This path may or may not pass through the root. 11 | 12 | Example: 13 | Given a binary tree 14 | 1 15 | / \ 16 | 2 3 17 | / \ 18 | 4 5 19 | Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 20 | 21 | Note: The length of path between two nodes is represented by the number of edges between them. 22 | */ 23 | 24 | // 问题:二叉树的直径,任意两节点的最长路径 25 | // 想法:此题有点怪 26 | 27 | // 只有一个节点可以同时使用左子树右子树,转折节点 28 | 29 | type TreeNode = util.TreeNode 30 | 31 | func diameterOfBinaryTree(root *TreeNode) int { 32 | result := 0 33 | lp(root, &result) 34 | return result 35 | } 36 | 37 | // 定义为,此节点下的最大长度 38 | func lp(root *TreeNode, result *int) int { 39 | if root == nil { 40 | return -1 41 | } 42 | 43 | l := lp(root.Left, result) + 1 44 | r := lp(root.Right, result) + 1 45 | *result = max(*result, l+r) 46 | 47 | return max(l, r) 48 | } 49 | 50 | func max(a, b int) int { 51 | if a > b { 52 | return a 53 | } 54 | return b 55 | } 56 | -------------------------------------------------------------------------------- /go/excel-sheet-column-number/excel-sheet-column-number.go: -------------------------------------------------------------------------------- 1 | package excel_sheet_column_number 2 | 3 | /* 4 | Related to question Excel Sheet Column Title 5 | 6 | Given a column title as appear in an Excel sheet, return its corresponding column number. 7 | 8 | For example: 9 | 10 | A -> 1 11 | B -> 2 12 | C -> 3 13 | ... 14 | Z -> 26 15 | AA -> 27 16 | AB -> 28 17 | */ 18 | 19 | func titleToNumber(s string) int { 20 | num := 0 21 | for _, c := range s { 22 | n := int(c - 'A' + 1) // rune -> int 23 | num = num*26 + n 24 | } 25 | return num 26 | } 27 | -------------------------------------------------------------------------------- /go/excel-sheet-column-number/excel-sheet-column-number_test.go: -------------------------------------------------------------------------------- 1 | package excel_sheet_column_number 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_titleToNumber(t *testing.T) { 8 | tt := []struct { 9 | name string 10 | s string 11 | expect int 12 | }{ 13 | { 14 | "如题", 15 | "A", 16 | 1, 17 | }, 18 | { 19 | "", 20 | "AB", 21 | 28, 22 | }, 23 | } 24 | for _, tc := range tt { 25 | t.Run(tc.name, func(t *testing.T) { 26 | if got := titleToNumber(tc.s); got != tc.expect { 27 | t.Fatalf("titleToNumber(%v) got %v, expect %v", tc.s, got, tc.expect) 28 | } 29 | }) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /go/find-all-anagrams-in-a-string/find-all-anagrams-in-a-string.go: -------------------------------------------------------------------------------- 1 | package find_all_anagrams_in_a_string 2 | 3 | /* 4 | Given a string s and a non-empty string p, 5 | find all the start indices of p's anagrams in s. 6 | 7 | Strings consists of lowercase English letters only and the length of 8 | both strings s and p will not be larger than 20,100. 9 | 10 | The order of output does not matter. 11 | 12 | Example 1: 13 | 14 | Input: 15 | s: "cbaebabacd" p: "abc" 16 | 17 | Output: 18 | [0, 6] 19 | 20 | Explanation: 21 | The substring with start index = 0 is "cba", which is an anagram of "abc". 22 | The substring with start index = 6 is "bac", which is an anagram of "abc". 23 | Example 2: 24 | 25 | Input: 26 | s: "abab" p: "ab" 27 | 28 | Output: 29 | [0, 1, 2] 30 | 31 | Explanation: 32 | The substring with start index = 0 is "ab", which is an anagram of "ab". 33 | The substring with start index = 1 is "ba", which is an anagram of "ab". 34 | The substring with start index = 2 is "ab", which is an anagram of "ab". 35 | */ 36 | 37 | // 描述:给定字符串S和P,找出S中所有和P字母构成相同(变位词)的子串,返回下标 38 | 39 | // 简单粗暴的方法 40 | func findAnagrams(s string, p string) []int { 41 | result := []int{} 42 | 43 | if len(s) == 0 || len(p) == 0 || len(s) < len(p) { 44 | return result 45 | } 46 | 47 | chars := [26]int{} 48 | for _, c := range p { 49 | chars[c-'a']++ 50 | } 51 | length := len(p) 52 | 53 | for i := 0; i < len(s)-length+1; i++ { 54 | window := [26]int{} 55 | // 从i开始的length个 56 | for j := i; j < i+length; j++ { 57 | window[s[j]-'a']++ 58 | } 59 | if window == chars { // 数组可以直接比较,slice要用reflect.DeepEqual 60 | result = append(result, i) 61 | } 62 | } 63 | 64 | return result 65 | } 66 | -------------------------------------------------------------------------------- /go/find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.go: -------------------------------------------------------------------------------- 1 | package find_all_duplicates_in_an_array 2 | 3 | /* 4 | Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), 5 | some elements appear twice and others appear once. 6 | 7 | Find all the elements that appear twice in this array. 8 | 9 | Could you do it without extra space and in O(n) runtime? 10 | 11 | Example: 12 | Input: 13 | [4,3,2,7,8,2,3,1] 14 | 15 | Output: 16 | [2,3] 17 | */ 18 | 19 | // 直观的解法。 20 | func findDuplicates(nums []int) []int { 21 | m := make(map[int]int, len(nums)) // 数字-->出现次数 22 | var result []int 23 | 24 | for _, n := range nums { 25 | m[n]++ 26 | } 27 | for k, v := range m { 28 | if v == 2 { 29 | result = append(result, k) 30 | } 31 | } 32 | 33 | return result 34 | } 35 | -------------------------------------------------------------------------------- /go/find-all-duplicates-in-an-array/find-all-duplicates-in-an-array_test.go: -------------------------------------------------------------------------------- 1 | package find_all_duplicates_in_an_array 2 | 3 | import ( 4 | "reflect" 5 | "sort" 6 | "testing" 7 | ) 8 | 9 | func TestFindDuplicates(t *testing.T) { 10 | tt := []struct { 11 | name string 12 | nums []int 13 | expect []int 14 | }{ 15 | { 16 | "如题", 17 | []int{4, 3, 2, 7, 8, 2, 3, 1}, 18 | []int{2, 3}, 19 | }, 20 | } 21 | for _, tc := range tt { 22 | t.Run(tc.name, func(t *testing.T) { 23 | got := findDuplicates(tc.nums) 24 | sort.Ints(got) 25 | if !reflect.DeepEqual(got, tc.expect) { 26 | t.Fatalf("findDuplicates(%v) got %v, expect %v", tc.nums, got, tc.expect) 27 | } 28 | }) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /go/find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.go: -------------------------------------------------------------------------------- 1 | package find_all_numbers_disappeared_in_an_array 2 | 3 | /* 4 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), 5 | some elements appear twice and others appear once. 6 | 7 | Find all the elements of [1, n] inclusive that do not appear in this array. 8 | 9 | Could you do it without extra space and in O(n) runtime? 10 | You may assume the returned list does not count as extra space. 11 | 12 | Example: 13 | 14 | Input: 15 | [4,3,2,7,8,2,3,1] 16 | 17 | Output: 18 | [5,6] 19 | */ 20 | 21 | func findDisappearedNumbers(nums []int) []int { 22 | for i := 0; i < len(nums); i++ { 23 | for nums[i] != nums[nums[i]-1] { // nums[i]-1是它该在的位置 24 | nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] 25 | } 26 | } 27 | 28 | result := make([]int, 0, len(nums)) 29 | for i, n := range nums { 30 | if n != i+1 { 31 | result = append(result, i+1) 32 | } 33 | } 34 | 35 | return result 36 | } 37 | -------------------------------------------------------------------------------- /go/first-unique-character-in-a-string/first-unique-character-in-a-string.go: -------------------------------------------------------------------------------- 1 | package first_unique_character_in_a_string 2 | 3 | /* 4 | Given a string, find the first non-repeating character in it and 5 | return it's index. If it doesn't exist, return -1. 6 | 7 | Examples: 8 | 9 | s = "leetcode" 10 | return 0. 11 | 12 | s = "loveleetcode", 13 | return 2. 14 | Note: You may assume the string contain only lowercase letters. 15 | */ 16 | 17 | func firstUniqChar(s string) int { 18 | rec := make([]rune, 26) 19 | for _, c := range s { 20 | rec[c-'a']++ 21 | } 22 | 23 | for i, c := range s { 24 | if rec[c-'a'] == 1 { 25 | return i 26 | } 27 | } 28 | 29 | return -1 30 | } 31 | 32 | func firstUniqChar2(s string) int { 33 | m := make(map[rune]int, len(s)) 34 | for _, c := range s { 35 | m[c] += 1 36 | } 37 | 38 | for i, c := range s { 39 | if m[c] == 1 { 40 | return i 41 | } 42 | } 43 | 44 | return -1 45 | } 46 | -------------------------------------------------------------------------------- /go/fizz-buzz/fizz-buzz.go: -------------------------------------------------------------------------------- 1 | package fizz_buzz 2 | 3 | import "strconv" 4 | 5 | /* 6 | Write a program that outputs the string representation of numbers from 1 to n. 7 | 8 | But for multiples of three it should output “Fizz” instead of the number 9 | and for the multiples of five output “Buzz”. 10 | For numbers which are multiples of both three and five output “FizzBuzz”. 11 | 12 | Example: 13 | 14 | n = 15, 15 | 16 | Return: 17 | [ 18 | "1", 19 | "2", 20 | "Fizz", 21 | "4", 22 | "Buzz", 23 | "Fizz", 24 | "7", 25 | "8", 26 | "Fizz", 27 | "Buzz", 28 | "11", 29 | "Fizz", 30 | "13", 31 | "14", 32 | "FizzBuzz" 33 | ] 34 | */ 35 | 36 | func fizzBuzz(n int) []string { 37 | result := make([]string, 0, n) 38 | for i := 1; i < n+1; i++ { 39 | if i%(3*5) == 0 { 40 | result = append(result, "FizzBuzz") 41 | } else if i%3 == 0 { 42 | result = append(result, "Fizz") 43 | } else if i%5 == 0 { 44 | result = append(result, "Buzz") 45 | } else { 46 | result = append(result, strconv.Itoa(i)) 47 | } 48 | } 49 | return result 50 | } 51 | -------------------------------------------------------------------------------- /go/fizz-buzz/fizz-buzz_test.go: -------------------------------------------------------------------------------- 1 | package fizz_buzz 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestFizzBuzz(t *testing.T) { 9 | tt := []struct { 10 | name string 11 | n int 12 | expect []string 13 | }{ 14 | { 15 | "如题", 16 | 15, 17 | []string{ 18 | "1", 19 | "2", 20 | "Fizz", 21 | "4", 22 | "Buzz", 23 | "Fizz", 24 | "7", 25 | "8", 26 | "Fizz", 27 | "Buzz", 28 | "11", 29 | "Fizz", 30 | "13", 31 | "14", 32 | "FizzBuzz", 33 | }, 34 | }, 35 | } 36 | for _, tc := range tt { 37 | t.Run(tc.name, func(t *testing.T) { 38 | if got := fizzBuzz(tc.n); !reflect.DeepEqual(got, tc.expect) { 39 | t.Fatalf("fizzBuzz(%v) got %v, expect %v", tc.n, got, tc.expect) 40 | } 41 | }) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /go/hamming-distance/hamming-distance.go: -------------------------------------------------------------------------------- 1 | package hamming_distance 2 | 3 | /* 4 | The Hamming distance between two integers is the number of positions 5 | at which the corresponding bits are different. 6 | 7 | Given two integers x and y, calculate the Hamming distance. 8 | 9 | Note: 10 | 0 ≤ x, y < 231. 11 | 12 | Example: 13 | 14 | Input: x = 1, y = 4 15 | 16 | Output: 2 17 | 18 | Explanation: 19 | 1 (0 0 0 1) 20 | 4 (0 1 0 0) 21 | ↑ ↑ 22 | 23 | The above arrows point to positions where the corresponding bits are different. 24 | */ 25 | 26 | // 汉明距离,对应位置的不同位的个数 27 | // 异或,然后找到 28 | func hammingDistance(x int, y int) int { 29 | result := 0 30 | 31 | x ^= y 32 | for x != 0 { 33 | result += x & 1 34 | x >>= 1 35 | } 36 | 37 | return result 38 | } 39 | -------------------------------------------------------------------------------- /go/hamming-distance/hamming-distance_test.go: -------------------------------------------------------------------------------- 1 | package hamming_distance 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestHammingDistance(t *testing.T) { 9 | tt := []struct { 10 | name string 11 | x int 12 | y int 13 | expect int 14 | }{ 15 | { 16 | "如题", 17 | 1, // 0 0 0 1 18 | 4, // 0 1 0 0 19 | 2, 20 | }, 21 | { 22 | "", 23 | 1, // 0 0 0 1 24 | 12, // 1 1 0 0 25 | 3, 26 | }, 27 | } 28 | for _, tc := range tt { 29 | t.Run(tc.name, func(t *testing.T) { 30 | if got := hammingDistance(tc.x, tc.y); !reflect.DeepEqual(got, tc.expect) { 31 | t.Fatalf("hammingDistance(%v, %v) got %v, expect %v", tc.x, tc.y, got, tc.expect) 32 | } 33 | }) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /go/happy-number/happy-number.go: -------------------------------------------------------------------------------- 1 | package happy_number 2 | 3 | /* 4 | Write an algorithm to determine if a number is "happy". 5 | 6 | A happy number is a number defined by the following process: 7 | Starting with any positive integer, replace the number by the sum of the squares of its digits, 8 | and repeat the process until the number equals 1 (where it will stay), 9 | or it loops endlessly in a cycle which does not include 1. 10 | Those numbers for which this process ends in 1 are happy numbers. 11 | 12 | Example: 19 is a happy number 13 | 14 | 12 + 92 = 82 15 | 82 + 22 = 68 16 | 62 + 82 = 100 17 | 12 + 02 + 02 = 1 18 | */ 19 | 20 | func isHappy(n int) bool { 21 | m := make(map[int]struct{}) 22 | m[n] = struct{}{} 23 | 24 | for { 25 | n = calc(n) 26 | if n == 1 { 27 | return true 28 | } 29 | 30 | // 如果在一个没有1的循环中,那么第二次循环的时候一定已经在里面了 31 | if _, ok := m[n]; ok { 32 | return false 33 | } 34 | m[n] = struct{}{} 35 | } 36 | 37 | return false 38 | } 39 | 40 | func calc(n int) int { 41 | result := 0 42 | for n != 0 { 43 | result += (n % 10) * (n % 10) 44 | n /= 10 45 | } 46 | return result 47 | } 48 | -------------------------------------------------------------------------------- /go/house-robber/house-robber.go: -------------------------------------------------------------------------------- 1 | package house_robber 2 | 3 | /* 4 | You are a professional robber planning to rob houses along a street. 5 | Each house has a certain amount of money stashed, 6 | the only constraint stopping you from robbing each of them is that 7 | adjacent houses have security system connected and it will automatically 8 | contact the police if two adjacent houses were broken into on the same night. 9 | 10 | Given a list of non-negative integers representing the amount of money of each house, 11 | determine the maximum amount of money you can rob tonight without alerting the police. 12 | */ 13 | 14 | // rob(n) = max(rob(n-2)+money[n], rob(n-1)) 15 | 16 | // 动态规划 Dynamic Programming 17 | 18 | func rob(nums []int) int { 19 | n := len(nums) 20 | if n == 0 { 21 | return 0 22 | } else if n == 1 { 23 | return nums[0] 24 | } 25 | 26 | // 下标为n的房子后,抢了多少钱 27 | dp := make([]int, n) 28 | dp[0] = nums[0] 29 | dp[1] = max(nums[0], nums[1]) 30 | 31 | for i := 2; i < n; i++ { 32 | dp[i] = max(dp[i-2]+num[i], dp[i-1]) 33 | } 34 | 35 | return dp[n-1] 36 | } 37 | 38 | func max(a, b int) int { 39 | if a > b { 40 | return a 41 | } 42 | return b 43 | } 44 | -------------------------------------------------------------------------------- /go/implement-strstr/implement-strstr.go: -------------------------------------------------------------------------------- 1 | package implement_strstr 2 | 3 | /* 4 | 28. 实现strStr() 5 | 6 | 实现 strStr() 函数。 7 | 8 | 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 9 | 10 | 示例 1: 11 | 12 | 输入: haystack = "hello", needle = "ll" 13 | 输出: 2 14 | 示例 2: 15 | 16 | 输入: haystack = "aaaaa", needle = "bba" 17 | 输出: -1 18 | 说明: 19 | 20 | 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 21 | 22 | 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。 23 | */ 24 | 25 | func strStr(haystack string, needle string) int { 26 | if needle == "" { 27 | return 0 28 | } 29 | 30 | l1, l2 := len(haystack), len(needle) 31 | for i := 0; i < l1-l2+1; i++ { 32 | if haystack[i:i+l2] == needle { 33 | return i 34 | } 35 | } 36 | 37 | return -1 38 | } 39 | -------------------------------------------------------------------------------- /go/intersection-of-two-arrays/intersection-of-two-arrays.go: -------------------------------------------------------------------------------- 1 | package intersection_of_two_arrays 2 | 3 | /* 4 | Given two arrays, write a function to compute their intersection. 5 | 6 | Example: 7 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 8 | 9 | Note: 10 | Each element in the result must be unique. 11 | The result can be in any order. 12 | */ 13 | 14 | // 问题描述:求交集 15 | 16 | func intersection(nums1 []int, nums2 []int) []int { 17 | if len(nums1) == 0 || len(nums2) == 0 { 18 | return []int{} 19 | } 20 | 21 | // 最好操作副本,没有副作用,此处省略 22 | sort.Ints(nums1) 23 | sort.Ints(nums2) 24 | 25 | result := []int{} 26 | for i, j := 0, 0; i < len(nums1) && j < len(nums2); { 27 | if nums1[i] < nums2[j] { 28 | i++ 29 | } else if nums1[i] > nums2[j] { 30 | j++ 31 | } else { 32 | if len(result) == 0 || nums1[i] != result[len(result)-1] { // 不重复的才加到结果集中 33 | result = append(result, nums1[i]) 34 | } 35 | i++ 36 | j++ 37 | } 38 | } 39 | 40 | return result 41 | } 42 | -------------------------------------------------------------------------------- /go/invert-binary-tree/invert-binary-tree.go: -------------------------------------------------------------------------------- 1 | package invert_binary_tree 2 | 3 | /* 4 | Invert a binary tree. 5 | 4 6 | / \ 7 | 2 7 8 | / \ / \ 9 | 1 3 6 9 10 | to 11 | 4 12 | / \ 13 | 7 2 14 | / \ / \ 15 | 9 6 3 1 16 | Trivia: 17 | This problem was inspired by this original tweet by Max Howell: 18 | Google: 90% of our engineers use the software you wrote (Homebrew), 19 | but you can’t invert a binary tree on a whiteboard so fuck off. 20 | */ 21 | 22 | // 问题:翻转二叉树 23 | 24 | type TreeNode struct { 25 | Val int 26 | Left *TreeNode 27 | Right *TreeNode 28 | } 29 | 30 | func invertTree(root *TreeNode) *TreeNode { 31 | if root == nil { 32 | return root 33 | } 34 | 35 | root.Left, root.Right = invertTree(root.Right), invertTree(root.Left) 36 | 37 | return root 38 | } 39 | -------------------------------------------------------------------------------- /go/length-of-last-word/length-of-last-word.go: -------------------------------------------------------------------------------- 1 | package length_of_last_word 2 | 3 | /* 4 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', 5 | return the length of last word in the string. 6 | 7 | If the last word does not exist, return 0. 8 | 9 | Note: A word is defined as a character sequence consists of non-space characters only. 10 | 11 | Example: 12 | 13 | Input: "Hello World" 14 | Output: 5 15 | */ 16 | 17 | func lengthOfLastWord(s string) int { 18 | result := 0 19 | l := len(s) 20 | 21 | for i := l - 1; i >= 0; i-- { 22 | if s[i] == ' ' { 23 | if result == 0 { // "abc " 排除末尾是' '的情况 24 | continue 25 | } 26 | break 27 | } 28 | result++ 29 | } 30 | 31 | return result 32 | } 33 | -------------------------------------------------------------------------------- /go/longest-common-prefix/longest-common-prefix.go: -------------------------------------------------------------------------------- 1 | package longest_common_prefix 2 | 3 | /* 4 | Write a function to find the longest common prefix string amongst an array of strings. 5 | */ 6 | 7 | 8 | // 或者,先找出最短的str 9 | func longestCommonPrefix(strs []string) string { 10 | if len(strs) == 0 { 11 | return "" 12 | } 13 | 14 | prefix := make([]byte, 0, len(strs[0])) 15 | s := []byte(strs[0]) 16 | for i, c := range s { 17 | for j := 1; j < len(strs); j++ { 18 | goto exit 19 | } 20 | } 21 | prefix = append(prefix, c) 22 | } 23 | 24 | exit: 25 | return string(prefix) 26 | } 27 | -------------------------------------------------------------------------------- /go/longest-increasing-subsequence/longest-increasing-subsequence.go: -------------------------------------------------------------------------------- 1 | package longest_increasing_subsequence 2 | 3 | /* 4 | Given an unsorted array of integers, find the length of longest increasing subsequence. 5 | 6 | For example, 7 | Given [10, 9, 2, 5, 3, 7, 101, 18], 8 | The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. 9 | Note that there may be more than one LIS combination, 10 | it is only necessary for you to return the length. 11 | 12 | Your algorithm should run in O(n2) complexity. 13 | 14 | Follow up: Could you improve it to O(n log n) time complexity? 15 | */ 16 | 17 | // TODO 没通过 18 | func lengthOfLIS(nums []int) int { 19 | if len(nums) == 0 { 20 | return 0 21 | } 22 | 23 | max := 1 24 | length := 1 25 | for i := 1; i < len(nums); i++ { 26 | if nums[i] > nums[i-1] { 27 | length++ 28 | if length > max { 29 | max = length 30 | } 31 | } else { 32 | length = 1 33 | } 34 | } 35 | 36 | return max 37 | } 38 | -------------------------------------------------------------------------------- /go/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.go: -------------------------------------------------------------------------------- 1 | package longest_substring_without_repeating_characters 2 | 3 | /* 4 | 3. 无重复字符的最长子串 5 | 6 | 给定一个字符串,找出不含有重复字符的最长子串的长度。 7 | 8 | 示例 1: 9 | 10 | 输入: "abcabcbb" 11 | 输出: 3 12 | 解释: 无重复字符的最长子串是 "abc",其长度为 3。 13 | 示例 2: 14 | 15 | 输入: "bbbbb" 16 | 输出: 1 17 | 解释: 无重复字符的最长子串是 "b",其长度为 1。 18 | 示例 3: 19 | 20 | 输入: "pwwkew" 21 | 输出: 3 22 | 解释: 无重复字符的最长子串是 "wke",其长度为 3。 23 | 请注意,答案必须是一个子串,"pwke" 是一个子序列 而不是子串。 24 | */ 25 | 26 | // 遍历该字符串,每遍历一个字母时,利用map去找该字母最近一次出现是什么时候,中间这一段便是无重复字符的字符串。 27 | func lengthOfLongestSubstring(s string) int { 28 | result := 0 29 | m := make(map[byte]int, len(s)) // 字符-->出现时的索引 30 | 31 | start := 0 // 起始点 当发现出现重复的时候,就调整 起始点 32 | for i, c := range []byte(s) { 33 | if index, ok := m[c]; !ok || index < start { // 不存在 或已经在start之前,即是遗留数据 34 | m[c] = i // 赋值或覆盖 35 | result = max(i-start+1, result) 36 | } else { // 存在了 37 | start = m[c] + 1 // 更新起始点 38 | m[c] = i // 覆盖 39 | } 40 | } 41 | 42 | return result 43 | } 44 | 45 | func max(a, b int) int { 46 | if a >= b { 47 | return a 48 | } 49 | return b 50 | } 51 | -------------------------------------------------------------------------------- /go/majority-element-ii/majority-element-ii.go: -------------------------------------------------------------------------------- 1 | package majority_element_ii 2 | 3 | /* 4 | Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. 5 | The algorithm should run in linear time and in O(1) space. 6 | */ 7 | 8 | func majorityElement(nums []int) []int { 9 | return nil 10 | } 11 | -------------------------------------------------------------------------------- /go/majority-element/majority-element.go: -------------------------------------------------------------------------------- 1 | package majority_element 2 | 3 | /* 4 | Given an array of size n, find the majority element. 5 | The majority element is the element that appears more than ⌊ n/2 ⌋ times. 6 | 7 | You may assume that the array is non-empty and the majority element always exist in the array. 8 | */ 9 | 10 | /* 11 | 问题:求众数 12 | 13 | 每两个不同的,则一块删除。最后剩下就是所求的。 14 | 可扩展到n/k的情况,每k个不同的一块删除。 15 | */ 16 | 17 | func majorityElement(nums []int) int { 18 | result := nums[0] 19 | cnt := 1 20 | 21 | for i := 1; i < len(nums); i++ { 22 | if cnt == 0 { 23 | result = nums[i] // 换下一个有可能 24 | cnt = 1 // 重置计数 25 | } else if nums[i] == result { 26 | cnt++ 27 | } else { 28 | cnt-- 29 | } 30 | } 31 | 32 | return result 33 | } 34 | -------------------------------------------------------------------------------- /go/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.go: -------------------------------------------------------------------------------- 1 | package maximum_depth_of_binary_tree 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | Given a binary tree, find its maximum depth. 9 | 10 | The maximum depth is the number of nodes along the longest path 11 | from the root node down to the farthest leaf node. 12 | */ 13 | 14 | type TreeNode = util.TreeNode 15 | 16 | func maxDepth(root *TreeNode) int { 17 | if root == nil { 18 | return 0 19 | } 20 | 21 | return 1 + max(maxDepth(root.Left), maxDepth(root.Right)) 22 | } 23 | 24 | func max(a, b int) int { 25 | if a > b { 26 | return a 27 | } 28 | return b 29 | } 30 | -------------------------------------------------------------------------------- /go/maximum-subarray/maximum-subarray.go: -------------------------------------------------------------------------------- 1 | package maximum_subarray 2 | 3 | /* 4 | Find the contiguous subarray within an array (containing at least one number) 5 | which has the largest sum. 6 | 7 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 8 | the contiguous subarray [4,-1,2,1] has the largest sum = 6. 9 | */ 10 | 11 | // 求:子串的最大值。也可以找出下标,即哪一段子串 12 | func maxSubArray(nums []int) int { 13 | if len(nums) == 0 { 14 | return 0 15 | } 16 | 17 | result, sum := nums[0], nums[0] 18 | 19 | for i := 1; i < len(nums); i++ { 20 | if sum >= 0 { 21 | sum += nums[i] 22 | } else { // sum已经是负数了,重新开始 23 | sum = nums[i] 24 | } 25 | 26 | if sum > result { 27 | result = sum 28 | } 29 | } 30 | 31 | return result 32 | } 33 | -------------------------------------------------------------------------------- /go/merge-sorted-array/merge-sorted-array.go: -------------------------------------------------------------------------------- 1 | package merge_sorted_array 2 | 3 | /* 4 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | 6 | Note: 7 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 8 | The number of elements initialized in nums1 and nums2 are m and n respectively. 9 | */ 10 | 11 | func merge(nums1 []int, m int, nums2 []int, n int) { 12 | i, j, index := 0, 0, 0 13 | tmp := make([]int, m+n) 14 | 15 | for i < m && j < n { 16 | if nums1[i] <= nums2[j] { 17 | tmp[index] = nums1[i] 18 | i++ 19 | } else { 20 | tmp[index] = nums2[j] 21 | j++ 22 | } 23 | index++ 24 | } 25 | 26 | for i < m { 27 | tmp[index] = nums1[i] 28 | i++ 29 | index++ 30 | } 31 | for j < n { 32 | tmp[index] = nums2[j] 33 | j++ 34 | index++ 35 | } 36 | 37 | copy(nums1, tmp) 38 | } 39 | -------------------------------------------------------------------------------- /go/merge-two-binary-trees/merge-two-binary-trees.go: -------------------------------------------------------------------------------- 1 | package merge_two_binary_trees 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | Given two binary trees and imagine that when you put one of them to cover the other, 9 | some nodes of the two trees are overlapped while the others are not. 10 | 11 | You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, 12 | then sum node values up as the new value of the merged node. 13 | Otherwise, the NOT null node will be used as the node of new tree. 14 | 15 | Example 1: 16 | Input: 17 | Tree 1 Tree 2 18 | 1 2 19 | / \ / \ 20 | 3 2 1 3 21 | / \ \ 22 | 5 4 7 23 | Output: 24 | Merged tree: 25 | 3 26 | / \ 27 | 4 5 28 | / \ \ 29 | 5 4 7 30 | Note: The merging process must start from the root nodes of both trees. 31 | */ 32 | 33 | type TreeNode = util.TreeNode 34 | 35 | func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode { 36 | if t1 == nil && t2 == nil { 37 | return nil 38 | } 39 | 40 | if t1 == nil { 41 | return t2 42 | } 43 | 44 | if t2 == nil { 45 | return t1 46 | } 47 | 48 | root := &TreeNode{Val: t1.Val + t2.Val} 49 | 50 | root.Left = mergeTrees(t1.Left, t2.Left) 51 | root.Right = mergeTrees(t1.Right, t2.Right) 52 | 53 | return root 54 | } 55 | -------------------------------------------------------------------------------- /go/merge-two-sorted-lists/merge-two-sorted-lists.go: -------------------------------------------------------------------------------- 1 | package merge_two_sorted_lists 2 | 3 | /* 4 | Merge two sorted linked lists and return it as a new list. 5 | The new list should be made by splicing together the nodes of the first two lists. 6 | 7 | Example: 8 | 9 | Input: 1->2->4, 1->3->4 10 | Output: 1->1->2->3->4->4 11 | */ 12 | 13 | type ListNode struct { 14 | Val int 15 | Next *ListNode 16 | } 17 | 18 | func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { 19 | if l1 == nil && l2 == nil { 20 | return nil 21 | } 22 | 23 | if l1 == nil { 24 | return l2 25 | } else if l2 == nil { 26 | return l1 27 | } 28 | 29 | iter1, iter2 := l1, l2 30 | head := &ListNode{0, nil} // 空头,好用 31 | it := head 32 | 33 | for iter1 != nil && iter2 != nil { 34 | if iter1.Val <= iter2.Val { 35 | it.Next = iter1 36 | iter1 = iter1.Next 37 | } else { 38 | it.Next = iter2 39 | iter2 = iter2.Next 40 | } 41 | 42 | it = it.Next 43 | } 44 | 45 | if iter1 == nil { 46 | it.Next = iter2 47 | } else { 48 | it.Next = iter1 49 | } 50 | 51 | return head.Next 52 | } 53 | -------------------------------------------------------------------------------- /go/min-stack/min-stack.go: -------------------------------------------------------------------------------- 1 | package min_stack 2 | 3 | /* 4 | Design a stack that supports push, pop, top, 5 | and retrieving the minimum element in constant time. 6 | 7 | push(x) -- Push element x onto stack. 8 | pop() -- Removes the element on top of the stack. 9 | top() -- Get the top element. 10 | getMin() -- Retrieve the minimum element in the stack. 11 | Example: 12 | MinStack minStack = new MinStack(); 13 | minStack.push(-2); 14 | minStack.push(0); 15 | minStack.push(-3); 16 | minStack.getMin(); --> Returns -3. 17 | minStack.pop(); 18 | minStack.top(); --> Returns 0. 19 | minStack.getMin(); --> Returns -2. 20 | */ 21 | 22 | type MinStack struct { 23 | stack []int 24 | minst []int // 保存最小值的栈 25 | } 26 | 27 | /** initialize your stack structure here. */ 28 | func Constructor() MinStack { 29 | return MinStack{ 30 | stack: []int{}, 31 | minst: []int{}, 32 | } 33 | } 34 | 35 | func (this *MinStack) Push(x int) { 36 | if len(this.minst) == 0 { 37 | this.minst = append(this.minst, x) 38 | } else if x <= this.GetMin() { // 等号必须有 39 | this.minst = append(this.minst, x) 40 | } 41 | 42 | this.stack = append(this.stack, x) 43 | } 44 | 45 | func (this *MinStack) Pop() { 46 | if len(this.stack) > 0 { 47 | if this.Top() == this.GetMin() { 48 | this.minst = this.minst[:len(this.minst)-1] 49 | } 50 | this.stack = this.stack[:len(this.stack)-1] 51 | } 52 | } 53 | 54 | func (this *MinStack) Top() int { 55 | return this.stack[len(this.stack)-1] 56 | } 57 | 58 | func (this *MinStack) GetMin() int { 59 | return this.minst[len(this.minst)-1] 60 | } 61 | -------------------------------------------------------------------------------- /go/minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.go: -------------------------------------------------------------------------------- 1 | package minimum_depth_of_binary_tree 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | 111. 二叉树的最小深度 9 | 10 | 给定一个二叉树,找出其最小深度。 11 | 12 | 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 13 | 14 | 说明: 叶子节点是指没有子节点的节点。 15 | 16 | 示例: 17 | 18 | 给定二叉树 [3,9,20,null,null,15,7], 19 | 20 | 3 21 | / \ 22 | 9 20 23 | / \ 24 | 15 7 25 | 返回它的最小深度 2. 26 | */ 27 | 28 | type TreeNode = util.TreeNode 29 | 30 | func minDepth(root *TreeNode) int { 31 | if root == nil { 32 | return 0 33 | } 34 | 35 | // 注意这两种情况 36 | /* 37 | 1 38 | 2 39 | 这颗子树的高度是1,而不是0 40 | */ 41 | if root.Left == nil { 42 | return 1 + minDepth(root.Right) 43 | } 44 | if root.Right == nil { 45 | return 1 + minDepth(root.Left) 46 | } 47 | 48 | return 1 + min(minDepth(root.Left), minDepth(root.Right)) 49 | } 50 | 51 | func min(a, b int) int { 52 | if a <= b { 53 | return a 54 | } 55 | return b 56 | } 57 | -------------------------------------------------------------------------------- /go/minimum-moves-to-equal-array-elements/minimum-moves-to-equal-array-elements.go: -------------------------------------------------------------------------------- 1 | package minimum_moves_to_equal_array_elements 2 | 3 | /* 4 | Given a non-empty integer array of size n, find the minimum number of moves required to 5 | make all array elements equal, where a move is incrementing n - 1 elements by 1. 6 | 7 | Example: 8 | 9 | Input: 10 | [1,2,3] 11 | 12 | Output: 13 | 3 14 | 15 | Explanation: 16 | Only three moves are needed (remember each move increments two elements): 17 | 18 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 19 | */ 20 | 21 | // n -1 个数+1,相当于1个数-1 22 | 23 | func minMoves(nums []int) int { 24 | sum, min := 0, nums[0] 25 | 26 | for _, n := range nums { 27 | sum += n 28 | if n < min { 29 | min = n 30 | } 31 | } 32 | 33 | return sum - min*len(nums) 34 | } 35 | -------------------------------------------------------------------------------- /go/minimum-path-sum/minimum-path-sum.go: -------------------------------------------------------------------------------- 1 | package minimum_path_sum 2 | 3 | /* 4 | Given a m x n grid filled with non-negative numbers, 5 | find a path from top left to bottom right which minimizes the sum of all numbers along its path. 6 | 7 | Note: You can only move either down or right at any point in time. 8 | 9 | Example 1: 10 | [[1,3,1], 11 | [1,5,1], 12 | [4,2,1]] 13 | Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. 14 | */ 15 | 16 | // dp[x][y] = min(dp[x-1][y],dp[x][y-1]) + grid[x][y] 17 | func minPathSum(grid [][]int) int { 18 | if len(grid) == 0 { 19 | return 0 20 | } 21 | 22 | row := len(grid) 23 | colume := len(grid[0]) 24 | 25 | dp := make([][]int, row) 26 | for i, _ := range dp { 27 | dp[i] = make([]int, colume) 28 | } 29 | 30 | dp[0][0] = grid[0][0] 31 | 32 | for i := 1; i < row; i++ { 33 | dp[i][0] = dp[i-1][0] + grid[i][0] 34 | } 35 | 36 | for j := 1; j < colume; j++ { 37 | dp[0][j] = dp[0][j-1] + grid[0][j] 38 | } 39 | 40 | for i := 1; i < row; i++ { 41 | for j := 1; j < colume; j++ { 42 | dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j] 43 | } 44 | } 45 | 46 | return dp[row-1][colume-1] 47 | } 48 | 49 | func min(a, b int) int { 50 | if a < b { 51 | return a 52 | } 53 | return b 54 | } 55 | -------------------------------------------------------------------------------- /go/missing-number/missing-number.go: -------------------------------------------------------------------------------- 1 | package missing_number 2 | 3 | /* 4 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, 5 | find the one that is missing from the array. 6 | 7 | Example 1 8 | 9 | Input: [3,0,1] 10 | Output: 2 11 | Example 2 12 | 13 | Input: [9,6,4,2,3,5,7,0,1] 14 | Output: 8 15 | 16 | Note: 17 | Your algorithm should run in linear runtime complexity. 18 | Could you implement it using only constant extra space complexity? 19 | */ 20 | 21 | func missingNumber(nums []int) int { 22 | n := len(nums) 23 | sum := n * (n + 1) / 2 24 | 25 | for _, num := range nums { 26 | sum -= num 27 | } 28 | 29 | return sum 30 | } 31 | 32 | /* 33 | 0 ^ 0 = 0 34 | b ^ b = 0 35 | 0 ^ a = a 36 | a ^ b ^ b = a 37 | 38 | 只有一个数,没有 异或过自己 39 | */ 40 | func missingNumber2(nums []int) int { 41 | result := 0 42 | 43 | for i, n := range nums { 44 | result ^= i ^ n 45 | } 46 | 47 | return result ^ len(nums) // 去掉最大的那个,剩下的就是要找的 48 | } 49 | 50 | // 放在该在的位置 比如3就放在下标为3的位置 错误的原因:内存不够,所以先append一个元素,扩展够 51 | // TODO 还未完成, 还挺难控制。。。 52 | func missingNumber3(nums []int) int { 53 | const E = -1 54 | nums = append(nums, E) // 新加的这个-1放在最后 55 | changed := false 56 | 57 | for i, n := range nums { 58 | if n != i { 59 | if n == len(nums)-1 && !changed { // 最后的位置是E,直接覆盖掉它,不要交换 60 | nums[n] = n 61 | changed = true 62 | } else { 63 | nums[i], nums[n] = nums[n], n 64 | } 65 | } 66 | } 67 | 68 | for i, n := range nums { 69 | if n != i { 70 | return i 71 | } 72 | } 73 | 74 | return -1 75 | } 76 | -------------------------------------------------------------------------------- /go/move-zeroes/move-zeroes.go: -------------------------------------------------------------------------------- 1 | package move_zeroes 2 | 3 | /* 4 | Given an array nums, write a function to move all 0's to the end of it 5 | while maintaining the relative order of the non-zero elements. 6 | 7 | For example, given nums = [0, 1, 0, 3, 12], 8 | after calling your function, nums should be [1, 3, 12, 0, 0]. 9 | 10 | Note: 11 | You must do this in-place without making a copy of the array. 12 | Minimize the total number of operations. 13 | */ 14 | 15 | // 原地倒腾,非零的都赋值到前面 操作len(nums)次 16 | func moveZeroes(nums []int) { 17 | index := 0 // 新的索引 18 | for _, n := range nums { 19 | if n != 0 { 20 | nums[index] = n 21 | index++ 22 | } 23 | } 24 | 25 | for j := index; j < len(nums); j++ { 26 | nums[j] = 0 27 | } 28 | } 29 | 30 | // 原地交换 操作 2*非零个数 次,所以非零很少的情况下才用此法 31 | func moveZeroes(nums []int) { 32 | index := 0 // 新的非零索引,指向目前第一个零的位置 33 | for i, n := range nums { 34 | if n != 0 { 35 | nums[index], nums[i] = nums[i], nums[index] 36 | index++ 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /go/palindrome-linked-list/palindrome-linked-list.go: -------------------------------------------------------------------------------- 1 | package palindrome_linked_list 2 | 3 | /* 4 | Given a singly linked list, determine if it is a palindrome. 5 | 6 | Follow up: 7 | Could you do it in O(n) time and O(1) space? 8 | */ 9 | 10 | type ListNode struct { 11 | Val int 12 | Next *ListNode 13 | } 14 | 15 | // 问题:判断是否是回文链表 16 | func isPalindrome(head *ListNode) bool { 17 | if head == nil { 18 | return true 19 | } 20 | 21 | // 放到数组里,然后判断数组是否是回文 22 | s := make([]int, 0) 23 | for ; head != nil; head = head.Next { 24 | s = append(s, head.Val) 25 | } 26 | 27 | left, right := 0, len(s)-1 28 | for left < right { 29 | if s[left] != s[right] { 30 | return false 31 | } 32 | left++ 33 | right-- 34 | } 35 | 36 | return true 37 | } 38 | -------------------------------------------------------------------------------- /go/palindrome-number/palindrome-number.go: -------------------------------------------------------------------------------- 1 | package palindrome_number 2 | 3 | /* 4 | Determine whether an integer is a palindrome. Do this without extra space. 5 | */ 6 | 7 | // 回文数字,比如12321 8 | func isPalindromeNumber(x int) bool { 9 | if x < 0 { 10 | return false 11 | } 12 | 13 | div := 1 // 数量级 14 | for n := x; n >= 10; n /= 10 { 15 | div *= 10 16 | } 17 | 18 | for x > 0 { 19 | if x/div != x%10 { 20 | return false 21 | } 22 | x = (x % div) / 10 // 去掉首尾 23 | div /= 100 24 | } 25 | 26 | return true 27 | } 28 | -------------------------------------------------------------------------------- /go/palindrome-number/palindrome-number_test.go: -------------------------------------------------------------------------------- 1 | package palindrome_number 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func Test_isPalindromeNumber(t *testing.T) { 9 | tt := []struct { 10 | name string 11 | input int 12 | expect bool 13 | }{ 14 | { 15 | "如题", 16 | 12321, 17 | true, 18 | }, 19 | { 20 | "", 21 | 1000021, 22 | false, 23 | }, 24 | } 25 | for _, tc := range tt { 26 | t.Run(tc.name, func(t *testing.T) { 27 | if got := isPalindromeNumber(tc.input); !reflect.DeepEqual(got, tc.expect) { 28 | t.Fatalf("isPalindromeNumber(%v) got %v, expect %v", tc.input, got, tc.expect) 29 | } 30 | }) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /go/path-sum-iii/path-sum-iii.go: -------------------------------------------------------------------------------- 1 | package path_sum_iii 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | You are given a binary tree in which each node contains an integer value. 9 | 10 | Find the number of paths that sum to a given value. 11 | 12 | The path does not need to start or end at the root or a leaf, 13 | but it must go downwards (traveling only from parent nodes to child nodes). 14 | 15 | The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. 16 | 17 | Example: 18 | 19 | root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 20 | 21 | 10 22 | / \ 23 | 5 -3 24 | / \ \ 25 | 3 2 11 26 | / \ \ 27 | 3 -2 1 28 | 29 | Return 3. The paths that sum to 8 are: 30 | 31 | 1. 5 -> 3 32 | 2. 5 -> 2 -> 1 33 | 3. -3 -> 11 34 | */ 35 | 36 | type TreeNode = util.TreeNode 37 | 38 | // 双重递归 39 | // 1 是dfs,找sum 40 | // 2 是从任意节点开始 41 | func pathSum(root *TreeNode, sum int) int { 42 | if root == nil { 43 | return 0 44 | } 45 | return dfs(root, sum) + pathSum(root.Left, sum) + pathSum(root.Right, sum) 46 | } 47 | 48 | func dfs(root *TreeNode, sum int) int { 49 | if root == nil { 50 | return 0 51 | } 52 | 53 | cnt := 0 54 | 55 | sum -= root.Val 56 | if sum == 0 { 57 | cnt++ 58 | } 59 | 60 | cnt += dfs(root.Left, sum) 61 | cnt += dfs(root.Right, sum) 62 | 63 | return cnt 64 | } 65 | -------------------------------------------------------------------------------- /go/path-sum/path-sum.go: -------------------------------------------------------------------------------- 1 | package path_sum 2 | 3 | /* 4 | Given a binary tree and a sum, 5 | determine if the tree has a root-to-leaf path such that 6 | adding up all the values along the path equals the given sum. 7 | 8 | For example: 9 | Given the below binary tree and sum = 22, 10 | 5 11 | / \ 12 | 4 8 13 | / / \ 14 | 11 13 4 15 | / \ \ 16 | 7 2 1 17 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 18 | */ 19 | 20 | type TreeNode struct { 21 | Val int 22 | Left *TreeNode 23 | Right *TreeNode 24 | } 25 | 26 | func hasPathSum(root *TreeNode, sum int) bool { 27 | return hasPathSumImpl(root, sum, 0) 28 | } 29 | 30 | func hasPathSumImpl(root *TreeNode, sum int, cur int) bool { 31 | if root == nil { 32 | return false 33 | } 34 | 35 | cur += root.Val 36 | if root.Left == nil && root.Right == nil { // 叶子节点 37 | return cur == sum 38 | } 39 | 40 | return hasPathSumImpl(root.Left, sum, cur) || hasPathSumImpl(root.Right, sum, cur) 41 | } 42 | 43 | // ---------- 44 | 45 | func hasPathSum2(root *TreeNode, sum int) bool { 46 | return hasPathSumImpl(root, sum) 47 | } 48 | 49 | func hasPathSumImpl2(root *TreeNode, sum int) bool { 50 | if root == nil { 51 | return false 52 | } 53 | 54 | sum -= root.Val // 剩下的sum 55 | if root.Left == nil && root.Right == nil { // 叶子节点 56 | return sum == 0 57 | } 58 | 59 | return hasPathSumImpl(root.Left, sum) || hasPathSumImpl(root.Right, sum) 60 | } 61 | -------------------------------------------------------------------------------- /go/plus-one/plus-one.go: -------------------------------------------------------------------------------- 1 | package plus_one 2 | 3 | /* 4 | 66. 加一 5 | 6 | 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 7 | 8 | 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。 9 | 10 | 你可以假设除了整数 0 之外,这个整数不会以零开头。 11 | 12 | 示例 1: 13 | 14 | 输入: [1,2,3] 15 | 输出: [1,2,4] 16 | 解释: 输入数组表示数字 123。 17 | 示例 2: 18 | 19 | 输入: [4,3,2,1] 20 | 输出: [4,3,2,2] 21 | 解释: 输入数组表示数字 4321。 22 | */ 23 | 24 | func plusOne(digits []int) []int { 25 | carry := 0 26 | 27 | i := len(digits) - 1 28 | carry = (digits[i] + 1) / 10 29 | digits[i] = (digits[i] + 1) % 10 30 | 31 | i-- 32 | var num int 33 | for ; carry > 0 && i >= 0; i-- { 34 | num = digits[i] + carry 35 | digits[i] = num % 10 36 | carry = num / 10 37 | } 38 | 39 | if carry > 0 { 40 | digits = append([]int{carry}, digits...) 41 | } 42 | 43 | return digits 44 | } 45 | -------------------------------------------------------------------------------- /go/product-of-array-except-self/product-of-array-except-self.go: -------------------------------------------------------------------------------- 1 | package product_of_array_except_self 2 | 3 | /* 4 | Given an array of n integers where n > 1, 5 | nums, return an array output such that output[i] is equal to 6 | the product of all the elements of nums except nums[i]. 7 | 8 | Solve it without division and in O(n). 9 | 10 | For example, given [1,2,3,4], return [24,12,8,6]. 11 | 12 | Follow up: 13 | Could you solve it with constant space complexity? 14 | (Note: The output array does not count as extra space for 15 | the purpose of space complexity analysis.) 16 | */ 17 | 18 | // TODO Time Limit Exceeded??? 19 | func productExceptSelf(nums []int) []int { 20 | length := len(nums) 21 | 22 | // 左侧乘积,右侧乘积 23 | left, right := make([]int, length), make([]int, length) 24 | left[0], right[length-1] = 1, 1 25 | 26 | for i := 1; i < length; i++ { 27 | left[i] = left[i-1] * nums[i-1] 28 | right[length-i-1] = right[length-i] * nums[length-i] 29 | } 30 | 31 | result := make([]int, length) 32 | for i, _ := range nums { 33 | result[i] = left[i] * right[i] 34 | } 35 | 36 | return result 37 | } 38 | -------------------------------------------------------------------------------- /go/ransom-note/ransom-note.go: -------------------------------------------------------------------------------- 1 | package ransom_note 2 | 3 | /* 4 | Given an arbitrary ransom note string and another string containing letters from all the magazines, 5 | write a function that will return true if the ransom note can be constructed from the magazines ; 6 | otherwise, it will return false. 7 | 8 | Each letter in the magazine string can only be used once in your ransom note. 9 | 10 | Note: 11 | You may assume that both strings contain only lowercase letters. 12 | 13 | canConstruct("a", "b") -> false 14 | canConstruct("aa", "ab") -> false 15 | canConstruct("aa", "aab") -> true 16 | */ 17 | 18 | // 也可以用长度的为26的数组记录次数 19 | func canConstruct(ransomNote string, magazine string) bool { 20 | m := make(map[rune]int) 21 | for _, c := range magazine { 22 | m[c] += 1 23 | } 24 | 25 | for _, c := range ransomNote { 26 | m[c] -= 1 27 | if m[c] < 0 { 28 | return false 29 | } 30 | } 31 | 32 | return true 33 | } 34 | -------------------------------------------------------------------------------- /go/remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.go: -------------------------------------------------------------------------------- 1 | package remove_duplicates_from_sorted_arraylongest_common_prefix 2 | 3 | /* 4 | Given a sorted array, remove the duplicates in-place 5 | such that each element appear only once and return the new length. 6 | 7 | Do not allocate extra space for another array, 8 | you must do this by modifying the input array in-place with O(1) extra memory. 9 | 10 | Example: 11 | 12 | Given nums = [1,1,2], 13 | 14 | Your function should return length = 2, with the first t 15 | */ 16 | 17 | // 原地去重 18 | func removeDuplicates(nums []int) int { 19 | if len(nums) == 0 { 20 | return 0 21 | } 22 | 23 | index := 0 // 新slice下标 24 | for i := 1; i < len(nums); i++ { 25 | if nums[i] != nums[index] { 26 | index++ 27 | nums[index] = nums[i] 28 | } 29 | } 30 | 31 | index++ 32 | nums = nums[:index] 33 | return index 34 | } 35 | -------------------------------------------------------------------------------- /go/remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.go: -------------------------------------------------------------------------------- 1 | package remove_duplicates_from_sorted_list 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | 83. 删除排序链表中的重复元素 9 | 10 | 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 11 | 12 | 示例 1: 13 | 14 | 输入: 1->1->2 15 | 输出: 1->2 16 | 示例 2: 17 | 18 | 输入: 1->1->2->3->3 19 | 输出: 1->2->3 20 | */ 21 | 22 | type ListNode = util.ListNode 23 | 24 | func deleteDuplicates(head *ListNode) *ListNode { 25 | if head == nil || head.Next == nil { 26 | return head 27 | } 28 | 29 | cur, next := head, head.Next 30 | 31 | for next != nil { 32 | if next.Val == cur.Val { 33 | cur.Next = next.Next // 删除next 34 | // cur 不动,next前移继续判断 35 | next = next.Next 36 | } else { // 不等,同时前移 37 | cur = next 38 | next = next.Next 39 | } 40 | } 41 | 42 | return head // head不会变 43 | } 44 | -------------------------------------------------------------------------------- /go/remove-element/remove-element.go: -------------------------------------------------------------------------------- 1 | package remove_element 2 | 3 | /* 4 | Given an array and a value, remove all instances of that value in-place and return the new length. 5 | 6 | Do not allocate extra space for another array, 7 | you must do this by modifying the input array in-place with O(1) extra memory. 8 | 9 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 10 | 11 | Example: 12 | 13 | Given nums = [3,2,2,3], val = 3, 14 | 15 | Your function should return length = 2, with the first two elements of nums being 2. 16 | */ 17 | 18 | func removeElement(nums []int, val int) int { 19 | index := 0 20 | 21 | for _, n := range nums { 22 | if n != val { 23 | nums[index] = n 24 | index++ 25 | } 26 | } 27 | 28 | return index 29 | } 30 | -------------------------------------------------------------------------------- /go/remove-linked-list-elements/remove-linked-list-elements.go: -------------------------------------------------------------------------------- 1 | package remove_linked_list_elements 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | Remove all elements from a linked list of integers that have value val. 9 | 10 | Example 11 | Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 12 | Return: 1 --> 2 --> 3 --> 4 --> 5 13 | */ 14 | 15 | type ListNode = util.ListNode 16 | 17 | func removeElements(head *ListNode, val int) *ListNode { 18 | dummy := ListNode{Next: head} 19 | pre, cur := &dummy, dummy.Next 20 | 21 | for cur != nil { 22 | if cur.Val == val { 23 | pre.Next = cur.Next 24 | } else { 25 | pre = cur 26 | } 27 | cur = cur.Next 28 | } 29 | 30 | return dummy.Next 31 | } 32 | -------------------------------------------------------------------------------- /go/reverse-linked-list/reverse-linked-list.go: -------------------------------------------------------------------------------- 1 | package reverse_linked_list 2 | 3 | import "fmt" 4 | 5 | /* 6 | Reverse a singly linked list. 7 | 8 | click to show more hints. 9 | 10 | Hint: 11 | A linked list can be reversed either iteratively or recursively. 12 | Could you implement both? 13 | */ 14 | 15 | type ListNode struct { 16 | Val int 17 | Next *ListNode 18 | } 19 | 20 | // 头插法,就倒置了 21 | func reverseList(head *ListNode) *ListNode { 22 | if head == nil || head.Next == nil { 23 | return head 24 | } 25 | 26 | dummy := &ListNode{-1, head} 27 | cur := head.Next // 第二个结点,从第二个结点开始,头插法 28 | head.Next = nil // 倒置后的尾结点 29 | 30 | for cur != nil { 31 | tmp := cur.Next 32 | 33 | cur.Next = dummy.Next 34 | dummy.Next = cur 35 | 36 | cur = tmp 37 | } 38 | 39 | return dummy.Next 40 | } 41 | -------------------------------------------------------------------------------- /go/reverse-linked-list/reverse-linked-list_test.go: -------------------------------------------------------------------------------- 1 | package reverse_linked_list 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func Test_reverseList(t *testing.T) { 9 | tt := []struct { 10 | name string 11 | input []int 12 | expect []int 13 | }{ 14 | { 15 | "如题", 16 | []int{1, 2, 3, 4, 5}, 17 | []int{5, 4, 3, 2, 1}, 18 | }, 19 | } 20 | for _, tc := range tt { 21 | t.Run(tc.name, func(t *testing.T) { 22 | if got := l2s(reverseList(s2l(tc.input))); !reflect.DeepEqual(got, tc.expect) { 23 | t.Fatalf("reverseList(%v) got %v, expect %v", tc.input, got, tc.expect) 24 | } 25 | }) 26 | } 27 | } 28 | 29 | // convert *ListNode to []int 30 | func l2s(head *ListNode) []int { 31 | res := []int{} 32 | 33 | for head != nil { 34 | res = append(res, head.Val) 35 | head = head.Next 36 | } 37 | 38 | return res 39 | } 40 | 41 | // convert []int to *ListNode 42 | func s2l(nums []int) *ListNode { 43 | if len(nums) == 0 { 44 | return nil 45 | } 46 | 47 | res := &ListNode{ 48 | Val: nums[0], 49 | } 50 | temp := res 51 | for i := 1; i < len(nums); i++ { 52 | temp.Next = &ListNode{ 53 | Val: nums[i], 54 | } 55 | temp = temp.Next 56 | } 57 | 58 | return res 59 | } 60 | -------------------------------------------------------------------------------- /go/reverse-string/reverse-string.go: -------------------------------------------------------------------------------- 1 | package reverse_string 2 | 3 | /* 4 | Write a function that takes a string as input and returns the string reversed. 5 | 6 | Example: 7 | Given s = "hello", return "olleh". 8 | */ 9 | 10 | func reverseString(s string) string { 11 | bs := []byte(s) 12 | left, right := 0, len(bs)-1 13 | 14 | for left < right { 15 | bs[left], bs[right] = bs[right], bs[left] 16 | left++ 17 | right-- 18 | } 19 | return string(bs) 20 | } 21 | -------------------------------------------------------------------------------- /go/reverse-string/reverse-string_test.go: -------------------------------------------------------------------------------- 1 | package reverse_string 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestReverseString(t *testing.T) { 8 | tt := []struct { 9 | name string 10 | input string 11 | expect string 12 | }{ 13 | { 14 | "如题", 15 | "hello", 16 | "olleh", 17 | }, 18 | } 19 | for _, tc := range tt { 20 | t.Run(tc.name, func(t *testing.T) { 21 | if got := reverseString(tc.input); got != tc.expect { 22 | t.Fatalf("reverseString(%v) got %v, expect %v", tc.input, got, tc.expect) 23 | } 24 | }) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /go/roman-to-integer/roman-to-integer.go: -------------------------------------------------------------------------------- 1 | package roman_to_integer 2 | 3 | /* 4 | Given a roman numeral, convert it to an integer. 5 | 6 | Input is guaranteed to be within the range from 1 to 3999. 7 | */ 8 | 9 | // "DCXXI" -- > 621 1 + 10 + 10 + 100 + 500 10 | // "XXXIX" -- > 39 10 - 1 + 10 + 10 + 10 11 | func romanToInt(s string) int { 12 | result := 0 13 | 14 | m := map[byte]int{ 15 | 'I': 1, 16 | 'V': 5, 17 | 'X': 10, 18 | 'L': 50, 19 | 'C': 100, 20 | 'D': 500, 21 | 'M': 1000, 22 | } 23 | 24 | pre := 0 25 | for i := len(s) - 1; i >= 0; i-- { 26 | num := m[s[i]] 27 | 28 | if num < pre { 29 | result -= num 30 | } else { 31 | result += num 32 | } 33 | pre = num 34 | } 35 | 36 | return result 37 | } 38 | -------------------------------------------------------------------------------- /go/same-tree/same-tree.go: -------------------------------------------------------------------------------- 1 | package same_tree 2 | 3 | import "../util" 4 | 5 | /* 6 | Given two binary trees, write a function to check if they are the same or not. 7 | 8 | Two binary trees are considered the same if they are structurally identical 9 | and the nodes have the same value. 10 | 11 | 12 | Example 1: 13 | 14 | Input: 1 1 15 | / \ / \ 16 | 2 3 2 3 17 | 18 | [1,2,3], [1,2,3] 19 | 20 | Output: true 21 | Example 2: 22 | 23 | Input: 1 1 24 | / \ 25 | 2 2 26 | 27 | [1,2], [1,null,2] 28 | 29 | Output: false 30 | Example 3: 31 | 32 | Input: 1 1 33 | / \ / \ 34 | 2 1 1 2 35 | 36 | [1,2,1], [1,1,2] 37 | 38 | Output: false 39 | */ 40 | 41 | type TreeNode = util.TreeNode 42 | 43 | func isSameTree(p *TreeNode, q *TreeNode) bool { 44 | if p == nil && q == nil { 45 | return true 46 | } 47 | 48 | if p == nil || q == nil { 49 | return false 50 | } 51 | 52 | return p.Val == q.Val && isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) 53 | } 54 | 55 | var ( 56 | IsSameTree = isSameTree 57 | ) 58 | -------------------------------------------------------------------------------- /go/search-insert-position/search-insert-position.go: -------------------------------------------------------------------------------- 1 | package search_insert_position 2 | 3 | /* 4 | 35. 搜索插入位置 5 | 6 | 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 7 | 8 | 你可以假设数组中无重复元素。 9 | 10 | 示例 1: 11 | 12 | 输入: [1,3,5,6], 5 13 | 输出: 2 14 | 示例 2: 15 | 16 | 输入: [1,3,5,6], 2 17 | 输出: 1 18 | 示例 3: 19 | 20 | 输入: [1,3,5,6], 7 21 | 输出: 4 22 | 示例 4: 23 | 24 | 输入: [1,3,5,6], 0 25 | 输出: 0 26 | */ 27 | 28 | func searchInsert(nums []int, target int) int { 29 | for i, n := range nums { 30 | if target <= n { 31 | return i 32 | } 33 | } 34 | return len(nums) 35 | } 36 | -------------------------------------------------------------------------------- /go/single-number-ii/single-number-ii.go: -------------------------------------------------------------------------------- 1 | package single_number_ii 2 | 3 | // 这种方法可以拓展为 每个元素都出现了k次,只有一个出现了1次,找出它 4 | func singleNumberII(nums []int) int { 5 | result := 0 6 | 7 | // int 是64位? 8 | for bit := uint(0); bit < 64; bit++ { 9 | count := 0 // 保存这个二进制位上的1出现的次数,每个位上都应该是3的倍数,除了要找的那一个 10 | for i := 0; i < len(nums); i++ { 11 | if (nums[i]>>bit)&1 > 0 { 12 | count++ 13 | } 14 | } 15 | result |= ((count % 3) << bit) 16 | } 17 | 18 | return result 19 | } 20 | -------------------------------------------------------------------------------- /go/single-number/single-number.go: -------------------------------------------------------------------------------- 1 | package single_number 2 | 3 | func singleNumber(nums []int) int { 4 | result := 0 5 | for _, n := range nums { 6 | result ^= n 7 | } 8 | return result 9 | } 10 | -------------------------------------------------------------------------------- /go/sort-colors/sort-colors.go: -------------------------------------------------------------------------------- 1 | package sort_colors 2 | 3 | /* 4 | Given an array with n objects colored red, white or blue, 5 | sort them so that objects of the same color are adjacent, 6 | with the colors in the order red, white and blue. 7 | 8 | Here, we will use the integers 0, 1, and 2 to represent the color red, 9 | white, and blue respectively. 10 | 11 | Note: 12 | You are not suppose to use the library's sort function for this problem. 13 | */ 14 | 15 | // 1 0 0 2 1 2 16 | func sortColors(nums []int) { 17 | left := 0 // 0后面的1的位置 001122 left=2 right=3 18 | right := len(nums) - 1 // 2前面1的位置 19 | index := 0 20 | 21 | for index <= right { 22 | if nums[index] == 0 { 23 | swap(nums, index, left) 24 | index++ 25 | left++ 26 | } else if nums[index] == 1 { 27 | index++ 28 | } else { 29 | swap(nums, index, right) 30 | right-- 31 | } 32 | } 33 | } 34 | 35 | func swap(nums []int, i, j int) { 36 | nums[i], nums[j] = nums[j], nums[i] 37 | } 38 | -------------------------------------------------------------------------------- /go/sqrtx/sqrtx.go: -------------------------------------------------------------------------------- 1 | package sqrtx 2 | 3 | /* 4 | Implement int sqrt(int x). 5 | 6 | Compute and return the square root of x. 7 | 8 | x is guaranteed to be a non-negative integer. 9 | 10 | 11 | Example 1: 12 | 13 | Input: 4 14 | Output: 2 15 | Example 2: 16 | 17 | Input: 8 18 | Output: 2 19 | Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, 20 | the decimal part will be truncated. 21 | */ 22 | 23 | // 二分法 24 | func mySqrt(x int) int { 25 | low, high := 1, x 26 | var mid int 27 | 28 | for low <= high { 29 | mid = (high-low)/2 + low 30 | if mid*mid == x { 31 | return mid 32 | } else if mid*mid < x { 33 | low = mid + 1 34 | } else { 35 | high = mid - 1 36 | } 37 | } 38 | 39 | // 到这里一定是low比high大了. 我们要选一个最接近的 40 | if low*low < x { 41 | return low 42 | } 43 | return high 44 | } 45 | 46 | // 牛顿迭代 47 | func mySqrt2(x int) int { 48 | i := x 49 | 50 | for i*i > x { 51 | i = (i + x/i) / 2 52 | } 53 | 54 | return i 55 | } 56 | -------------------------------------------------------------------------------- /go/subtree-of-another-tree/subtree-of-another-tree.go: -------------------------------------------------------------------------------- 1 | package subtree_of_another_tree 2 | 3 | import ( 4 | "../same-tree" 5 | "../util" 6 | ) 7 | 8 | /* 9 | Given two non-empty binary trees s and t, 10 | check whether tree t has exactly the same structure and node values with a subtree of s. 11 | A subtree of s is a tree consists of a node in s and all of this node's descendants. 12 | The tree s could also be considered as a subtree of itself. 13 | 14 | Example 1: 15 | Given tree s: 16 | 17 | 3 18 | / \ 19 | 4 5 20 | / \ 21 | 1 2 22 | Given tree t: 23 | 4 24 | / \ 25 | 1 2 26 | Return true, because t has the same structure and node values with a subtree of s. 27 | Example 2: 28 | Given tree s: 29 | 30 | 3 31 | / \ 32 | 4 5 33 | / \ 34 | 1 2 35 | / 36 | 0 37 | Given tree t: 38 | 4 39 | / \ 40 | 1 2 41 | Return false. 42 | */ 43 | 44 | type TreeNode = util.TreeNode 45 | 46 | func isSubtree(s *TreeNode, t *TreeNode) bool { 47 | if s == nil { 48 | return false 49 | } 50 | if same_tree.IsSameTree(s, t) { 51 | return true 52 | } 53 | 54 | return isSubtree(s.Left, t) || isSubtree(s.Right, t) 55 | } 56 | -------------------------------------------------------------------------------- /go/sum-of-left-leaves/sum-of-left-leaves.go: -------------------------------------------------------------------------------- 1 | package sum_of_left_leaves 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | Find the sum of all left leaves in a given binary tree. 9 | 10 | Example: 11 | 12 | 3 13 | / \ 14 | 9 20 15 | / \ 16 | 15 7 17 | 18 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 19 | */ 20 | 21 | type TreeNode = util.TreeNode 22 | 23 | func sumOfLeftLeaves(root *TreeNode) int { 24 | if root == nil { 25 | return 0 26 | } 27 | 28 | if root.Left == nil { 29 | return sumOfLeftLeaves(root.Right) 30 | } 31 | 32 | ret := 0 33 | // 左侧叶子节点 34 | if root.Left.Left == nil && root.Left.Right == nil { 35 | ret += root.Left.Val 36 | } 37 | return ret + sumOfLeftLeaves(root.Left) + sumOfLeftLeaves(root.Right) 38 | } 39 | -------------------------------------------------------------------------------- /go/symmetric-tree/symmetric-tree.go: -------------------------------------------------------------------------------- 1 | package symmetric_tree 2 | 3 | import ( 4 | "../util" 5 | ) 6 | 7 | /* 8 | Given a binary tree, check whether it is a mirror of itself 9 | (ie, symmetric around its center). 10 | 11 | For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 12 | 13 | 1 14 | / \ 15 | 2 2 16 | / \ / \ 17 | 3 4 4 3 18 | But the following [1,2,2,null,3,null,3] is not: 19 | 1 20 | / \ 21 | 2 2 22 | \ \ 23 | 3 3 24 | Note: 25 | Bonus points if you could solve it both recursively and iteratively. 26 | */ 27 | 28 | // 问题:是否是对称树 29 | 30 | type TreeNode = util.TreeNode 31 | 32 | func isSymmetric(root *TreeNode) bool { 33 | if root == nil { 34 | return true 35 | } 36 | 37 | return symmetric(root.Left, root.Right) 38 | } 39 | 40 | func symmetric(left *TreeNode, right *TreeNode) bool { 41 | if left == nil && right == nil { 42 | return true 43 | } 44 | // 只有一个是nil 45 | if left == nil || right == nil { 46 | return false 47 | } 48 | 49 | if left.Val != right.Val { 50 | return false 51 | } 52 | 53 | return symmetric(left.Left, right.Right) && symmetric(left.Right, right.Left) 54 | } 55 | -------------------------------------------------------------------------------- /go/two-sum/two-sum.go: -------------------------------------------------------------------------------- 1 | package two_sum 2 | 3 | import "sort" // twoSum2 4 | 5 | /* 6 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 7 | 8 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 9 | 10 | Example: 11 | Given nums = [2, 7, 11, 15], target = 9, 12 | 13 | Because nums[0] + nums[1] = 2 + 7 = 9, 14 | return [0, 1]. 15 | */ 16 | 17 | // map即哈希表,遍历,每个元素到map中找一下target-v,有即返回,没有则放在map中 18 | func twoSum(nums []int, target int) []int { 19 | m := make(map[int]int, len(nums)) // num->index 20 | for i, v := range nums { 21 | if _, ok := m[target-v]; ok { 22 | return []int{m[target-v], i} // 注意先后 23 | } 24 | m[v] = i 25 | } 26 | return nil 27 | } 28 | 29 | // 前提是没有重复的元素,否则两个相同元素的位置会覆盖成一个 30 | // 先排序,然后首尾向中间靠拢 31 | func twoSum2(srcNums []int, target int) []int { 32 | nums := make([]int, len(srcNums)) 33 | copy(nums, srcNums) // 为了不改变原slice,因为要排序 34 | m := make(map[int]int, len(nums)) 35 | for i, v := range nums { 36 | m[v] = i 37 | } 38 | sort.Ints(nums) 39 | left, right := 0, len(nums)-1 40 | 41 | for left < right { 42 | if nums[left]+nums[right] < target { 43 | left++ 44 | } else if nums[left]+nums[right] > target { 45 | right-- 46 | } else { 47 | return []int{m[nums[left]], m[nums[right]]} 48 | } 49 | } 50 | 51 | return nil 52 | } 53 | -------------------------------------------------------------------------------- /go/two-sum/two-sum_test.go: -------------------------------------------------------------------------------- 1 | package two_sum 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestTwoSum(t *testing.T) { 9 | tt := []struct { 10 | name string 11 | nums []int 12 | target int 13 | expect []int 14 | }{ 15 | { 16 | "如题", 17 | []int{2, 7, 11, 15}, 18 | 9, 19 | []int{0, 1}, 20 | }, 21 | { 22 | "不存在", 23 | []int{2, 7, 11, 15}, 24 | 3, 25 | nil, 26 | }, 27 | { 28 | "有相同元素", 29 | []int{2, 7, 3, 2}, 30 | 4, 31 | []int{0, 3}, 32 | }, 33 | } 34 | for _, tc := range tt { 35 | t.Run(tc.name, func(t *testing.T) { 36 | if got := twoSum(tc.nums, tc.target); !reflect.DeepEqual(got, tc.expect) { 37 | t.Fatalf("twoSum(%v, %d) got %v, expect %v", tc.nums, tc.target, got, tc.expect) 38 | } 39 | if got := twoSum2(tc.nums, tc.target); !reflect.DeepEqual(got, tc.expect) { 40 | t.Fatalf("twoSum2(%v, %d) got %v, expect %v", tc.nums, tc.target, got, tc.expect) 41 | } 42 | }) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /go/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | type TreeNode struct { 9 | Val int 10 | Left *TreeNode 11 | Right *TreeNode 12 | } 13 | -------------------------------------------------------------------------------- /go/valid-anagram/valid-anagram.go: -------------------------------------------------------------------------------- 1 | package valid_anagram 2 | 3 | /* 4 | Given two strings s and t, write a function to determine if t is an anagram of s. 5 | 6 | For example, 7 | s = "anagram", t = "nagaram", return true. 8 | s = "rat", t = "car", return false. 9 | 10 | Note: 11 | You may assume the string contains only lowercase alphabets. 12 | 13 | Follow up: 14 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 15 | */ 16 | 17 | func isAnagram(s string, t string) bool { 18 | if len(s) != len(t) { 19 | return false 20 | } 21 | 22 | // Unicode字符 23 | arr1 := []rune(s) 24 | arr2 := []rune(t) 25 | 26 | m := make(map[rune]int, len(arr1)) 27 | for i := range arr1 { 28 | m[arr1[i]]++ 29 | m[arr2[i]]-- 30 | } 31 | 32 | for _, n := range m { 33 | if n != 0 { 34 | return false 35 | } 36 | } 37 | 38 | return true 39 | } 40 | -------------------------------------------------------------------------------- /go/valid-parentheses/valid-parentheses.go: -------------------------------------------------------------------------------- 1 | package valid_parentheses 2 | 3 | /* 4 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', 5 | determine if the input string is valid. 6 | 7 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 8 | */ 9 | 10 | // 栈的典型应用 11 | func isValid(s string) bool { 12 | bs := []byte(s) 13 | stack := make([]byte, 0, len(bs)) 14 | 15 | for _, b := range bs { 16 | switch b { 17 | case '(', '{', '[': 18 | stack = append(stack, b) 19 | case ')', '}', ']': 20 | if len(stack) == 0 { 21 | return false 22 | } 23 | 24 | if match(stack[len(stack)-1], b) { 25 | stack = stack[:len(stack)-1] 26 | } else { 27 | stack = append(stack, b) 28 | } 29 | } 30 | } 31 | 32 | if len(stack) > 0 { 33 | return false 34 | } 35 | return true 36 | } 37 | 38 | func match(a, b byte) bool { 39 | if a == '(' && b == ')' || a == '{' && b == '}' || a == '[' && b == ']' { 40 | return true 41 | } 42 | return false 43 | } 44 | -------------------------------------------------------------------------------- /go/valid-perfect-square/valid-perfect-square.go: -------------------------------------------------------------------------------- 1 | package valid_perfect_square 2 | 3 | /* 4 | Given a positive integer num, write a function which returns True 5 | if num is a perfect square else False. 6 | 7 | Note: Do not use any built-in library function such as sqrt. 8 | 9 | Example 1: 10 | 11 | Input: 16 12 | Returns: True 13 | Example 2: 14 | 15 | Input: 14 16 | Returns: False 17 | */ 18 | 19 | // 最笨的方法:直接从1循环到n,判断即可。不推荐 20 | 21 | // 二分法 22 | func isPerfectSquare(num int) bool { 23 | low, high := 1, num 24 | var mid int 25 | 26 | for low <= high { 27 | mid = (high-low)/2 + low 28 | if mid*mid == num { 29 | return true 30 | } else if mid*mid < num { 31 | low = mid + 1 32 | } else { 33 | high = mid - 1 34 | } 35 | } 36 | 37 | return false 38 | } 39 | 40 | // 牛顿迭代 https://www.zhihu.com/question/41881138 41 | func isPerfectSquare2(num int) bool { 42 | x := num 43 | for x*x > num { 44 | x = (x + num/x) / 2 45 | } 46 | 47 | return x*x == num 48 | } 49 | -------------------------------------------------------------------------------- /mysql/big-countries.sql: -------------------------------------------------------------------------------- 1 | /* 2 | There is a table World 3 | 4 | +-----------------+------------+------------+--------------+---------------+ 5 | | name | continent | area | population | gdp | 6 | +-----------------+------------+------------+--------------+---------------+ 7 | | Afghanistan | Asia | 652230 | 25500100 | 20343000 | 8 | | Albania | Europe | 28748 | 2831741 | 12960000 | 9 | | Algeria | Africa | 2381741 | 37100000 | 188681000 | 10 | | Andorra | Europe | 468 | 78115 | 3712000 | 11 | | Angola | Africa | 1246700 | 20609294 | 100990000 | 12 | +-----------------+------------+------------+--------------+---------------+ 13 | A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million. 14 | 15 | Write a SQL solution to output big countries' name, population and area. 16 | 17 | For example, according to the above table, we should output: 18 | 19 | +--------------+-------------+--------------+ 20 | | name | population | area | 21 | +--------------+-------------+--------------+ 22 | | Afghanistan | 25500100 | 652230 | 23 | | Algeria | 37100000 | 2381741 | 24 | +--------------+-------------+--------------+ 25 | */ 26 | 27 | -- 28 | select name, population, area 29 | from World 30 | where area > 3000000 or population > 25000000; 31 | 32 | -- 33 | select name, population, area 34 | from World 35 | where area > 3000000 36 | union 37 | select name, population, area 38 | from World 39 | where population > 25000000; 40 | -------------------------------------------------------------------------------- /mysql/combine-two-tables.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Table: Person 3 | 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | PersonId | int | 8 | | FirstName | varchar | 9 | | LastName | varchar | 10 | +-------------+---------+ 11 | PersonId is the primary key column for this table. 12 | Table: Address 13 | 14 | +-------------+---------+ 15 | | Column Name | Type | 16 | +-------------+---------+ 17 | | AddressId | int | 18 | | PersonId | int | 19 | | City | varchar | 20 | | State | varchar | 21 | +-------------+---------+ 22 | AddressId is the primary key column for this table. 23 | 24 | Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people: 25 | 26 | FirstName, LastName, City, State 27 | */ 28 | 29 | select p.FirstName, p.LastName, a.City, a.State 30 | from Person p left join Address a 31 | on p.PersonId = a.PersonId 32 | -------------------------------------------------------------------------------- /mysql/consecutive-numbers.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Write a SQL query to find all numbers that appear at least three times consecutively. 3 | 4 | +----+-----+ 5 | | Id | Num | 6 | +----+-----+ 7 | | 1 | 1 | 8 | | 2 | 1 | 9 | | 3 | 1 | 10 | | 4 | 2 | 11 | | 5 | 1 | 12 | | 6 | 2 | 13 | | 7 | 2 | 14 | +----+-----+ 15 | For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times. 16 | */ 17 | 18 | select distinct(l1.Num) 19 | from Logs l1, Logs l2, Logs l3 20 | where 21 | l1.Id + 1 = l2.Id and l1.Num = l2.Num and 22 | l2.Id + 1 = l3.Id and l2.Num = l3.Num 23 | -------------------------------------------------------------------------------- /mysql/customers-who-never-order.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Suppose that a website contains two tables, the Customers table and the Orders table. 3 | Write a SQL query to find all customers who never order anything. 4 | 5 | Table: Customers. 6 | 7 | +----+-------+ 8 | | Id | Name | 9 | +----+-------+ 10 | | 1 | Joe | 11 | | 2 | Henry | 12 | | 3 | Sam | 13 | | 4 | Max | 14 | +----+-------+ 15 | Table: Orders. 16 | 17 | +----+------------+ 18 | | Id | CustomerId | 19 | +----+------------+ 20 | | 1 | 3 | 21 | | 2 | 1 | 22 | +----+------------+ 23 | Using the above tables as example, return the following: 24 | 25 | +-----------+ 26 | | Customers | 27 | +-----------+ 28 | | Henry | 29 | | Max | 30 | +-----------+ 31 | */ 32 | 33 | select Name 34 | from Customers 35 | where id not in (select CustomerId from Orders) 36 | -------------------------------------------------------------------------------- /mysql/delete-duplicate-emails.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Write a SQL query to delete all duplicate email entries in a table named Person, 3 | keeping only unique emails based on its smallest Id. 4 | 5 | +----+------------------+ 6 | | Id | Email | 7 | +----+------------------+ 8 | | 1 | john@example.com | 9 | | 2 | bob@example.com | 10 | | 3 | john@example.com | 11 | +----+------------------+ 12 | Id is the primary key column for this table. 13 | For example, after running your query, the above Person table should have the following rows: 14 | 15 | +----+------------------+ 16 | | Id | Email | 17 | +----+------------------+ 18 | | 1 | john@example.com | 19 | | 2 | bob@example.com | 20 | +----+------------------+ 21 | */ 22 | 23 | delete p1 24 | from Person p1, Person p2 25 | where p1.Email = p2.Email and 26 | p1.Id > p2.Id 27 | -------------------------------------------------------------------------------- /mysql/department-highest-salary.sql: -------------------------------------------------------------------------------- 1 | /* 2 | The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id. 3 | 4 | +----+-------+--------+--------------+ 5 | | Id | Name | Salary | DepartmentId | 6 | +----+-------+--------+--------------+ 7 | | 1 | Joe | 70000 | 1 | 8 | | 2 | Henry | 80000 | 2 | 9 | | 3 | Sam | 60000 | 2 | 10 | | 4 | Max | 90000 | 1 | 11 | +----+-------+--------+--------------+ 12 | The Department table holds all departments of the company. 13 | 14 | +----+----------+ 15 | | Id | Name | 16 | +----+----------+ 17 | | 1 | IT | 18 | | 2 | Sales | 19 | +----+----------+ 20 | Write a SQL query to find employees who have the highest salary in each of the departments. 21 | For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department. 22 | 23 | +------------+----------+--------+ 24 | | Department | Employee | Salary | 25 | +------------+----------+--------+ 26 | | IT | Max | 90000 | 27 | | Sales | Henry | 80000 | 28 | +------------+----------+--------+ 29 | */ 30 | 31 | select d.Name Department, e.Name Employee, e.Salary Salary 32 | from Employee e, Department d 33 | where 34 | e.DepartmentId = d.Id and 35 | (e.DepartmentId, e.Salary) in 36 | (select ee.DepartmentId, max(ee.Salary) 37 | from Employee ee 38 | group by ee.DepartmentId) 39 | -------------------------------------------------------------------------------- /mysql/department-top-three-salaries.sql: -------------------------------------------------------------------------------- 1 | /* 2 | The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id. 3 | 4 | +----+-------+--------+--------------+ 5 | | Id | Name | Salary | DepartmentId | 6 | +----+-------+--------+--------------+ 7 | | 1 | Joe | 70000 | 1 | 8 | | 2 | Henry | 80000 | 2 | 9 | | 3 | Sam | 60000 | 2 | 10 | | 4 | Max | 90000 | 1 | 11 | | 5 | Janet | 69000 | 1 | 12 | | 6 | Randy | 85000 | 1 | 13 | +----+-------+--------+--------------+ 14 | The Department table holds all departments of the company. 15 | 16 | +----+----------+ 17 | | Id | Name | 18 | +----+----------+ 19 | | 1 | IT | 20 | | 2 | Sales | 21 | +----+----------+ 22 | Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows. 23 | 24 | +------------+----------+--------+ 25 | | Department | Employee | Salary | 26 | +------------+----------+--------+ 27 | | IT | Max | 90000 | 28 | | IT | Randy | 85000 | 29 | | IT | Joe | 70000 | 30 | | Sales | Henry | 80000 | 31 | | Sales | Sam | 60000 | 32 | +------------+----------+--------+ 33 | */ 34 | 35 | select d.Name Department, e.Name Employee, e.Salary Salary 36 | from Employee e 37 | inner join Department d 38 | on e.DepartmentId = d.id 39 | where 40 | (select count(distinct(Salary)) from Employee 41 | where DepartmentId = e.DepartmentId and Salary > e.Salary) < 3 /* 少于3个比当前的条目薪水高 */ 42 | order by e.DepartmentId, e.Salary desc; 43 | -------------------------------------------------------------------------------- /mysql/duplicate-emails.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Write a SQL query to find all duplicate emails in a table named Person. 3 | 4 | +----+---------+ 5 | | Id | Email | 6 | +----+---------+ 7 | | 1 | a@b.com | 8 | | 2 | c@d.com | 9 | | 3 | a@b.com | 10 | +----+---------+ 11 | For example, your query should return the following for the above table: 12 | 13 | +---------+ 14 | | Email | 15 | +---------+ 16 | | a@b.com | 17 | +---------+ 18 | Note: All emails are in lowercase. 19 | */ 20 | 21 | select Email 22 | from Person 23 | group by Email 24 | having count(*) > 1 25 | -------------------------------------------------------------------------------- /mysql/employees-earning-more-than-their-managers.sql: -------------------------------------------------------------------------------- 1 | /* 2 | The Employee table holds all employees including their managers. 3 | Every employee has an Id, and there is also a column for the manager Id. 4 | 5 | +----+-------+--------+-----------+ 6 | | Id | Name | Salary | ManagerId | 7 | +----+-------+--------+-----------+ 8 | | 1 | Joe | 70000 | 3 | 9 | | 2 | Henry | 80000 | 4 | 10 | | 3 | Sam | 60000 | NULL | 11 | | 4 | Max | 90000 | NULL | 12 | +----+-------+--------+-----------+ 13 | Given the Employee table, write a SQL query that finds out employees who earn more than their managers. 14 | For the above table, Joe is the only employee who earns more than his manager. 15 | 16 | +----------+ 17 | | Employee | 18 | +----------+ 19 | | Joe | 20 | +----------+ 21 | */ 22 | 23 | select e1.Name from Employee e1, Employee e2 24 | where e1.ManagerId = e2.Id and e1.Salary > e2.Salary 25 | -------------------------------------------------------------------------------- /mysql/not-boring-movies.sql: -------------------------------------------------------------------------------- 1 | /* 2 | X city opened a new cinema, many people would like to go to this cinema. 3 | The cinema also gives out a poster indicating the movies’ ratings and descriptions. 4 | 5 | Please write a SQL query to output movies with an odd numbered ID and a description that is not 'boring'. 6 | Order the result by rating. 7 | 8 | For example, table cinema: 9 | 10 | +---------+-----------+--------------+-----------+ 11 | | id | movie | description | rating | 12 | +---------+-----------+--------------+-----------+ 13 | | 1 | War | great 3D | 8.9 | 14 | | 2 | Science | fiction | 8.5 | 15 | | 3 | irish | boring | 6.2 | 16 | | 4 | Ice song | Fantacy | 8.6 | 17 | | 5 | House card| Interesting| 9.1 | 18 | +---------+-----------+--------------+-----------+ 19 | For the example above, the output should be: 20 | +---------+-----------+--------------+-----------+ 21 | | id | movie | description | rating | 22 | +---------+-----------+--------------+-----------+ 23 | | 5 | House card| Interesting| 9.1 | 24 | | 1 | War | great 3D | 8.9 | 25 | +---------+-----------+--------------+-----------+ 26 | */ 27 | 28 | select * 29 | from cinema 30 | where mod(id, 2) = 1 and description != 'boring' 31 | order by rating desc; 32 | -------------------------------------------------------------------------------- /mysql/rank-scores.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Write a SQL query to rank scores. If there is a tie between two scores, 3 | both should have the same ranking. Note that after a tie, 4 | the next ranking number should be the next consecutive integer value. 5 | In other words, there should be no "holes" between ranks. 6 | 7 | +----+-------+ 8 | | Id | Score | 9 | +----+-------+ 10 | | 1 | 3.50 | 11 | | 2 | 3.65 | 12 | | 3 | 4.00 | 13 | | 4 | 3.85 | 14 | | 5 | 4.00 | 15 | | 6 | 3.65 | 16 | +----+-------+ 17 | For example, given the above Scores table, your query should generate the following report (order by highest score): 18 | 19 | +-------+------+ 20 | | Score | Rank | 21 | +-------+------+ 22 | | 4.00 | 1 | 23 | | 4.00 | 1 | 24 | | 3.85 | 2 | 25 | | 3.65 | 3 | 26 | | 3.65 | 3 | 27 | | 3.50 | 4 | 28 | +-------+------+ 29 | */ 30 | 31 | -- 排名为 比自己大的分数种数 + 1 32 | select 33 | t1.Score, 34 | (select count(distinct(Score)) from Scores t2 where t2.Score > t1.Score) + 1 35 | from Scores t1 36 | order by Score desc 37 | -------------------------------------------------------------------------------- /mysql/rising-temperature.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Given a Weather table, 3 | write a SQL query to find all dates' Ids with higher temperature compared to its previous (yesterday's) dates. 4 | 5 | +---------+------------+------------------+ 6 | | Id(INT) | Date(DATE) | Temperature(INT) | 7 | +---------+------------+------------------+ 8 | | 1 | 2015-01-01 | 10 | 9 | | 2 | 2015-01-02 | 25 | 10 | | 3 | 2015-01-03 | 20 | 11 | | 4 | 2015-01-04 | 30 | 12 | +---------+------------+------------------+ 13 | For example, return the following Ids for the above Weather table: 14 | +----+ 15 | | Id | 16 | +----+ 17 | | 2 | 18 | | 4 | 19 | +----+ 20 | */ 21 | 22 | select w1.id 23 | from Weather w1 24 | where w1.Temperature > (select Temperature from Weather where (TO_DAYS(Date) + 1)=TO_DAYS(w1.Date)) 25 | -------------------------------------------------------------------------------- /mysql/second-highest-salary.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Write a SQL query to get the second highest salary from the Employee table. 3 | 4 | +----+--------+ 5 | | Id | Salary | 6 | +----+--------+ 7 | | 1 | 100 | 8 | | 2 | 200 | 9 | | 3 | 300 | 10 | +----+--------+ 11 | For example, given the above Employee table, the second highest salary is 200. 12 | If there is no second highest salary, then the query should return null. 13 | */ 14 | 15 | select max(Salary) from Employee 16 | where Salary not in (select max(salary) from Employee) 17 | -------------------------------------------------------------------------------- /mysql/swap-salary.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values 3 | (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table. 4 | 5 | For example: 6 | | id | name | sex | salary | 7 | |----|------|-----|--------| 8 | | 1 | A | m | 2500 | 9 | | 2 | B | f | 1500 | 10 | | 3 | C | m | 5500 | 11 | | 4 | D | f | 500 | 12 | After running your query, the above salary table should have the following rows: 13 | | id | name | sex | salary | 14 | |----|------|-----|--------| 15 | | 1 | A | f | 2500 | 16 | | 2 | B | m | 1500 | 17 | | 3 | C | f | 5500 | 18 | | 4 | D | m | 500 | 19 | */ 20 | 21 | update salary 22 | set sex = case sex when 'm' then 'f' else 'm' end; 23 | -------------------------------------------------------------------------------- /python/Fizz_Buzz.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that outputs the string representation of numbers from 1 to n. 3 | 4 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. 5 | For numbers which are multiples of both three and five output “FizzBuzz”. 6 | 7 | Example: 8 | 9 | n = 15, 10 | 11 | Return: 12 | [ 13 | "1", 14 | "2", 15 | "Fizz", 16 | "4", 17 | "Buzz", 18 | "Fizz", 19 | "7", 20 | "8", 21 | "Fizz", 22 | "Buzz", 23 | "11", 24 | "Fizz", 25 | "13", 26 | "14", 27 | "FizzBuzz" 28 | ] 29 | """ 30 | 31 | class Solution(object): 32 | def fizzBuzz(self, n): 33 | """ 34 | :type n: int 35 | :rtype: List[str] 36 | """ 37 | result = [] 38 | for i in xrange(1, n+1): 39 | if i % (3*5) == 0: 40 | result.append("FizzBuzz") 41 | elif i % 3 == 0: 42 | result.append("Fizz") 43 | elif i % 5 == 0: 44 | result.append("Buzz") 45 | else: 46 | result.append(str(i)) 47 | return result 48 | 49 | def fizzBuzz2(self, n): 50 | return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in xrange(1, n+1)] 51 | -------------------------------------------------------------------------------- /python/Nim_Game.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, 3 | each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. 4 | You will take the first turn to remove the stones. 5 | 6 | Both of you are very clever and have optimal strategies for the game. 7 | Write a function to determine whether you can win the game given the number of stones in the heap. 8 | 9 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, 10 | the last stone will always be removed by your friend. 11 | """ 12 | 13 | class Solution(object): 14 | def canWinNim(self, n): 15 | """ 16 | :type n: int 17 | :rtype: bool 18 | """ 19 | return n % 4 != 0 -------------------------------------------------------------------------------- /python/Reverse_String.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes a string as input and returns the string reversed. 3 | 4 | Example: 5 | Given s = "hello", return "olleh". 6 | """ 7 | 8 | class Solution(object): 9 | def reverseString(self, s): 10 | """ 11 | :type s: str 12 | :rtype: str 13 | """ 14 | return s[::-1] 15 | 16 | def reverseString2(self, s): 17 | """ 18 | :type s: str 19 | :rtype: str 20 | """ 21 | str = list(s) 22 | left, right = 0, len(str) - 1 23 | while left < right: 24 | str[left], str[right] = str[right], str[left] 25 | left += 1 26 | right -= 1 27 | return "".join(str) -------------------------------------------------------------------------------- /python/Single_Number.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, every element appears twice except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. 6 | Could you implement it without using extra memory? 7 | """ 8 | 9 | class Solution(object): 10 | def singleNumber(self, nums): 11 | """ 12 | :type nums: List[int] 13 | :rtype: int 14 | """ 15 | result = 0 16 | for i in nums: 17 | result ^= i 18 | return result 19 | 20 | def singleNumber2(self, A): 21 | return reduce(operator.xor, A) -------------------------------------------------------------------------------- /shell/Tenth_Line.sh: -------------------------------------------------------------------------------- 1 | ################################################################################### 2 | #How would you print just the 10th line of a file? 3 | # 4 | #For example, assume that file.txt has the following content: 5 | # 6 | #Line 1 7 | #Line 2 8 | #Line 3 9 | #Line 4 10 | #Line 5 11 | #Line 6 12 | #Line 7 13 | #Line 8 14 | #Line 9 15 | #Line 10 16 | #Your script should output the tenth line, which is: 17 | #Line 10 18 | ################################################################################## 19 | 20 | #!/bin/bash 21 | 22 | sed -n '10p' file.txt 23 | -------------------------------------------------------------------------------- /shell/Transpose_File.sh: -------------------------------------------------------------------------------- 1 | ################################################################################################################ 2 | # Given a text file file.txt, transpose its content. 3 | # 4 | # You may assume that each row has the same number of columns and each field is separated by the ' ' character. 5 | # 6 | # For example, if file.txt has the following content: 7 | # 8 | # name age 9 | # alice 21 10 | # ryan 30 11 | # Output the following: 12 | # 13 | # name alice ryan 14 | # age 21 30 15 | ################################################################################################################ 16 | 17 | #!/bin/bash 18 | 19 | awk ' 20 | { 21 | for(i = 1; i <= NF; i++) 22 | { 23 | if (NR == 1) 24 | { 25 | result[i] = $i; 26 | } 27 | else 28 | { 29 | result[i] = result[i] " " $i 30 | } 31 | } 32 | } 33 | END{ 34 | for (i = 1; i <= NF; i++) 35 | { 36 | print result[i]; 37 | } 38 | } 39 | ' file.txt 40 | -------------------------------------------------------------------------------- /shell/Valid_Phone_Numbers.sh: -------------------------------------------------------------------------------- 1 | ####################################################################################### 2 | #Given a text file file.txt that contains list of phone numbers (one per line), 3 | #write a one liner bash script to print all valid phone numbers. 4 | # 5 | #You may assume that a valid phone number must appear in one of the following two formats: 6 | # (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit) 7 | # 8 | #You may also assume each line in the text file must not contain leading or trailing white spaces. 9 | # 10 | #For example, assume that file.txt has the following content: 11 | # 12 | #987-123-4567 13 | #123 456 7890 14 | #(123) 456-7890 15 | #Your script should output the following valid phone numbers: 16 | #987-123-4567 17 | #(123) 456-7890 18 | ####################################################################################### 19 | #!/bin/bash 20 | 21 | grep -E '^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$' file.txt 22 | -------------------------------------------------------------------------------- /shell/Word_Frequency.sh: -------------------------------------------------------------------------------- 1 | ################################################################################################ 2 | # Write a bash script to calculate the frequency of each word in a text file words.txt. 3 | # 4 | # For simplicity sake, you may assume: 5 | # 6 | # words.txt contains only lowercase characters and space ' ' characters. 7 | # Each word must consist of lowercase characters only. 8 | # Words are separated by one or more whitespace characters. 9 | # For example, assume that words.txt has the following content: 10 | # 11 | # the day is sunny the the 12 | # the sunny is is 13 | # Your script should output the following, sorted by descending frequency: 14 | # the 4 15 | # is 3 16 | # sunny 2 17 | # day 1 18 | # Note: 19 | # Don't worry about handling ties, it is guaranteed that each word's frequency count is unique. 20 | ################################################################################################ 21 | 22 | #!/bin/bash 23 | 24 | cat words.txt | tr -s ' ' '\n' | tr '[:upper:]' '[:lower:]'| sort |uniq -c | sort -nr | awk '{ print $2,$1}' 25 | --------------------------------------------------------------------------------