├── Algorithms ├── Plus One │ ├── README.md │ └── plus-one.js ├── Pascal's Triangle │ ├── README.md │ └── pascals-triangle.js ├── Valid Parentheses │ ├── README.md │ └── valid-parentheses.js ├── H-Index II │ ├── README.md │ └── h-index-ii.js ├── H-Index │ ├── README.md │ └── h-index.js ├── Binary Tree Paths │ └── README.md ├── Count and Say │ └── README.md ├── Game of Life │ └── README.md ├── Invert Binary Tree │ ├── README.md │ └── invert-binary-tree.js ├── Length of Last Word │ ├── README.md │ └── length-of-last-word.js ├── Unique Paths │ ├── README.md │ └── unique-paths.js ├── ZigZag Conversion │ └── README.md ├── Sort Colors │ ├── README.md │ └── sort-colors.js ├── Valid Anagram │ ├── README.md │ └── valid-anagram.js ├── Bulls and Cows │ └── README.md ├── Implement strStr() │ ├── README.md │ └── implement-strstr.js ├── Kth Largest Element in an Array │ ├── README.md │ └── kth-largest-element-in-an-array.js ├── Happy Number │ ├── README.md │ └── happy-number.js ├── Move Zeroes │ ├── README.md │ └── move-zeroes.js ├── Rectangle Area │ ├── README.md │ ├── index_best_solution.js │ └── index.js ├── Power of Two │ ├── README.md │ └── power-of-two.js ├── Additive Number │ └── README.md ├── Implement Stack using Queues │ ├── README.md │ └── implement-stack-using-queues.js ├── Isomorphic Strings │ ├── README.md │ └── isomorphic-strings.js ├── Power of Three │ ├── README.md │ └── power-of-three.js ├── Range Sum Query 2D - Immutable │ └── README.md ├── Reverse String │ ├── README.md │ └── reverse-string.js ├── Set Matrix Zeroes │ ├── README.md │ └── set-matrix-zeroes.js ├── Summary Ranges │ ├── README.md │ └── summary-ranges.js ├── Find Peak Element │ ├── README.md │ └── find-peak-element.js ├── Longest Common Prefix │ ├── README.md │ └── longest-common-prefix.js ├── Palindrome Number │ ├── README.md │ └── palindrome-number.js ├── Remove Element │ ├── README.md │ └── remove-element.js ├── Ugly Number │ ├── README.md │ └── ugly-number.js ├── Excel Sheet Column Title │ ├── README.md │ └── excel-sheet-column-title.js ├── Palindrome Partitioning │ └── README.md ├── Add Digits │ ├── README.md │ └── add-digits.js ├── Remove Linked List Elements │ ├── README.md │ └── remove-linked-list-elements.js ├── First Missing Positive │ ├── README.md │ └── first-missing-positive.js ├── Flatten Binary Tree to Linked List │ └── README.md ├── Sqrt(x) │ ├── README.md │ └── sqrtx.js ├── Predict the Winner │ └── README.md ├── Search Insert Position │ ├── README.md │ └── search-insert-position.js ├── Implement Queue using Stacks │ ├── README.md │ └── implement-queue-using-stacks.js ├── Missing Number │ ├── README.md │ └── missing-number.js ├── Pascal's Triangle II │ ├── README.md │ └── pascals-triangle-ii.js ├── Letter Combinations of a Phone Number │ ├── README.md │ └── letter-combinations-of-a-phone-number.js ├── Regular Expression Matching │ ├── README.md │ └── regular-expression-matching.js ├── Number of Islands │ └── README.md ├── Count Primes │ ├── README.md │ └── count-primes.js ├── Merge Sorted Array │ ├── README.md │ └── merge-sorted-array.js ├── Palindrome Partitioning II │ └── README.md ├── Partition List │ └── README.md ├── Word Pattern │ ├── README.md │ └── word-pattern.js ├── Reverse Words in a String │ ├── README.md │ └── reverse-words-in-a-string.js ├── Sort List │ ├── README.md │ └── sort-list.js ├── Search a 2D Matrix II │ ├── README.md │ └── search-a-2d-matrix-ii.js ├── Valid Palindrome │ ├── README.md │ └── valid-palindrome.js ├── Merge Two Sorted Lists │ ├── README.md │ └── merge-two-sorted-lists.js ├── Search for a Range │ ├── README.md │ └── search-for-a-range.js ├── Unique Paths II │ ├── README.md │ └── unique-paths-ii.js ├── Find the Duplicate Number │ ├── README.md │ └── find-the-duplicate-number.js ├── Add Binary │ ├── README.md │ └── add-binary.js ├── Palindrome Linked List │ ├── README.md │ └── palindrome-linked-list.js ├── LRU Cache │ └── README.md ├── Rotate Array │ ├── README.md │ └── rotate-array.js ├── Find Median from Data Stream │ └── README.md ├── Reverse Vowels of a String │ ├── README.md │ └── reverse-vowels-of-a-string.js ├── Best Time to Buy and Sell Stock │ ├── README.md │ └── best-time-to-buy-and-sell-stock.js ├── Fraction to Recurring Decimal │ └── README.md ├── Ugly Number II │ ├── README.md │ └── ugly-number-ii.js ├── First Bad Version │ └── README.md ├── Remove Duplicates from Sorted Array │ ├── README.md │ └── remove-duplicates-from-sorted-array.js ├── Majority Element │ ├── README.md │ └── majority-element.js ├── Rotate List │ ├── README.md │ └── rotate-list.js ├── Swap Nodes in Pairs │ └── README.md ├── Range Sum Query - Immutable │ └── README.md ├── Longest Substring with At Least K Repeating Characters │ ├── not-a-good-solution.js │ └── better-solution.js ├── Shortest Palindrome │ └── README.md ├── Nim Game │ ├── README.md │ └── nim-game.js ├── Remove Duplicates from Sorted Array II │ ├── README.md │ └── remove-duplicates-from-sorted-array-ii.js ├── Add and Search Word - Data structure design │ └── README.md ├── Excel Sheet Column Number │ ├── README.md │ └── excel-sheet-column-number.js ├── Valid Number │ ├── README.md │ └── valid-number.js ├── Maximum Gap │ ├── README.md │ └── maximum-gap.js ├── Climbing Stairs │ ├── README.md │ └── climbing-stairs.js ├── Compare Version Numbers │ ├── README.md │ └── compare-version-numbers.js ├── Linked List Cycle │ ├── README.md │ └── linked-list-cycle.js ├── Super Ugly Number │ └── README.md ├── Divide Two Integers │ ├── README.md │ └── divide-two-integers.js ├── Power of Four │ ├── README.md │ └── power-of-four.js ├── Repeated DNA Sequences │ ├── README.md │ └── repeated-dna-sequences.js ├── Reverse Integer │ ├── README.md │ └── reverse-integer.js ├── Delete Node in a Linked List │ ├── README.md │ └── delete-node-in-a-linked-list.js ├── Gray Code │ ├── indexⅡ.js │ └── indexⅠ.js ├── Pow(x, n) │ └── powx-n.js ├── Top K Frequent Elements │ ├── README.md │ └── top-k-frequent-elements.js ├── Patching Array │ ├── README.md │ └── patching-array.js ├── Bulb Switcher │ ├── README.md │ └── bulb-switcher.js ├── Flatten Nested List Iterator │ └── README.md ├── Range Sum Query - Mutable │ └── README.md ├── Remove Nth Node From End of List │ ├── README.md │ └── remove-nth-node-from-end-of-list.js ├── Two Sum │ ├── README.md │ └── two-sum.js ├── Arranging Coins │ └── arranging-coins.js ├── Detect Capital │ └── detect-capital.js ├── Find Minimum in Rotated Sorted Array │ └── find-minimum-in-rotated-sorted-array.js ├── Find Minimum in Rotated Sorted Array II │ └── find-minimum-in-rotated-sorted-array-ii.js ├── House Robber III │ └── README.md ├── Longest Palindromic Substring │ └── README.md ├── Single Number │ └── single-number.js ├── Number of 1 Bits │ └── number-of-1-bits.js ├── Reverse Words in a String III │ ├── reverse-words-in-a-string-iii.js │ └── reverse-words-in-a-string-iii.py ├── Factorial Trailing Zeroes │ ├── README.md │ └── factorial-trailing-zeroes.js ├── Hamming Distance │ └── hamming-distance.js ├── Construct the Rectangle │ └── construct-the-rectangle.js ├── Reverse Bits │ ├── README.md │ └── reverse-bits.js ├── Search in Rotated Sorted Array II │ └── search-in-rotated-sorted-array-ii.js ├── Number Complement │ └── number-complement.js ├── Number of Segments in a String │ └── number-of-segments-in-a-string.js ├── Contains Duplicate │ └── contains-duplicate.js ├── Jump Game │ └── jump-game.js ├── Search in Rotated Sorted Array │ └── search-in-rotated-sorted-array.js ├── Find the Difference │ └── find-the-difference.js ├── Search a 2D Matrix │ └── search-a-2d-matrix.js ├── First Unique Character in a String │ └── first-unique-character-in-a-string.js ├── Sum of Square Numbers │ ├── sum-of-square-numbers.js │ └── sum-of-square-numbers.py ├── Best Time to Buy and Sell Stock with Cooldown │ └── README.md ├── Integer Break │ ├── README.md │ └── integer-break.js ├── Is Subsequence │ └── is-subsequence.js ├── Maximum Subarray │ └── maximum-subarray.js ├── Sum of Two Integers │ └── sum-of-two-integers.js ├── Distribute Candies │ ├── distribute-candies.js │ └── distribute-candies.py ├── Increasing Triplet Subsequence │ └── README.md ├── Largest Number │ ├── largest-number.js │ └── README.md ├── Single Number II │ └── single-number-ii.js ├── Valid Word Abbreviation │ └── valid-word-abbreviation.js ├── Base 7 │ └── base-7.js ├── Fizz Buzz │ └── fizz-buzz.js ├── Max Consecutive Ones │ └── max-consecutive-ones.js ├── Unique Binary Search Trees │ └── unique-binary-search-trees.js ├── N-Queens II │ └── n-queens-ii.js ├── Contains Duplicate III │ └── contains-duplicate-iii.js ├── Counting Bits │ ├── README.md │ └── counting-bits.js ├── Number of Digit One │ └── number-of-digit-one.js ├── Perfect Squares │ ├── perfect-squares.js │ └── README.md ├── Valid Perfect Square │ └── valid-perfect-square.js ├── Group Anagrams │ └── anagrams.js ├── Longest Uncommon Subsequence I │ └── longest-uncommon-subsequence-i.py ├── Single Number III │ └── single-number-iii.js ├── Binary Tree Inorder Traversal │ └── binary-tree-inorder-traversal.js ├── Minimum Moves to Equal Array Elements II │ └── minimum-moves-to-equal-array-elements-ii.js ├── Container With Most Water │ └── O(n).js ├── Perfect Number │ └── perfect-number.py ├── Queue Reconstruction by Height │ └── queue-reconstruction-by-height.js ├── Longest Increasing Subsequence │ └── README.md ├── Median of Two Sorted Arrays │ ├── O(nlogn).js │ └── O(n).js ├── Complex Number Multiplication │ └── complex-number-multiplication.py ├── Lexicographical Numbers │ └── lexicographical-numbers.js ├── String to Integer (atoi) │ └── string-to-integer-atoi.js ├── Find All Duplicates in an Array │ └── find-all-duplicates-in-an-array.js ├── Reverse Linked List │ ├── indexⅢ.js │ ├── index.js │ └── indexⅡ.js ├── Magical String │ └── magical-string.js ├── Maximum Product Subarray │ └── maximum-product-subarray.js ├── Contains Duplicate II │ └── contains-duplicate-ii.js ├── Find All Numbers Disappeared in an Array │ └── find-all-numbers-disappeared-in-an-array.js ├── Longest Palindrome │ └── longest-palindrome.js ├── Two Sum II - Input array is sorted │ └── two-sum-ii-input-array-is-sorted.js ├── Rotate Function │ └── rotate-function.js ├── Rotate Image │ └── rotate-image.js ├── Kth Smallest Element in a Sorted Matrix │ └── kth-smallest-element-in-a-sorted-matrix.js ├── Minimum Moves to Equal Array Elements │ └── minimum-moves-to-equal-array-elements.js ├── Triangle │ └── triangle.js ├── Count of Smaller Numbers After Self │ └── README.md ├── Course Schedule │ └── README.md ├── Validate IP Address │ └── regexp_solution.js ├── House Robber │ └── house-robber.js ├── Intersection of Two Arrays │ └── intersection-of-two-arrays.js ├── Generate Parentheses │ └── generate-parentheses.js ├── Continuous Subarray Sum │ └── continuous-subarray-sum.py ├── Add Strings │ └── add-strings.js ├── Binary Tree Preorder Traversal │ └── binary-tree-preorder-traversal.js ├── Maximum XOR of Two Numbers in an Array │ ├── README.md │ └── maximum-xor-of-two-numbers-in-an-array.js ├── Arithmetic Slices │ └── arithmetic-slices.js ├── Combination Sum IV │ └── combination-sum-iv.js ├── Majority Element II │ └── majority-element-ii.js ├── Minimum Size Subarray Sum │ └── minimum-size-subarray-sum.js ├── Beautiful Arrangement │ └── beautiful-arrangement.js ├── Best Time to Buy and Sell Stock II │ ├── best-time-to-buy-and-sell-stock-ii.js │ └── dp_solution.js ├── Binary Tree Postorder Traversal │ └── binary-tree-postorder-traversal.js ├── Reverse String II │ └── reverse-string-ii.py ├── Subsets │ └── subsets.js ├── Coin Change │ ├── README.md │ └── coin-change.js ├── Daily Temperatures │ ├── daily-temperatures.js │ └── daily-temperatures.py ├── Maximum Depth of Binary Tree │ └── maximum-depth-of-binary-tree.js ├── Teemo Attacking │ └── teemo-attacking.js ├── Binary Tree Tilt │ ├── binary-tree-tilt.js │ └── binary-tree-tilt.py ├── Longest Consecutive Sequence │ └── longest-consecutive-sequence.js ├── Nth Digit │ └── nth-digit.js ├── Random Pick Index │ └── random-pick-index.py ├── License Key Formatting │ └── license-key-formatting.js ├── Symmetric Tree │ └── clever-recursion-solution.js ├── Find Bottom Left Tree Value │ └── find-bottom-left-tree-value.js ├── Friend Circles │ └── friend-circles.py ├── Minimum Time Difference │ └── minimum-time-difference.js ├── Repeated Substring Pattern │ └── repeated-substring-pattern.js ├── Roman to Integer │ └── roman-to-integer.js ├── Same Tree │ └── index.js ├── Sort Characters By Frequency │ └── sort-characters-by-frequency.js ├── Count Numbers with Unique Digits │ └── count-numbers-with-unique-digits.js ├── Keyboard Row │ └── keyboard-row.js ├── Matchsticks to Square │ └── README.md ├── Balanced Binary Tree │ └── balanced-binary-tree.js ├── Convert a Number to Hexadecimal │ └── convert-a-number-to-hexadecimal.js ├── Insertion Sort List │ └── insertion-sort-list.js ├── Product of Array Except Self │ └── product-of-array-except-self.js ├── Total Hamming Distance │ └── total-hamming-distance.js ├── Count Complete Tree Nodes │ └── better-recursion.js ├── Ransom Note │ └── ransom-note.js ├── Sum of Left Leaves │ └── sum-of-left-leaves.js ├── Lonely Pixel I │ └── lonely-pixel-i.py ├── Next Greater Element I │ └── next-greater-element-i.js ├── 4Sum II │ └── 4sum-ii.js ├── Linked List Cycle II │ └── linked-list-cycle-ii.js ├── Permutations │ └── permutations.js ├── Verify Preorder Serialization of a Binary Tree │ └── verify-preorder-serialization-of-a-binary-tree.js ├── Path Sum │ └── path-sum.js ├── Find Largest Value in Each Tree Row │ └── find-largest-value-in-each-tree-row.js ├── Guess Number Higher or Lower │ └── guess-number-higher-or-lower.cpp ├── Combination Sum III │ └── combination-sum-iii.js ├── Simplify Path │ └── simplify-path.js ├── Convert Sorted Array to Binary Search Tree │ └── convert-sorted-array-to-binary-search-tree.js ├── Degree of an Array │ └── degree-of-an-array.js ├── Minimum Path Sum │ └── minimum-path-sum.js ├── Populating Next Right Pointers in Each Node │ └── dfs-solution.js ├── Assign Cookies │ └── assign-cookies.js ├── Subsets II │ └── subsets-ii.js ├── Bitwise AND of Numbers Range │ └── bitwise-and-of-numbers-range.js ├── Maximal Square │ └── index_2.js ├── Merge k Sorted Lists │ └── merge-k-sorted-lists.js ├── Sum Root to Leaf Numbers │ └── sum-root-to-leaf-numbers.js ├── Combinations │ └── combinations.js ├── Decode Ways │ └── decode-ways.js ├── Intersection of Two Arrays II │ └── intersection-of-two-arrays-ii.js ├── Largest Rectangle in Histogram │ └── largest-rectangle-in-histogram.js ├── Convert BST to Greater Tree │ └── convert-bst-to-greater-tree.py ├── Different Ways to Add Parentheses │ └── divide-and-conquer.js ├── Target Sum │ └── better-solution.js ├── Lowest Common Ancestor of a Binary Tree │ └── better-solution.js ├── Minimum Depth of Binary Tree │ └── minimum-depth-of-binary-tree.js ├── Binary Tree Right Side View │ └── binary-tree-right-side-view.js ├── Longest Substring Without Repeating Characters │ └── longest-substring-without-repeating-characters.js ├── Number of Boomerangs │ └── number-of-boomerangs.js ├── Remove Duplicates from Sorted List │ └── remove-duplicates-from-sorted-list.js └── Binary Tree Level Order Traversal II │ └── binary-tree-level-order-traversal-ii.js ├── .gitignore ├── package.json └── CONTRIBUTING.md /Algorithms/Plus One/README.md: -------------------------------------------------------------------------------- 1 | It's simple. -------------------------------------------------------------------------------- /Algorithms/Pascal's Triangle/README.md: -------------------------------------------------------------------------------- 1 | Simple. -------------------------------------------------------------------------------- /Algorithms/Valid Parentheses/README.md: -------------------------------------------------------------------------------- 1 | Use stack. -------------------------------------------------------------------------------- /Algorithms/H-Index II/README.md: -------------------------------------------------------------------------------- 1 | Easy problem, see the code. -------------------------------------------------------------------------------- /Algorithms/H-Index/README.md: -------------------------------------------------------------------------------- 1 | Easy problem, see the code. -------------------------------------------------------------------------------- /Algorithms/Binary Tree Paths/README.md: -------------------------------------------------------------------------------- 1 | Use depth-first-search. -------------------------------------------------------------------------------- /Algorithms/Count and Say/README.md: -------------------------------------------------------------------------------- 1 | Simple simulation problem. -------------------------------------------------------------------------------- /Algorithms/Game of Life/README.md: -------------------------------------------------------------------------------- 1 | An easy Simulation Problem. -------------------------------------------------------------------------------- /Algorithms/Invert Binary Tree/README.md: -------------------------------------------------------------------------------- 1 | Simple with recursion. -------------------------------------------------------------------------------- /Algorithms/Length of Last Word/README.md: -------------------------------------------------------------------------------- 1 | It seems easy, be careful! -------------------------------------------------------------------------------- /Algorithms/Unique Paths/README.md: -------------------------------------------------------------------------------- 1 | Simple dynamic programming problem. -------------------------------------------------------------------------------- /Algorithms/ZigZag Conversion/README.md: -------------------------------------------------------------------------------- 1 | Simple simulation problem. -------------------------------------------------------------------------------- /Algorithms/Sort Colors/README.md: -------------------------------------------------------------------------------- 1 | I just use `sort` with one line code. -------------------------------------------------------------------------------- /Algorithms/Valid Anagram/README.md: -------------------------------------------------------------------------------- 1 | Use `split` and `sort`, easy solution. -------------------------------------------------------------------------------- /Algorithms/Bulls and Cows/README.md: -------------------------------------------------------------------------------- 1 | An easy problem, just don't be careless! -------------------------------------------------------------------------------- /Algorithms/Implement strStr()/README.md: -------------------------------------------------------------------------------- 1 | Use `search` function, nothing else. -------------------------------------------------------------------------------- /Algorithms/Kth Largest Element in an Array/README.md: -------------------------------------------------------------------------------- 1 | Think less, use `sort` ... -------------------------------------------------------------------------------- /Algorithms/Happy Number/README.md: -------------------------------------------------------------------------------- 1 | Easy problem, do what the problem asks you to do. -------------------------------------------------------------------------------- /Algorithms/Move Zeroes/README.md: -------------------------------------------------------------------------------- 1 | Use `splice` and `push`, it's easy in JavaScript! -------------------------------------------------------------------------------- /Algorithms/Rectangle Area/README.md: -------------------------------------------------------------------------------- 1 | The only thing you should do is to be careful! -------------------------------------------------------------------------------- /Algorithms/Power of Two/README.md: -------------------------------------------------------------------------------- 1 | Use `Math.log()`, and you need a little math knowledge. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | template.js 3 | template.py 4 | .DS_Store 5 | generate.js 6 | -------------------------------------------------------------------------------- /Algorithms/Additive Number/README.md: -------------------------------------------------------------------------------- 1 | Use Depth-First-Search Algorithm, do whatever you love. -------------------------------------------------------------------------------- /Algorithms/Implement Stack using Queues/README.md: -------------------------------------------------------------------------------- 1 | Some basic operations of JavaScript Array. -------------------------------------------------------------------------------- /Algorithms/Isomorphic Strings/README.md: -------------------------------------------------------------------------------- 1 | Be careful, think it over, you can solve it smoothly! -------------------------------------------------------------------------------- /Algorithms/Power of Three/README.md: -------------------------------------------------------------------------------- 1 | Use `Math.log`, don't forget to consider the **accuracy**. -------------------------------------------------------------------------------- /Algorithms/Range Sum Query 2D - Immutable/README.md: -------------------------------------------------------------------------------- 1 | An easy `dynamic programming` problem. -------------------------------------------------------------------------------- /Algorithms/Reverse String/README.md: -------------------------------------------------------------------------------- 1 | Use `split` and `join` in JavaScript Array, it's simple! -------------------------------------------------------------------------------- /Algorithms/Set Matrix Zeroes/README.md: -------------------------------------------------------------------------------- 1 | First check, then set, with the complexity of O(n*m). -------------------------------------------------------------------------------- /Algorithms/Summary Ranges/README.md: -------------------------------------------------------------------------------- 1 | The only thing to do is to be careful! You can solve it! -------------------------------------------------------------------------------- /Algorithms/Find Peak Element/README.md: -------------------------------------------------------------------------------- 1 | Simple problem, use `for` to enum every element, and judge. -------------------------------------------------------------------------------- /Algorithms/Longest Common Prefix/README.md: -------------------------------------------------------------------------------- 1 | Use `Array.reduce` and `Array.every` to make it easier. -------------------------------------------------------------------------------- /Algorithms/Palindrome Number/README.md: -------------------------------------------------------------------------------- 1 | Use `toString`, `split`, `reverse` and `join`, it's easy. -------------------------------------------------------------------------------- /Algorithms/Remove Element/README.md: -------------------------------------------------------------------------------- 1 | Use `splice` in JavaScript when deleting an item from an array. -------------------------------------------------------------------------------- /Algorithms/Ugly Number/README.md: -------------------------------------------------------------------------------- 1 | Such an easy problem, don't forget the condition when `num === 0`. -------------------------------------------------------------------------------- /Algorithms/Excel Sheet Column Title/README.md: -------------------------------------------------------------------------------- 1 | Try to know the conversion rules, and it will be easy. -------------------------------------------------------------------------------- /Algorithms/Palindrome Partitioning/README.md: -------------------------------------------------------------------------------- 1 | You should know something about the algorithm **Manacher**. -------------------------------------------------------------------------------- /Algorithms/Add Digits/README.md: -------------------------------------------------------------------------------- 1 | I solve it by loop/recursion, but it seems that there is a rule about it. -------------------------------------------------------------------------------- /Algorithms/Remove Linked List Elements/README.md: -------------------------------------------------------------------------------- 1 | I do it in the most stupid way, cut the list into nodes. -------------------------------------------------------------------------------- /Algorithms/First Missing Positive/README.md: -------------------------------------------------------------------------------- 1 | I think my solution is not the one the problem provider appreciates. -------------------------------------------------------------------------------- /Algorithms/Flatten Binary Tree to Linked List/README.md: -------------------------------------------------------------------------------- 1 | Just do a preorder traversal, you will get the answer. -------------------------------------------------------------------------------- /Algorithms/Sqrt(x)/README.md: -------------------------------------------------------------------------------- 1 | I just use `Math.sqrt` for convenience, it's better to use binary search obviously. -------------------------------------------------------------------------------- /Algorithms/Predict the Winner/README.md: -------------------------------------------------------------------------------- 1 | It seems to be a nim game, but it's a dynamic programming problem instead! 2 | -------------------------------------------------------------------------------- /Algorithms/Search Insert Position/README.md: -------------------------------------------------------------------------------- 1 | The best solution is using **binary search** obviously, I am sorry I don't. -------------------------------------------------------------------------------- /Algorithms/Implement Queue using Stacks/README.md: -------------------------------------------------------------------------------- 1 | Use `push` and `shift` in JavaScript, really enjoy JavaScript functions! -------------------------------------------------------------------------------- /Algorithms/Missing Number/README.md: -------------------------------------------------------------------------------- 1 | Could you implement it using only constant extra space complexity? Sorry, I didn't ... -------------------------------------------------------------------------------- /Algorithms/Pascal's Triangle II/README.md: -------------------------------------------------------------------------------- 1 | Simple as [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/). -------------------------------------------------------------------------------- /Algorithms/Letter Combinations of a Phone Number/README.md: -------------------------------------------------------------------------------- 1 | It's easy to use **depth-first-search** to find all possible strings. -------------------------------------------------------------------------------- /Algorithms/Regular Expression Matching/README.md: -------------------------------------------------------------------------------- 1 | It is easy using JavaScript, just use raw regular expression, the basic usage. -------------------------------------------------------------------------------- /Algorithms/Number of Islands/README.md: -------------------------------------------------------------------------------- 1 | Use breadth first search. 2 | 3 | You cannot modify a string, so you should use a hash array. -------------------------------------------------------------------------------- /Algorithms/Count Primes/README.md: -------------------------------------------------------------------------------- 1 | Just see the **Hint** in the question. 2 | 3 | It's a common way to get primes within a certain range. -------------------------------------------------------------------------------- /Algorithms/Merge Sorted Array/README.md: -------------------------------------------------------------------------------- 1 | I just use `push` and `sort`, and the complexity is O((n+m)log(n+m)), you can solve it with O(n+m)! -------------------------------------------------------------------------------- /Algorithms/Palindrome Partitioning II/README.md: -------------------------------------------------------------------------------- 1 | You should know something about the algorithm **Manacher**, then do a dynamic programming. -------------------------------------------------------------------------------- /Algorithms/Partition List/README.md: -------------------------------------------------------------------------------- 1 | I just use the most stupid way, cut the list into nodes, do something, and make a new list from nodes. -------------------------------------------------------------------------------- /Algorithms/Word Pattern/README.md: -------------------------------------------------------------------------------- 1 | An easy problem, and be careful! You should think it over from two directions!(a to b, and also b to a) -------------------------------------------------------------------------------- /Algorithms/Reverse Words in a String/README.md: -------------------------------------------------------------------------------- 1 | Use regular expression, it's easy. 2 | 3 | Just remove the needless blanks, and make a reverse. -------------------------------------------------------------------------------- /Algorithms/Sort List/README.md: -------------------------------------------------------------------------------- 1 | > Sort a linked list in O(n log n) time using constant space complexity. 2 | 3 | I use O(n) space complexity.. -------------------------------------------------------------------------------- /Algorithms/Search a 2D Matrix II/README.md: -------------------------------------------------------------------------------- 1 | I use `O(n^2)` to solve it, there will be a better solution! 2 | 3 | Think it over using binary search. -------------------------------------------------------------------------------- /Algorithms/Valid Palindrome/README.md: -------------------------------------------------------------------------------- 1 | Firstly, remove irrelevant characters, then make a **toLowerCase** change, at last make a reverse and compare. -------------------------------------------------------------------------------- /Algorithms/Merge Two Sorted Lists/README.md: -------------------------------------------------------------------------------- 1 | Cut the list into nodes, do something, and make a new list, my normal way to deal with such kind of problems.. -------------------------------------------------------------------------------- /Algorithms/Search for a Range/README.md: -------------------------------------------------------------------------------- 1 | I just solve it with O(n) complexity, maybe you can try **binary search** to reduce the complexity to O(log n). -------------------------------------------------------------------------------- /Algorithms/Unique Paths II/README.md: -------------------------------------------------------------------------------- 1 | Similar to [Unique Paths](https://leetcode.com/problems/unique-paths/), one more judgement when doing `for` loop. -------------------------------------------------------------------------------- /Algorithms/Find the Duplicate Number/README.md: -------------------------------------------------------------------------------- 1 | I don't follow the requirement of this problem, that use only O(1) extra space. I use O(n), but still pass it. -------------------------------------------------------------------------------- /Algorithms/Add Binary/README.md: -------------------------------------------------------------------------------- 1 | It seems that the input data is so large that you cannot use `parseInt` & `toString`, so you should do it with the most stupid way.. -------------------------------------------------------------------------------- /Algorithms/Palindrome Linked List/README.md: -------------------------------------------------------------------------------- 1 | > **Follow up:** 2 | > 3 | > Could you do it in O(n) time and O(1) space? 4 | 5 | 6 | I didn't, I use O(n) space ... -------------------------------------------------------------------------------- /Algorithms/LRU Cache/README.md: -------------------------------------------------------------------------------- 1 | To save the `key-value` pairs, we use `object` in JavaScript, and to find the least recently used item, we use an array to hash the keys. -------------------------------------------------------------------------------- /Algorithms/Rotate Array/README.md: -------------------------------------------------------------------------------- 1 | It is a very simple problem, using some Array functions like `slice`, `splice` and `unshift`. Anyway, you can solve it in other ways. -------------------------------------------------------------------------------- /Algorithms/Find Median from Data Stream/README.md: -------------------------------------------------------------------------------- 1 | The difficulty is how to maintain a sorted array, in JavaScript it's quite easy by using `binary search` and `splice` function. -------------------------------------------------------------------------------- /Algorithms/Reverse Vowels of a String/README.md: -------------------------------------------------------------------------------- 1 | I just solve it with the most stupid way, step by step as the question tells us to do. Maybe it can be solved with regular expression. -------------------------------------------------------------------------------- /Algorithms/Best Time to Buy and Sell Stock/README.md: -------------------------------------------------------------------------------- 1 | Easy to find a O(n^2) solution, but you should do it with O(n), it's easy, maintain a variable that represents the lowest price that can buy. -------------------------------------------------------------------------------- /Algorithms/Fraction to Recurring Decimal/README.md: -------------------------------------------------------------------------------- 1 | The difficulty is how to find the loop, use an array to hash. 2 | 3 | Notice that both numerator and denominator can be negative. 4 | 5 | -------------------------------------------------------------------------------- /Algorithms/Ugly Number II/README.md: -------------------------------------------------------------------------------- 1 | An easy dynamic programming problem. 2 | 3 | `dp[i]` means the `ith` ugly number, and `dp[i]*2`, `dp[i]*3`, `dp[i]*5` are also ugly numbers.. think it over -------------------------------------------------------------------------------- /Algorithms/First Bad Version/README.md: -------------------------------------------------------------------------------- 1 | Easy `binary search` problem. 2 | 3 | Remember not to use `~~` and `>>1` because the number is so large, use `Math.floor()` or `Math.ceil()` and `/` instead. -------------------------------------------------------------------------------- /Algorithms/Remove Duplicates from Sorted Array/README.md: -------------------------------------------------------------------------------- 1 | Use `splice` to remove an item from an array. 2 | 3 | To this problem, you should enum items from `nums.length-1` to `0` to make it easier. -------------------------------------------------------------------------------- /Algorithms/Majority Element/README.md: -------------------------------------------------------------------------------- 1 | Use the array `hash` to calculate the time one element appears. For instance, `hash[i]` means the time `i` appears. And when `hash[i] > len / 2`, we can say that `i` is the answer. -------------------------------------------------------------------------------- /Algorithms/Rotate List/README.md: -------------------------------------------------------------------------------- 1 | I do it with the most stupid way, cut the list into some nodes, put them into an array, rearrange the array, at last make a new list .. 2 | 3 | You can solve it with a better solution! -------------------------------------------------------------------------------- /Algorithms/Swap Nodes in Pairs/README.md: -------------------------------------------------------------------------------- 1 | Simple question, just cut the list into some single nodes, and put them in an array, then rearrange the array as the problem asks, at last make a new list from the rearranged array. -------------------------------------------------------------------------------- /Algorithms/Range Sum Query - Immutable/README.md: -------------------------------------------------------------------------------- 1 | Define `sum[i]` as the sum from `index=0` to `index=i`, you can find the sum between `index=i` to `index=j` using `sum[j] - sum[i - 1]`. 2 | 3 | Take care of the boundary value ! -------------------------------------------------------------------------------- /Algorithms/Longest Substring with At Least K Repeating Characters/not-a-good-solution.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lessfish/leetcode/HEAD/Algorithms/Longest Substring with At Least K Repeating Characters/not-a-good-solution.js -------------------------------------------------------------------------------- /Algorithms/Shortest Palindrome/README.md: -------------------------------------------------------------------------------- 1 | If you are Chinese, I suggest you reading [this article](http://www.cnblogs.com/zichi/p/4753930.html) written by me. 2 | 3 | If you are not, I suggest you learning the algorithm named `Manacher`. -------------------------------------------------------------------------------- /Algorithms/Nim Game/README.md: -------------------------------------------------------------------------------- 1 | If the number(n) of the stones cannot be exactly divided by 4, then you will win. How? Firstly take the number of `n % 4`, then your friend takes `m`, you can take `4-m`, and the last will always be taken by you. -------------------------------------------------------------------------------- /Algorithms/Remove Duplicates from Sorted Array II/README.md: -------------------------------------------------------------------------------- 1 | Similar to [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/). 2 | 3 | Use another array to count the times one number appears. -------------------------------------------------------------------------------- /Algorithms/Add and Search Word - Data structure design/README.md: -------------------------------------------------------------------------------- 1 | JavaScript does not have Pointer like C++, but we can use `new` to simulate. 2 | 3 | What's more? The string may contain `.`, so we should use depth first search to find the answer. -------------------------------------------------------------------------------- /Algorithms/Excel Sheet Column Number/README.md: -------------------------------------------------------------------------------- 1 | Try to know the conversion rules, and it will be easy. 2 | 3 | Similar problem [Excel Sheet Column Title](https://github.com/hanzichi/leetcode/tree/master/Algorithms/Excel%20Sheet%20Column%20Title). -------------------------------------------------------------------------------- /Algorithms/Valid Number/README.md: -------------------------------------------------------------------------------- 1 | In javascript, you can convert String to Number use `Number()`, if a given string is not numeric, then you will get `NaN` as a result. Particularly, Number("") will get 0, notice that and make a specially judgement. -------------------------------------------------------------------------------- /Algorithms/Maximum Gap/README.md: -------------------------------------------------------------------------------- 1 | The problem asks us to try to solve it in linear time/space. But I do not, using `sort` makes it quite simple, and the result: **You are here! 2 | Your runtime beats 100.00% of javascriptsubmissions.** unbelievable .. -------------------------------------------------------------------------------- /Algorithms/Climbing Stairs/README.md: -------------------------------------------------------------------------------- 1 | Simple Recurrence Problem. 2 | 3 | To get the ways you are climbing to Step 3, you can either climb from Step 2, or Step 1. So if you know the answer that you climb to Step 2 and 1, you can also know the answer to Step 3. -------------------------------------------------------------------------------- /Algorithms/Compare Version Numbers/README.md: -------------------------------------------------------------------------------- 1 | It may be easy, but you should notice that `.` may appear many times in one version number, as well as 0 times. So just cut two version numbers according to `.`, and compare the corresponding two numbers after cutting. -------------------------------------------------------------------------------- /Algorithms/Linked List Cycle/README.md: -------------------------------------------------------------------------------- 1 | I just solve it with using extra space. 2 | 3 | Traverse the Linked List, mark the node which has been traversed (here use extra space). 4 | 5 | It's alse strange that we cannot use window.xx in this code, it's quite strange. -------------------------------------------------------------------------------- /Algorithms/Super Ugly Number/README.md: -------------------------------------------------------------------------------- 1 | I don't think it's worth thinking of. I just use the algorithm as [264. Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) does, solving it with O(10^8), not only not tle, but also getting a quite acceptable ranking. -------------------------------------------------------------------------------- /Algorithms/Divide Two Integers/README.md: -------------------------------------------------------------------------------- 1 | I think it's designed for some language such as C, C++, because they have int overflow.. 2 | 3 | I do it with JavaScript, and I do not have these trouble.. Maybe I have misunderstood the real purpose of the provider of this problem. -------------------------------------------------------------------------------- /Algorithms/Nim Game/nim-game.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/nim-game/ 2 | // Author : Han Zichi 3 | // Date : 2016-01-20 4 | 5 | /** 6 | * @param {number} n 7 | * @return {boolean} 8 | */ 9 | var canWinNim = function(n) { 10 | return n % 4 11 | }; -------------------------------------------------------------------------------- /Algorithms/Power of Four/README.md: -------------------------------------------------------------------------------- 1 | Similar to the problem [Power of Two](https://github.com/hanzichi/leetcode/tree/master/Algorithms/Power%20of%20Two) and [Power of Three](https://github.com/hanzichi/leetcode/tree/master/Algorithms/Power%20of%20Three). 2 | 3 | Use `Math.log`. -------------------------------------------------------------------------------- /Algorithms/Repeated DNA Sequences/README.md: -------------------------------------------------------------------------------- 1 | I solve it by a kind of `hash` (maybe a little hack), also using `Set`. I regard `ACGT` as `0123`. 2 | 3 | I don't think it is a good solution. But the result is **You are here! 4 | Your runtime beats 100.00% of javascript submissions.** -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "generate-readme", 3 | "version": "0.0.0", 4 | "description": "generate readme for my leetcode repo", 5 | "dependencies": { 6 | "cheerio": "latest", 7 | "eventproxy": "^0.3.5", 8 | "superagent": "latest" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Algorithms/Reverse Integer/README.md: -------------------------------------------------------------------------------- 1 | Notice: 2 | 3 | - the int32 range: -2^31 ~ 2^31-1 4 | - this problem is a little puzzling, you should take overflow into consideration 5 | - although it's really nothing to JavaScript 6 | - you should also notice that 1 << 31 will overflow in JavaScript -------------------------------------------------------------------------------- /Algorithms/Delete Node in a Linked List/README.md: -------------------------------------------------------------------------------- 1 | Simple problem, to be careful. 2 | 3 | See the code: 4 | 5 | ```javascript 6 | var deleteNode = function(node) { 7 | node.val = node.next.val; 8 | var tmp = node.next; 9 | node.next = node.next.next; 10 | tmp = null; 11 | }; 12 | ``` -------------------------------------------------------------------------------- /Algorithms/Gray Code/indexⅡ.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/gray-code/ 2 | // Author : Han Zichi 3 | // Date : 2015-09-20 4 | 5 | var grayCode = function(n) { 6 | var ans = []; 7 | for (var i = 0; i < (1 << n); i++) 8 | ans[i] = i ^ (i >> 1); 9 | return ans; 10 | }; -------------------------------------------------------------------------------- /Algorithms/Pow(x, n)/powx-n.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/powx-n/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number} x 7 | * @param {number} n 8 | * @return {number} 9 | */ 10 | 11 | var myPow = function(x, n) { 12 | return Math.pow(x, n); 13 | }; -------------------------------------------------------------------------------- /Algorithms/Top K Frequent Elements/README.md: -------------------------------------------------------------------------------- 1 | Use O(n) to get the times every item appears, store in an array with an object, the key is the item, and the value is the times, for instance, `[1, 1, 1, 2, 2, 3]`, we can use an array `[{"1": 3}, {"2": 2}, {"3": 1}]`, then we can sort the array and get the answer. 2 | -------------------------------------------------------------------------------- /Algorithms/Move Zeroes/move-zeroes.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/move-zeroes/ 2 | // Author : Han Zichi 3 | // Date : 2015-09-20 4 | 5 | var moveZeroes = function(nums) { 6 | for (var i = nums.length; i--; ) { 7 | if (!nums[i]) { 8 | nums.splice(i, 1); 9 | nums.push(0); 10 | } 11 | } 12 | }; -------------------------------------------------------------------------------- /Algorithms/Patching Array/README.md: -------------------------------------------------------------------------------- 1 | If there is not any number in the array, we should obviously choose 1, 2, 4, 8, 16 ... such numbers can make up "big number" with the fewest numbers. 2 | 3 | And if there is no 1, we should certainly choose 1, after choosing, we can see what numbers we can make up, and choose another, until reaching the goal. -------------------------------------------------------------------------------- /Algorithms/Bulb Switcher/README.md: -------------------------------------------------------------------------------- 1 | `n` is Infinity, so we cannot simulate the process, we should find the rule. 2 | 3 | After running the first several thousand cases, we finally find the rule as below: 4 | 5 | ```javascript 6 | var bulbSwitch = function(n) { 7 | var ans = -1 + Math.sqrt(1 + n); 8 | return Math.ceil(ans); 9 | }; 10 | ``` -------------------------------------------------------------------------------- /Algorithms/Sort Colors/sort-colors.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sort-colors/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {void} Do not return anything, modify nums in-place instead. 8 | */ 9 | 10 | var sortColors = function(nums) { 11 | nums.sort(); 12 | }; -------------------------------------------------------------------------------- /Algorithms/Valid Number/valid-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-number/ 2 | // Author : Han Zichi 3 | // Date : 2016-04-30 4 | 5 | /** 6 | * @param {string} s 7 | * @return {boolean} 8 | */ 9 | var isNumber = function(s) { 10 | if (s.trim() === "") 11 | return false; 12 | return !isNaN(Number(s)); 13 | }; -------------------------------------------------------------------------------- /Algorithms/Flatten Nested List Iterator/README.md: -------------------------------------------------------------------------------- 1 | How to say, it's not a difficult problem, but a rather troublesome one. 2 | 3 | You should always notice that `nestedList` is consist of instances of `NestedInteger` . And then you can flatten it with functions `getInteger` or `getList`. 4 | 5 | Use `shift` and `unshift` in javascript, it will be easier. -------------------------------------------------------------------------------- /Algorithms/Sqrt(x)/sqrtx.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sqrtx/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number} x 7 | * @return {number} 8 | */ 9 | 10 | // I really do not know what the meaning of this problem is 11 | var mySqrt = function(x) { 12 | return Math.floor(Math.sqrt(x)); 13 | }; -------------------------------------------------------------------------------- /Algorithms/Bulb Switcher/bulb-switcher.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/bulb-switcher/ 2 | // Author : Han Zichi 3 | // Date : 2016-01-20 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | 10 | // 打表 11 | var bulbSwitch = function(n) { 12 | var ans = -1 + Math.sqrt(1 + n); 13 | return Math.ceil(ans); 14 | }; -------------------------------------------------------------------------------- /Algorithms/Power of Two/power-of-two.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-two/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number} n 7 | * @return {boolean} 8 | */ 9 | 10 | var isPowerOfTwo = function(n) { 11 | var tmp = ~~(Math.log(n) / Math.log(2)); 12 | return n === (1 << tmp); 13 | }; -------------------------------------------------------------------------------- /Algorithms/Range Sum Query - Mutable/README.md: -------------------------------------------------------------------------------- 1 | It's the easiest `Binary Indexed Tree` problem. 2 | 3 | If you are Chinese, I suggest you reading [this](http://www.cnblogs.com/zichi/p/4806998.html) and [this](http://www.cnblogs.com/zichi/p/4807072.html) to learn Binary Indexed Tree once written by me. 4 | 5 | If you are not, I suggest you turning to Google for help. -------------------------------------------------------------------------------- /Algorithms/Remove Nth Node From End of List/README.md: -------------------------------------------------------------------------------- 1 | I just solve it with the most stupid way, get every node from the list, push them to an array, delete the one which shoud be deleted, make the items in the array with another list, that's the answer. 2 | 3 | Notice that `splice` function will operate the original array, and return the deleted items with an array. -------------------------------------------------------------------------------- /Algorithms/Two Sum/README.md: -------------------------------------------------------------------------------- 1 | Use array `a` to show the position of a number. 2 | 3 | For instance, if `a[i] === undefined`, it means we don't have the number of `i` in the array, and if not, it means the number of `i` appears in the position of `index === a[i]`. 4 | 5 | So it will be easy, we can enum the array, and check if `a[target - item]` is undefined or not. -------------------------------------------------------------------------------- /Algorithms/Implement strStr()/implement-strstr.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/implement-strstr/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-23 4 | 5 | /** 6 | * @param {string} haystack 7 | * @param {string} needle 8 | * @return {number} 9 | */ 10 | var strStr = function(haystack, needle) { 11 | return haystack.search(needle); 12 | }; -------------------------------------------------------------------------------- /Algorithms/Palindrome Number/palindrome-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/palindrome-number/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number} x 7 | * @return {boolean} 8 | */ 9 | 10 | var isPalindrome = function(x) { 11 | return x.toString() == x.toString().split('').reverse().join(''); 12 | }; -------------------------------------------------------------------------------- /Algorithms/Reverse String/reverse-string.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-string/ 2 | // Author : Han Zichi 3 | // Date : 2016-04-26 4 | 5 | /** 6 | * @param {string} s 7 | * @return {string} 8 | */ 9 | var reverseString = function(s) { 10 | if (s === null) 11 | return s; 12 | 13 | return s.split('').reverse().join(''); 14 | }; -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # CONTRIBUTING 2 | 3 | It's a personal project for leetcode solutions, but PRs welcomed as well. 4 | 5 | You should meet the following conditions: 6 | 7 | - the question of the solution you submit should have been solved by me 8 | - you should have a better solution either in time complexity or space complexity 9 | - you should use JavaScript or Python -------------------------------------------------------------------------------- /Algorithms/Arranging Coins/arranging-coins.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/arranging-coins/ 2 | // Author : Han Zichi 3 | // Date : 2016-10-31 4 | 5 | "use strict"; 6 | 7 | /** 8 | * @param {number} n 9 | * @return {number} 10 | */ 11 | var arrangeCoins = function(n) { 12 | let ans = Math.sqrt(1 + 8 * n) - 1; 13 | ans /= 2; 14 | 15 | return ~~ans; 16 | }; -------------------------------------------------------------------------------- /Algorithms/Detect Capital/detect-capital.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/detect-capital/?tab=Description 2 | // Author : Han Zichi 3 | // Date : 2017-02-27 4 | 5 | /** 6 | * @param {string} word 7 | * @return {boolean} 8 | */ 9 | var detectCapitalUse = function(word) { 10 | let p = /^([a-z]+|[A-Z]+|[A-Z]{1}[a-z]+)$/; 11 | return p.test(word); 12 | }; 13 | -------------------------------------------------------------------------------- /Algorithms/Find Minimum in Rotated Sorted Array/find-minimum-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var findMin = function(nums) { 11 | return Math.min.apply(null, nums); 12 | }; -------------------------------------------------------------------------------- /Algorithms/H-Index II/h-index-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/h-index-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-09-11 4 | 5 | var hIndex = function(citations) { 6 | var len = citations.length; 7 | for (var i = len; ; i--) { 8 | if ((!i || citations[len - i] >= i) && (len - i - 1 < 0 || citations[len - i - 1] <= i)) 9 | return i; 10 | } 11 | }; -------------------------------------------------------------------------------- /Algorithms/Find Minimum in Rotated Sorted Array II/find-minimum-in-rotated-sorted-array-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var findMin = function(nums) { 11 | return Math.min.apply(null, nums); 12 | }; -------------------------------------------------------------------------------- /Algorithms/House Robber III/README.md: -------------------------------------------------------------------------------- 1 | Use dfs + dp. 2 | 3 | To a node, `dp[0]` means the maximum acount with taking this node's value (with its child nodes considered), while `dp[1]` means the maximum acount without taking this node's value. 4 | 5 | And use dfs to get the dp array from buttom to top (you should and you have to). So the answer is very clear, `max(head.dp[0], head.dp[1])`. 6 | 7 | -------------------------------------------------------------------------------- /Algorithms/Longest Palindromic Substring/README.md: -------------------------------------------------------------------------------- 1 | If you are Chinese, I suggest you reading [this article](http://www.cnblogs.com/zichi/p/4753930.html) written by me. 2 | 3 | If you are not, I suggest you learning the algorithm named `Manacher`. 4 | 5 | Similar to [Shortest Palindrome](https://github.com/hanzichi/leetcode/tree/499881dc6bdea4625ff68caccb27c952e9236395/Algorithms/Shortest%20Palindrome) -------------------------------------------------------------------------------- /Algorithms/Single Number/single-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/single-number/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var singleNumber = function(nums) { 11 | var ans = 0; 12 | for(var i = 0, len = nums.length; i < len; i++) 13 | ans ^= nums[i]; 14 | 15 | return ans; 16 | }; -------------------------------------------------------------------------------- /Algorithms/Climbing Stairs/climbing-stairs.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/climbing-stairs/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | 10 | var climbStairs = function(n) { 11 | var a = []; 12 | a[0] = 1, a[1] = 1; 13 | for(var i = 2; i <= n; i++) 14 | a[i] = a[i - 1] + a[i - 2]; 15 | return a[n]; 16 | }; -------------------------------------------------------------------------------- /Algorithms/Number of 1 Bits/number-of-1-bits.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-1-bits/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-21 4 | 5 | /** 6 | * @param {number} n - a positive integer 7 | * @return {number} 8 | */ 9 | 10 | var hammingWeight = function(n) { 11 | var ans = 0; 12 | while(n) { 13 | if (n & 1) ans ++; 14 | n /= 2; 15 | } 16 | 17 | return ans; 18 | }; -------------------------------------------------------------------------------- /Algorithms/Valid Palindrome/valid-palindrome.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-palindrome/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {string} s 7 | * @return {boolean} 8 | */ 9 | 10 | var isPalindrome = function(s) { 11 | s = s.replace(/[\W]/g, ''); 12 | s = s.toLowerCase(); 13 | var _s = s.split('').reverse().join(''); 14 | return s === _s; 15 | }; 16 | -------------------------------------------------------------------------------- /Algorithms/Power of Three/power-of-three.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-three/ 2 | // Author : Han Zichi 3 | // Date : 2016-01-16 4 | 5 | /** 6 | * @param {number} n 7 | * @return {boolean} 8 | */ 9 | var isPowerOfThree = function(n) { 10 | if (!n) return false; 11 | var a = Math.log(n) / Math.log(3); 12 | return Math.pow(3, Math.floor(a)) === n || Math.pow(3, Math.ceil(a)) === n; 13 | }; -------------------------------------------------------------------------------- /Algorithms/Reverse Words in a String III/reverse-words-in-a-string-iii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ 2 | // Author : Fish.Yu 3 | // Date : 2017-12-26 4 | 5 | /** 6 | * @param {string} s 7 | * @return {string} 8 | */ 9 | var reverseWords = function(s) { 10 | let arr = s.split(' ').map(item => item.split('').reverse().join('')) 11 | return arr.join(' ') 12 | }; -------------------------------------------------------------------------------- /Algorithms/Factorial Trailing Zeroes/README.md: -------------------------------------------------------------------------------- 1 | It may be a case to calculate how many times `n!` can be divided by 5. It's quite easy, see the code straightly: 2 | 3 | ```javascript 4 | /** 5 | * @param {number} n 6 | * @return {number} 7 | */ 8 | var trailingZeroes = function(n) { 9 | var ans = 0; 10 | while (n) { 11 | ans += ~~(n / 5); 12 | n /= 5; 13 | n = ~~n; 14 | } 15 | 16 | return ans; 17 | }; 18 | ``` -------------------------------------------------------------------------------- /Algorithms/Factorial Trailing Zeroes/factorial-trailing-zeroes.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/factorial-trailing-zeroes/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var trailingZeroes = function(n) { 10 | var ans = 0; 11 | while (n) { 12 | ans += ~~(n / 5); 13 | n /= 5; 14 | n = ~~n; 15 | } 16 | 17 | return ans; 18 | }; -------------------------------------------------------------------------------- /Algorithms/Reverse Words in a String/reverse-words-in-a-string.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-size-subarray-sum/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-03 4 | 5 | /** 6 | * @param {string} str 7 | * @returns {string} 8 | */ 9 | var reverseWords = function(str) { 10 | str = str.trim(); 11 | str = str.replace(/\s+/g, ' '); 12 | var arr = str.split(' ').reverse(); 13 | return arr.join(' '); 14 | }; -------------------------------------------------------------------------------- /Algorithms/Gray Code/indexⅠ.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/gray-code/ 2 | // Author : Han Zichi 3 | // Date : 2015-09-20 4 | 5 | var grayCode = function(n) { 6 | if (!n) return [0]; 7 | 8 | var ans = []; 9 | ans[0] = 0, ans[1] = 1; 10 | 11 | for (var i = 1; i < n; i++) 12 | for (var j = 1 << i; j < (1 << i + 1); j++) 13 | ans[j] = ans[(1 << (i + 1)) - 1 - j] + (1 << i); 14 | 15 | return ans; 16 | }; -------------------------------------------------------------------------------- /Algorithms/Power of Four/power-of-four.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-four/ 2 | // Author : Han Zichi 3 | // Date : 2016-04-26 4 | 5 | /** 6 | * @param {number} num 7 | * @return {boolean} 8 | */ 9 | var isPowerOfFour = function(num) { 10 | if (!num) 11 | return false; 12 | 13 | var a = Math.log(num) / Math.log(4); 14 | return Math.pow(4, Math.floor(a)) === num || Math.pow(4, Math.ceil(a)) === num; 15 | }; -------------------------------------------------------------------------------- /Algorithms/Regular Expression Matching/regular-expression-matching.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/regular-expression-matching/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {string} s 7 | * @param {string} p 8 | * @return {boolean} 9 | */ 10 | 11 | var isMatch = function(s, p) { 12 | var p = '^' + p + '$'; 13 | var pattern = new RegExp(p, 'g'); 14 | return pattern.test(s); 15 | }; 16 | 17 | -------------------------------------------------------------------------------- /Algorithms/Hamming Distance/hamming-distance.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/hamming-distance/ 2 | // Author : Han Zichi 3 | // Date : 2016-12-23 4 | 5 | /** 6 | * @param {number} x 7 | * @param {number} y 8 | * @return {number} 9 | */ 10 | var hammingDistance = function(x, y) { 11 | let ans = 0; 12 | while (x || y) { 13 | ans += (x & 1) ^ (y & 1); 14 | x >>= 1; 15 | y >>= 1; 16 | } 17 | return ans; 18 | }; 19 | -------------------------------------------------------------------------------- /Algorithms/Missing Number/missing-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/missing-number/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-24 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var missingNumber = function(nums) { 10 | var hash = []; 11 | nums.forEach(function(item) { 12 | hash[item] = true; 13 | }); 14 | 15 | for (var i = 0; ; i++) 16 | if (!hash[i]) 17 | return i; 18 | }; -------------------------------------------------------------------------------- /Algorithms/Construct the Rectangle/construct-the-rectangle.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/construct-the-rectangle/ 2 | // Author : Han Zichi 3 | // Date : 2017-01-22 4 | 5 | /** 6 | * @param {number} area 7 | * @return {number[]} 8 | */ 9 | var constructRectangle = function(area) { 10 | let mid = Math.ceil(Math.sqrt(area)); 11 | 12 | for ( ; ; mid++) { 13 | if (area % mid === 0) 14 | return [mid, area / mid]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Algorithms/Kth Largest Element in an Array/kth-largest-element-in-an-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/kth-largest-element-in-an-array/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} k 8 | * @return {number} 9 | */ 10 | 11 | var findKthLargest = function(nums, k) { 12 | nums.sort(function(a, b) { 13 | return b - a; 14 | }); 15 | 16 | return nums[k - 1]; 17 | }; -------------------------------------------------------------------------------- /Algorithms/Reverse Bits/README.md: -------------------------------------------------------------------------------- 1 | I just solve it simply. 2 | 3 | Firstly I change the integer to binary string using `toString` function. Then I add some `0` to the head of the string as it is not longer enough. Lastly we can calculate the answer with the string. 4 | 5 | If this function is called many times, how would you optimize it? Well, I calculate 2^1, 2^2, 2^3 .. until 2^32 before the function is called, so we can use it immediately in the `reverseBits` function. -------------------------------------------------------------------------------- /Algorithms/Search in Rotated Sorted Array II/search-in-rotated-sorted-array-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} target 8 | * @return {boolean} 9 | */ 10 | 11 | var search = function(nums, target) { 12 | return nums.some(function(item, index, array) { 13 | return item === target; 14 | }); 15 | }; -------------------------------------------------------------------------------- /Algorithms/Add Digits/add-digits.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-digits/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-17 4 | 5 | /** 6 | * @param {number} num 7 | * @return {number} 8 | */ 9 | var addDigits = function(num) { 10 | while(num.toString().length !== 1) { 11 | var sum = 0; 12 | while (num) { 13 | sum += num % 10; 14 | num = ~~(num / 10); 15 | } 16 | num = sum; 17 | } 18 | 19 | return num; 20 | }; 21 | -------------------------------------------------------------------------------- /Algorithms/Number Complement/number-complement.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-complement/ 2 | // Author : Han Zichi 3 | // Date : 2017-01-10 4 | 5 | /** 6 | * @param {number} num 7 | * @return {number} 8 | */ 9 | var findComplement = function(num) { 10 | let ans = 0 11 | , add = 1; 12 | 13 | while (num) { 14 | if (!(num & 1)) 15 | ans += add; 16 | num >>= 1; 17 | add <<= 1; 18 | } 19 | 20 | return ans; 21 | }; 22 | -------------------------------------------------------------------------------- /Algorithms/Number of Segments in a String/number-of-segments-in-a-string.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-segments-in-a-string/ 2 | // Author : Han Zichi 3 | // Date : 2016-12-23 4 | 5 | /** 6 | * @param {string} s 7 | * @return {number} 8 | */ 9 | var countSegments = function(s) { 10 | let arr = s.split(' '); 11 | let ans = 0; 12 | 13 | arr.forEach(function(item) { 14 | item && (ans++); 15 | }); 16 | 17 | return ans; 18 | }; 19 | -------------------------------------------------------------------------------- /Algorithms/Valid Anagram/valid-anagram.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-anagram/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-19 4 | 5 | /** 6 | * @param {string} s 7 | * @param {string} t 8 | * @return {boolean} 9 | */ 10 | var isAnagram = function(s, t) { 11 | if (s.length !== t.length) 12 | return false; 13 | 14 | var a = s.split('').sort() 15 | , b = t.split('').sort(); 16 | 17 | return a.toString() === b.toString(); 18 | }; -------------------------------------------------------------------------------- /Algorithms/Contains Duplicate/contains-duplicate.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {boolean} 8 | */ 9 | 10 | var containsDuplicate = function(nums) { 11 | var hash = {}; 12 | for(var i = 0, len = nums.length; i < len; i++) { 13 | if (hash[nums[i]]) return true; 14 | hash[nums[i]] = true; 15 | } 16 | return false; 17 | }; -------------------------------------------------------------------------------- /Algorithms/Remove Element/remove-element.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-element/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-12 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} val 8 | * @return {number} 9 | */ 10 | 11 | var removeElement = function(nums, val) { 12 | var ans = 0; 13 | for(var i = nums.length; i--; ) 14 | if (nums[i] !== val) 15 | ans++; 16 | else nums.splice(i, 1); 17 | 18 | return ans; 19 | }; -------------------------------------------------------------------------------- /Algorithms/Jump Game/jump-game.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/jump-game/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-25 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {boolean} 8 | */ 9 | 10 | var canJump = function(nums) { 11 | var rightMost = 1; 12 | for (var i = 0, len = nums.length; i < len; i++) { 13 | if (rightMost < i + 1) break; 14 | rightMost = Math.max(rightMost, i + 1 + nums[i]); 15 | } 16 | return rightMost >= len; 17 | }; -------------------------------------------------------------------------------- /Algorithms/Ugly Number/ugly-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ugly-number/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-19 4 | 5 | /** 6 | * @param {number} num 7 | * @return {boolean} 8 | */ 9 | var isUgly = function(num) { 10 | if (num === 0) 11 | return false; 12 | 13 | var a = [2, 3, 5]; 14 | for (var i = 0; i < 3; i++) { 15 | while (num % a[i] === 0) 16 | num /= a[i]; 17 | } 18 | 19 | return num === 1 ? true : false; 20 | }; -------------------------------------------------------------------------------- /Algorithms/Search in Rotated Sorted Array/search-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-in-rotated-sorted-array/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} target 8 | * @return {number} 9 | */ 10 | 11 | var search = function(nums, target) { 12 | for(var i = 0, len = nums.length; i < len; i++) 13 | if (nums[i] === target) 14 | return i; 15 | return -1; 16 | }; -------------------------------------------------------------------------------- /Algorithms/Two Sum/two-sum.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/two-sum/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} target 8 | * @return {number[]} 9 | */ 10 | 11 | var twoSum = function(nums, target) { 12 | var a = []; 13 | for (var i = 0, len = nums.length; i < len; i++) { 14 | var tmp = target - nums[i]; 15 | if (a[tmp] !== undefined) return [a[tmp], i]; 16 | a[nums[i]] = i; 17 | } 18 | }; -------------------------------------------------------------------------------- /Algorithms/Find the Difference/find-the-difference.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-the-difference/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-28 4 | 5 | /** 6 | * @param {string} s 7 | * @param {string} t 8 | * @return {character} 9 | */ 10 | var findTheDifference = function(s, t) { 11 | s = s.split('').sort(); 12 | t = t.split('').sort(); 13 | 14 | for (var i = 0, len = t.length; i < len; i++) { 15 | if (s[i] !== t[i]) 16 | return t[i]; 17 | } 18 | }; -------------------------------------------------------------------------------- /Algorithms/Find Peak Element/find-peak-element.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-peak-element/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var findPeakElement = function(nums) { 11 | var len = nums.length; 12 | nums[-1] = nums[len] = -Number.MAX_VALUE; 13 | for(var i = 0; i < len; i++) { 14 | if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) 15 | return i; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Algorithms/Search a 2D Matrix/search-a-2d-matrix.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-a-2d-matrix/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-18 4 | 5 | /** 6 | * @param {number[][]} matrix 7 | * @param {number} target 8 | * @return {boolean} 9 | */ 10 | var searchMatrix = function(matrix, target) { 11 | for (var i = 0; i < matrix.length; i++) 12 | for (var j = 0; j < matrix[i].length; j++) 13 | if (matrix[i][j] === target) return true; 14 | 15 | return false; 16 | }; -------------------------------------------------------------------------------- /Algorithms/First Unique Character in a String/first-unique-character-in-a-string.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/first-unique-character-in-a-string/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-22 4 | 5 | /** 6 | * @param {string} s 7 | * @return {number} 8 | */ 9 | var firstUniqChar = function(s) { 10 | for (var i = 0, len = s.length; i < len; i++) { 11 | var item = s[i]; 12 | if (s.lastIndexOf(item) === s.indexOf(item)) 13 | return i; 14 | } 15 | 16 | return -1; 17 | }; -------------------------------------------------------------------------------- /Algorithms/Excel Sheet Column Number/excel-sheet-column-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/excel-sheet-column-number/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-26 4 | 5 | /** 6 | * @param {string} s 7 | * @return {number} 8 | */ 9 | var titleToNumber = function(s) { 10 | var a = s.split('').reverse(); 11 | s = a.join(''); 12 | var ans = a.reduce(function(pre, item, index) { 13 | return pre + Math.pow(26, index) * (s.charCodeAt(index) - 64); 14 | }, 0); 15 | return ans; 16 | }; -------------------------------------------------------------------------------- /Algorithms/Search a 2D Matrix II/search-a-2d-matrix-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-a-2d-matrix-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-18 4 | 5 | /** 6 | * @param {number[][]} matrix 7 | * @param {number} target 8 | * @return {boolean} 9 | */ 10 | var searchMatrix = function(matrix, target) { 11 | for (var i = 0; i < matrix.length; i++) 12 | for (var j = 0; j < matrix[i].length; j++) 13 | if (matrix[i][j] === target) return true; 14 | 15 | return false; 16 | }; -------------------------------------------------------------------------------- /Algorithms/Sum of Square Numbers/sum-of-square-numbers.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sum-of-square-numbers/description/ 2 | // Author : Han Zichi 3 | // Date : 2017-07-29 4 | 5 | /** 6 | * @param {number} c 7 | * @return {boolean} 8 | */ 9 | var judgeSquareSum = function(c) { 10 | let mid = ~~(Math.sqrt(c)) 11 | 12 | for (let i = 0; i <= mid; i++) { 13 | let rem = c - i * i 14 | if (rem === Math.pow(~~Math.sqrt(rem), 2)) 15 | return true 16 | } 17 | 18 | return false 19 | }; -------------------------------------------------------------------------------- /Algorithms/Best Time to Buy and Sell Stock with Cooldown/README.md: -------------------------------------------------------------------------------- 1 | It's like [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/). Go to solve that problem and see the [explanation](https://github.com/hanzichi/leetcode/blob/master/Algorithms/Best%20Time%20to%20Buy%20and%20Sell%20Stock%20II/README.md) here firstly. 2 | 3 | In this problem, we can define three array named `sell`, `buy`, and `rest`, everyday we can sell, buy, or rest, it's the DP problem as well. 4 | 5 | Think it over. -------------------------------------------------------------------------------- /Algorithms/Integer Break/README.md: -------------------------------------------------------------------------------- 1 | A simple dynamic programming problem. 2 | 3 | Define array `dp`, `dp[i]` means the answer when `n === i`, if you want to get `dp[10]`, you may compare dp[1] * 9, dp[2] * 8, dp[3] * 7 ... That's really dynamic programming by O(n^2) Complexity. 4 | 5 | To make it easier, I consider the case `n === 2` and `n === 3` as the special cases to avoid some error. That's because dp[i] may be made up by only one factor, dp[2] is 2, not 1, and dp[3] is 3, not 2, after dp[3], we can get correct answer as we expect. -------------------------------------------------------------------------------- /Algorithms/Is Subsequence/is-subsequence.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/is-subsequence/ 2 | // Author : Han Zichi 3 | // Date : 2016-09-05 4 | 5 | /** 6 | * @param {string} s 7 | * @param {string} t 8 | * @return {boolean} 9 | */ 10 | var isSubsequence = function(s, t) { 11 | var index = 0 12 | , len = s.length; 13 | 14 | for (var item of t) { 15 | if (item === s[index]) 16 | index++; 17 | 18 | if (index === len) 19 | break; 20 | } 21 | 22 | return index === len; 23 | }; -------------------------------------------------------------------------------- /Algorithms/Rotate Array/rotate-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-array/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} k 8 | * @return {void} Do not return anything, modify nums in-place instead. 9 | */ 10 | 11 | var rotate = function(nums, k) { 12 | k %= nums.length; 13 | var tmp = []; 14 | if (k) 15 | tmp = nums.slice(-k); 16 | nums.splice(-k, k); 17 | 18 | Array.prototype.unshift.apply(nums, tmp); 19 | }; 20 | -------------------------------------------------------------------------------- /Algorithms/First Missing Positive/first-missing-positive.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/first-missing-positive/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var firstMissingPositive = function(nums) { 11 | var hash = []; 12 | for(var i = 0, len = nums.length; i < len; i++) 13 | if (nums[i] <= 0) continue; 14 | else hash[nums[i]] = true; 15 | 16 | for(var i = 1; ; i++) 17 | if (!hash[i]) 18 | return i; 19 | }; -------------------------------------------------------------------------------- /Algorithms/Majority Element/majority-element.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/majority-element/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var majorityElement = function(nums) { 11 | var hash = []; 12 | for(var i = 0, len = nums.length; i < len; i++) { 13 | if (!hash[nums[i]]) hash[nums[i]] = 1; 14 | else hash[nums[i]]++; 15 | 16 | if (hash[nums[i]] > len / 2) 17 | return nums[i]; 18 | } 19 | }; 20 | 21 | -------------------------------------------------------------------------------- /Algorithms/Maximum Subarray/maximum-subarray.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-subarray/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var maxSubArray = function(nums) { 11 | var maxn = -Number.MAX_VALUE; 12 | var sum = 0; 13 | nums.forEach(function(item, index, array) { 14 | sum += item; 15 | if (sum > maxn) 16 | maxn = sum; 17 | if (sum < 0) 18 | sum = 0; 19 | }); 20 | 21 | return maxn; 22 | }; -------------------------------------------------------------------------------- /Algorithms/Sum of Two Integers/sum-of-two-integers.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sum-of-two-integers/ 2 | // Author : Han Zichi 3 | // Date : 2016-06-30 4 | 5 | // it's not the right answer according to the description of the question 6 | // but I really do not want to solve it in another way 7 | // be wilful! 8 | // unless you return me with the result of WA 9 | 10 | /** 11 | * @param {number} a 12 | * @param {number} b 13 | * @return {number} 14 | */ 15 | var getSum = function(a, b) { 16 | return a + b; 17 | }; -------------------------------------------------------------------------------- /Algorithms/Distribute Candies/distribute-candies.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/distribute-candies/description/ 2 | // Author : Fish.Yu 3 | // Date : 2017-12-25 4 | 5 | /** 6 | * @param {number[]} candies 7 | * @return {number} 8 | */ 9 | var distributeCandies = function(candies) { 10 | let p = new Map() 11 | 12 | for (let item of candies) { 13 | p.set(item, ~~p.get(item) + 1) 14 | } 15 | 16 | let res = [...p.values()].sort((a, b) => a - b) 17 | 18 | return Math.min(res.length, candies.length >> 1) 19 | }; -------------------------------------------------------------------------------- /Algorithms/Increasing Triplet Subsequence/README.md: -------------------------------------------------------------------------------- 1 | We define two variables `first` and `second` as the first two of the increasing subsequence of length 3, and `first2` and `second2` as the "backup", we replace `first2` and `second2` for `first` and `second` at the right time. 2 | 3 | Here comes an example. If the array is `[1, 2, -3, -2, -1]`, firstly, `first = 1`, and `second = 2`, then comes `first2 = -3, second2 = -2`. After comparing, we replace `first2 = -3, second2 = -2` for `first = 1, second = 2`, because it is more likely to reach the goal. -------------------------------------------------------------------------------- /Algorithms/Reverse Words in a String III/reverse-words-in-a-string-iii.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ 2 | # Author : Fish.Yu 3 | # Date : 2017-12-26 4 | 5 | class Solution: 6 | def reverseWords(self, s): 7 | """ 8 | :type s: str 9 | :rtype: str 10 | """ 11 | def f(x): 12 | l = list(x) 13 | l.reverse() 14 | return ''.join(l) 15 | 16 | arr = list(map(f, s.split(' '))) 17 | return ' '.join(arr) -------------------------------------------------------------------------------- /Algorithms/Largest Number/largest-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/largest-number/ 2 | // Author : Han Zichi 3 | // Date : 2016-02-02 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {string} 8 | */ 9 | var largestNumber = function(nums) { 10 | nums.sort(function(a, b) { 11 | return (b + '' + a) - (a + '' + b); 12 | }); 13 | 14 | var ans = nums.join(''); 15 | 16 | for (var i = 0; i < ans.length - 1; i++) { 17 | if (ans[i] !== '0') 18 | break; 19 | } 20 | 21 | return ans.substring(i); 22 | }; -------------------------------------------------------------------------------- /Algorithms/Length of Last Word/length-of-last-word.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/length-of-last-word/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-19 4 | 5 | /** 6 | * @param {string} s 7 | * @return {number} 8 | */ 9 | var lengthOfLastWord = function(s) { 10 | s = s.trim(); 11 | var _str = s.replace(/\s/g, ''); 12 | if (!_str.length) return 0; 13 | 14 | for (var i = s.length; i--; ) { 15 | if (s[i] === ' ') 16 | return s.length - i - 1; 17 | 18 | if (i === 0) 19 | return s.length - i; 20 | } 21 | }; -------------------------------------------------------------------------------- /Algorithms/Maximum Gap/maximum-gap.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-gap/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var maximumGap = function(nums) { 10 | if (nums.length < 2) 11 | return 0; 12 | 13 | nums.sort(function(a, b) { 14 | return a - b; 15 | }); 16 | 17 | var ans = -1; 18 | nums.reduce(function(pre, cur, index, array) { 19 | ans = Math.max(ans, cur - pre); 20 | return cur; 21 | }); 22 | 23 | return ans; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Single Number II/single-number-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/single-number-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var singleNumber = function(nums) { 11 | var tmp = []; 12 | for(var i = 0, len = nums.length; i < len; i++) 13 | if (!tmp[nums[i]]) 14 | tmp[nums[i]] = 1; 15 | else 16 | tmp[nums[i]]++; 17 | 18 | for(var i = 0; i < len; i++) 19 | if (tmp[nums[i]] === 1) 20 | return nums[i]; 21 | }; -------------------------------------------------------------------------------- /Algorithms/Valid Word Abbreviation/valid-word-abbreviation.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-word-abbreviation 2 | // Author : Han Zichi 3 | // Date : 2016-10-02 4 | 5 | /** 6 | * @param {string} word 7 | * @param {string} abbr 8 | * @return {boolean} 9 | */ 10 | var validWordAbbreviation = function(word, abbr) { 11 | // 排除孤立的 `0` 的干扰 12 | if (/([^1-9]|^)0+/.test(abbr)) 13 | return false; 14 | 15 | abbr = abbr.replace(/\d+/g, "[A-z]{$&}"); 16 | abbr = "^" + abbr + "$"; 17 | 18 | return new RegExp(abbr).test(word); 19 | }; -------------------------------------------------------------------------------- /Algorithms/Base 7/base-7.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/base-7/ 2 | // Author : Han Zichi 3 | // Date : 2017-02-15 4 | 5 | /** 6 | * @param {number} num 7 | * @return {string} 8 | */ 9 | var convertToBase7 = function(num) { 10 | if (num === 0) 11 | return '0'; 12 | 13 | let prefix = num < 0 ? '-' : '' 14 | , res = [] 15 | , base = 7; 16 | 17 | num = Math.abs(num); 18 | 19 | while (num) { 20 | res.push(num % base); 21 | num = ~~(num / base); 22 | } 23 | 24 | return prefix + res.reverse().join(''); 25 | }; 26 | -------------------------------------------------------------------------------- /Algorithms/Fizz Buzz/fizz-buzz.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/fizz-buzz/ 2 | // Author : Han Zichi 3 | // Date : 2016-10-17 4 | 5 | "use strict"; 6 | 7 | /** 8 | * @param {number} n 9 | * @return {string[]} 10 | */ 11 | var fizzBuzz = function(n) { 12 | let ans = []; 13 | for (let i = 1; i <= n; i++) { 14 | let str = ''; 15 | if (i % 3 === 0) 16 | str += 'Fizz'; 17 | if (i % 5 === 0) 18 | str += 'Buzz'; 19 | if (str === '') 20 | str += i; 21 | 22 | ans.push(str); 23 | } 24 | 25 | return ans; 26 | }; -------------------------------------------------------------------------------- /Algorithms/Max Consecutive Ones/max-consecutive-ones.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/max-consecutive-ones/ 2 | // Author : Han Zichi 3 | // Date : 2017-01-15 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var findMaxConsecutiveOnes = function(nums) { 10 | let ans = 0 11 | , sum = 0; 12 | 13 | nums.push(0); 14 | 15 | for (let item of nums) { 16 | if (item) 17 | sum += 1; 18 | else { 19 | ans = Math.max(ans, sum); 20 | sum = 0; 21 | } 22 | } 23 | 24 | return ans; 25 | }; 26 | -------------------------------------------------------------------------------- /Algorithms/Unique Binary Search Trees/unique-binary-search-trees.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/unique-binary-search-trees/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-28 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var numTrees = function(n) { 10 | var ans = []; 11 | ans[0] = 1, ans[1] = 1; 12 | 13 | for (var i = 2; i <= n; i++) { 14 | ans[i] = 0; 15 | 16 | // j as the root 17 | for (var j = 1; j <= i; j++) 18 | ans[i] += ans[j - 1] * ans[i - j]; 19 | } 20 | 21 | return ans[n]; 22 | }; -------------------------------------------------------------------------------- /Algorithms/Largest Number/README.md: -------------------------------------------------------------------------------- 1 | If you are Chinese, I suggest you reading [this article](http://www.cnblogs.com/zichi/p/5180489.html) written by me. 2 | 3 | Anyway, it's a case of `sort`. If the array is `[1, 23]`, obviously we will compare `123` with `231`, and find the bigger one, that's the answer. As there may be more elements in the array, we can sort the array with a comparing function, as below: 4 | 5 | ```javascript 6 | nums.sort(function(a, b) { 7 | return (b + '' + a) - (a + '' + b); 8 | }); 9 | ``` 10 | 11 | Be careful, the integer cannot begin with `0`! -------------------------------------------------------------------------------- /Algorithms/Search for a Range/search-for-a-range.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-for-a-range/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} target 8 | * @return {number[]} 9 | */ 10 | 11 | var searchRange = function(nums, target) { 12 | var idx = []; 13 | nums.forEach(function(item, index, array) { 14 | if (item === target) 15 | idx.push(index); 16 | }); 17 | 18 | if (!idx.length) 19 | return [-1, -1]; 20 | return [idx[0], idx[idx.length - 1]]; 21 | }; -------------------------------------------------------------------------------- /Algorithms/N-Queens II/n-queens-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/n-queens-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-09-11 4 | 5 | function dfs(l, r, c, index, n) { 6 | if (index === n) 7 | return 1; 8 | 9 | var ans = 0; 10 | 11 | for (var i = 0; i < n; i++) { 12 | var tmp = 1 << i; 13 | if ((tmp & l) || (tmp & r) || (tmp & c)) continue; 14 | ans += dfs((tmp | l) << 1, (tmp | r) >> 1, tmp | c, index + 1, n); 15 | } 16 | 17 | return ans; 18 | } 19 | 20 | var totalNQueens = function(n) { 21 | return dfs(0, 0, 0, 0, n); 22 | }; -------------------------------------------------------------------------------- /Algorithms/Contains Duplicate III/contains-duplicate-iii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate-iii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} k 8 | * @param {number} t 9 | * @return {boolean} 10 | */ 11 | var containsNearbyAlmostDuplicate = function(nums, k, t) { 12 | var len = nums.length; 13 | for (var i = 0; i < len; i++) 14 | for (var j = i + 1; j <= Math.min(i + k, len - 1); j++) 15 | if (Math.abs(nums[i] - nums[j]) <= t) return true; 16 | return false; 17 | }; -------------------------------------------------------------------------------- /Algorithms/Counting Bits/README.md: -------------------------------------------------------------------------------- 1 | There is a quick way to calculate the 1 bits in one number converting to a binary number, as below: 2 | 3 | ```javascript 4 | var hammingWeight = function(n) { 5 | n = ((n & 0xAAAAAAAA) >>> 1) + (n & 0x55555555); 6 | n = ((n & 0xCCCCCCCC) >>> 2) + (n & 0x33333333); 7 | n = ((n & 0xF0F0F0F0) >>> 4) + (n & 0x0F0F0F0F); 8 | n = ((n & 0xFF00FF00) >>> 8) + (n & 0x00FF00FF); 9 | n = ((n & 0xFFFF0000) >>> 16) + (n & 0x0000FFFF); 10 | return n; 11 | }; 12 | ``` 13 | 14 | It is not the best way to solve this problem, but it may be a hacking way. -------------------------------------------------------------------------------- /Algorithms/Number of Digit One/number-of-digit-one.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-digit-one/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-21 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var countDigitOne = function(n) { 10 | var len = n.toString().length, ans = 0; 11 | n++; 12 | 13 | var tmp = 1; 14 | for (var i = 0; i < len; i++) { 15 | ans += ~~(n / tmp / 10) * tmp; 16 | ans += (n % (tmp * 10) - tmp) > tmp ? tmp : Math.max(0, n % (tmp * 10) - tmp); 17 | tmp *= 10; 18 | } 19 | 20 | return ans; 21 | }; -------------------------------------------------------------------------------- /Algorithms/Plus One/plus-one.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/plus-one/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} digits 7 | * @return {number[]} 8 | */ 9 | 10 | var plusOne = function(digits) { 11 | var ans = [] 12 | , add = 0 13 | , len = digits.length; 14 | 15 | digits[len - 1]++; 16 | 17 | for(var i = len - 1; i >= 0; i--) { 18 | var sum = digits[i] + add; 19 | ans[i] = sum % 10; 20 | add = ~~(sum / 10); 21 | } 22 | 23 | if (add) 24 | ans.unshift(add); 25 | 26 | return ans; 27 | }; -------------------------------------------------------------------------------- /Algorithms/Ugly Number II/ugly-number-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ugly-number-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-19 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var nthUglyNumber = function(n) { 10 | var dp = [], a, b, c; 11 | dp[0] = 1, a = b = c = 0; 12 | 13 | for (var i = 1; i < n; i++) { 14 | dp[i] = Math.min(dp[a] * 2, dp[b] * 3, dp[c] * 5); 15 | if (dp[i] === dp[a] * 2) a++; 16 | if (dp[i] === dp[b] * 3) b++; 17 | if (dp[i] === dp[c] * 5) c++; 18 | } 19 | 20 | return dp[n - 1]; 21 | }; -------------------------------------------------------------------------------- /Algorithms/Best Time to Buy and Sell Stock/best-time-to-buy-and-sell-stock.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-01 4 | 5 | /** 6 | * @param {number[]} prices 7 | * @return {number} 8 | */ 9 | var maxProfit = function(prices) { 10 | var ans = 0; 11 | 12 | var len = prices.length; 13 | 14 | var minn = Infinity; 15 | 16 | for (var i = 0; i < len; i++) { 17 | minn = Math.min(minn, prices[i]); 18 | ans = Math.max(ans, prices[i] - minn); 19 | } 20 | 21 | return ans; 22 | 23 | }; -------------------------------------------------------------------------------- /Algorithms/Perfect Squares/perfect-squares.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/perfect-squares/ 2 | // Author : Han Zichi 3 | // Date : 2015-09-21 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var numSquares = function(n) { 10 | var dp = []; 11 | 12 | for (var i = 1; i <= n; i++) 13 | dp[i] = Infinity; 14 | 15 | dp[0] = 0; 16 | 17 | for (var i = 0; i <= n; i++) 18 | for (var j = 1; ; j++) { 19 | if (i + j * j > n) break; 20 | dp[i + j * j] = Math.min(dp[i + j * j], dp[i] + 1); 21 | } 22 | 23 | return dp[n]; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Remove Duplicates from Sorted Array/remove-duplicates-from-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-12 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var removeDuplicates = function(nums) { 11 | var ans = 0; 12 | for (var i = nums.length; i--; ) { 13 | if (i === nums.length - 1) 14 | ans++; 15 | else if (nums[i] === nums[i + 1]) 16 | nums.splice(i, 1); 17 | else 18 | ans++; 19 | } 20 | 21 | return ans; 22 | }; -------------------------------------------------------------------------------- /Algorithms/Valid Perfect Square/valid-perfect-square.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-perfect-square/ 2 | // Author : Han Zichi 3 | // Date : 2016-06-27 4 | 5 | /** 6 | * @param {number} num 7 | * @return {boolean} 8 | */ 9 | var isPerfectSquare = function(num) { 10 | var a = 0 11 | , b = num; 12 | 13 | while (a <= b) { 14 | var mid = (a + b) >> 1 15 | , ans = mid * mid; 16 | 17 | if (ans > num) 18 | b = mid - 1; 19 | else if (ans < num) 20 | a = mid + 1; 21 | else 22 | return true; 23 | } 24 | 25 | return false; 26 | }; -------------------------------------------------------------------------------- /Algorithms/Group Anagrams/anagrams.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/anagrams/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-12 4 | 5 | /** 6 | * @param {string[]} strs 7 | * @return {string[][]} 8 | */ 9 | var groupAnagrams = function(strs) { 10 | var ans = []; 11 | var hash = {}; 12 | 13 | strs.forEach(function(item) { 14 | var str = item.split('').sort().join(''); 15 | if (hash[str] === undefined) { 16 | hash[str] = ans.length; 17 | ans.push([item]); 18 | } else { 19 | ans[hash[str]].push(item); 20 | } 21 | }); 22 | 23 | return ans; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Longest Uncommon Subsequence I/longest-uncommon-subsequence-i.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/longest-uncommon-subsequence-i/#/description 2 | # Author : Han Zichi 3 | # Date : 2017-04-23 4 | 5 | class Solution(object): 6 | def findLUSlength(self, a, b): 7 | """ 8 | :type a: str 9 | :type b: str 10 | :rtype: int 11 | """ 12 | if a == b: 13 | return -1 14 | if a.find(b) != -1: 15 | return len(a) 16 | if b.find(a) != -1: 17 | return len(b) 18 | return max(len(a), len(b)) -------------------------------------------------------------------------------- /Algorithms/Merge Sorted Array/merge-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-sorted-array/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-12 4 | 5 | /** 6 | * @param {number[]} nums1 7 | * @param {number} m 8 | * @param {number[]} nums2 9 | * @param {number} n 10 | * @return {void} Do not return anything, modify nums1 in-place instead. 11 | */ 12 | 13 | var merge = function(nums1, m, nums2, n) { 14 | nums1.length = m, 15 | nums2.length = n; 16 | 17 | Array.prototype.push.apply(nums1, nums2); 18 | nums1.sort(function(a, b) { 19 | return a - b; 20 | }); 21 | }; -------------------------------------------------------------------------------- /Algorithms/Single Number III/single-number-iii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/single-number-iii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-18 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number[]} 8 | */ 9 | var singleNumber = function(nums) { 10 | var ans = [] 11 | , hash = []; 12 | 13 | nums.forEach(function(item) { 14 | if (!hash[item]) 15 | hash[item] = 1; 16 | else 17 | hash[item]++; 18 | }); 19 | 20 | nums.forEach(function(item) { 21 | if (hash[item] === 1) 22 | ans.push(item); 23 | }); 24 | 25 | return ans; 26 | }; -------------------------------------------------------------------------------- /Algorithms/Binary Tree Inorder Traversal/binary-tree-inorder-traversal.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val) { 4 | * this.val = val; 5 | * this.left = this.right = null; 6 | * } 7 | */ 8 | /** 9 | * @param {TreeNode} root 10 | * @return {number[]} 11 | */ 12 | 13 | function dfs(root, ans) { 14 | if (!root) return; 15 | 16 | dfs(root.left, ans); 17 | 18 | // 中序 19 | ans.push(root.val); 20 | 21 | dfs(root.right, ans); 22 | } 23 | 24 | var inorderTraversal = function(root) { 25 | var ans = []; 26 | dfs(root, ans); 27 | return ans; 28 | }; -------------------------------------------------------------------------------- /Algorithms/Minimum Moves to Equal Array Elements II/minimum-moves-to-equal-array-elements-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ 2 | // Author : Han Zichi 3 | // Date : 2016-11-20 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var minMoves2 = function(nums) { 10 | nums.sort(function(a, b) {return a - b;}); 11 | 12 | let len = nums.length; 13 | let midValue = nums[len >> 1]; 14 | let ans = 0; 15 | 16 | for (let i = 0; i < len; i++) 17 | ans += Math.abs(nums[i] - midValue); 18 | 19 | return ans; 20 | }; 21 | -------------------------------------------------------------------------------- /Algorithms/Container With Most Water/O(n).js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/container-with-most-water/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-07 4 | 5 | /** 6 | * @param {number[]} height 7 | * @return {number} 8 | */ 9 | var maxArea = function(height) { 10 | var start = 0 11 | , end = height.length - 1 12 | , maxn = 0; 13 | 14 | while (start <= end) { 15 | maxn = Math.max(maxn, Math.min(height[end], height[start]) * (end - start)); 16 | 17 | if (height[end] < height[start]) 18 | end --; 19 | else 20 | start ++; 21 | } 22 | 23 | return maxn; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Distribute Candies/distribute-candies.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/distribute-candies/description/ 2 | # Author : Fish.Yu 3 | # Date : 2017-12-26 4 | 5 | class Solution: 6 | def distributeCandies(self, candies): 7 | """ 8 | :type candies: List[int] 9 | :rtype: int 10 | """ 11 | d = {} 12 | for item in candies: 13 | if item in d: 14 | d[item] += 1 15 | else: 16 | d[item] = 1 17 | 18 | res = sorted(list(d.values())) 19 | 20 | return min(len(res), len(candies) >> 1) -------------------------------------------------------------------------------- /Algorithms/Happy Number/happy-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/happy-number/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number} n 7 | * @return {boolean} 8 | */ 9 | 10 | function add(n) { 11 | var ans = 0; 12 | while(n) { 13 | ans += (n % 10) * (n % 10); 14 | n /= 10; 15 | n = parseInt(n.toString()); 16 | } 17 | return ans; 18 | } 19 | 20 | var isHappy = function(n) { 21 | hash = []; 22 | while(n) { 23 | if (n === 1) return true; 24 | if (hash[n]) return false; 25 | hash[n] = true; 26 | n = add(n); 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/Perfect Number/perfect-number.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/perfect-number/#/description 2 | # Author : Han Zichi 3 | # Date : 2017-04-23 4 | 5 | import math 6 | class Solution(object): 7 | def checkPerfectNumber(self, num): 8 | """ 9 | :type num: int 10 | :rtype: bool 11 | """ 12 | if num <= 1: 13 | return False 14 | 15 | total = 1 16 | end = int(math.sqrt(num)) 17 | for i in range(2, end + 1): 18 | if num % i == 0: 19 | total += i + num / i 20 | 21 | return total == num -------------------------------------------------------------------------------- /Algorithms/Queue Reconstruction by Height/queue-reconstruction-by-height.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/queue-reconstruction-by-height/ 2 | // Author : Han Zichi 3 | // Date : 2016-09-26 4 | 5 | /** 6 | * @param {number[][]} people 7 | * @return {number[][]} 8 | */ 9 | var reconstructQueue = function(people) { 10 | people.sort(function(a, b) { 11 | if (a[0] !== b[0]) 12 | return b[0] - a[0]; 13 | return a[1] - b[1]; 14 | }); 15 | 16 | let ans = []; 17 | 18 | people.forEach(function(item) { 19 | ans.splice(item[1], 0, item); 20 | }); 21 | 22 | return ans; 23 | }; -------------------------------------------------------------------------------- /Algorithms/Sum of Square Numbers/sum-of-square-numbers.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/sum-of-square-numbers/description/ 2 | # Author : Han Zichi 3 | # Date : 2017-07-29 4 | 5 | import math 6 | 7 | class Solution: 8 | def judgeSquareSum(self, c): 9 | """ 10 | :type c: int 11 | :rtype: bool 12 | """ 13 | mid = math.floor(math.sqrt(c)) 14 | 15 | for i in range(0, mid + 1): 16 | rem = c - i * i 17 | if (rem == math.pow(math.floor(math.sqrt(rem)), 2)): 18 | return True 19 | 20 | return False 21 | 22 | obj = Solution() 23 | print(obj.judgeSquareSum(5)) -------------------------------------------------------------------------------- /Algorithms/Excel Sheet Column Title/excel-sheet-column-title.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/excel-sheet-column-title/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-26 4 | 5 | /** 6 | * @param {number} n 7 | * @return {string} 8 | */ 9 | var convertToTitle = function(n) { 10 | var ans = ''; 11 | while (n) { 12 | if (n % 26 === 0) { 13 | ans += String.fromCharCode(26 + 64); 14 | n = (n / 26) - 1; 15 | } 16 | else { 17 | ans += String.fromCharCode(n % 26 + 64); 18 | n = ~~(n / 26); 19 | } 20 | } 21 | 22 | return ans.split('').reverse().join(''); 23 | }; -------------------------------------------------------------------------------- /Algorithms/Longest Increasing Subsequence/README.md: -------------------------------------------------------------------------------- 1 | An easy `dynamic programming` problem. 2 | 3 | Given array `arr`, we can define another array `dp`, `dp[i]` means the length of longest increasing subsequence when the last item is `arr[i]`. How to get `dp[i]`? We can get it by enumerating from `index=0` to `index=i-1`(for instance j), and check the value of `arr[j]` and `arr[i]`, if `arr[i] > arr[j]`, then `dp[i]=max(dp[i],dp[j]+1)`. 4 | 5 | The algorithm above runs in O(n2) complexity, how to improve it to O(n log n) time complexity? Use binary search, see the code in detail. My runtime beats 100.00% of javascript submissions. -------------------------------------------------------------------------------- /Algorithms/Median of Two Sorted Arrays/O(nlogn).js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number[]} nums1 7 | * @param {number[]} nums2 8 | * @return {number} 9 | */ 10 | 11 | // the test data is weak, so.. 12 | 13 | var findMedianSortedArrays = function(nums1, nums2) { 14 | var s = nums1.concat(nums2); 15 | s.sort(function(a, b) { 16 | return a - b; 17 | }); 18 | 19 | var len = s.length; 20 | if (len & 1) return s[~~(len / 2)]; 21 | else return (s[len / 2 - 1] + s[len / 2]) / 2; 22 | }; -------------------------------------------------------------------------------- /Algorithms/Complex Number Multiplication/complex-number-multiplication.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/complex-number-multiplication/#/description 2 | # Author : Han Zichi 3 | # Date : 2017-04-23 4 | 5 | class Solution(object): 6 | def complexNumberMultiply(self, a, b): 7 | """ 8 | :type a: str 9 | :type b: str 10 | :rtype: str 11 | """ 12 | a = [int(i) for i in a[:-1].split('+')] 13 | b = [int(i) for i in b[:-1].split('+')] 14 | c = a[0] * b[0] - a[1] * b[1] 15 | d = a[0] * b[1] + a[1] * b[0] 16 | return str(c) + '+' + str(d) + 'i' -------------------------------------------------------------------------------- /Algorithms/Lexicographical Numbers/lexicographical-numbers.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/lexicographical-numbers/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-22 4 | 5 | var ans; 6 | var index; 7 | 8 | /** 9 | * @param {number} n 10 | * @return {number[]} 11 | */ 12 | var lexicalOrder = function(n) { 13 | ans = []; 14 | index = -1; 15 | 16 | for (var i = 1; i <= 9; i++) 17 | dfs(i, n); 18 | 19 | return ans; 20 | }; 21 | 22 | function dfs(num, n) { 23 | if (num > n) 24 | return; 25 | 26 | ans.push(num); 27 | 28 | for (var i = 0; i <= 9; i++) 29 | dfs(num * 10 + i, n); 30 | } -------------------------------------------------------------------------------- /Algorithms/String to Integer (atoi)/string-to-integer-atoi.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/string-to-integer-atoi/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-05 4 | 5 | /** 6 | * @param {string} str 7 | * @return {number} 8 | */ 9 | var myAtoi = function(str) { 10 | str = str.trim(); 11 | 12 | var pattern = /^(\-|\+)?[0-9]+/; 13 | var tmp = pattern.exec(str); 14 | 15 | if (tmp) { 16 | var num = Number(tmp[0]); 17 | if (num < -2147483648) 18 | return -2147483648; 19 | if (num > 2147483647) 20 | return 2147483647; 21 | return num; 22 | } 23 | 24 | return 0; 25 | }; -------------------------------------------------------------------------------- /Algorithms/Divide Two Integers/divide-two-integers.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/divide-two-integers/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-03 4 | 5 | /** 6 | * @param {number} dividend 7 | * @param {number} divisor 8 | * @return {number} 9 | */ 10 | var divide = function(dividend, divisor) { 11 | var MAX_POSITIVE_INT = ~(1 << 31); 12 | var MAX_NEGATIVE_INT = (1 << 31); 13 | 14 | var ans = Math.floor(dividend / divisor); 15 | 16 | if (ans < MAX_NEGATIVE_INT) 17 | ans = MAX_NEGATIVE_INT; 18 | 19 | if (ans > MAX_POSITIVE_INT) 20 | ans = MAX_POSITIVE_INT; 21 | 22 | return ans; 23 | }; -------------------------------------------------------------------------------- /Algorithms/Find All Duplicates in an Array/find-all-duplicates-in-an-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-all-duplicates-in-an-array/ 2 | // Author : Han Zichi 3 | // Date : 2016-12-28 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number[]} 8 | */ 9 | var findDuplicates = function(nums) { 10 | let len = nums.length; 11 | let ans = []; 12 | 13 | for (let i = 0; i < len; i++) { 14 | let item = nums[i]; 15 | let val = Math.abs(item) - 1; 16 | 17 | if (nums[val] < 0) 18 | ans.push(val + 1); 19 | else 20 | nums[val] *= -1; 21 | } 22 | 23 | return ans; 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/Reverse Linked List/indexⅢ.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-17 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @return {ListNode} 15 | */ 16 | 17 | var reverseList = function(head) { 18 | var pre = null; 19 | 20 | while (head) { 21 | var next = head.next; 22 | head.next = pre; 23 | pre = head; 24 | head = next; 25 | } 26 | 27 | return pre; 28 | }; 29 | 30 | -------------------------------------------------------------------------------- /Algorithms/Delete Node in a Linked List/delete-node-in-a-linked-list.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/delete-node-in-a-linked-list/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-12 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} node 14 | * @return {void} Do not return anything, modify node in-place instead. 15 | */ 16 | var deleteNode = function(node) { 17 | node.val = node.next.val; 18 | var tmp = node.next; 19 | node.next = node.next.next; 20 | tmp = null; 21 | }; -------------------------------------------------------------------------------- /Algorithms/Magical String/magical-string.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/magical-string/ 2 | // Author : Han Zichi 3 | // Date : 2017-01-10 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var magicalString = function(n) { 10 | let arr = [1, 2, 2]; 11 | let index = 2; 12 | 13 | while (arr.length < n) { 14 | let item = arr[arr.length - 1] === 2 ? 1 : 2; 15 | for (let i = 0; i < arr[index]; i++) 16 | arr[arr.length] = item; 17 | index++; 18 | } 19 | 20 | let ans = 0; 21 | for (let i = 0; i < n; i++) 22 | (arr[i] === 1) && ans++; 23 | 24 | return ans; 25 | }; 26 | -------------------------------------------------------------------------------- /Algorithms/Maximum Product Subarray/maximum-product-subarray.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-product-subarray/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-26 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var maxProduct = function(nums) { 10 | var ans = -Infinity 11 | , res = 1 12 | , tmp = 1; 13 | 14 | nums.forEach(function(item) { 15 | var _res = res * item 16 | , _tmp = tmp * item; 17 | 18 | ans = Math.max(ans, _res, _tmp); 19 | 20 | res = Math.max(_res, _tmp, 1); 21 | tmp = Math.min(_res, _tmp, 1); 22 | }); 23 | 24 | return ans; 25 | }; -------------------------------------------------------------------------------- /Algorithms/Contains Duplicate II/contains-duplicate-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} k 8 | * @return {boolean} 9 | */ 10 | 11 | var containsNearbyDuplicate = function(nums, k) { 12 | var pos = []; 13 | for(var i = 0, len = nums.length; i < len; i++) { 14 | if (pos[nums[i]] === undefined) 15 | pos[nums[i]] = i; 16 | else { 17 | if (i - pos[nums[i]] <= k) 18 | return true; 19 | pos[nums[i]] = i; 20 | } 21 | } 22 | 23 | return false; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Find All Numbers Disappeared in an Array/find-all-numbers-disappeared-in-an-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ 2 | // Author : Han Zichi 3 | // Date : 2016-11-04 4 | 5 | "use strict"; 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @return {number[]} 10 | */ 11 | var findDisappearedNumbers = function(nums) { 12 | let len = nums.length; 13 | let hash = {}; 14 | let ans = []; 15 | 16 | nums.forEach(function(item) { 17 | hash[item] = true; 18 | }); 19 | 20 | for (let i = 1; i <= len; i++) 21 | !hash[i] && (ans.push(i)); 22 | 23 | return ans; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Longest Palindrome/longest-palindrome.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-palindrome/ 2 | // Author : Han Zichi 3 | // Date : 2016-10-02 4 | 5 | "use strict"; 6 | /** 7 | * @param {string} s 8 | * @return {number} 9 | */ 10 | var longestPalindrome = function(s) { 11 | let hash = {}; 12 | 13 | for (let item of s) 14 | hash[item] = ~~hash[item] + 1; 15 | 16 | let exsitsOld = false; 17 | let ans = 0; 18 | 19 | for (let key in hash) { 20 | let cnt = hash[key]; 21 | ans += cnt & 1 ? cnt - 1 : cnt; 22 | (cnt & 1) && (exsitsOld = true); 23 | } 24 | 25 | return ans + exsitsOld; 26 | }; -------------------------------------------------------------------------------- /Algorithms/Two Sum II - Input array is sorted/two-sum-ii-input-array-is-sorted.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-19 4 | 5 | /** 6 | * @param {number[]} numbers 7 | * @param {number} target 8 | * @return {number[]} 9 | */ 10 | var twoSum = function(numbers, target) { 11 | var hash = {}; 12 | for (var i = 0, len = numbers.length; i < len; i++) { 13 | var item = target - numbers[i]; 14 | if (hash[item] === undefined) { 15 | hash[numbers[i]] = i; 16 | continue; 17 | } 18 | return [hash[item] + 1, i + 1]; 19 | } 20 | }; -------------------------------------------------------------------------------- /Algorithms/H-Index/h-index.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/h-index/ 2 | // Author : Han Zichi 3 | // Date : 2015-09-11 4 | 5 | /* You are here! 6 | Your runtime beats 100.00% of javascript submissions. 7 | I cannot believe my eyes */ 8 | 9 | var hIndex = function(citations) { 10 | var len = citations.length; 11 | for (var i = len; ; i--) { 12 | var cnt = 0 13 | , cnt_equal = 0; 14 | citations.forEach(function(item) { 15 | if (item > i) cnt++; 16 | if (item === i) cnt_equal++; 17 | }); 18 | 19 | if (cnt > i) continue; 20 | if (cnt + cnt_equal < i) continue; 21 | return i; 22 | } 23 | }; -------------------------------------------------------------------------------- /Algorithms/Rotate Function/rotate-function.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-function/ 2 | // Author : Han Zichi 3 | // Date : 2016-09-12 4 | 5 | /** 6 | * @param {number[]} A 7 | * @return {number} 8 | */ 9 | var maxRotateFunction = function(A) { 10 | var ans 11 | , sum = 0 12 | , tmp = 0 13 | , len = A.length; 14 | 15 | A.forEach(function(item, index) { 16 | sum += item; 17 | tmp += index * item; 18 | }); 19 | 20 | ans = tmp; 21 | 22 | while (A.length) { 23 | var last = A.pop(); 24 | tmp = tmp + sum - last * len; 25 | ans = Math.max(ans, tmp); 26 | } 27 | 28 | return ans; 29 | }; -------------------------------------------------------------------------------- /Algorithms/Rotate Image/rotate-image.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-image/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {number[][]} matrix 7 | * @return {void} Do not return anything, modify matrix in-place instead. 8 | */ 9 | var rotate = function(matrix) { 10 | var len = matrix.length 11 | , tmp = []; 12 | 13 | for (var i = 0; i < len; i++) { 14 | tmp [i] = []; 15 | for (var j = 0; j < len; j++) 16 | tmp[i][j] = matrix[i][j]; 17 | } 18 | 19 | for (var i = 0; i < len; i++) 20 | for (var j = 0; j < len; j++) 21 | matrix[i][j] = tmp[len - j - 1][i]; 22 | }; -------------------------------------------------------------------------------- /Algorithms/Kth Smallest Element in a Sorted Matrix/kth-smallest-element-in-a-sorted-matrix.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-01 4 | 5 | /** 6 | * @param {number[][]} matrix 7 | * @param {number} k 8 | * @return {number} 9 | */ 10 | var kthSmallest = function(matrix, k) { 11 | var arr = []; 12 | for (var i = 0, len = matrix.length; i < len; i++) 13 | for (var j = 0, _len = matrix[i].length; j < _len; j++) 14 | arr.push(matrix[i][j]); 15 | 16 | arr.sort(function(a, b) { 17 | return a - b; 18 | }); 19 | 20 | return arr[k - 1]; 21 | }; -------------------------------------------------------------------------------- /Algorithms/Remove Duplicates from Sorted Array II/remove-duplicates-from-sorted-array-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-12 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | var removeDuplicates = function(nums) { 11 | var ans = 0 12 | , hash = []; 13 | 14 | for (var i = nums.length; i--; ) { 15 | if (!hash[nums[i]]) 16 | hash[nums[i]] = 1, ans++; 17 | else if (hash[nums[i]] === 1) 18 | hash[nums[i]]++, ans++; 19 | else 20 | nums.splice(i, 1); 21 | } 22 | 23 | return ans; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Minimum Moves to Equal Array Elements/minimum-moves-to-equal-array-elements.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-moves-to-equal-array-elements/ 2 | // Author : Han Zichi 3 | // Date : 2016-11-15 4 | 5 | "use strict"; 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @return {number} 10 | */ 11 | var minMoves = function(nums) { 12 | let n = nums.length; 13 | let sum = 0; 14 | for (let i = 0; i < n; i++) 15 | sum += nums[i]; 16 | let minn = Math.min.apply(null, nums); 17 | 18 | for (let i = 0; ; i++) { 19 | if ((sum - i) % n) 20 | continue; 21 | 22 | return Math.max(sum - n * minn, i); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/Triangle/triangle.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/triangle/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number[][]} triangle 7 | * @return {number} 8 | */ 9 | 10 | var minimumTotal = function(triangle) { 11 | var n = triangle.length; 12 | var tmp = []; 13 | for(var i = 0; i <= n; i++) 14 | tmp[i] = []; 15 | for(var j = 0; j <= n; j++) 16 | tmp[n][j] = 0; 17 | 18 | for(var i = n - 1; i >= 0; i--) 19 | for(var j = 0; j < triangle[i].length; j++) { 20 | tmp[i][j] = Math.min(tmp[i + 1][j], tmp[i + 1][j + 1]) + triangle[i][j]; 21 | } 22 | 23 | return tmp[0][0]; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Count of Smaller Numbers After Self/README.md: -------------------------------------------------------------------------------- 1 | If you are Chinese, I suggest you reading [this article](http://www.cnblogs.com/zichi/p/5107442.html) written by me. 2 | 3 | Change a thought, give you an array, and count the smaller numbers before self. If the numbers before self are sorted, we can use binary search to find the answer, so we can enum the items of the array, ans maintain another array which is sorted, after one item is enumed, insert it to the sorted array using binary search. 4 | 5 | In fact, I solve the problem using Binary Indexed Tree at first which makes it really Complicated, also using discretization in it. 6 | 7 | Both solutions are right there. -------------------------------------------------------------------------------- /Algorithms/Course Schedule/README.md: -------------------------------------------------------------------------------- 1 | Use Topological Sort and BFS. 2 | 3 | The courses we can learn firstly are the ones that have no prerequisites, it's obvious! We can define an array `indegree`, indegree[i] means the number of prerequisites of course i, so when indegree[i] equals to 0, course i can be learned. Go on, we put i whose number of prerequisites is 0 to a queue, which means the course could be learned, and when the queue does a pop operation, we could update the array `indegree`, and if indegree[i] is 0, we could push i to the queue that means we could learn that course i. Until there is no item in the queue, check if we have already finished all the courses. 4 | 5 | -------------------------------------------------------------------------------- /Algorithms/Reverse Bits/reverse-bits.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-bits/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number} n - a positive integer 7 | * @return {number} - a positive integer 8 | */ 9 | 10 | var sum = []; 11 | sum[0] = 1; 12 | for(var i = 1; i <= 32; i++) 13 | sum[i] = 2 * sum[i - 1]; 14 | 15 | var reverseBits = function(n) { 16 | var tmp = n.toString(2); 17 | for(var i = tmp.length; i <= 31; i++) 18 | tmp = '0' + tmp; 19 | var ans = 0; 20 | for(var i = 0, len = tmp.length; i < len; i++) { 21 | if (tmp[i] === '1') 22 | ans += sum[i]; 23 | } 24 | return ans; 25 | }; -------------------------------------------------------------------------------- /Algorithms/Reverse Linked List/index.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-17 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @return {ListNode} 15 | */ 16 | 17 | var reverseList = function(head) { 18 | if (head === null || head.next === null) 19 | return head; 20 | 21 | var next = head.next; 22 | head.next = null; 23 | var newHead = reverseList(next); 24 | next.next = head; 25 | 26 | return newHead; 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /Algorithms/Validate IP Address/regexp_solution.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/validate-ip-address/ 2 | // Author : Han Zichi 3 | // Date : 2016-12-11 4 | 5 | /** 6 | * @param {string} IP 7 | * @return {string} 8 | */ 9 | var validIPAddress = function(IP) { 10 | 11 | function isIPv4(IP) { 12 | let p = /^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){4}$/; 13 | return p.test(IP + '.'); 14 | } 15 | 16 | function isIPv6(IP) { 17 | let p = /^([0-9a-fA-F]{1,4}:){8}$/; 18 | return p.test(IP + ':'); 19 | } 20 | 21 | if (isIPv4(IP)) 22 | return 'IPv4'; 23 | 24 | if (isIPv6(IP)) 25 | return 'IPv6'; 26 | 27 | return 'Neither'; 28 | }; 29 | -------------------------------------------------------------------------------- /Algorithms/House Robber/house-robber.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/house-robber/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var rob = function(nums) { 10 | var len = nums.length; 11 | if (!len) return 0; 12 | 13 | var dp = []; 14 | dp[0] = []; 15 | dp[0][0] = 0, // not steal 1st room 16 | dp[0][1] = nums[0]; // steal 1st room 17 | 18 | for (var i = 1; i < len; i++) { 19 | dp[i] = []; 20 | 21 | dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]); 22 | dp[i][1] = dp[i - 1][0] + nums[i]; 23 | } 24 | 25 | return Math.max(dp[len - 1][0], dp[len - 1][1]); 26 | }; -------------------------------------------------------------------------------- /Algorithms/Intersection of Two Arrays/intersection-of-two-arrays.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/intersection-of-two-arrays/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-20 4 | 5 | 6 | /** 7 | * @param {number[]} nums1 8 | * @param {number[]} nums2 9 | * @return {number[]} 10 | */ 11 | var intersection = function(nums1, nums2) { 12 | var hash = {}; 13 | 14 | nums1.forEach(function(item) { 15 | hash[item] = 1; 16 | }); 17 | 18 | nums2.forEach(function(item) { 19 | if (hash[item]) 20 | hash[item] = 2; 21 | }); 22 | 23 | var ans = []; 24 | 25 | for (var k in hash) 26 | hash[k] === 2 && (ans.push(+k)); 27 | 28 | return ans; 29 | }; -------------------------------------------------------------------------------- /Algorithms/Valid Parentheses/valid-parentheses.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-parentheses/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {string} s 7 | * @return {boolean} 8 | */ 9 | 10 | // stack use 11 | var isValid = function(s) { 12 | var sta = [], target = {}; 13 | target['('] = ')'; 14 | target['['] = ']'; 15 | target['{'] = '}'; 16 | for(var i = 0, len = s.length; i < len; i++) { 17 | if (!sta.length) sta.push(s[i]); 18 | else { 19 | if (s[i] === target[sta[sta.length - 1]]) 20 | sta.pop(); 21 | else 22 | sta.push(s[i]); 23 | } 24 | } 25 | 26 | return !sta.length; 27 | }; -------------------------------------------------------------------------------- /Algorithms/Generate Parentheses/generate-parentheses.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/generate-parentheses/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-23 4 | 5 | /** 6 | * @param {number} n 7 | * @return {string[]} 8 | */ 9 | 10 | var ans; 11 | 12 | function dfs(s, left, right, n) { 13 | if (left === n && right === n) { 14 | ans.push(s); 15 | return; 16 | } 17 | 18 | if (left + 1 <= n) 19 | dfs(s + '(', left + 1, right, n); 20 | 21 | if (right + 1 <= n && right + 1 <= left) 22 | dfs(s + ')', left, right + 1, n); 23 | 24 | } 25 | 26 | var generateParenthesis = function(n) { 27 | ans = []; 28 | dfs('', 0, 0, n); 29 | return ans; 30 | }; -------------------------------------------------------------------------------- /Algorithms/Unique Paths/unique-paths.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/unique-paths/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number} m 7 | * @param {number} n 8 | * @return {number} 9 | */ 10 | var uniquePaths = function(m, n) { 11 | var ans = []; 12 | for(var i = 0; i < m; i++) 13 | ans[i] = []; 14 | 15 | for(var i = 0; i < m; i++) 16 | for(var j = 0; j < n; j++) { 17 | if (i + j === 0) ans[i][j] = 1; 18 | else if (i === 0) ans[i][j] = ans[i][j - 1]; 19 | else if (j === 0) ans[i][j] = ans[i - 1][j]; 20 | else ans[i][j] = ans[i][j - 1] + ans[i - 1][j]; 21 | } 22 | 23 | return ans[m - 1][n - 1]; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Continuous Subarray Sum/continuous-subarray-sum.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/continuous-subarray-sum/?tab=Description 2 | # Author : Han Zichi 3 | # Date : 2017-03-01 4 | 5 | class Solution(object): 6 | def checkSubarraySum(self, nums, k): 7 | """ 8 | :type nums: List[int] 9 | :type k: int 10 | :rtype: bool 11 | """ 12 | sum, pre, s = 0, 0, set() 13 | 14 | for item in nums: 15 | sum += item 16 | if (k): 17 | sum %= k 18 | 19 | if (sum in s): 20 | return True 21 | 22 | s.add(pre) 23 | pre = sum 24 | 25 | return False 26 | -------------------------------------------------------------------------------- /Algorithms/Find the Duplicate Number/find-the-duplicate-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-the-duplicate-number/ 2 | // Author : Han Zichi 3 | // Date : 2016-01-20 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | // 时间复杂度O(n) & 空间复杂度O(n) 11 | // 如果要求时间复杂度O(nlogn) & 空间复杂度O(1) 的解法 12 | // 提供一种思路。用一个 string 存储数字,用一个特殊字符隔开 13 | // 比如 "1,2,2,3,3,4,5,6" 14 | // 然后二分查找,插入,因为插入只是 string 的简单拼接,所以速度应该不慢 15 | 16 | var findDuplicate = function(nums) { 17 | var hash = {}; 18 | for (var i = 0, len = nums.length; i < len; i++) { 19 | var item = nums[i]; 20 | if (!hash[item]) 21 | hash[item] = true; 22 | else 23 | return item; 24 | } 25 | }; -------------------------------------------------------------------------------- /Algorithms/Isomorphic Strings/isomorphic-strings.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/isomorphic-strings/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-13 4 | 5 | /** 6 | * @param {string} s 7 | * @param {string} t 8 | * @return {boolean} 9 | */ 10 | var isIsomorphic = function(s, t) { 11 | if (s.length !== t.length) 12 | return false; 13 | 14 | var len = s.length 15 | , hash = {} 16 | , _hash = {}; 17 | 18 | for (var i = 0; i < len; i++) { 19 | var a = s[i] 20 | , b = t[i]; 21 | 22 | if (!hash[a] && !_hash[b]) 23 | hash[a] = b, _hash[b] = a; 24 | else if (hash[a] !== b || _hash[b] !== a) 25 | return false; 26 | } 27 | 28 | return true; 29 | }; -------------------------------------------------------------------------------- /Algorithms/Search Insert Position/search-insert-position.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-insert-position/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} target 8 | * @return {number} 9 | */ 10 | 11 | var searchInsert = function(nums, target) { 12 | var hash = []; 13 | for (var i = 0, len = nums.length; i < len; i++) 14 | hash[nums[i]] = i; 15 | if (hash[target] !== undefined) 16 | return hash[target]; 17 | 18 | nums[-1] = -Number.MAX_VALUE; 19 | nums[len] = Number.MAX_VALUE; 20 | 21 | for (var i = 0; i <= len; i++) 22 | if (nums[i - 1] < target && target < nums[i]) 23 | return i; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Set Matrix Zeroes/set-matrix-zeroes.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/set-matrix-zeroes/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {number[][]} matrix 7 | * @return {void} Do not return anything, modify matrix in-place instead. 8 | */ 9 | 10 | var setZeroes = function(matrix) { 11 | var n = matrix.length; 12 | var m = matrix[0].length; 13 | var a = [], b = []; 14 | 15 | for(var i = 0; i < n; i++) 16 | for(var j = 0; j < m; j++) 17 | if (matrix[i][j] === 0) 18 | a[i] = b[j] = true; 19 | 20 | for(var i = 0; i < n; i++) 21 | for(var j = 0; j < m; j++) 22 | if (a[i] || b[j]) 23 | matrix[i][j] = 0; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Add Strings/add-strings.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-strings/ 2 | // Author : Han Zichi 3 | // Date : 2016-10-09 4 | 5 | // "use strict"; 6 | 7 | /** 8 | * @param {string} num1 9 | * @param {string} num2 10 | * @return {string} 11 | */ 12 | var addStrings = function(num1, num2) { 13 | let [i, j] = [num1.length, num2.length]; 14 | let ans = ''; 15 | let add = 0; 16 | 17 | i -= 1, j -= 1; 18 | for ( ; i >= 0 || j >= 0; i--, j--) { 19 | let a = i >= 0 ? +num1[i] : 0; 20 | let b = j >= 0 ? +num2[j] : 0; 21 | let sum = a + b + add; 22 | ans = sum % 10 + ans; 23 | add = ~~(sum / 10); 24 | } 25 | 26 | add && (ans = add + ans); 27 | return ans; 28 | }; -------------------------------------------------------------------------------- /Algorithms/Binary Tree Preorder Traversal/binary-tree-preorder-traversal.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-preorder-traversal/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-18 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number[]} 15 | */ 16 | function dfs(root, ans) { 17 | if (!root) return; 18 | ans.push(root.val); 19 | 20 | dfs(root.left, ans); 21 | dfs(root.right, ans); 22 | } 23 | 24 | var preorderTraversal = function(root) { 25 | var ans = []; 26 | dfs(root, ans); 27 | return ans; 28 | }; -------------------------------------------------------------------------------- /Algorithms/Integer Break/integer-break.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/integer-break/ 2 | // Author : Han Zichi 3 | // Date : 2016-04-26 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var integerBreak = function(n) { 10 | // n === 2 and n === 3 are special cases 11 | if (n === 2) 12 | return 1; 13 | 14 | if (n === 3) 15 | return 2; 16 | 17 | var dp = []; 18 | 19 | dp[0] = 1; 20 | dp[1] = 1; 21 | 22 | for (var i = 2; i <= n; i++) 23 | dp[i] = -1; 24 | 25 | for (var i = 2; i <= n; i++) 26 | // j + (i - j) = i; 27 | for (var j = 0; j < i; j++) { 28 | dp[i] = Math.max(dp[i], dp[j] * (i - j)); 29 | } 30 | 31 | return dp[n]; 32 | }; -------------------------------------------------------------------------------- /Algorithms/Maximum XOR of Two Numbers in an Array/README.md: -------------------------------------------------------------------------------- 1 | Clear solution [here](https://discuss.leetcode.com/topic/63213/java-o-n-solution-using-bit-manipulation-and-hashmap) and [here](https://discuss.leetcode.com/topic/63299/python-6-lines-bit-by-bit). 2 | 3 | > Build the answer bit by bit from left to right. Let's say we already know the largest first seven bits we can create. How to find the largest first eight bits we can create? Well it's that maximal seven-bits prefix followed by 0 or 1. Append 0 and then try to create the 1 one (i.e., answer ^ 1) from two eight-bits prefixes from nums. If we can, then change that 0 to 1. 4 | 5 | And also remember this: 6 | 7 | A ^ B = C 8 | => (A ^ C = B) & (B ^ C = A) -------------------------------------------------------------------------------- /Algorithms/Arithmetic Slices/arithmetic-slices.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/arithmetic-slices/ 2 | // Author : Han Zichi 3 | // Date : 2016-10-17 4 | 5 | "use strict"; 6 | 7 | /** 8 | * @param {number[]} A 9 | * @return {number} 10 | */ 11 | var numberOfArithmeticSlices = function(A) { 12 | let len = A.length; 13 | let ans = 0; 14 | 15 | for (let i = 0; i < len; i++) { 16 | let diff; 17 | let num = 2; 18 | for (let j = i + 1; j < len; j++) { 19 | if (j === i + 1) 20 | diff = A[j] - A[i]; 21 | else if (A[j] - A[j - 1] === diff) 22 | num++; 23 | else 24 | break; 25 | } 26 | 27 | ans += num - 2; 28 | } 29 | 30 | return ans; 31 | }; -------------------------------------------------------------------------------- /Algorithms/Combination Sum IV/combination-sum-iv.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/combination-sum-iv/ 2 | // Author : Han Zichi 3 | // Date : 2016-07-26 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} target 8 | * @return {number} 9 | */ 10 | var combinationSum4 = function(nums, target) { 11 | // ans[i] 表示组成 i 的方案数 12 | var ans = []; 13 | ans[0] = 1; 14 | 15 | for (var i = 1; i <= target; i++) { 16 | ans[i] = 0; 17 | for (var j = 0, len = nums.length; j < len; j++) { 18 | var item = nums[j]; 19 | if (i - item < 0) 20 | continue; 21 | // (i - item) + item = i 22 | ans[i] += ans[i - item]; 23 | } 24 | } 25 | 26 | return ans[target]; 27 | }; -------------------------------------------------------------------------------- /Algorithms/Invert Binary Tree/invert-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/invert-binary-tree/ 2 | // Author : Han Zichi 3 | // Date : 2016-04-30 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {TreeNode} 15 | */ 16 | var invertTree = function(root) { 17 | if (!root) 18 | return root; 19 | 20 | var left = root.left; 21 | 22 | var right = root.right; 23 | 24 | left && invertTree(left); 25 | 26 | right && invertTree(right); 27 | 28 | root.left = right; 29 | root.right = left; 30 | 31 | return root; 32 | }; -------------------------------------------------------------------------------- /Algorithms/Longest Common Prefix/longest-common-prefix.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-common-prefix/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {string[]} strs 7 | * @return {string} 8 | */ 9 | var longestCommonPrefix = function(strs) { 10 | if (!strs.length) return ''; 11 | 12 | var len = strs.reduce(function(pre, item) { 13 | return Math.min(pre, item.length); 14 | }, Number.MAX_VALUE); 15 | 16 | var ans = ''; 17 | for (var i = 0; i < len; i++) { 18 | var a = strs[0][i]; 19 | var f = strs.every(function(item) { 20 | return item[i] === a; 21 | }); 22 | 23 | if (!f) break; 24 | ans += a; 25 | } 26 | 27 | return ans; 28 | }; -------------------------------------------------------------------------------- /Algorithms/Majority Element II/majority-element-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/majority-element-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number[]} 8 | */ 9 | 10 | var majorityElement = function(nums) { 11 | var hash_num = [] 12 | , len = nums.length 13 | , ans = [] 14 | , hash_ans = []; 15 | 16 | nums.forEach(function(item, index, array) { 17 | if (!hash_num[item]) 18 | hash_num[item] = 1; 19 | else 20 | hash_num[item]++; 21 | 22 | if (!hash_ans[item] && hash_num[item] > len / 3) { 23 | hash_ans[item] = true; 24 | ans.push(item); 25 | } 26 | }); 27 | 28 | return ans; 29 | }; -------------------------------------------------------------------------------- /Algorithms/Minimum Size Subarray Sum/minimum-size-subarray-sum.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-size-subarray-sum/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number} s 7 | * @param {number[]} nums 8 | * @return {number} 9 | */ 10 | 11 | var minSubArrayLen = function(s, nums) { 12 | var ans = Number.MAX_VALUE; 13 | var n = nums.length; 14 | // start pos 15 | for (var i = 0; i < n; i++) { 16 | var sum = 0; 17 | for (var j = i; j < n; j++) { 18 | sum += nums[j]; 19 | if (sum < s) continue; 20 | if (j - i + 1 >= ans) break; 21 | ans = j - i + 1; 22 | break; 23 | } 24 | } 25 | 26 | return ans === Number.MAX_VALUE ? 0 : ans; 27 | }; -------------------------------------------------------------------------------- /Algorithms/Perfect Squares/README.md: -------------------------------------------------------------------------------- 1 | Solved by `dynamic programming`. 2 | 3 | define an array named `dp`, and `dp[i]` means the fewest number that can make up `i`, we can enum 1, 4, 9 .. and update the value `dp[i]` at the same time. 4 | 5 | See the code below: 6 | 7 | ```javascript 8 | /** 9 | * @param {number} n 10 | * @return {number} 11 | */ 12 | var numSquares = function(n) { 13 | var dp = []; 14 | 15 | for (var i = 1; i <= n; i++) 16 | dp[i] = Infinity; 17 | 18 | dp[0] = 0; 19 | 20 | for (var i = 0; i <= n; i++) 21 | for (var j = 1; ; j++) { 22 | if (i + j * j > n) break; 23 | dp[i + j * j] = Math.min(dp[i + j * j], dp[i] + 1); 24 | } 25 | 26 | return dp[n]; 27 | }; 28 | ``` -------------------------------------------------------------------------------- /Algorithms/Beautiful Arrangement/beautiful-arrangement.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/beautiful-arrangement/?tab=Description 2 | // Author : Han Zichi 3 | // Date : 2017-02-27 4 | 5 | /** 6 | * @param {number} N 7 | * @return {number} 8 | */ 9 | var countArrangement = function(N) { 10 | let [ans, hash] = [0, {}]; 11 | 12 | let dfs = (index) => { 13 | if (index === N + 1) { 14 | ans++; 15 | return; 16 | } 17 | 18 | for (let i = 1; i <= N; i++) { 19 | if (!hash[i] && (index % i === 0 || i % index === 0)) { 20 | hash[i] = true; 21 | dfs(index + 1); 22 | hash[i] = false; 23 | } 24 | } 25 | }; 26 | 27 | dfs(1); 28 | return ans; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/Best Time to Buy and Sell Stock II/best-time-to-buy-and-sell-stock-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-01 4 | 5 | /** 6 | * @param {number[]} prices 7 | * @return {number} 8 | */ 9 | var maxProfit = function(prices) { 10 | prices.push(0); 11 | 12 | var len = prices.length; 13 | var sum = 0; 14 | var begin; 15 | 16 | for (var i = 0; i < len; i++) { 17 | if (i === 0) { 18 | begin = prices[i]; 19 | continue; 20 | } 21 | 22 | if (prices[i] >= prices[i - 1]) 23 | continue; 24 | 25 | sum += (prices[i - 1] - begin); 26 | begin = prices[i]; 27 | } 28 | 29 | return sum; 30 | }; -------------------------------------------------------------------------------- /Algorithms/Binary Tree Postorder Traversal/binary-tree-postorder-traversal.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-postorder-traversal/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-25 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number[]} 15 | */ 16 | 17 | function dfs(root, ans) { 18 | if (!root) return; 19 | 20 | dfs(root.left, ans); 21 | dfs(root.right, ans); 22 | 23 | ans.push(root.val); 24 | } 25 | 26 | var postorderTraversal = function(root) { 27 | var ans = []; 28 | dfs(root, ans); 29 | return ans; 30 | }; -------------------------------------------------------------------------------- /Algorithms/Count Primes/count-primes.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/count-primes/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-26 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | 10 | var countPrimes = function(n) { 11 | // if modified to 'var hash = []' 12 | // it will be Memory Limit Exceeded 13 | // I don't know why 14 | // I think both are the same 15 | var hash = new Array(n) 16 | , a = Math.sqrt(n); 17 | 18 | for (var i = 2; i <= a; i++) { 19 | if (!hash[i]) 20 | for (var j = i * i; j < n; j += i) 21 | hash[j] = true; 22 | } 23 | 24 | var ans = 0; 25 | for (var i = 2; i < n; i++) 26 | if (!hash[i]) 27 | ans ++; 28 | 29 | return ans; 30 | }; -------------------------------------------------------------------------------- /Algorithms/Counting Bits/counting-bits.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/counting-bits/ 2 | // Author : Han Zichi 3 | // Date : 2016-03-25 4 | 5 | /** 6 | * @param {number} num 7 | * @return {number[]} 8 | */ 9 | var countBits = function(num) { 10 | var ans = Array(num + 1); 11 | for (var i = 0; i <= num; i++) 12 | ans[i] = hammingWeight(i); 13 | 14 | return ans; 15 | }; 16 | 17 | var hammingWeight = function(n) { 18 | n = ((n & 0xAAAAAAAA) >>> 1) + (n & 0x55555555); 19 | n = ((n & 0xCCCCCCCC) >>> 2) + (n & 0x33333333); 20 | n = ((n & 0xF0F0F0F0) >>> 4) + (n & 0x0F0F0F0F); 21 | n = ((n & 0xFF00FF00) >>> 8) + (n & 0x00FF00FF); 22 | n = ((n & 0xFFFF0000) >>> 16) + (n & 0x0000FFFF); 23 | return n; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Palindrome Linked List/palindrome-linked-list.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/palindrome-linked-list/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-12 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @return {boolean} 15 | */ 16 | var isPalindrome = function(head) { 17 | var ans = []; 18 | while (head) { 19 | var tmp = head.val; 20 | ans.push(tmp); 21 | head = head.next; 22 | } 23 | 24 | for(var i = 0, len = ans.length; i < len; i++) 25 | if (ans[i] !== ans[len - 1 - i]) 26 | return false; 27 | 28 | return true; 29 | }; -------------------------------------------------------------------------------- /Algorithms/Patching Array/patching-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/patching-array/ 2 | // Author : Han Zichi 3 | // Date : 2016-01-31 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} n 8 | * @return {number} 9 | */ 10 | 11 | // 如果没有任何数字,则尽量选取 1, 2, 4, 8, 16 12 | var minPatches = function(nums, n) { 13 | var sum = 0; 14 | var index = 0; 15 | var ans = 0; 16 | 17 | while (sum < n) { 18 | if (nums[index] === undefined) { 19 | sum = sum * 2 + 1; 20 | ans++; 21 | } else { 22 | if (sum + 1 < nums[index]) { 23 | ans++; 24 | sum = sum * 2 + 1; 25 | } else { 26 | sum += nums[index++]; 27 | } 28 | } 29 | } 30 | 31 | return ans; 32 | }; -------------------------------------------------------------------------------- /Algorithms/Reverse String II/reverse-string-ii.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/reverse-string-ii/#/description 2 | # Author : Han Zichi 3 | # Date : 2017-04-23 4 | 5 | class Solution(object): 6 | def reverseStr(self, s, k): 7 | """ 8 | :type s: str 9 | :type k: int 10 | :rtype: str 11 | """ 12 | l = len(s) 13 | tmp = [] 14 | 15 | for i in range(0, l, k * 2): 16 | tmp.append(s[i:i+k*2]) 17 | 18 | ans = '' 19 | for item in tmp: 20 | if k <= len(item) <= k * 2: 21 | ans += item[0:k][::-1] + item[k:min(k*2, len(item))] 22 | else: 23 | ans += item[::-1] 24 | 25 | return ans -------------------------------------------------------------------------------- /Algorithms/Subsets/subsets.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/subsets/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-20 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number[][]} 8 | */ 9 | var ans, res, len; 10 | 11 | function dfs(index, nums) { 12 | var tmp = res.map(function(item) { 13 | return item; 14 | }); 15 | 16 | ans.push(tmp); 17 | 18 | for (var i = index; i < len; i++) { 19 | res.push(nums[i]); 20 | dfs(i + 1, nums); 21 | res.pop(); 22 | } 23 | } 24 | 25 | var subsets = function(nums) { 26 | nums.sort(function(a, b) { 27 | return a - b; 28 | }); 29 | 30 | ans = [], 31 | res = [], 32 | len = nums.length; 33 | 34 | dfs(0, nums); 35 | 36 | return ans; 37 | }; -------------------------------------------------------------------------------- /Algorithms/Compare Version Numbers/compare-version-numbers.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/compare-version-numbers/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-02 4 | 5 | /** 6 | * @param {string} version1 7 | * @param {string} version2 8 | * @return {number} 9 | */ 10 | var compareVersion = function(version1, version2) { 11 | var a = version1.split('.'); 12 | var b = version2.split('.'); 13 | 14 | var len1 = a.length; 15 | var len2 = b.length; 16 | for (var i = 0, len = Math.max(len1, len2); i < len; i++) { 17 | var item1 = i < len1 ? +a[i] : 0; 18 | var item2 = i < len2 ? +b[i] : 0; 19 | 20 | if (item1 > item2) 21 | return 1; 22 | 23 | if (item1 < item2) 24 | return -1; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/Pascal's Triangle/pascals-triangle.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/pascals-triangle/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {number} numRows 7 | * @return {number[][]} 8 | */ 9 | var generate = function(numRows) { 10 | var ans = []; 11 | 12 | for (var i = 0; i < numRows; i++) { 13 | if (i === 0) { 14 | ans[i] = [1]; 15 | continue; 16 | } 17 | 18 | ans[i] = []; 19 | for (var j = 0; j <= i; j++) 20 | if (j === 0) 21 | ans[i][j] = ans[i - 1][j]; 22 | else if (j === i) 23 | ans[i][j] = ans[i - 1][j - 1]; 24 | else 25 | ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]; 26 | } 27 | 28 | return ans; 29 | }; -------------------------------------------------------------------------------- /Algorithms/Coin Change/README.md: -------------------------------------------------------------------------------- 1 | An easy dynamic programming problem. 2 | 3 | We define `ans[i]` as the fewest numbers that we can make up the amount `i`, and if can not, we define it as the value `undefined`, then we can enum every number that the array `coins` give, update the array `ans`, finally to check the value `ans[amount]`. 4 | 5 | The recursion is as below: 6 | 7 | ```javascript 8 | for (var i = 0, len = coins.length; i < len; i++) { 9 | var item = coins[i]; 10 | for (var j = 0; j + item <= amount; j++) { 11 | if (ans[j] === undefined) 12 | continue; 13 | if (ans[j + item] === undefined) 14 | ans[j + item] = ans[j] + 1; 15 | else 16 | ans[j + item] = Math.min(ans[j + item], ans[j] + 1); 17 | } 18 | } 19 | ``` -------------------------------------------------------------------------------- /Algorithms/Daily Temperatures/daily-temperatures.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/daily-temperatures/description/ 2 | // Author : Fish.Yu 3 | // Date : 2017-12-26 4 | 5 | /** 6 | * @param {number[]} temperatures 7 | * @return {number[]} 8 | */ 9 | var dailyTemperatures = function(temperatures) { 10 | let hash = [] 11 | let ans = [] 12 | 13 | for (let i = temperatures.length; i--; ) { 14 | let temperature = temperatures[i] 15 | ans[i] = Infinity 16 | 17 | for (let j = temperature + 1; j <= 100; j++) { 18 | if (hash[j] && hash[j] - i < ans[i]) { 19 | ans[i] = hash[j] - i 20 | } 21 | } 22 | 23 | if (ans[i] === Infinity) ans[i] = 0 24 | hash[temperature] = i 25 | } 26 | 27 | return ans 28 | }; -------------------------------------------------------------------------------- /Algorithms/Maximum Depth of Binary Tree/maximum-depth-of-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-17 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number} 15 | */ 16 | var maxn; 17 | 18 | function dfs(root, depth) { 19 | if (!root) { 20 | maxn = Math.max(maxn, depth); 21 | return; 22 | } 23 | 24 | dfs(root.left, depth + 1); 25 | dfs(root.right, depth + 1); 26 | } 27 | 28 | var maxDepth = function(root) { 29 | maxn = -1; 30 | dfs(root, 0); 31 | return maxn; 32 | }; -------------------------------------------------------------------------------- /Algorithms/Pascal's Triangle II/pascals-triangle-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/pascals-triangle-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {number} rowIndex 7 | * @return {number[]} 8 | */ 9 | var getRow = function(rowIndex) { 10 | var ans = []; 11 | 12 | for (var i = 0; i < rowIndex + 1; i++) { 13 | if (i === 0) { 14 | ans[i] = [1]; 15 | continue; 16 | } 17 | 18 | ans[i] = []; 19 | for (var j = 0; j <= i; j++) 20 | if (j === 0) 21 | ans[i][j] = ans[i - 1][j]; 22 | else if (j === i) 23 | ans[i][j] = ans[i - 1][j - 1]; 24 | else 25 | ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]; 26 | } 27 | 28 | return ans[rowIndex]; 29 | }; -------------------------------------------------------------------------------- /Algorithms/Teemo Attacking/teemo-attacking.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/teemo-attacking/ 2 | // Author : Han Zichi 3 | // Date : 2017-02-04 4 | 5 | /** 6 | * @param {number[]} timeSeries 7 | * @param {number} duration 8 | * @return {number} 9 | */ 10 | var findPoisonedDuration = function(timeSeries, duration) { 11 | let ans = 0; 12 | 13 | for (let i = 0, len = timeSeries.length; i < len; i++) { 14 | if (i === len - 1) { 15 | ans += duration; 16 | continue; 17 | } 18 | 19 | let curItem = timeSeries[i] 20 | , nextItem = timeSeries[i + 1]; 21 | 22 | if (curItem + duration <= nextItem) 23 | ans += duration; 24 | else 25 | ans += nextItem - curItem; 26 | } 27 | 28 | return ans; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/Binary Tree Tilt/binary-tree-tilt.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-tilt/description/ 2 | // Author : Fish.Yu 3 | // Date : 2017-12-26 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number} 15 | */ 16 | var findTilt = function(root) { 17 | function sumOfNode(root) { 18 | if (!root) return 0 19 | 20 | let left = sumOfNode(root.left) 21 | let right = sumOfNode(root.right) 22 | 23 | ans += Math.abs(left - right) 24 | 25 | return left + right + root.val 26 | } 27 | 28 | let ans = 0 29 | sumOfNode(root) 30 | return ans 31 | }; -------------------------------------------------------------------------------- /Algorithms/Longest Consecutive Sequence/longest-consecutive-sequence.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-consecutive-sequence/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-21 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var longestConsecutive = function(nums) { 10 | var hash = []; 11 | nums.forEach(function(item) { 12 | hash[item] = true; 13 | }); 14 | 15 | var ans = -1; 16 | nums.forEach(function(item, idx) { 17 | // this item is the largest in the sequence 18 | if (!hash[item + 1]) { 19 | var tmp = 0, index = item; 20 | while (hash[index]) { 21 | tmp++; 22 | index--; 23 | } 24 | ans = Math.max(ans, tmp); 25 | } 26 | }); 27 | 28 | return ans; 29 | }; -------------------------------------------------------------------------------- /Algorithms/Nth Digit/nth-digit.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/nth-digit/ 2 | // Author : Han Zichi 3 | // Date : 2016-09-18 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var findNthDigit = function(n) { 10 | return dfs(1, n); 11 | 12 | function dfs(digits, left) { 13 | let start = Math.pow(10, digits - 1); 14 | let last = Math.pow(10, digits) - 1; 15 | let len = last - start + 1; 16 | let num = len * digits; 17 | 18 | if (num < left) 19 | return dfs(digits + 1, left - num); 20 | else { 21 | let remainder = left % digits ? left % digits : digits; 22 | let rightNumber = Math.ceil(left / digits) - 1 + start; 23 | 24 | return +String(rightNumber)[remainder - 1]; 25 | } 26 | } 27 | }; -------------------------------------------------------------------------------- /Algorithms/Random Pick Index/random-pick-index.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/random-pick-index/#/description 2 | # Author : Han Zichi 3 | # Date : 2017-04-23 4 | 5 | import random 6 | class Solution(object): 7 | 8 | def __init__(self, nums): 9 | """ 10 | 11 | :type nums: List[int] 12 | :type numsSize: int 13 | """ 14 | self.nums = nums 15 | 16 | def pick(self, target): 17 | """ 18 | :type target: int 19 | :rtype: int 20 | """ 21 | array = [] 22 | for index, item in enumerate(self.nums): 23 | if item == target: 24 | array.append(index) 25 | 26 | index = int(random.random() * len(array)) 27 | return array[index] 28 | -------------------------------------------------------------------------------- /Algorithms/Add Binary/add-binary.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-binary/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-10 4 | 5 | /** 6 | * @param {string} a 7 | * @param {string} b 8 | * @return {string} 9 | */ 10 | 11 | var addBinary = function(a, b) { 12 | a = a.split('').reverse(); 13 | b = b.split('').reverse(); 14 | 15 | var c = []; 16 | var add = 0; 17 | 18 | for(var i = 0, len = Math.max(a.length, b.length);i < len; i++) { 19 | var sum = (a[i] === undefined ? 0 : Number(a[i])) + (b[i] === undefined ? 0: Number(b[i])) + add; 20 | c[i] = sum & 1; 21 | if (sum >= 2) 22 | add = 1; 23 | else 24 | add = 0; 25 | } 26 | 27 | if (add) 28 | c[len] = 1; 29 | 30 | return c.reverse().join('').toString(); 31 | }; -------------------------------------------------------------------------------- /Algorithms/Best Time to Buy and Sell Stock II/dp_solution.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-11 4 | 5 | /** 6 | * @param {number[]} prices 7 | * @return {number} 8 | */ 9 | var maxProfit = function(prices) { 10 | if (!prices.length) 11 | return 0; 12 | 13 | var buy = [] 14 | , sell = []; 15 | 16 | prices.forEach(function(item, index) { 17 | if (!index) { 18 | buy[index] = -item; 19 | sell[index] = 0; 20 | } else { 21 | buy[index] = Math.max(buy[index - 1], sell[index - 1] - item); 22 | sell[index] = Math.max(sell[index - 1], buy[index - 1] + item); 23 | } 24 | }); 25 | 26 | var len = prices.length; 27 | return sell[len - 1]; 28 | }; -------------------------------------------------------------------------------- /Algorithms/License Key Formatting/license-key-formatting.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/license-key-formatting/ 2 | // Author : Han Zichi 3 | // Date : 2017-01-11 4 | // Runtime: 86 ms 5 | 6 | // Your runtime beats 100.00% of javascript submissions 7 | 8 | /** 9 | * @param {string} S 10 | * @param {number} K 11 | * @return {string} 12 | */ 13 | var licenseKeyFormatting = function(S, K) { 14 | S = S.toUpperCase().replace(/-/g, ''); 15 | 16 | let ans = []; 17 | let index = 0; 18 | 19 | if (S.length % K) { 20 | let str = S.substr(0, S.length % K); 21 | ans.push(str); 22 | index = S.length % K; 23 | } 24 | 25 | for (let i = index, len = S.length; i < len; i += K) 26 | ans.push(S.substr(i, K)); 27 | 28 | return ans.join('-'); 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/Symmetric Tree/clever-recursion-solution.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/symmetric-tree/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-05 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {boolean} 15 | */ 16 | var isSymmetric = function(root) { 17 | if (!root) 18 | return true; 19 | 20 | return isMirror(root.left, root.right); 21 | }; 22 | 23 | function isMirror(a, b) { 24 | if (!a && !b) 25 | return true; 26 | 27 | if (!a || !b) 28 | return false; 29 | 30 | return (a.val === b.val) && isMirror(a.left, b.right) && isMirror(a.right, b.left); 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/Find Bottom Left Tree Value/find-bottom-left-tree-value.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-bottom-left-tree-value/ 2 | // Author : Han Zichi 3 | // Date : 2017-02-17 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number} 15 | */ 16 | var findBottomLeftValue = function(root) { 17 | let res = []; 18 | 19 | let dfs = (node, step) => { 20 | if (res[step] === undefined) 21 | res[step] = node.val; 22 | 23 | node.left && dfs(node.left, step + 1); 24 | node.right && dfs(node.right, step + 1); 25 | }; 26 | 27 | dfs(root, 0); 28 | return res.pop(); 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/Friend Circles/friend-circles.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/friend-circles/#/description 2 | # Author : Han Zichi 3 | # Date : 2017-04-23 4 | 5 | class Solution(object): 6 | def findCircleNum(self, M): 7 | """ 8 | :type M: List[List[int]] 9 | :rtype: int 10 | """ 11 | def dfs(index): 12 | hash[index] = True 13 | for index, item in enumerate(M[index]): 14 | if hash[index] == False and item == 1: 15 | dfs(index) 16 | 17 | n = len(M) 18 | ans = 0 19 | hash = [False] * n 20 | 21 | for i in range(n): 22 | if hash[i] == False: 23 | ans += 1 24 | dfs(i) 25 | 26 | return ans -------------------------------------------------------------------------------- /Algorithms/Minimum Time Difference/minimum-time-difference.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-time-difference/#/description 2 | // Author : Han Zichi 3 | // Date : 2016-03-26 4 | 5 | /** 6 | * @param {string[]} timePoints 7 | * @return {number} 8 | */ 9 | var findMinDifference = function(timePoints) { 10 | let helper = str => { 11 | let arr = str.split(':'); 12 | return +arr[0] * 60 + (+arr[1]); 13 | }; 14 | 15 | timePoints = timePoints.map(helper); 16 | timePoints = [...timePoints, ...timePoints.map(item => item + 60 * 24)]; 17 | timePoints.sort((a, b) => a - b); 18 | 19 | let ans = Infinity; 20 | for (let i = 1, len = timePoints.length; i < len; i++) 21 | ans = Math.min(ans, timePoints[i] - timePoints[i - 1]); 22 | 23 | return ans; 24 | }; -------------------------------------------------------------------------------- /Algorithms/Repeated Substring Pattern/repeated-substring-pattern.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/repeated-substring-pattern/ 2 | // Author : Han Zichi 3 | // Date : 2016-11-16 4 | 5 | "use strict"; 6 | 7 | /** 8 | * @param {string} str 9 | * @return {boolean} 10 | */ 11 | var repeatedSubstringPattern = function(str) { 12 | let len = str.length; 13 | 14 | loop: 15 | for (let i = 2; i <= len; i++) { // divided into i parts 16 | if (len % i ) continue; 17 | 18 | let partLen = len / i; 19 | let base = str.substr(0, partLen); 20 | 21 | for (let j = partLen; j < len; j += partLen) { 22 | let sub = str.substr(j, partLen); 23 | if (base !== sub) continue loop; 24 | } 25 | 26 | return true; 27 | } 28 | 29 | return false; 30 | }; 31 | -------------------------------------------------------------------------------- /Algorithms/Roman to Integer/roman-to-integer.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/roman-to-integer/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-04 4 | 5 | /** 6 | * @param {string} s 7 | * @return {number} 8 | */ 9 | var romanToInt = function(s) { 10 | var hash = {}; 11 | hash["I"] = 1; 12 | hash["X"] = 10; 13 | hash["C"] = 100; 14 | hash["M"] = 1000; 15 | hash["V"] = 5; 16 | hash["L"] = 50; 17 | hash["D"] = 500; 18 | 19 | var sum = 0; 20 | 21 | for (var i = 0, len = s.length; i < len; i++) { 22 | var item = hash[s[i]]; 23 | 24 | var nextItem = i + 1 === len ? 0 : hash[s[i + 1]]; 25 | 26 | if (nextItem > item) { 27 | sum += nextItem - item; 28 | i++; 29 | } else 30 | sum += item; 31 | } 32 | 33 | return sum; 34 | }; -------------------------------------------------------------------------------- /Algorithms/Same Tree/index.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/same-tree/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-17 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} p 14 | * @param {TreeNode} q 15 | * @return {boolean} 16 | */ 17 | var isSameTree = function(p, q) { 18 | if (p === null && q === null) return true; 19 | if (p === null && q !== null) return false; 20 | if (p !== null && q === null) return false; 21 | 22 | // p & q not null 23 | if (p.val !== q.val) return false; 24 | 25 | var a = isSameTree(p.left, q.left) 26 | , b = isSameTree(p.right, q.right); 27 | 28 | return a && b; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/Sort Characters By Frequency/sort-characters-by-frequency.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sort-characters-by-frequency/ 2 | // Author : Han Zichi 3 | // Date : 2016-11-04 4 | 5 | "use strict"; 6 | 7 | /** 8 | * @param {string} s 9 | * @return {string} 10 | */ 11 | var frequencySort = function(s) { 12 | let hash = {}; 13 | for (let item of s) 14 | hash[item] = ~~hash[item] + 1; 15 | 16 | let arr = []; 17 | Object.keys(hash).forEach(function(item) { 18 | arr.push({item: item, count: hash[item]}); 19 | }); 20 | 21 | arr.sort(function(a, b) { 22 | return b.count - a.count; 23 | }); 24 | 25 | let ans = ''; 26 | arr.forEach(function(item) { 27 | while (item.count--) 28 | ans += item.item; 29 | }); 30 | 31 | return ans; 32 | }; -------------------------------------------------------------------------------- /Algorithms/Coin Change/coin-change.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/coin-change/ 2 | // Author : Han Zichi 3 | // Date : 2016-01-20 4 | 5 | /** 6 | * @param {number[]} coins 7 | * @param {number} amount 8 | * @return {number} 9 | */ 10 | var coinChange = function(coins, amount) { 11 | var ans = []; 12 | ans[0] = 0; 13 | 14 | for (var i = 0, len = coins.length; i < len; i++) { 15 | var item = coins[i]; 16 | for (var j = 0; j + item <= amount; j++) { 17 | if (ans[j] === undefined) 18 | continue; 19 | if (ans[j + item] === undefined) 20 | ans[j + item] = ans[j] + 1; 21 | else 22 | ans[j + item] = Math.min(ans[j + item], ans[j] + 1); 23 | } 24 | 25 | } 26 | 27 | return ans[amount] === undefined ? -1 : ans[amount]; 28 | }; -------------------------------------------------------------------------------- /Algorithms/Count Numbers with Unique Digits/count-numbers-with-unique-digits.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/count-numbers-with-unique-digits/ 2 | // Author : Han Zichi 3 | // Date : 2016-06-13 4 | 5 | /** 6 | * @param {number} n 7 | * @return {number} 8 | */ 9 | var countNumbersWithUniqueDigits = function(n) { 10 | if (!n) 11 | return 1; 12 | 13 | var ans = 0; 14 | 15 | for (var i = 1; i <= n; i++) { 16 | if (i === 1) 17 | ans += 10; 18 | else if (i <= 10) { 19 | ans += A(10, i); 20 | ans -= A(9, i - 1); 21 | } else { 22 | break; 23 | } 24 | } 25 | 26 | return ans; 27 | }; 28 | 29 | 30 | function A(a, b) { 31 | var ans = 1; 32 | 33 | for (var i = a; i >= a - b + 1; i--) 34 | ans *= i; 35 | 36 | return ans; 37 | } -------------------------------------------------------------------------------- /Algorithms/Keyboard Row/keyboard-row.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/keyboard-row/ 2 | // Author : Han Zichi 3 | // Date : 2017-02-07 4 | 5 | /** 6 | * @param {string[]} words 7 | * @return {string[]} 8 | */ 9 | var findWords = function(words) { 10 | let keys = [ 11 | 'qwertyuiop', 12 | 'asdfghjkl', 13 | 'zxcvbnm' 14 | ]; 15 | 16 | let ans = []; 17 | 18 | words.forEach(function(item) { 19 | let s = new Set(); 20 | let word = item.toLowerCase(); 21 | 22 | for (let letter of word) { 23 | for (let i = 0; i < 3; i++) 24 | if (keys[i].indexOf(letter) !== -1) { 25 | s.add(i); 26 | break; 27 | } 28 | } 29 | 30 | if (s.size === 1) 31 | ans.push(item); 32 | }); 33 | 34 | return ans; 35 | }; 36 | -------------------------------------------------------------------------------- /Algorithms/Matchsticks to Square/README.md: -------------------------------------------------------------------------------- 1 | At first, I think it over in the wrong way. We define `sum` as the sum of the total length, I think if there is a way to reach the goal, any combination that can reach `sum / 4` can be a side of the four sides of the square. 2 | 3 | It's wrong! If the array is `[5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3]`, obviously it can make up a square, and `[4, 4, 4]` can be a side of the square, but if we choose them from the array, the remaining cannot make another three sides! (can make only one side, use `[5, 4, 3]`) 4 | 5 | So I use simple depth-first search with backtrace. 6 | 7 | PS: At first I use `sort` to resort the array from large to small, but it seems that it makes no sense in leetcode, but I think it's of use to cut down the times of recursions in the depth-first search. 8 | -------------------------------------------------------------------------------- /Algorithms/Top K Frequent Elements/top-k-frequent-elements.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/top-k-frequent-elements/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-01 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} k 8 | * @return {number[]} 9 | */ 10 | var topKFrequent = function(nums, k) { 11 | var obj = {}; 12 | nums.forEach(function(item) { 13 | if (!obj[item]) 14 | obj[item] = 1; 15 | else 16 | obj[item]++; 17 | }); 18 | 19 | var arr = []; 20 | 21 | for (var key in obj) { 22 | arr.push({key: key, value: obj[key]}); 23 | } 24 | 25 | arr.sort(function(a, b) { 26 | return b.value - a.value; 27 | }); 28 | 29 | var ans = []; 30 | for (var i = 0; i < k; i++) 31 | ans.push(+arr[i].key); 32 | 33 | return ans; 34 | }; -------------------------------------------------------------------------------- /Algorithms/Balanced Binary Tree/balanced-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/balanced-binary-tree/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {boolean} 15 | */ 16 | 17 | var ans; 18 | 19 | function dfs(root) { 20 | if (!root) return; 21 | 22 | var a = root.left ? dfs(root.left) : 0 23 | , b = root.right ? dfs(root.right) : 0; 24 | 25 | if (Math.abs(a - b) > 1) { 26 | ans = false; 27 | } 28 | 29 | return Math.max(a, b) + 1; 30 | } 31 | 32 | var isBalanced = function(root) { 33 | ans = true; 34 | dfs(root); 35 | return ans; 36 | }; -------------------------------------------------------------------------------- /Algorithms/Convert a Number to Hexadecimal/convert-a-number-to-hexadecimal.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/convert-a-number-to-hexadecimal/ 2 | // Author : Han Zichi 3 | // Date : 2016-09-26 4 | 5 | /** 6 | * @param {number} num 7 | * @return {string} 8 | */ 9 | var toHex = function(num) { 10 | if (num > 0) 11 | return help(num); 12 | else if (num === 0) 13 | return '0'; 14 | else { 15 | num = -num; 16 | return help(0xffffffff - num + 1); 17 | } 18 | 19 | function help(num) { 20 | let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; 21 | let ans = ''; 22 | 23 | while (num) { 24 | let mod = num % 16; 25 | ans = arr[mod] + ans; 26 | num = ~~(num / 16); 27 | } 28 | 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /Algorithms/Implement Queue using Stacks/implement-queue-using-stacks.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/implement-queue-using-stacks/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @constructor 7 | */ 8 | var Queue = function() { 9 | this.a = []; 10 | }; 11 | 12 | /** 13 | * @param {number} x 14 | * @returns {void} 15 | */ 16 | Queue.prototype.push = function(x) { 17 | this.a.push(x); 18 | }; 19 | 20 | /** 21 | * @returns {void} 22 | */ 23 | Queue.prototype.pop = function() { 24 | this.a.shift(); 25 | }; 26 | 27 | /** 28 | * @returns {number} 29 | */ 30 | Queue.prototype.peek = function() { 31 | return this.a[0]; 32 | }; 33 | 34 | /** 35 | * @returns {boolean} 36 | */ 37 | Queue.prototype.empty = function() { 38 | return this.a.length ? false : true; 39 | }; -------------------------------------------------------------------------------- /Algorithms/Insertion Sort List/insertion-sort-list.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/insertion-sort-list/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-17 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @return {ListNode} 15 | */ 16 | var insertionSortList = function(head) { 17 | var ans = []; 18 | while (head) { 19 | ans.push(new ListNode(head.val)); 20 | head = head.next; 21 | } 22 | 23 | ans.sort(function(a, b) { 24 | return a.val - b.val; 25 | }); 26 | 27 | if (!ans.length) return null; 28 | for (var i = 0, len = ans.length; i < len - 1; i++) 29 | ans[i].next = ans[i + 1]; 30 | 31 | return ans[0]; 32 | }; -------------------------------------------------------------------------------- /Algorithms/Product of Array Except Self/product-of-array-except-self.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/product-of-array-except-self/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number[]} 8 | */ 9 | 10 | function fn(array, idx) { 11 | var ans = 1; 12 | array.forEach(function(item, index, array) { 13 | if (idx !== index) 14 | ans *= item; 15 | }); 16 | 17 | return ans; 18 | } 19 | 20 | var productExceptSelf = function(nums) { 21 | var tmp = nums.reduce(function(pre, cur, index, array) { 22 | return pre * cur; 23 | }); 24 | 25 | var ans = nums.map(function(item, index, array) { 26 | if (item === 0) 27 | return fn(array, index); 28 | return tmp / item; 29 | }); 30 | 31 | return ans; 32 | }; -------------------------------------------------------------------------------- /Algorithms/Total Hamming Distance/total-hamming-distance.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/total-hamming-distance/ 2 | // Author : Han Zichi 3 | // Date : 2016-12-21 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var totalHammingDistance = function(nums) { 10 | let one = [] 11 | , len = nums.length; 12 | 13 | nums.forEach(function(item) { 14 | let index = 0; 15 | while (item) { 16 | if (item & 1) 17 | one[index] = ~~one[index] + 1; 18 | 19 | item >>= 1; 20 | index++; 21 | } 22 | }); 23 | 24 | let ans = 0; 25 | for (let i = 0, oneLen = one.length; i < oneLen; i++) { 26 | let oneNum = ~~one[i] 27 | , zeroNum = len - oneNum; 28 | 29 | ans += oneNum * zeroNum; 30 | } 31 | 32 | return ans; 33 | }; 34 | -------------------------------------------------------------------------------- /Algorithms/Count Complete Tree Nodes/better-recursion.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/count-complete-tree-nodes/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-31 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number} 15 | */ 16 | var countNodes = function(root) { 17 | if (!root) 18 | return 0; 19 | 20 | var l = findDepth(root.left) 21 | , r = findDepth(root.right); 22 | 23 | if (l === r) 24 | return (1 << l) + countNodes(root.right); 25 | else 26 | return (1 << r) + countNodes(root.left); 27 | 28 | function findDepth(node) { 29 | return node ? 1 + findDepth(node.left) : 0; 30 | } 31 | }; -------------------------------------------------------------------------------- /Algorithms/Reverse Linked List/indexⅡ.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-17 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @return {ListNode} 15 | */ 16 | 17 | var reverseList = function(head) { 18 | var ans = []; 19 | 20 | while (head) { 21 | var node = new ListNode(head.val); 22 | ans.push(node); 23 | head = head.next; 24 | } 25 | 26 | ans.reverse(); 27 | 28 | if (!ans.length) 29 | return null; 30 | 31 | for (var i = 0, len = ans.length; i < len - 1; i++) { 32 | ans[i].next = ans[i + 1]; 33 | } 34 | 35 | return ans[0]; 36 | }; 37 | 38 | -------------------------------------------------------------------------------- /Algorithms/Sort List/sort-list.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sort-list/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @return {ListNode} 15 | */ 16 | var sortList = function(head) { 17 | if (head === null) 18 | return null; 19 | 20 | var tmp = []; 21 | while (head) { 22 | var node = new ListNode(head.val); 23 | tmp.push(node); 24 | head = head.next; 25 | } 26 | 27 | tmp.sort(function(a, b) { 28 | return a.val - b.val; 29 | }); 30 | 31 | for (var i = 0, len = tmp.length; i < len - 1; i++) 32 | tmp[i].next = tmp[i + 1]; 33 | 34 | return tmp[0]; 35 | }; -------------------------------------------------------------------------------- /Algorithms/Linked List Cycle/linked-list-cycle.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/linked-list-cycle/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-02 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | 13 | /** 14 | * @param {ListNode} head 15 | * @return {boolean} 16 | */ 17 | var hasCycle = function(head) { 18 | flag = false; 19 | 20 | dfs(head); 21 | 22 | return flag; 23 | }; 24 | 25 | function dfs(node) { 26 | if (flag) 27 | return; 28 | 29 | if (node === null) 30 | return; 31 | 32 | if (node.flag) { 33 | flag = true; 34 | return; 35 | } 36 | 37 | if (node.next === null) 38 | return; 39 | 40 | node.flag = true; 41 | 42 | dfs(node.next); 43 | } -------------------------------------------------------------------------------- /Algorithms/Ransom Note/ransom-note.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ransom-note/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-11 4 | 5 | // notice: don't try to apply for a large memory 6 | // for you will get a MLE(Memory Limit Exceeded) error 7 | 8 | /** 9 | * @param {string} ransomNote 10 | * @param {string} magazine 11 | * @return {boolean} 12 | */ 13 | var canConstruct = function(ransomNote, magazine) { 14 | hash = {}; 15 | for (var i = 0, len = ransomNote.length; i < len; i++) { 16 | var item = ransomNote[i]; 17 | 18 | for (var j = 0, _len = magazine.length; j < _len; j++) { 19 | if (hash[j] || magazine[j] !== item) 20 | continue; 21 | hash[j] = true; 22 | break; 23 | } 24 | if (j === _len) 25 | return false; 26 | } 27 | return true; 28 | }; -------------------------------------------------------------------------------- /Algorithms/Sum of Left Leaves/sum-of-left-leaves.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sum-of-left-leaves/ 2 | // Author : Han Zichi 3 | // Date : 2016-09-26 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number} 15 | */ 16 | var sumOfLeftLeaves = function(root) { 17 | let ans = 0; 18 | 19 | root && root.left && dfs(root.left, 1); 20 | root && root.right && dfs(root.right, 0); 21 | 22 | function dfs(node, pos) { 23 | pos && node && !node.left && !node.right && (ans += node.val); 24 | 25 | node && node.left && dfs(node.left, 1); 26 | node && node.right && dfs(node.right, 0); 27 | } 28 | 29 | return ans; 30 | }; -------------------------------------------------------------------------------- /Algorithms/Implement Stack using Queues/implement-stack-using-queues.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/implement-stack-using-queues/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @constructor 7 | */ 8 | var Stack = function() { 9 | this.a = []; 10 | }; 11 | 12 | /** 13 | * @param {number} x 14 | * @returns {void} 15 | */ 16 | Stack.prototype.push = function(x) { 17 | this.a.push(x); 18 | }; 19 | 20 | /** 21 | * @returns {void} 22 | */ 23 | Stack.prototype.pop = function() { 24 | this.a.pop(); 25 | }; 26 | 27 | /** 28 | * @returns {number} 29 | */ 30 | Stack.prototype.top = function() { 31 | return this.a[this.a.length - 1]; 32 | }; 33 | 34 | /** 35 | * @returns {boolean} 36 | */ 37 | Stack.prototype.empty = function() { 38 | return !this.a.length ? true : false; 39 | }; -------------------------------------------------------------------------------- /Algorithms/Lonely Pixel I/lonely-pixel-i.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/lonely-pixel-i/?tab=Description 2 | # Author : Han Zichi 3 | # Date : 2017-03-06 4 | 5 | class Solution(object): 6 | def findLonelyPixel(self, picture): 7 | """ 8 | :type picture: List[List[str]] 9 | :rtype: int 10 | """ 11 | rows, ans = [], 0 12 | n, m = len(picture), len(picture[0]) 13 | 14 | for item in picture: 15 | rows.append(item.count('B')) 16 | 17 | # Column j 18 | for j in range(m): 19 | letters = [picture[i][j] for i in range(n)] 20 | if letters.count('B') == 1: 21 | pos = letters.index('B') # Row pos 22 | if rows[pos] == 1: 23 | ans += 1 24 | 25 | return ans 26 | -------------------------------------------------------------------------------- /Algorithms/Next Greater Element I/next-greater-element-i.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/next-greater-element-i/ 2 | // Author : Han Zichi 3 | // Date : 2017-02-07 4 | 5 | /** 6 | * @param {number[]} findNums 7 | * @param {number[]} nums 8 | * @return {number[]} 9 | */ 10 | var nextGreaterElement = function(findNums, nums) { 11 | let ans = []; 12 | let len = nums.length; 13 | 14 | findNums.forEach((item) => { 15 | let pos = nums.indexOf(item); 16 | let hasNextGreaterElement = false; 17 | 18 | for (let i = pos + 1; i < len; i++) { 19 | if (nums[i] > item) { 20 | ans.push(nums[i]); 21 | hasNextGreaterElement = true; 22 | break; 23 | } 24 | } 25 | 26 | if (!hasNextGreaterElement) 27 | ans.push(-1); 28 | }); 29 | 30 | return ans; 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/Remove Nth Node From End of List/remove-nth-node-from-end-of-list.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-02 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @param {number} n 15 | * @return {ListNode} 16 | */ 17 | var removeNthFromEnd = function(head, n) { 18 | var arr = []; 19 | 20 | while (head) { 21 | arr.push(new ListNode(head.val)); 22 | head = head.next; 23 | } 24 | 25 | arr.splice(-n, 1); 26 | 27 | for (var i = 0, len = arr.length; i < len - 1; i++) 28 | arr[i].next = arr[i + 1]; 29 | 30 | return arr.length === 0 ? null : arr[0]; 31 | }; -------------------------------------------------------------------------------- /Algorithms/4Sum II/4sum-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/4sum-ii/ 2 | // Author : Han Zichi 3 | // Date : 2016-11-16 4 | 5 | /** 6 | * @param {number[]} A 7 | * @param {number[]} B 8 | * @param {number[]} C 9 | * @param {number[]} D 10 | * @return {number} 11 | */ 12 | var fourSumCount = function(A, B, C, D) { 13 | let p = new Map(); 14 | for (let i = 0, lenA = A.length; i < lenA; i++) 15 | for (let j = 0, lenB = B.length; j < lenB; j++) { 16 | let sum = A[i] + B[j]; 17 | let count = ~~p.get(sum); 18 | p.set(sum, count + 1); 19 | } 20 | 21 | let ans = 0; 22 | for (let i = 0, lenC = C.length; i < lenC; i++) 23 | for (let j = 0, lenD = D.length; j < lenD; j++) { 24 | let sum = C[i] + D[j]; 25 | ans += ~~p.get(-sum); 26 | } 27 | 28 | return ans; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/Linked List Cycle II/linked-list-cycle-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/linked-list-cycle-ii/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-22 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | 13 | /** 14 | * @param {ListNode} head 15 | * @return {ListNode} 16 | */ 17 | var detectCycle = function(head) { 18 | flag = null; 19 | 20 | dfs(head); 21 | 22 | return flag; 23 | }; 24 | 25 | function dfs(node) { 26 | if (flag) 27 | return; 28 | 29 | if (node === null) 30 | return; 31 | 32 | if (node.flag) { 33 | flag = node; 34 | return; 35 | } 36 | 37 | if (node.next === null) 38 | return; 39 | 40 | node.flag = true; 41 | 42 | dfs(node.next); 43 | } -------------------------------------------------------------------------------- /Algorithms/Permutations/permutations.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/permutations/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-20 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number[][]} 8 | */ 9 | var ans, res, hash, len; 10 | 11 | function dfs(num, nums) { 12 | if (num === len) { 13 | var tmp = res.map(function(item) { 14 | return item; 15 | }); 16 | 17 | ans.push(tmp); 18 | return; 19 | } 20 | 21 | for (var i = 0; i < len; i++) { 22 | if (hash[i]) continue; 23 | hash[i] = true; 24 | res.push(nums[i]); 25 | dfs(num + 1, nums); 26 | hash[i] = false; 27 | res.pop(); 28 | } 29 | } 30 | 31 | var permute = function(nums) { 32 | len = nums.length, 33 | ans = [], 34 | res = [], 35 | hash = []; 36 | 37 | dfs(0, nums); 38 | return ans; 39 | }; -------------------------------------------------------------------------------- /Algorithms/Verify Preorder Serialization of a Binary Tree/verify-preorder-serialization-of-a-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-29 4 | 5 | /** 6 | * @param {string} preorder 7 | * @return {boolean} 8 | */ 9 | var isValidSerialization = function(preorder) { 10 | var ans = preorder.split(','); 11 | var s = [{left: true}]; 12 | 13 | for (var i = 0, len = ans.length; i < len; i++) { 14 | var item = ans[i]; 15 | 16 | if (s.length) { 17 | var last = s[s.length - 1]; 18 | if (!last.left) 19 | last.left = true; 20 | else { 21 | s.pop(); 22 | } 23 | } else 24 | return false; 25 | 26 | item !== '#' && s.push({}); 27 | } 28 | 29 | return !s.length; 30 | }; -------------------------------------------------------------------------------- /Algorithms/Median of Two Sorted Arrays/O(n).js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-10 4 | 5 | /** 6 | * @param {number[]} nums1 7 | * @param {number[]} nums2 8 | * @return {number} 9 | */ 10 | 11 | var findMedianSortedArrays = function(nums1, nums2) { 12 | // 合并数组,返回有序数组 13 | var s = merge(nums1, nums2); 14 | 15 | var len = s.length; 16 | 17 | // 根据数组长度求中位数 18 | if (len & 1) return s[~~(len / 2)]; 19 | else return (s[len / 2 - 1] + s[len / 2]) / 2; 20 | }; 21 | 22 | function merge(left, right) { 23 | var tmp = []; 24 | 25 | while (left.length && right.length) { 26 | if (left[0] < right[0]) 27 | tmp.push(left.shift()); 28 | else 29 | tmp.push(right.shift()); 30 | } 31 | 32 | return tmp.concat(left, right); 33 | } -------------------------------------------------------------------------------- /Algorithms/Path Sum/path-sum.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/path-sum/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @param {number} sum 15 | * @return {boolean} 16 | */ 17 | 18 | 19 | var hasPathSum = function(root, sum) { 20 | if (!root) 21 | return false; 22 | 23 | if (!root.left && !root.right) { 24 | if (root.val === sum) 25 | return true; 26 | return false; 27 | } 28 | 29 | if (root.left) 30 | var a = hasPathSum(root.left, sum - root.val); 31 | 32 | if (root.right) 33 | var b = hasPathSum(root.right, sum - root.val); 34 | 35 | return Boolean(a || b); 36 | }; -------------------------------------------------------------------------------- /Algorithms/Reverse Vowels of a String/reverse-vowels-of-a-string.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-four/ 2 | // Author : Han Zichi 3 | // Date : 2016-04-26 4 | 5 | /** 6 | * @param {string} s 7 | * @return {string} 8 | */ 9 | var reverseVowels = function(s) { 10 | var vowelString = "aeiouAEIOU" 11 | , arr = s.split('') 12 | , len = arr.length; 13 | 14 | var vowelArr = []; 15 | 16 | for (var i = 0; i < len; i++) { 17 | if (vowelString.indexOf(arr[i]) !== -1) 18 | vowelArr.push(arr[i]); 19 | } 20 | 21 | vowelArr.reverse(); 22 | 23 | var ansStr = '' 24 | , idx = 0; 25 | 26 | for (var i = 0; i < len; i++) { 27 | if (vowelString.indexOf(arr[i]) !== -1) 28 | ansStr += vowelArr[idx++]; 29 | else 30 | ansStr += arr[i]; 31 | } 32 | 33 | return ansStr; 34 | }; -------------------------------------------------------------------------------- /Algorithms/Find Largest Value in Each Tree Row/find-largest-value-in-each-tree-row.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-largest-value-in-each-tree-row/ 2 | // Author : Han Zichi 3 | // Date : 2017-02-17 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number[]} 15 | */ 16 | var largestValues = function(root) { 17 | let maxn = []; 18 | 19 | let getMax = (a, b = -Number.MAX_VALUE) => Math.max(a, b); 20 | 21 | let dfs = (node, step) => { 22 | if (!node) return; 23 | maxn[step] = getMax(node.val, maxn[step]); 24 | dfs(node.left, step + 1); 25 | dfs(node.right, step + 1); 26 | }; 27 | 28 | dfs(root, 0); 29 | return maxn; 30 | }; 31 | 32 | -------------------------------------------------------------------------------- /Algorithms/Guess Number Higher or Lower/guess-number-higher-or-lower.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/guess-number-higher-or-lower/ 2 | // Author : Han Zichi 3 | // Date : 2016-07-21 4 | 5 | // Forward declaration of guess API. 6 | // @param num, your guess 7 | // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 8 | int guess(int num); 9 | 10 | class Solution { 11 | public: 12 | int guessNumber(int n) { 13 | int start = 1, end = n; 14 | int ans; 15 | 16 | while (start <= end) { 17 | int mid = start + (end - start) / 2; 18 | int val = guess(mid); 19 | 20 | if (val == -1) 21 | end = mid - 1; 22 | else if (val == 1) 23 | start = mid + 1; 24 | else { 25 | ans = mid; 26 | break; 27 | } 28 | } 29 | 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /Algorithms/Rectangle Area/index_best_solution.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rectangle-area/ 2 | // Author : Han Zichi 3 | // Date : 2016-01-18 4 | 5 | /** 6 | * @param {number} A 7 | * @param {number} B 8 | * @param {number} C 9 | * @param {number} D 10 | * @param {number} E 11 | * @param {number} F 12 | * @param {number} G 13 | * @param {number} H 14 | * @return {number} 15 | */ 16 | var computeArea = function(A, B, C, D, E, F, G, H) { 17 | // use Vanilla JS if want to be faster 18 | // http://vanilla-js.com/ 19 | var width = (C - A) + (G - E) - Math.abs(Math.max(G, C) - Math.min(E, A)) ; 20 | width < 0 && (width = 0); 21 | 22 | var height = (D - B) + (H - F) - Math.abs(Math.max(H, D) - Math.min(F, B)); 23 | height < 0 && (width = 0); 24 | 25 | return (C - A) * (D - B) + (G - E) * (H - F) - width * height; 26 | }; -------------------------------------------------------------------------------- /Algorithms/Combination Sum III/combination-sum-iii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/combination-sum-iii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {number} k 7 | * @param {number} n 8 | * @return {number[][]} 9 | */ 10 | 11 | function dfs(arr, last, num, k, sum, n) { 12 | if (num === k && sum === n) { 13 | var tmp = arr.map(function(item) { 14 | return item; 15 | }); 16 | 17 | ans.push(tmp); 18 | return; 19 | } 20 | 21 | if (num > k || sum > n ) 22 | return; 23 | 24 | for(var i = last + 1; i <= 9; i++) { 25 | arr[arr.length] = i; 26 | dfs(arr, i, num + 1, k, sum + i, n); 27 | arr.pop(); 28 | } 29 | } 30 | 31 | var combinationSum3 = function(k, n) { 32 | ans = []; 33 | for(var i = 1; i <= 9; i++) 34 | dfs([i], i, 1, k, i, n); 35 | return ans; 36 | }; -------------------------------------------------------------------------------- /Algorithms/Simplify Path/simplify-path.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/simplify-path/ 2 | // Author : Han Zichi 3 | // Date : 2017-01-23 4 | 5 | /** 6 | * @param {string} path 7 | * @return {string} 8 | */ 9 | var simplifyPath = function(path) { 10 | let res = [] 11 | , str = ''; 12 | 13 | for (let item of path) { 14 | if (item === '/') { 15 | if (str === '' || str === '.') { 16 | // nothing to do 17 | } else if (str === '..') { 18 | if (res.length) 19 | res.pop(); 20 | } else { 21 | res.push(str); 22 | } 23 | str = ''; 24 | } else { 25 | str += item; 26 | } 27 | } 28 | 29 | if (str && str !== '.' && str !== '..') 30 | res.push(str); 31 | else if (str === '..' && res.length) 32 | res.pop(); 33 | 34 | return '/' + res.join('/'); 35 | }; 36 | -------------------------------------------------------------------------------- /Algorithms/Convert Sorted Array to Binary Search Tree/convert-sorted-array-to-binary-search-tree.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-28 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {number[]} nums 14 | * @return {TreeNode} 15 | */ 16 | var sortedArrayToBST = function(nums) { 17 | return dfs(0, nums.length - 1); 18 | 19 | function dfs(start, end) { 20 | if (start > end) 21 | return null; 22 | 23 | var mid = (start + end) >> 1; 24 | var node = new TreeNode(nums[mid]); 25 | node.left = dfs(start, mid - 1); 26 | node.right = dfs(mid + 1, end); 27 | 28 | return node; 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/Degree of an Array/degree-of-an-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/degree-of-an-array/description/ 2 | // Author : Fish.Yu 3 | // Date : 2017-12-25 4 | /** 5 | * @param {number[]} nums 6 | * @return {number} 7 | */ 8 | var findShortestSubArray = function(nums) { 9 | let p = new Map() 10 | let degreeLen = 0 11 | 12 | nums.forEach((item, index) => { 13 | if (!p.has(item)) p.set(item, {}) 14 | let obj = p.get(item) 15 | obj.start = obj.start === void 0 ? index : obj.start 16 | obj.end = index 17 | obj.count = ~~obj.count + 1 18 | degreeLen = Math.max(degreeLen, obj.count) 19 | }) 20 | 21 | let ans = Number.POSITIVE_INFINITY 22 | for (let value of p.values()) { 23 | if (value.count !== degreeLen) continue 24 | ans = Math.min(ans, value.end - value.start + 1) 25 | } 26 | 27 | return ans 28 | }; -------------------------------------------------------------------------------- /Algorithms/Minimum Path Sum/minimum-path-sum.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-path-sum/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[][]} grid 7 | * @return {number} 8 | */ 9 | 10 | var minPathSum = function(grid) { 11 | var n = grid.length 12 | , m = grid[0].length 13 | , ans = []; 14 | 15 | for (var i = 0; i < n; i++) 16 | ans[i] = []; 17 | 18 | for (var i = 0; i < n; i++) 19 | for (var j = 0; j < m; j++) { 20 | if (i + j === 0) 21 | ans[i][j] = grid[i][j]; 22 | else if (i === 0) 23 | ans[i][j] = ans[i][j - 1] + grid[i][j]; 24 | else if (j === 0) 25 | ans[i][j] = ans[i - 1][j] + grid[i][j]; 26 | else 27 | ans[i][j] = grid[i][j] + Math.min(ans[i][j - 1], ans[i - 1][j]); 28 | } 29 | 30 | return ans[n - 1][m - 1]; 31 | }; -------------------------------------------------------------------------------- /Algorithms/Daily Temperatures/daily-temperatures.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/daily-temperatures/description/ 2 | # Author : Fish.Yu 3 | # Date : 2017-12-26 4 | 5 | import sys 6 | 7 | class Solution: 8 | def dailyTemperatures(self, temperatures): 9 | """ 10 | :type temperatures: List[int] 11 | :rtype: List[int] 12 | """ 13 | hash = [None] * 105 14 | ans = [sys.maxsize] * len(temperatures) 15 | 16 | for i in range(len(temperatures) - 1, -1, -1): 17 | temperature = temperatures[i] 18 | for j in range(temperature + 1, 101): 19 | if hash[j] and hash[j] - i < ans[i]: 20 | ans[i] = hash[j] - i 21 | if ans[i] == sys.maxsize: 22 | ans[i] = 0 23 | hash[temperature] = i 24 | 25 | return ans -------------------------------------------------------------------------------- /Algorithms/Maximum XOR of Two Numbers in an Array/maximum-xor-of-two-numbers-in-an-array.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/ 2 | // Author : Han Zichi 3 | // Date : 2016-10-31 4 | 5 | "use strict"; 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @return {number} 10 | */ 11 | var findMaximumXOR = function(nums) { 12 | let maxn = 0 13 | , mask = 0; 14 | 15 | for (let i = 31; i >= 0; i--) { 16 | mask |= (1 << i); 17 | 18 | let set = new Set(); 19 | 20 | nums.forEach(function(item) { 21 | set.add(item & mask); 22 | }); 23 | 24 | // 如果该位可取 25 | let tmp = maxn | (1 << i); 26 | 27 | for (let item of set) { 28 | // A ^ B = C 29 | // => (A ^ C = B) & (B ^ C = A) 30 | if (set.has(tmp ^ item)) 31 | maxn = tmp; 32 | } 33 | } 34 | 35 | return maxn; 36 | }; -------------------------------------------------------------------------------- /Algorithms/Unique Paths II/unique-paths-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/unique-paths-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-11 4 | 5 | /** 6 | * @param {number[][]} obstacleGrid 7 | * @return {number} 8 | */ 9 | 10 | var uniquePathsWithObstacles = function(obstacleGrid) { 11 | var ans = [] 12 | , m = obstacleGrid.length 13 | , n = obstacleGrid[0].length; 14 | 15 | for(var i = 0; i < m; i++) 16 | ans[i] = []; 17 | 18 | for(var i = 0; i < m; i++) 19 | for(var j = 0; j < n; j++) { 20 | if (obstacleGrid[i][j] === 1) 21 | ans[i][j] = 0; 22 | else if (i + j === 0) ans[i][j] = 1; 23 | else if (i === 0) ans[i][j] = ans[i][j - 1]; 24 | else if (j === 0) ans[i][j] = ans[i - 1][j]; 25 | else ans[i][j] = ans[i][j - 1] + ans[i - 1][j]; 26 | } 27 | 28 | return ans[m - 1][n - 1]; 29 | }; -------------------------------------------------------------------------------- /Algorithms/Word Pattern/word-pattern.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/word-pattern/ 2 | // Author : Han Zichi 3 | // Date : 2016-01-09 4 | 5 | /** 6 | * @param {string} pattern 7 | * @param {string} str 8 | * @return {boolean} 9 | */ 10 | var wordPattern = function(pattern, str) { 11 | var arr = str.split(' '); 12 | 13 | if (pattern.length !== arr.length) 14 | return false; 15 | 16 | var a2b = {} 17 | , b2a = {}; 18 | 19 | for (var i = 0, len = pattern.length; i < len; i++) { 20 | var a = pattern[i] 21 | , b = arr[i]; 22 | 23 | if (!a2b[a]) { 24 | a2b[a] = b; 25 | } else { 26 | if (a2b[a] !== b) 27 | return false; 28 | } 29 | 30 | if (!b2a[b]) { 31 | b2a[b] = a; 32 | } else { 33 | if (baa[b] !== a) 34 | return false; 35 | } 36 | } 37 | 38 | return true; 39 | }; -------------------------------------------------------------------------------- /Algorithms/Populating Next Right Pointers in Each Node/dfs-solution.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-29 4 | // Note : You may only use constant extra space 5 | 6 | /** 7 | * Definition for binary tree with next pointer. 8 | * function TreeLinkNode(val) { 9 | * this.val = val; 10 | * this.left = this.right = this.next = null; 11 | * } 12 | */ 13 | 14 | /** 15 | * @param {TreeLinkNode} root 16 | * @return {void} Do not return anything, modify tree in-place instead. 17 | */ 18 | var connect = function(root) { 19 | if (!root) 20 | return; 21 | 22 | if (root.left) { 23 | root.left.next = root.right; 24 | 25 | if (root.next) 26 | root.right.next = root.next.left; 27 | } 28 | 29 | connect(root.left); 30 | connect(root.right); 31 | }; -------------------------------------------------------------------------------- /Algorithms/Assign Cookies/assign-cookies.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/assign-cookies/ 2 | // Author : Han Zichi 3 | // Date : 2016-11-16 4 | 5 | /** 6 | * @param {number[]} g 7 | * @param {number[]} s 8 | * @return {number} 9 | */ 10 | var findContentChildren = function(g, s) { 11 | g.sort(function(a, b) {return a - b;}); 12 | s.sort(function(a, b) {return a - b;}); 13 | 14 | let ans = 0; 15 | let sIndex = 0; 16 | let sLen = s.length; 17 | 18 | // greedy 19 | loop: 20 | for (let i = 0, len = g.length; i < len; i++) { 21 | let item = g[i]; 22 | 23 | for (let j = sIndex; j < sLen; j++) { 24 | if (s[j] >= item) { 25 | ans++; 26 | sIndex = j + 1; // the index next loop should be from 27 | if (sIndex === sLen) break loop; 28 | break; 29 | } 30 | } 31 | } 32 | 33 | return ans; 34 | }; 35 | -------------------------------------------------------------------------------- /Algorithms/Subsets II/subsets-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/subsets-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-20 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number[][]} 8 | */ 9 | var ans, res, len; 10 | var hashAns; 11 | 12 | function dfs(index, nums) { 13 | var tmp = res.map(function(item) { 14 | return item; 15 | }); 16 | 17 | if (!hashAns[tmp.toString()]) { 18 | hashAns[tmp.toString()] = true; 19 | ans.push(tmp); 20 | } 21 | 22 | for (var i = index; i < len; i++) { 23 | res.push(nums[i]); 24 | dfs(i + 1, nums); 25 | res.pop(); 26 | } 27 | } 28 | 29 | var subsetsWithDup = function(nums) { 30 | nums.sort(function(a, b) { 31 | return a - b; 32 | }); 33 | 34 | ans = [], 35 | res = [], 36 | len = nums.length, 37 | hashAns = []; 38 | 39 | dfs(0, nums); 40 | 41 | return ans; 42 | }; -------------------------------------------------------------------------------- /Algorithms/Summary Ranges/summary-ranges.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/summary-ranges/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {string[]} 8 | */ 9 | 10 | var summaryRanges = function(nums) { 11 | var ans = []; 12 | var tmp = []; 13 | for(var i = 0, len = nums.length; i < len; i++) { 14 | if (!tmp.length) tmp.push(nums[i]); 15 | else if (nums[i] === tmp[tmp.length - 1] + 1) 16 | tmp.push(nums[i]); 17 | else { 18 | if (tmp.length === 1) ans.push(tmp[0] + ''); 19 | else ans.push(tmp[0] + '->' + tmp[tmp.length - 1]); 20 | tmp = []; 21 | tmp.push(nums[i]); 22 | } 23 | } 24 | 25 | if (tmp.length) { 26 | if (tmp.length === 1) ans.push(tmp[0] + ''); 27 | else ans.push(tmp[0] + '->' + tmp[tmp.length - 1]); 28 | } 29 | 30 | return ans; 31 | }; -------------------------------------------------------------------------------- /Algorithms/Bitwise AND of Numbers Range/bitwise-and-of-numbers-range.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/bitwise-and-of-numbers-range/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-27 4 | 5 | /** 6 | * @param {number} m 7 | * @param {number} n 8 | * @return {number} 9 | */ 10 | 11 | function getBitNum(a, pos) { 12 | a++; 13 | var res = Math.pow(2, pos) 14 | , loop = ~~(a / res) 15 | , num = loop * (res / 2) + Math.max(a % res - res / 2, 0); 16 | return num; 17 | } 18 | 19 | var rangeBitwiseAnd = function(m, n) { 20 | var ans = 0 21 | , tmp = n 22 | , digits = 0; 23 | 24 | while (tmp) { 25 | digits++; 26 | tmp >>= 1; 27 | } 28 | 29 | for (var i = 0; i < digits; i++) { 30 | var num = getBitNum(n, i + 1) - getBitNum(m - 1, i + 1); 31 | if (num === n - m + 1) 32 | ans += Math.pow(2, i); 33 | } 34 | 35 | return ans; 36 | }; -------------------------------------------------------------------------------- /Algorithms/Maximal Square/index_2.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximal-square/ 2 | // Author : Han Zichi 3 | // Date : 2016-02-07 4 | 5 | /** 6 | * @param {character[][]} matrix 7 | * @return {number} 8 | */ 9 | var maximalSquare = function(matrix) { 10 | if (!matrix.length) 11 | return 0; 12 | 13 | var n = matrix.length 14 | , m = matrix[0].length; 15 | 16 | var ans = 0; 17 | 18 | var dp = []; 19 | 20 | for (var i = 0; i < n; i++) 21 | dp[i] = []; 22 | 23 | for (var i = 0; i < n; i++) 24 | for (var j = 0; j < m; j++) { 25 | if (matrix[i][j] === '1') { 26 | dp[i][j] = Math.min(i && j ? dp[i - 1][j - 1] : 0, j ? dp[i][j - 1] : 0, i ? dp[i - 1][j] : 0) + 1; 27 | 28 | ans = dp[i][j] > ans ? dp[i][j] : ans; 29 | } else { 30 | dp[i][j] = 0; 31 | } 32 | } 33 | 34 | return ans * ans; 35 | }; -------------------------------------------------------------------------------- /Algorithms/Merge k Sorted Lists/merge-k-sorted-lists.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-k-sorted-lists/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-07 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode[]} lists 14 | * @return {ListNode} 15 | */ 16 | var mergeKLists = function(lists) { 17 | var ans = []; 18 | 19 | lists.forEach(function(item) { 20 | while (item) { 21 | ans.push(new ListNode(item.val)); 22 | item = item.next; 23 | } 24 | }); 25 | 26 | ans.sort(function(a, b) { 27 | return a.val - b.val; 28 | }); 29 | 30 | if (!ans.length) 31 | return null; 32 | 33 | for (var i = 0, len = ans.length - 1; i < len; i++) 34 | ans[i].next = ans[i + 1]; 35 | 36 | return ans[0]; 37 | }; -------------------------------------------------------------------------------- /Algorithms/Sum Root to Leaf Numbers/sum-root-to-leaf-numbers.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sum-root-to-leaf-numbers/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number} 15 | */ 16 | 17 | var ans; 18 | 19 | function dfs(root, sum) { 20 | if (!root.left && !root.right) { 21 | ans += sum * 10 + root.val; 22 | return; 23 | } 24 | 25 | if (root.left) 26 | dfs(root.left, sum * 10 + root.val); 27 | 28 | if (root.right) 29 | dfs(root.right, sum * 10 + root.val); 30 | } 31 | 32 | var sumNumbers = function(root) { 33 | if (root === null) 34 | return 0; 35 | 36 | ans = 0; 37 | dfs(root, 0); 38 | return ans; 39 | }; -------------------------------------------------------------------------------- /Algorithms/Combinations/combinations.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/combinations/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {number} n 7 | * @param {number} k 8 | * @return {number[][]} 9 | */ 10 | 11 | // return an array of k numbers with 1 ~ n 12 | 13 | var ans = [] 14 | , tmp = []; 15 | 16 | function dfs(next, n, num, k) { 17 | if (num === k) { 18 | var res = tmp.map(function(item) { 19 | return item; 20 | }); 21 | 22 | ans.push(res); 23 | return; 24 | } 25 | 26 | for (var i = next; i <= n; i++) { 27 | tmp.push(i); 28 | dfs(i + 1, n, num + 1, k); 29 | tmp.pop(); 30 | } 31 | } 32 | 33 | var combine = function(n, k) { 34 | ans = []; 35 | // select the 1st number 36 | for (var i = 1; i <= n; i++) { 37 | tmp[0] = i; 38 | dfs(i + 1, n, 1, k); 39 | } 40 | 41 | return ans; 42 | }; -------------------------------------------------------------------------------- /Algorithms/Decode Ways/decode-ways.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/decode-ways/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {string} s 7 | * @return {number} 8 | */ 9 | var numDecodings = function(s) { 10 | if (!s.length) return 0; 11 | if (s[0] === '0') return 0; 12 | 13 | var len = s.length 14 | , dp = []; 15 | 16 | for (var i = 0; i < len; i++) { 17 | dp[i] = []; 18 | if (i === 0) { 19 | dp[i][0] = 1; 20 | dp[i][1] = 1; 21 | } else { 22 | dp[i][0] = dp[i - 1][1], 23 | dp[i][1] = 0; 24 | 25 | if (s[i] !== '0') 26 | dp[i][1] += dp[i - 1][1]; 27 | 28 | if (s[i - 1] !== '0') { 29 | var num = Number(s[i - 1] + s[i]); 30 | if (num >= 1 && num <= 26) 31 | dp[i][1] += dp[i - 1][0]; 32 | } 33 | } 34 | } 35 | 36 | return dp[len - 1][1]; 37 | }; -------------------------------------------------------------------------------- /Algorithms/Intersection of Two Arrays II/intersection-of-two-arrays-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/ 2 | // Author : Han Zichi 3 | // Date : 2016-05-21 4 | 5 | /** 6 | * @param {number[]} nums1 7 | * @param {number[]} nums2 8 | * @return {number[]} 9 | */ 10 | var intersect = function(nums1, nums2) { 11 | var hash1 = {}; 12 | var hash2 = {}; 13 | 14 | nums1.forEach(function(item) { 15 | if (!hash1[item]) 16 | hash1[item] = 1; 17 | else 18 | hash1[item]++; 19 | }); 20 | 21 | nums2.forEach(function(item) { 22 | if (!hash2[item]) 23 | hash2[item] = 1; 24 | else 25 | hash2[item]++; 26 | }); 27 | 28 | var ans = []; 29 | 30 | for (var k in hash1) { 31 | var times = Math.min(hash1[k], hash2[k] || 0); 32 | while (times--) 33 | ans.push(+k); 34 | } 35 | 36 | return ans; 37 | }; -------------------------------------------------------------------------------- /Algorithms/Largest Rectangle in Histogram/largest-rectangle-in-histogram.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/largest-rectangle-in-histogram/ 2 | // Author : Han Zichi 3 | // Date : 2016-02-18 4 | 5 | // 112 ms 6 | // Your runtime beats 100.00% of javascriptsubmissions 7 | 8 | /** 9 | * @param {number[]} heights 10 | * @return {number} 11 | */ 12 | var largestRectangleArea = function(heights) { 13 | heights.push(0); 14 | 15 | var maxn = 0; 16 | 17 | var stack = []; 18 | 19 | for (var i = 0, len = heights.length; i < len; i++) { 20 | while (stack.length && heights[i] < heights[stack[stack.length - 1]]) { 21 | var top = stack.pop(); 22 | 23 | var nextTop = stack.length === 0 ? -1 : stack[stack.length - 1]; 24 | 25 | maxn = Math.max((i - nextTop - 1) * heights[top], maxn); 26 | } 27 | 28 | stack.push(i); 29 | } 30 | 31 | return maxn; 32 | }; -------------------------------------------------------------------------------- /Algorithms/Convert BST to Greater Tree/convert-bst-to-greater-tree.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/convert-bst-to-greater-tree/#/description 2 | # Author : Han Zichi 3 | # Date : 2017-04-23 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def convertBST(self, root): 14 | """ 15 | :type root: TreeNode 16 | :rtype: TreeNode 17 | """ 18 | def dfs(node): 19 | if node == None: 20 | return 21 | else: 22 | dfs(node.right) 23 | node.val += dfs.total 24 | dfs.total = node.val 25 | dfs(node.left) 26 | 27 | dfs.total = 0 28 | dfs(root) 29 | return root -------------------------------------------------------------------------------- /Algorithms/Different Ways to Add Parentheses/divide-and-conquer.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/different-ways-to-add-parentheses/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-18 4 | 5 | /** 6 | * @param {string} input 7 | * @return {number[]} 8 | */ 9 | var diffWaysToCompute = function(input) { 10 | // save the possible values from the string input 11 | var ans = []; 12 | for (var i = 0, len = input.length; i < len; i++) { 13 | var item = input[i]; 14 | if (~'+-*'.indexOf(item)) { 15 | var left = diffWaysToCompute(input.substring(0, i)); 16 | var right = diffWaysToCompute(input.substring(i + 1)); 17 | left.forEach(function(a) { 18 | right.forEach(function(b) { 19 | ans.push(eval('(' + a + ')' + item + '(' + b + ')')); 20 | }); 21 | }); 22 | } 23 | } 24 | 25 | !ans.length && ans.push(+input); 26 | return ans; 27 | }; -------------------------------------------------------------------------------- /Algorithms/Repeated DNA Sequences/repeated-dna-sequences.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/repeated-dna-sequences/ 2 | // Author : Han Zichi 3 | // Date : 2015-09-11 4 | 5 | /** 6 | * @param {string} s 7 | * @return {string[]} 8 | */ 9 | var findRepeatedDnaSequences = function(s) { 10 | var map = [] 11 | , hash = new Set() 12 | , hash_ans = new Set() 13 | , ans = []; 14 | 15 | map['A'] = 0, map['C'] = 1, map['G'] = 2, map['T'] = 3; 16 | 17 | var tmp = 0; 18 | for (var i = 0, len = s.length; i < len; i++) { 19 | tmp = tmp << 2 | map[s[i]]; 20 | if (i < 9) continue; 21 | if (i > 9) tmp = tmp & 0xfffff; 22 | 23 | if (!hash.has(tmp)) 24 | hash.add(tmp); 25 | else { 26 | if (!hash_ans.has(tmp)) { 27 | hash_ans.add(tmp); 28 | ans.push(s.substring(i - 9, i + 1)); 29 | } 30 | } 31 | } 32 | 33 | return ans; 34 | }; -------------------------------------------------------------------------------- /Algorithms/Target Sum/better-solution.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/target-sum/ 2 | // Author : Han Zichi 3 | // Date : 2017-01-22 4 | // Runtime: 122 ms 5 | 6 | /** 7 | * @param {number[]} nums 8 | * @param {number} S 9 | * @return {number} 10 | */ 11 | var findTargetSumWays = function(nums, S) { 12 | let total = 0 13 | , len = nums.length; 14 | 15 | for (let item of nums) 16 | total += item; 17 | 18 | let target = total - S; 19 | 20 | if (target & 1) 21 | return 0; 22 | if (target < 0) 23 | return 0; 24 | 25 | target >>= 1; 26 | 27 | let dp = []; 28 | for (let i = 0; i <= target; i++) 29 | dp[i] = 0; 30 | dp[0] = 1; 31 | 32 | for (let item of nums) { 33 | for (let i = target; i >= 0; i--) { 34 | if (i - item < 0) 35 | break; 36 | dp[i] += dp[i - item]; 37 | } 38 | } 39 | 40 | return dp[target]; 41 | }; 42 | -------------------------------------------------------------------------------- /Algorithms/Reverse Integer/reverse-integer.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-integer/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-09 4 | 5 | /** 6 | * @param {number} x 7 | * @return {number} 8 | */ 9 | 10 | // the int32 range: -2^31 ~ 2^31-1 11 | // this problem is a little puzzling, you should take overflow into consideration 12 | // although it's really nothing to JavaScript 13 | // you should also notice that 1 << 31 will overflow in JavaScript 14 | 15 | var reverse = function(x) { 16 | var minn = - (1 << 30) * 2; 17 | var maxn = (1 << 30) * 2 - 1; 18 | var ans; 19 | var arr = x.toString().split(''); 20 | if (x < 0) 21 | arr.shift(); // remove '-' 22 | ans = Number(arr.reverse().join('')); 23 | if (x < 0) 24 | ans *= -1; 25 | console.log(minn, maxn) 26 | if (ans < minn || ans > maxn) 27 | return 0; 28 | else 29 | return ans; 30 | }; 31 | 32 | -------------------------------------------------------------------------------- /Algorithms/Lowest Common Ancestor of a Binary Tree/better-solution.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ 2 | // Author : Han Zichi 3 | // Date : 2016-09-01 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @param {TreeNode} p 15 | * @param {TreeNode} q 16 | * @return {TreeNode} 17 | */ 18 | var lowestCommonAncestor = function(root, p, q) { 19 | if (!root) 20 | return null; 21 | 22 | if (root === p || root === q) 23 | return root; 24 | 25 | var left = lowestCommonAncestor(root.left, p, q); 26 | var right = lowestCommonAncestor(root.right, p, q); 27 | 28 | if (left && right) 29 | return root; 30 | else if (left) 31 | return left; 32 | else 33 | return right; 34 | }; -------------------------------------------------------------------------------- /Algorithms/Minimum Depth of Binary Tree/minimum-depth-of-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-depth-of-binary-tree/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number} 15 | */ 16 | 17 | var ans; 18 | 19 | function dfs(root, depth) { 20 | if (!root) 21 | return; 22 | 23 | if (ans && depth >= ans) 24 | return; 25 | 26 | if (!root.left && !root.right) { 27 | ans = depth; 28 | return; 29 | } 30 | 31 | if (root.left) 32 | dfs(root.left, depth + 1); 33 | 34 | if (root.right) 35 | dfs(root.right, depth + 1); 36 | } 37 | 38 | var minDepth = function(root) { 39 | ans = 0; 40 | dfs(root, 1); 41 | return ans; 42 | }; -------------------------------------------------------------------------------- /Algorithms/Binary Tree Right Side View/binary-tree-right-side-view.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val) { 4 | * this.val = val; 5 | * this.left = this.right = null; 6 | * } 7 | */ 8 | /** 9 | * @param {TreeNode} root 10 | * @return {number[]} 11 | */ 12 | var rightSideView = function(root) { 13 | if (!root) return []; 14 | 15 | var ans = [] 16 | , tmp = [root]; 17 | 18 | while (tmp.length) { 19 | var res = [] 20 | , a = []; 21 | 22 | for (var i = 0, len = tmp.length; i < len; i++) { 23 | if (!tmp[i]) continue; 24 | res.push(tmp[i].val); 25 | a.push(tmp[i].left); 26 | a.push(tmp[i].right); 27 | } 28 | 29 | tmp = a.concat(); 30 | if (res.length) 31 | ans.push(res); 32 | } 33 | 34 | var a = []; 35 | ans.forEach(function(item) { 36 | a.push(item.pop()); 37 | }); 38 | 39 | return a; 40 | }; -------------------------------------------------------------------------------- /Algorithms/Binary Tree Tilt/binary-tree-tilt.py: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/binary-tree-tilt/description/ 2 | # Author : Fish.Yu 3 | # Date : 2017-12-26 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode: 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution: 13 | def findTilt(self, root): 14 | """ 15 | :type root: TreeNode 16 | :rtype: int 17 | """ 18 | global ans 19 | ans = 0 20 | self.sumOfNode(root) 21 | return ans 22 | 23 | def sumOfNode(self, root): 24 | if (root == None): 25 | return 0 26 | 27 | left = self.sumOfNode(root.left) 28 | right = self.sumOfNode(root.right) 29 | 30 | global ans 31 | ans += abs(left - right) 32 | return left + right + root.val -------------------------------------------------------------------------------- /Algorithms/Longest Substring Without Repeating Characters/longest-substring-without-repeating-characters.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-substring-without-repeating-characters/ 2 | // Author : Han Zichi 3 | // Date : 2016-08-05 4 | 5 | /** 6 | * @param {string} s 7 | * @return {number} 8 | */ 9 | var lengthOfLongestSubstring = function(s) { 10 | var hash = {}; 11 | var start = 0; 12 | var ans = 0; 13 | 14 | for (var i = 0, len = s.length; i < len; i++) { 15 | var item = s[i]; 16 | 17 | if (!hash[item]) 18 | hash[item] = true; 19 | else { 20 | // item 已经在 substring 中存在了 21 | for (; ;) { 22 | if (s[start] === item) { 23 | start++; 24 | break; 25 | } 26 | 27 | hash[s[start]] = false; 28 | start++; 29 | } 30 | } 31 | 32 | ans = Math.max(ans, i - start + 1); 33 | } 34 | 35 | return ans; 36 | }; -------------------------------------------------------------------------------- /Algorithms/Rectangle Area/index.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rectangle-area/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {number} A 7 | * @param {number} B 8 | * @param {number} C 9 | * @param {number} D 10 | * @param {number} E 11 | * @param {number} F 12 | * @param {number} G 13 | * @param {number} H 14 | * @return {number} 15 | */ 16 | var computeArea = function(A, B, C, D, E, F, G, H) { 17 | var width, height; 18 | 19 | if (C <= E || G <= A || D <= F || H <= B) 20 | width = height = 0; 21 | else { 22 | var tmp = [A, C, E, G].sort(function(a, b) { 23 | return a - b; 24 | }); 25 | 26 | width = tmp[2] - tmp[1]; 27 | 28 | tmp = [B, D, F, H].sort(function(a, b) { 29 | return a - b; 30 | }); 31 | 32 | height = tmp[2] - tmp[1]; 33 | } 34 | 35 | return (C - A) * (D - B) + (G - E) * (H - F) - width * height; 36 | }; -------------------------------------------------------------------------------- /Algorithms/Rotate List/rotate-list.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-list/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-20 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @param {number} k 15 | * @return {ListNode} 16 | */ 17 | var rotateRight = function(head, k) { 18 | if (head === null) 19 | return null; 20 | 21 | var tmp = []; 22 | while (head) { 23 | tmp.push(new ListNode(head.val)); 24 | head = head.next; 25 | } 26 | 27 | k %= tmp.length; 28 | 29 | var res = []; 30 | if (k) 31 | res = tmp.slice(-k); 32 | 33 | tmp.splice(-k, k); 34 | 35 | Array.prototype.unshift.apply(tmp, res); 36 | 37 | for (var i = 0; i < tmp.length - 1; i++) 38 | tmp[i].next = tmp[i + 1]; 39 | 40 | return tmp[0]; 41 | }; -------------------------------------------------------------------------------- /Algorithms/Longest Substring with At Least K Repeating Characters/better-solution.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ 2 | // Author : Han Zichi 3 | // Date : 2016-09-21 4 | // Runtime: 89 ms 5 | 6 | /** 7 | * @param {string} s 8 | * @param {number} k 9 | * @return {number} 10 | */ 11 | var longestSubstring = function(s, k) { 12 | if (k > s.length) 13 | return 0; 14 | 15 | if (k <= 1) 16 | return s.length; 17 | 18 | let hash = {}; 19 | for (let item of s) 20 | !hash[item] ? hash[item] = 1 : hash[item]++; 21 | 22 | for (let i = 0, len = s.length; i < len; i++) { 23 | let item = s[i]; 24 | if (hash[item] < k) { 25 | let subA = s.substring(0, i); 26 | let subB = s.substring(i + 1); 27 | return Math.max(longestSubstring(subA, k), longestSubstring(subB, k)); 28 | } 29 | } 30 | 31 | return s.length; 32 | }; -------------------------------------------------------------------------------- /Algorithms/Number of Boomerangs/number-of-boomerangs.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-boomerangs/ 2 | // Author : Han Zichi 3 | // Date : 2016-11-15 4 | 5 | "use strict"; 6 | 7 | /** 8 | * @param {number[][]} points 9 | * @return {number} 10 | */ 11 | var numberOfBoomerangs = function(points) { 12 | let len = points.length; 13 | let ans = 0; 14 | 15 | for (let i = 0; i < len; i++) { // as the middle one 16 | let p = new Map(); 17 | for (let j = 0; j < len; j++) { 18 | if (i === j) continue; 19 | let dis = getDis(i, j); 20 | let count = ~~p.get(dis); 21 | ans += count; 22 | p.set(dis, count + 1); 23 | } 24 | } 25 | 26 | return ans * 2; 27 | 28 | function getDis(i, j) { 29 | return (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) 30 | + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1]); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Algorithms/Remove Duplicates from Sorted List/remove-duplicates-from-sorted-list.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-18 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @return {ListNode} 15 | */ 16 | var deleteDuplicates = function(head) { 17 | var ans = []; 18 | while (head) { 19 | ans.push(new ListNode(head.val)); 20 | head = head.next; 21 | } 22 | 23 | if (!ans.length) 24 | return null; 25 | 26 | for (var i = ans.length; i--; ) { 27 | if (i && ans[i].val === ans[i - 1].val) 28 | ans.splice(i, 1); 29 | } 30 | 31 | for (var i = 0, len = ans.length; i < len - 1; i++) 32 | ans[i].next = ans[i + 1]; 33 | 34 | return ans[0]; 35 | }; -------------------------------------------------------------------------------- /Algorithms/Remove Linked List Elements/remove-linked-list-elements.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-linked-list-elements/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-18 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @param {number} val 15 | * @return {ListNode} 16 | */ 17 | var removeElements = function(head, val) { 18 | var ans = []; 19 | 20 | while (head) { 21 | ans.push(new ListNode(head.val)); 22 | head = head.next; 23 | } 24 | 25 | for (var i = ans.length; i--; ) { 26 | if (ans[i].val === val) 27 | ans.splice(i, 1); 28 | } 29 | 30 | if (!ans.length) 31 | return null; 32 | 33 | for (var i = 0, len = ans.length; i < len - 1; i++) 34 | ans[i].next = ans[i + 1]; 35 | 36 | return ans[0]; 37 | }; -------------------------------------------------------------------------------- /Algorithms/Merge Two Sorted Lists/merge-two-sorted-lists.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-two-sorted-lists/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-17 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val) { 8 | * this.val = val; 9 | * this.next = null; 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} l1 14 | * @param {ListNode} l2 15 | * @return {ListNode} 16 | */ 17 | var mergeTwoLists = function(l1, l2) { 18 | var ans = []; 19 | while (l1) { 20 | ans.push(new ListNode(l1.val)); 21 | l1 = l1.next; 22 | } 23 | 24 | while (l2) { 25 | ans.push(new ListNode(l2.val)); 26 | l2 = l2.next; 27 | } 28 | 29 | ans.sort(function(a, b) { 30 | return a.val - b.val; 31 | }); 32 | 33 | if (!ans.length) return null; 34 | for (var i = 0, len = ans.length; i < len - 1; i++) 35 | ans[i].next = ans[i + 1]; 36 | 37 | return ans[0]; 38 | }; -------------------------------------------------------------------------------- /Algorithms/Binary Tree Level Order Traversal II/binary-tree-level-order-traversal-ii.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ 2 | // Author : Han Zichi 3 | // Date : 2015-09-16 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val) { 8 | * this.val = val; 9 | * this.left = this.right = null; 10 | * } 11 | */ 12 | /** 13 | * @param {TreeNode} root 14 | * @return {number[][]} 15 | */ 16 | var levelOrderBottom = function(root) { 17 | if (!root) return []; 18 | 19 | var ans = [], tmp = [root]; 20 | 21 | while (tmp.length) { 22 | var res = [], _tmp = []; 23 | 24 | tmp.forEach(function(item) { 25 | res.push(item.val); 26 | if (item.left) 27 | _tmp.push(item.left); 28 | if (item.right) 29 | _tmp.push(item.right); 30 | }); 31 | 32 | ans.push(res); 33 | tmp = _tmp; 34 | } 35 | 36 | return ans.reverse(); 37 | 38 | }; -------------------------------------------------------------------------------- /Algorithms/Letter Combinations of a Phone Number/letter-combinations-of-a-phone-number.js: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 2 | // Author : Han Zichi 3 | // Date : 2015-08-14 4 | 5 | /** 6 | * @param {string} digits 7 | * @return {string[]} 8 | */ 9 | var ans, tmp; 10 | 11 | function dfs(str, idx, digits) { 12 | if (idx === digits.length) { 13 | ans.push(str); 14 | return; 15 | } 16 | 17 | var num = Number(digits[idx]); 18 | if (num <= 1) 19 | dfs(str, idx + 1, digits); 20 | else { 21 | for (var i = 0, len = tmp[num].length; i < len; i++) 22 | dfs(str + tmp[num][i], idx + 1, digits); 23 | } 24 | } 25 | 26 | var letterCombinations = function(digits) { 27 | if (!digits.length) 28 | return []; 29 | 30 | tmp = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'], 31 | ans = []; 32 | 33 | dfs('', 0, digits); 34 | return ans; 35 | }; --------------------------------------------------------------------------------