From 6495e14da0a6bb7b48bfcd90eaf4b290807f971d Mon Sep 17 00:00:00 2001 From: Ciro Santilli Date: Thu, 10 Dec 2015 07:29:24 -0200 Subject: [PATCH 001/105] gitignore java *.class files for those without IDE --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 1f1c65c40..25a4d2a65 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .idea algorithms-java/out +*.class From cc7fc84f38679f8808f92a3ac77f2e0117fffb24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciro=20Santilli=20=E5=85=AD=E5=9B=9B=E4=BA=8B=E4=BB=B6=20?= =?UTF-8?q?=E6=B3=95=E8=BD=AE=E5=8A=9F?= Date: Thu, 10 Dec 2015 07:29:24 -0200 Subject: [PATCH 002/105] gitignore java *.class files for those without IDE --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 1f1c65c40..25a4d2a65 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .idea algorithms-java/out +*.class From 728ad252ab04b5ee0d6817d7ef6c9c724f9f71b5 Mon Sep 17 00:00:00 2001 From: Ciro Santilli Date: Thu, 10 Dec 2015 07:21:27 -0200 Subject: [PATCH 003/105] java LRUCache with LinkedHashMap --- algorithms/java/src/lruCache/LRUCache.java | 45 +++++++++++++++++ .../java/src/lruCache/LRUCacheTest.java | 49 +++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 algorithms/java/src/lruCache/LRUCache.java create mode 100644 algorithms/java/src/lruCache/LRUCacheTest.java diff --git a/algorithms/java/src/lruCache/LRUCache.java b/algorithms/java/src/lruCache/LRUCache.java new file mode 100644 index 000000000..5ea5c2950 --- /dev/null +++ b/algorithms/java/src/lruCache/LRUCache.java @@ -0,0 +1,45 @@ +/* +Analogous to the C++ solution at: +https://github.com/haoel/leetcode/blob/625ad10464701fc4177b9ef33c8ad052d0a7d984/algorithms/cpp/LRUCache/LRUCache.cpp +which uses linked list + hash map. But the Java stdlib provides LinkedHashMap +which already implements that for us, making this solution shorter. + +This could also be done by using, but that generates +some inheritance boilerplate, and ends up taking the same number of lines: +https://github.com/cirosantilli/haoel-leetcode/commit/ff04930b2dc31f270854e40b560723577c7b49fd +*/ + +import java.util.LinkedHashMap; +import java.util.Iterator; + +public class LRUCache { + + private int capacity; + private LinkedHashMap map; + + public LRUCache(int capacity) { + this.capacity = capacity; + this.map = new LinkedHashMap<>(); + } + + public int get(int key) { + Integer value = this.map.get(key); + if (value == null) { + value = -1; + } else { + this.set(key, value); + } + return value; + } + + public void set(int key, int value) { + if (this.map.containsKey(key)) { + this.map.remove(key); + } else if (this.map.size() == this.capacity) { + Iterator it = this.map.keySet().iterator(); + it.next(); + it.remove(); + } + map.put(key, value); + } +} diff --git a/algorithms/java/src/lruCache/LRUCacheTest.java b/algorithms/java/src/lruCache/LRUCacheTest.java new file mode 100644 index 000000000..b8166873e --- /dev/null +++ b/algorithms/java/src/lruCache/LRUCacheTest.java @@ -0,0 +1,49 @@ +import java.util.ArrayList; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class LRUCacheTest { + + private LRUCache c; + + public LRUCacheTest() { + this.c = new LRUCache(2); + } + + @Test + public void testCacheStartsEmpty() { + assertEquals(c.get(1), -1); + } + + @Test + public void testSetBelowCapacity() { + c.set(1, 1); + assertEquals(c.get(1), 1); + assertEquals(c.get(2), -1); + c.set(2, 4); + assertEquals(c.get(1), 1); + assertEquals(c.get(2), 4); + } + + @Test + public void testCapacityReachedOldestRemoved() { + c.set(1, 1); + c.set(2, 4); + c.set(3, 9); + assertEquals(c.get(1), -1); + assertEquals(c.get(2), 4); + assertEquals(c.get(3), 9); + } + + @Test + public void testGetRenewsEntry() { + c.set(1, 1); + c.set(2, 4); + assertEquals(c.get(1), 1); + c.set(3, 9); + assertEquals(c.get(1), 1); + assertEquals(c.get(2), -1); + assertEquals(c.get(3), 9); + } +} From 2a8222328fa9d677f26059a09602a10c7b1a029d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciro=20Santilli=20=E5=85=AD=E5=9B=9B=E4=BA=8B=E4=BB=B6=20?= =?UTF-8?q?=E6=B3=95=E8=BD=AE=E5=8A=9F?= Date: Thu, 10 Dec 2015 07:21:27 -0200 Subject: [PATCH 004/105] java LRUCache with LinkedHashMap --- algorithms/java/src/lruCache/LRUCache.java | 45 +++++++++++++++++ .../java/src/lruCache/LRUCacheTest.java | 49 +++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 algorithms/java/src/lruCache/LRUCache.java create mode 100644 algorithms/java/src/lruCache/LRUCacheTest.java diff --git a/algorithms/java/src/lruCache/LRUCache.java b/algorithms/java/src/lruCache/LRUCache.java new file mode 100644 index 000000000..5ea5c2950 --- /dev/null +++ b/algorithms/java/src/lruCache/LRUCache.java @@ -0,0 +1,45 @@ +/* +Analogous to the C++ solution at: +https://github.com/haoel/leetcode/blob/625ad10464701fc4177b9ef33c8ad052d0a7d984/algorithms/cpp/LRUCache/LRUCache.cpp +which uses linked list + hash map. But the Java stdlib provides LinkedHashMap +which already implements that for us, making this solution shorter. + +This could also be done by using, but that generates +some inheritance boilerplate, and ends up taking the same number of lines: +https://github.com/cirosantilli/haoel-leetcode/commit/ff04930b2dc31f270854e40b560723577c7b49fd +*/ + +import java.util.LinkedHashMap; +import java.util.Iterator; + +public class LRUCache { + + private int capacity; + private LinkedHashMap map; + + public LRUCache(int capacity) { + this.capacity = capacity; + this.map = new LinkedHashMap<>(); + } + + public int get(int key) { + Integer value = this.map.get(key); + if (value == null) { + value = -1; + } else { + this.set(key, value); + } + return value; + } + + public void set(int key, int value) { + if (this.map.containsKey(key)) { + this.map.remove(key); + } else if (this.map.size() == this.capacity) { + Iterator it = this.map.keySet().iterator(); + it.next(); + it.remove(); + } + map.put(key, value); + } +} diff --git a/algorithms/java/src/lruCache/LRUCacheTest.java b/algorithms/java/src/lruCache/LRUCacheTest.java new file mode 100644 index 000000000..b8166873e --- /dev/null +++ b/algorithms/java/src/lruCache/LRUCacheTest.java @@ -0,0 +1,49 @@ +import java.util.ArrayList; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class LRUCacheTest { + + private LRUCache c; + + public LRUCacheTest() { + this.c = new LRUCache(2); + } + + @Test + public void testCacheStartsEmpty() { + assertEquals(c.get(1), -1); + } + + @Test + public void testSetBelowCapacity() { + c.set(1, 1); + assertEquals(c.get(1), 1); + assertEquals(c.get(2), -1); + c.set(2, 4); + assertEquals(c.get(1), 1); + assertEquals(c.get(2), 4); + } + + @Test + public void testCapacityReachedOldestRemoved() { + c.set(1, 1); + c.set(2, 4); + c.set(3, 9); + assertEquals(c.get(1), -1); + assertEquals(c.get(2), 4); + assertEquals(c.get(3), 9); + } + + @Test + public void testGetRenewsEntry() { + c.set(1, 1); + c.set(2, 4); + assertEquals(c.get(1), 1); + c.set(3, 9); + assertEquals(c.get(1), 1); + assertEquals(c.get(2), -1); + assertEquals(c.get(3), 9); + } +} From 738bc45ec9969f4bc7ca0a11394b7cd06243090d Mon Sep 17 00:00:00 2001 From: Vally Date: Mon, 28 Dec 2015 18:36:22 +0200 Subject: [PATCH 005/105] added bulbSwitcher --- README.md | 1 + algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp | 44 ++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp diff --git a/README.md b/README.md index 3f71fe9be..fc0f24320 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| |307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Mutable/RangeSumQueryMutable.cpp)|Medium| |306|[Additive Number](https://leetcode.com/problems/additive-number/) | [C++](./algorithms/cpp/additiveNumber/AdditiveNumber.cpp)|Medium| diff --git a/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp b/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp new file mode 100644 index 000000000..04b046391 --- /dev/null +++ b/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp @@ -0,0 +1,44 @@ +// Source : https://leetcode.com/problems/bulb-switcher/ +// Author : Calinescu Valentin +// Date : 2015-12-28 + +/*************************************************************************************** + * + * There are n bulbs that are initially off. You first turn on all the bulbs. Then, you + * turn off every second bulb. On the third round, you toggle every third bulb (turning + * on if it's off or turning off if it's on). For the nth round, you only toggle the + * last bulb. Find how many bulbs are on after n rounds. + * + * Example: + * + * Given n = 3. + * + * At first, the three bulbs are [off, off, off]. + * After first round, the three bulbs are [on, on, on]. + * After second round, the three bulbs are [on, off, on]. + * After third round, the three bulbs are [on, off, off]. + * + * So you should return 1, because there is only one bulb is on. + * + ***************************************************************************************/ + /* + * Solution 1 - O(1) + * ========= + * + * We notice that for every light bulb on position i there will be one toggle for every + * one of its divisors, given that you toggle all of the multiples of one number. The + * total number of toggles is irrelevant, because there are only 2 possible positions(on, + * off). We quickly find that 2 toggles cancel each other so given that the start position + * is always off a light bulb will be in if it has been toggled an odd number of times. + * The only integers with an odd number of divisors are perfect squares(because the square + * root only appears once, not like the other divisors that form pairs). The problem comes + * down to finding the number of perfect squares <= n. That number is the integer part of + * the square root of n. + * + */ +class Solution { +public: + int bulbSwitch(int n) { + return (int)sqrt(n); + } +}; From a6368c99b3a1edc99489a152a54d849d10a913fc Mon Sep 17 00:00:00 2001 From: Vally Date: Mon, 28 Dec 2015 18:36:22 +0200 Subject: [PATCH 006/105] added bulbSwitcher --- README.md | 1 + algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp | 44 ++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp diff --git a/README.md b/README.md index 3f71fe9be..fc0f24320 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| |307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Mutable/RangeSumQueryMutable.cpp)|Medium| |306|[Additive Number](https://leetcode.com/problems/additive-number/) | [C++](./algorithms/cpp/additiveNumber/AdditiveNumber.cpp)|Medium| diff --git a/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp b/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp new file mode 100644 index 000000000..04b046391 --- /dev/null +++ b/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp @@ -0,0 +1,44 @@ +// Source : https://leetcode.com/problems/bulb-switcher/ +// Author : Calinescu Valentin +// Date : 2015-12-28 + +/*************************************************************************************** + * + * There are n bulbs that are initially off. You first turn on all the bulbs. Then, you + * turn off every second bulb. On the third round, you toggle every third bulb (turning + * on if it's off or turning off if it's on). For the nth round, you only toggle the + * last bulb. Find how many bulbs are on after n rounds. + * + * Example: + * + * Given n = 3. + * + * At first, the three bulbs are [off, off, off]. + * After first round, the three bulbs are [on, on, on]. + * After second round, the three bulbs are [on, off, on]. + * After third round, the three bulbs are [on, off, off]. + * + * So you should return 1, because there is only one bulb is on. + * + ***************************************************************************************/ + /* + * Solution 1 - O(1) + * ========= + * + * We notice that for every light bulb on position i there will be one toggle for every + * one of its divisors, given that you toggle all of the multiples of one number. The + * total number of toggles is irrelevant, because there are only 2 possible positions(on, + * off). We quickly find that 2 toggles cancel each other so given that the start position + * is always off a light bulb will be in if it has been toggled an odd number of times. + * The only integers with an odd number of divisors are perfect squares(because the square + * root only appears once, not like the other divisors that form pairs). The problem comes + * down to finding the number of perfect squares <= n. That number is the integer part of + * the square root of n. + * + */ +class Solution { +public: + int bulbSwitch(int n) { + return (int)sqrt(n); + } +}; From cc1f6554dedcdb0b8aab5b339d5ad2604733e70a Mon Sep 17 00:00:00 2001 From: Vally Date: Mon, 28 Dec 2015 19:44:50 +0200 Subject: [PATCH 007/105] added coinChange --- README.md | 1 + algorithms/cpp/coinChange/coinChange.cpp | 62 ++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 algorithms/cpp/coinChange/coinChange.cpp diff --git a/README.md b/README.md index fc0f24320..539f6b37d 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| |307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Mutable/RangeSumQueryMutable.cpp)|Medium| diff --git a/algorithms/cpp/coinChange/coinChange.cpp b/algorithms/cpp/coinChange/coinChange.cpp new file mode 100644 index 000000000..e8ddc9c51 --- /dev/null +++ b/algorithms/cpp/coinChange/coinChange.cpp @@ -0,0 +1,62 @@ +// Source : https://leetcode.com/problems/coin-change/ +// Author : Calinescu Valentin +// Date : 2015-12-28 + +/*************************************************************************************** + * + * You are given coins of different denominations and a total amount of money amount. + * Write a function to compute the fewest number of coins that you need to make up that + * amount. If that amount of money cannot be made up by any combination of the coins, + * return -1. + * + * Example 1: + * coins = [1, 2, 5], amount = 11 + * return 3 (11 = 5 + 5 + 1) + * + * Example 2: + * coins = [2], amount = 3 + * return -1. + * + * Note: + * You may assume that you have an infinite number of each kind of coin. + * + * Credits: + * Special thanks to @jianchao.li.fighter for adding this problem and creating all test + * cases. + * + ***************************************************************************************/ + /* + * Solution 1 - O(N * amount) + * ========= + * + * This problem can be solved using dynamic programming, thus building the optimal + * solution from previous smaller ones. For every coin of value t and every sum of money + * i the sum can be traced back to a previous sum i - t that was already computed and uses + * the smallest number of coins possible. This way we can construct every sum i as the + * minimum of all these previous sums for every coin value. To be sure we'll find a minimum + * we can populate the solution vector with an amount bigger than the maximum possible, + * which is amount + 1(when the sum is made up of only coins of value 1). The only exception + * is sol[0] which is 0 as we need 0 coins to have a sum of 0. In the end we need to look + * if the program found a solution in sol[amount] or it remained the same, in which case we + * can return -1. + * + */ +class Solution { +public: + + int coinChange(vector& coins, int amount) { + int sol[amount + 1]; + sol[0] = 0; + for(int i = 1; i <= amount; i++) + sol[i] = amount + 1; + for(int i = 0; i < coins.size(); i++) + { + for(int j = coins[i]; j <= amount; j++) + sol[j] = min(sol[j], sol[j - coins[i]] + 1); + } + if(sol[amount] != amount + 1) + return sol[amount]; + else + return -1; + } +}; From 7c7528fbc4b1805c47428fe7cce6fb9bfc9a7565 Mon Sep 17 00:00:00 2001 From: Vally Date: Mon, 28 Dec 2015 19:44:50 +0200 Subject: [PATCH 008/105] added coinChange --- README.md | 1 + algorithms/cpp/coinChange/coinChange.cpp | 62 ++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 algorithms/cpp/coinChange/coinChange.cpp diff --git a/README.md b/README.md index fc0f24320..539f6b37d 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| |307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Mutable/RangeSumQueryMutable.cpp)|Medium| diff --git a/algorithms/cpp/coinChange/coinChange.cpp b/algorithms/cpp/coinChange/coinChange.cpp new file mode 100644 index 000000000..e8ddc9c51 --- /dev/null +++ b/algorithms/cpp/coinChange/coinChange.cpp @@ -0,0 +1,62 @@ +// Source : https://leetcode.com/problems/coin-change/ +// Author : Calinescu Valentin +// Date : 2015-12-28 + +/*************************************************************************************** + * + * You are given coins of different denominations and a total amount of money amount. + * Write a function to compute the fewest number of coins that you need to make up that + * amount. If that amount of money cannot be made up by any combination of the coins, + * return -1. + * + * Example 1: + * coins = [1, 2, 5], amount = 11 + * return 3 (11 = 5 + 5 + 1) + * + * Example 2: + * coins = [2], amount = 3 + * return -1. + * + * Note: + * You may assume that you have an infinite number of each kind of coin. + * + * Credits: + * Special thanks to @jianchao.li.fighter for adding this problem and creating all test + * cases. + * + ***************************************************************************************/ + /* + * Solution 1 - O(N * amount) + * ========= + * + * This problem can be solved using dynamic programming, thus building the optimal + * solution from previous smaller ones. For every coin of value t and every sum of money + * i the sum can be traced back to a previous sum i - t that was already computed and uses + * the smallest number of coins possible. This way we can construct every sum i as the + * minimum of all these previous sums for every coin value. To be sure we'll find a minimum + * we can populate the solution vector with an amount bigger than the maximum possible, + * which is amount + 1(when the sum is made up of only coins of value 1). The only exception + * is sol[0] which is 0 as we need 0 coins to have a sum of 0. In the end we need to look + * if the program found a solution in sol[amount] or it remained the same, in which case we + * can return -1. + * + */ +class Solution { +public: + + int coinChange(vector& coins, int amount) { + int sol[amount + 1]; + sol[0] = 0; + for(int i = 1; i <= amount; i++) + sol[i] = amount + 1; + for(int i = 0; i < coins.size(); i++) + { + for(int j = coins[i]; j <= amount; j++) + sol[j] = min(sol[j], sol[j - coins[i]] + 1); + } + if(sol[amount] != amount + 1) + return sol[amount]; + else + return -1; + } +}; From 38f5b0b655c65eca4a6d1fb6bd65776e0112ad06 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 14 Jan 2016 09:31:58 +0800 Subject: [PATCH 009/105] typo --- .../findMinimumInRotatedSortedArray.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp b/algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp index 2ac3e33a3..9c8cc43cb 100644 --- a/algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp +++ b/algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp @@ -38,7 +38,7 @@ int findMin(vector &num) { } // The array is rotated - // Spli it into two part, the minimal value must be the rotated part + // Split it into two part, the minimal value must be the rotated part // if the left part is rotated, warch the left part if (num[low] > num [mid]){ From e8d5796753a79cabf44fbd635033be0918c0aafd Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 14 Jan 2016 09:31:58 +0800 Subject: [PATCH 010/105] typo --- .../findMinimumInRotatedSortedArray.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp b/algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp index 2ac3e33a3..9c8cc43cb 100644 --- a/algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp +++ b/algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp @@ -38,7 +38,7 @@ int findMin(vector &num) { } // The array is rotated - // Spli it into two part, the minimal value must be the rotated part + // Split it into two part, the minimal value must be the rotated part // if the left part is rotated, warch the left part if (num[low] > num [mid]){ From be27a989a5e0f330f0936b68835c31921edc9c54 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 14 Jan 2016 09:32:20 +0800 Subject: [PATCH 011/105] New Problem "Power of Three" --- README.md | 1 + algorithms/cpp/powerOfThree/PowerOfThree.cpp | 66 ++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 algorithms/cpp/powerOfThree/PowerOfThree.cpp diff --git a/README.md b/README.md index 539f6b37d..67b0f1199 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| diff --git a/algorithms/cpp/powerOfThree/PowerOfThree.cpp b/algorithms/cpp/powerOfThree/PowerOfThree.cpp new file mode 100644 index 000000000..a75143b91 --- /dev/null +++ b/algorithms/cpp/powerOfThree/PowerOfThree.cpp @@ -0,0 +1,66 @@ +// Source : https://leetcode.com/problems/power-of-three/ +// Author : Hao Chen +// Date : 2016-01-14 + +/*************************************************************************************** + * + * Given an integer, write a function to determine if it is a power of three. + * + * Follow up: + * Could you do it without using any loop / recursion? + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + * + ***************************************************************************************/ + +class Solution { + +public: + + bool isPowerOfThree(int n) { + return isPowerOfThree03(n); //140ms + return isPowerOfThree02(n);//130ms + return isPowerOfThree01(n); //140ms + return isPowerOfThree_loop(n); //136ms + return isPowerOfThree_recursive(n); //168ms + } + + bool isPowerOfThree03(int n) { + double logRes = log10(n)/log10(3); + return (logRes - int(logRes) == 0); + } + bool isPowerOfThree02(int n) { + return n>0 ? (1162261467%n==0) : false; + } + + void init(unordered_map& power ){ + int p = 1; + power[1]=true; + while(1){ + p *= 3; + power[p] = true; + if (p > INT_MAX/3) break; + + } + } + bool isPowerOfThree01(int n) { + static unordered_map power; + if (power.size()==0) init(power); + return power.find(n) != power.end(); + } + + bool isPowerOfThree_loop(int n) { + for(;n>0;n /= 3){ + if (n==1 || n==3) return true; + if (n%3 != 0) return false; + } + return false; + } + + bool isPowerOfThree_recursive(int n) { + if ( n == 1 || n == 3) return true; + if ( n==0 || n%3 != 0 ) return false; + return isPowerOfThree_recursive(n/3); + } +}; From 73279a1a75af7011a864e6c2d496fe3df0162e98 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 14 Jan 2016 09:32:20 +0800 Subject: [PATCH 012/105] New Problem "Power of Three" --- README.md | 1 + algorithms/cpp/powerOfThree/PowerOfThree.cpp | 66 ++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 algorithms/cpp/powerOfThree/PowerOfThree.cpp diff --git a/README.md b/README.md index 539f6b37d..67b0f1199 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| diff --git a/algorithms/cpp/powerOfThree/PowerOfThree.cpp b/algorithms/cpp/powerOfThree/PowerOfThree.cpp new file mode 100644 index 000000000..a75143b91 --- /dev/null +++ b/algorithms/cpp/powerOfThree/PowerOfThree.cpp @@ -0,0 +1,66 @@ +// Source : https://leetcode.com/problems/power-of-three/ +// Author : Hao Chen +// Date : 2016-01-14 + +/*************************************************************************************** + * + * Given an integer, write a function to determine if it is a power of three. + * + * Follow up: + * Could you do it without using any loop / recursion? + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + * + ***************************************************************************************/ + +class Solution { + +public: + + bool isPowerOfThree(int n) { + return isPowerOfThree03(n); //140ms + return isPowerOfThree02(n);//130ms + return isPowerOfThree01(n); //140ms + return isPowerOfThree_loop(n); //136ms + return isPowerOfThree_recursive(n); //168ms + } + + bool isPowerOfThree03(int n) { + double logRes = log10(n)/log10(3); + return (logRes - int(logRes) == 0); + } + bool isPowerOfThree02(int n) { + return n>0 ? (1162261467%n==0) : false; + } + + void init(unordered_map& power ){ + int p = 1; + power[1]=true; + while(1){ + p *= 3; + power[p] = true; + if (p > INT_MAX/3) break; + + } + } + bool isPowerOfThree01(int n) { + static unordered_map power; + if (power.size()==0) init(power); + return power.find(n) != power.end(); + } + + bool isPowerOfThree_loop(int n) { + for(;n>0;n /= 3){ + if (n==1 || n==3) return true; + if (n%3 != 0) return false; + } + return false; + } + + bool isPowerOfThree_recursive(int n) { + if ( n == 1 || n == 3) return true; + if ( n==0 || n%3 != 0 ) return false; + return isPowerOfThree_recursive(n/3); + } +}; From 7b084c822038e474e2a595cf46af31f860a19917 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 15 Jan 2016 15:03:32 +0800 Subject: [PATCH 013/105] another solution --- .../countOfSmallerNumbersAfterSelf.cpp | 79 ++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp b/algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp index cac1435c4..badec47d2 100644 --- a/algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp +++ b/algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp @@ -1,5 +1,5 @@ // Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/ -// Author : Calinescu Valentin +// Author : Calinescu Valentin, Hao Chen // Date : 2015-12-08 /*************************************************************************************** @@ -73,3 +73,80 @@ class Solution { return sol; } }; + + +/*************************************************************************************** + * Another solution - Binary Search Tree + ***************************************************************************************/ + + +class BinarySearchTreeNode +{ + public: + int val; + int less; // count of members less than val + int count; // count of members equal val + BinarySearchTreeNode *left, *right; + BinarySearchTreeNode(int value) : val(value), less(0),count(1),left(NULL), right(NULL) {} +}; + +class BinarySearchTree +{ + private: + BinarySearchTreeNode* root; + public: + BinarySearchTree(const int value):root(new BinarySearchTreeNode(value)){ } + ~BinarySearchTree() { + freeTree(root); + } + void insert(const int value, int &numLessThan) { + insert(root, value, numLessThan); + } + private: + void freeTree(BinarySearchTreeNode* root){ + if (root == NULL) return; + if (root->left) freeTree(root->left); + if (root->right) freeTree(root->right); + delete root; + } + + void insert(BinarySearchTreeNode* root, const int value, int &numLessThan) { + + if(value < root->val) { // left + root->less++; + if(root->left == NULL) { + root->left = new BinarySearchTreeNode(value); + }else{ + this->insert(root->left, value, numLessThan); + } + } else if(value > root->val) { // right + numLessThan += root->less + root->count; + if(!root->right) { + root->right = new BinarySearchTreeNode(value); + }else{ + this->insert(root->right, value, numLessThan); + } + } else { + numLessThan += root->less; + root->count++; + return; + } + } +}; + +class Solution { + public: + vector countSmaller(vector& nums) { + vector counts(nums.size()); + if(nums.size() == 0) return counts; + + BinarySearchTree tree(nums[nums.size()-1]); + + for(int i = nums.size() - 2; i >= 0; i--) { + int numLessThan = 0; + tree.insert( nums[i], numLessThan); + counts[i] = numLessThan; + } + return counts; + } +}; From 12450188eceacab8e98e2ab1c02027e4ae380d9b Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 15 Jan 2016 15:03:32 +0800 Subject: [PATCH 014/105] another solution --- .../countOfSmallerNumbersAfterSelf.cpp | 79 ++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp b/algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp index cac1435c4..badec47d2 100644 --- a/algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp +++ b/algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp @@ -1,5 +1,5 @@ // Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/ -// Author : Calinescu Valentin +// Author : Calinescu Valentin, Hao Chen // Date : 2015-12-08 /*************************************************************************************** @@ -73,3 +73,80 @@ class Solution { return sol; } }; + + +/*************************************************************************************** + * Another solution - Binary Search Tree + ***************************************************************************************/ + + +class BinarySearchTreeNode +{ + public: + int val; + int less; // count of members less than val + int count; // count of members equal val + BinarySearchTreeNode *left, *right; + BinarySearchTreeNode(int value) : val(value), less(0),count(1),left(NULL), right(NULL) {} +}; + +class BinarySearchTree +{ + private: + BinarySearchTreeNode* root; + public: + BinarySearchTree(const int value):root(new BinarySearchTreeNode(value)){ } + ~BinarySearchTree() { + freeTree(root); + } + void insert(const int value, int &numLessThan) { + insert(root, value, numLessThan); + } + private: + void freeTree(BinarySearchTreeNode* root){ + if (root == NULL) return; + if (root->left) freeTree(root->left); + if (root->right) freeTree(root->right); + delete root; + } + + void insert(BinarySearchTreeNode* root, const int value, int &numLessThan) { + + if(value < root->val) { // left + root->less++; + if(root->left == NULL) { + root->left = new BinarySearchTreeNode(value); + }else{ + this->insert(root->left, value, numLessThan); + } + } else if(value > root->val) { // right + numLessThan += root->less + root->count; + if(!root->right) { + root->right = new BinarySearchTreeNode(value); + }else{ + this->insert(root->right, value, numLessThan); + } + } else { + numLessThan += root->less; + root->count++; + return; + } + } +}; + +class Solution { + public: + vector countSmaller(vector& nums) { + vector counts(nums.size()); + if(nums.size() == 0) return counts; + + BinarySearchTree tree(nums[nums.size()-1]); + + for(int i = nums.size() - 2; i >= 0; i--) { + int numLessThan = 0; + tree.insert( nums[i], numLessThan); + counts[i] = numLessThan; + } + return counts; + } +}; From b430d99d3bbd9c57b8b11b548a88b58fafb0d5c9 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 15 Jan 2016 22:42:31 +0800 Subject: [PATCH 015/105] New Problem "Count of Range Sum" --- README.md | 1 + .../cpp/countOfRangeSum/CountOfRangeSum.cpp | 163 ++++++++++++++++++ 2 files changed, 164 insertions(+) create mode 100644 algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp diff --git a/README.md b/README.md index cfee4ebf2..c4c976e14 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| |326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| diff --git a/algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp b/algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp new file mode 100644 index 000000000..81b1f21bb --- /dev/null +++ b/algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp @@ -0,0 +1,163 @@ +// Source : https://leetcode.com/problems/count-of-range-sum/ +// Author : Hao Chen +// Date : 2016-01-15 + +/*************************************************************************************** + * + * Given an integer array nums, return the number of range sums that lie in [lower, + * upper] inclusive. + * + * Range sum S(i, j) is defined as the sum of the elements in nums between indices + * i and + * j (i ≤ j), inclusive. + * + * Note: + * A naive algorithm of O(n2) is trivial. You MUST do better than that. + * + * Example: + * Given nums = [-2, 5, -1], lower = -2, upper = 2, + * Return 3. + * The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2. + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + * + ***************************************************************************************/ + + +/* + * At first of all, we can do preprocess to calculate the prefix sums + * + * S[i] = S(0, i), then S(i, j) = S[j] - S[i]. + * + * Note: S(i, j) as the sum of range [i, j) where j exclusive and j > i. + * + * With these prefix sums, it is trivial to see that with O(n^2) time we can find all S(i, j) + * in the range [lower, upper] + * + * int countRangeSum(vector& nums, int lower, int upper) { + * int n = nums.size(); + * long[] sums = new long[n + 1]; + * for (int i = 0; i < n; ++i) { + * sums[i + 1] = sums[i] + nums[i]; + * } + * int ans = 0; + * for (int i = 0; i < n; ++i) { + * for (int j = i + 1; j <= n; ++j) { + * if (sums[j] - sums[i] >= lower && sums[j] - sums[i] <= upper) { + * ans++; + * } + * } + * } + * delete []sums; + * return ans; + * } + * + * The above solution would get time limit error. + * + * Recall `count smaller number after self` where we encountered the problem + * + * count[i] = count of nums[j] - nums[i] < 0 with j > i + * + * Here, after we did the preprocess, we need to solve the problem + * + * count[i] = count of a <= S[j] - S[i] <= b with j > i + * + * In other words, if we maintain the prefix sums sorted, and then are able to find out + * - how many of the sums are less than 'lower', say num1, + * - how many of the sums are less than 'upper + 1', say num2, + * Then 'num2 - num1' is the number of sums that lie within the range of [lower, upper]. + * + */ + +class Node{ + public: + long long val; + int cnt; //amount of the nodes + Node *left, *right; + Node(long long v):val(v), cnt(1), left(NULL), right(NULL) {} +}; + +// a tree stores all of prefix sums +class Tree{ + public: + Tree():root(NULL){ } + ~Tree() { freeTree(root); } + + void Insert(long long val) { + Insert(root, val); + } + int LessThan(long long sum, int val) { + return LessThan(root, sum, val, 0); + } + + private: + Node* root; + + //general binary search tree insert algorithm + void Insert(Node* &root, long long val) { + if (!root) { + root = new Node(val); + return; + } + + root->cnt++; + + if (val < root->val ) { + Insert(root->left, val); + }else if (val > root->val) { + Insert(root->right, val); + } + } + //return how many of the sums less than `val` + // - `sum` is the new sums which hasn't been inserted + // - `val` is the `lower` or `upper+1` + int LessThan(Node* root, long long sum, int val, int res) { + + if (!root) return res; + + if ( sum - root->val < val) { + //if (sum[j, i] < val), which means all of the right branch must be less than `val` + //so we add the amounts of sums in right branch, and keep going the left branch. + res += (root->cnt - (root->left ? root->left->cnt : 0) ); + return LessThan(root->left, sum, val, res); + }else if ( sum - root->val > val) { + //if (sum[j, i] > val), which means all of left brach must be greater than `val` + //so we just keep going the right branch. + return LessThan(root->right, sum, val, res); + }else { + //if (sum[j,i] == val), which means we find the correct place, + //so we just return the the amounts of right branch.] + return res + (root->right ? root->right->cnt : 0); + } + } + void freeTree(Node* root){ + if (!root) return; + if (root->left) freeTree(root->left); + if (root->right) freeTree(root->right); + delete root; + } + +}; + + + +class Solution { +public: + int countRangeSum(vector& nums, int lower, int upper) { + Tree tree; + tree.Insert(0); + long long sum = 0; + int res = 0; + + for (int n : nums) { + sum += n; + int lcnt = tree.LessThan(sum, lower); + int hcnt = tree.LessThan(sum, upper + 1); + res += (hcnt - lcnt); + tree.Insert(sum); + } + + return res; + } +}; From b40ca7942d9b2d1fd711b8e5cbd2b5e8007975d3 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 15 Jan 2016 22:42:31 +0800 Subject: [PATCH 016/105] New Problem "Count of Range Sum" --- README.md | 1 + .../cpp/countOfRangeSum/CountOfRangeSum.cpp | 163 ++++++++++++++++++ 2 files changed, 164 insertions(+) create mode 100644 algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp diff --git a/README.md b/README.md index cfee4ebf2..c4c976e14 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| |326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| diff --git a/algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp b/algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp new file mode 100644 index 000000000..81b1f21bb --- /dev/null +++ b/algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp @@ -0,0 +1,163 @@ +// Source : https://leetcode.com/problems/count-of-range-sum/ +// Author : Hao Chen +// Date : 2016-01-15 + +/*************************************************************************************** + * + * Given an integer array nums, return the number of range sums that lie in [lower, + * upper] inclusive. + * + * Range sum S(i, j) is defined as the sum of the elements in nums between indices + * i and + * j (i ≤ j), inclusive. + * + * Note: + * A naive algorithm of O(n2) is trivial. You MUST do better than that. + * + * Example: + * Given nums = [-2, 5, -1], lower = -2, upper = 2, + * Return 3. + * The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2. + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + * + ***************************************************************************************/ + + +/* + * At first of all, we can do preprocess to calculate the prefix sums + * + * S[i] = S(0, i), then S(i, j) = S[j] - S[i]. + * + * Note: S(i, j) as the sum of range [i, j) where j exclusive and j > i. + * + * With these prefix sums, it is trivial to see that with O(n^2) time we can find all S(i, j) + * in the range [lower, upper] + * + * int countRangeSum(vector& nums, int lower, int upper) { + * int n = nums.size(); + * long[] sums = new long[n + 1]; + * for (int i = 0; i < n; ++i) { + * sums[i + 1] = sums[i] + nums[i]; + * } + * int ans = 0; + * for (int i = 0; i < n; ++i) { + * for (int j = i + 1; j <= n; ++j) { + * if (sums[j] - sums[i] >= lower && sums[j] - sums[i] <= upper) { + * ans++; + * } + * } + * } + * delete []sums; + * return ans; + * } + * + * The above solution would get time limit error. + * + * Recall `count smaller number after self` where we encountered the problem + * + * count[i] = count of nums[j] - nums[i] < 0 with j > i + * + * Here, after we did the preprocess, we need to solve the problem + * + * count[i] = count of a <= S[j] - S[i] <= b with j > i + * + * In other words, if we maintain the prefix sums sorted, and then are able to find out + * - how many of the sums are less than 'lower', say num1, + * - how many of the sums are less than 'upper + 1', say num2, + * Then 'num2 - num1' is the number of sums that lie within the range of [lower, upper]. + * + */ + +class Node{ + public: + long long val; + int cnt; //amount of the nodes + Node *left, *right; + Node(long long v):val(v), cnt(1), left(NULL), right(NULL) {} +}; + +// a tree stores all of prefix sums +class Tree{ + public: + Tree():root(NULL){ } + ~Tree() { freeTree(root); } + + void Insert(long long val) { + Insert(root, val); + } + int LessThan(long long sum, int val) { + return LessThan(root, sum, val, 0); + } + + private: + Node* root; + + //general binary search tree insert algorithm + void Insert(Node* &root, long long val) { + if (!root) { + root = new Node(val); + return; + } + + root->cnt++; + + if (val < root->val ) { + Insert(root->left, val); + }else if (val > root->val) { + Insert(root->right, val); + } + } + //return how many of the sums less than `val` + // - `sum` is the new sums which hasn't been inserted + // - `val` is the `lower` or `upper+1` + int LessThan(Node* root, long long sum, int val, int res) { + + if (!root) return res; + + if ( sum - root->val < val) { + //if (sum[j, i] < val), which means all of the right branch must be less than `val` + //so we add the amounts of sums in right branch, and keep going the left branch. + res += (root->cnt - (root->left ? root->left->cnt : 0) ); + return LessThan(root->left, sum, val, res); + }else if ( sum - root->val > val) { + //if (sum[j, i] > val), which means all of left brach must be greater than `val` + //so we just keep going the right branch. + return LessThan(root->right, sum, val, res); + }else { + //if (sum[j,i] == val), which means we find the correct place, + //so we just return the the amounts of right branch.] + return res + (root->right ? root->right->cnt : 0); + } + } + void freeTree(Node* root){ + if (!root) return; + if (root->left) freeTree(root->left); + if (root->right) freeTree(root->right); + delete root; + } + +}; + + + +class Solution { +public: + int countRangeSum(vector& nums, int lower, int upper) { + Tree tree; + tree.Insert(0); + long long sum = 0; + int res = 0; + + for (int n : nums) { + sum += n; + int lcnt = tree.LessThan(sum, lower); + int hcnt = tree.LessThan(sum, upper + 1); + res += (hcnt - lcnt); + tree.Insert(sum); + } + + return res; + } +}; From eb58453db5801615133c36965e77bad0f803b302 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 16 Jan 2016 21:02:16 +0800 Subject: [PATCH 017/105] filter out the blank line --- scripts/comments.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/comments.sh b/scripts/comments.sh index 1d518fe24..69a6a10b6 100755 --- a/scripts/comments.sh +++ b/scripts/comments.sh @@ -160,14 +160,14 @@ fi # 2) the last two `sed` commands are used to add the comments tags case $FILE_EXT in .cpp ) xidel ${leetcode_url} -q -e "css('div.question-content')" | \ - grep -v ' ' | sed '/^$/N;/^\n$/D' | fold -w 85 -s |\ + grep -v ' ' | sed '/^$/N;/^\n$/D' | fold -w 85 -s |\ sed 's/^/ * /' | sed '1i\'$'\n'"/*$(printf '%.0s*' {0..85}) "$'\n' |\ sed '2i\'$'\n''!@#$%'$'\n' | sed 's/!@#$%/ */' | \ sed '$a\'$'\n'"*$(printf '%.0s*' {0..85})*/"$'\n'| \ sed 's/^*/ /' > /tmp/tmp.txt ;; .sh ) xidel ${leetcode_url} -q -e "css('div.question-content')" | \ - grep -v ' ' |sed '/^$/N;/^\n$/D' | fold -w 85 -s| \ + grep -v ' ' |sed '/^$/N;/^\n$/D' | fold -w 85 -s| \ sed 's/^/# /' | sed '1i\'$'\n'"#$(printf '%.0s#' {0..85}) "$'\n' | \ sed '2i\'$'\n''#'$'\n' | sed '$a\'$'\n'"#$(printf '%.0s#' {0..85})"$'\n'\ > /tmp/tmp.txt From e3b71eed8590fe9d1571d25f1cad00a34a60ea9a Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 16 Jan 2016 21:04:17 +0800 Subject: [PATCH 018/105] New Problem "Expression Add Operators" --- .../ExpressionAddOperators.cpp | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 algorithms/cpp/expressionAddOperators/ExpressionAddOperators.cpp diff --git a/algorithms/cpp/expressionAddOperators/ExpressionAddOperators.cpp b/algorithms/cpp/expressionAddOperators/ExpressionAddOperators.cpp new file mode 100644 index 000000000..573d4fd26 --- /dev/null +++ b/algorithms/cpp/expressionAddOperators/ExpressionAddOperators.cpp @@ -0,0 +1,81 @@ +// Source : https://leetcode.com/problems/expression-add-operators/ +// Author : Hao Chen +// Date : 2016-01-16 + +/*************************************************************************************** + * + * Given a string that contains only digits 0-9 and a target value, return all + * possibilities to add binary operators (not unary) +, -, or * between the digits so + * they evaluate to the target value. + * + * Examples: + * "123", 6 -> ["1+2+3", "1*2*3"] + * "232", 8 -> ["2*3+2", "2+3*2"] + * "105", 5 -> ["1*0+5","10-5"] + * "00", 0 -> ["0+0", "0-0", "0*0"] + * "3456237490", 9191 -> [] + * + * Credits:Special thanks to @davidtan1890 for adding this problem and creating all + * test cases. + ***************************************************************************************/ + + +class Solution { +public: + vector addOperators(string num, int target) { + vector result; + if (num.size() == 0) return result; + helper(num, target, result, "", 0, 0, 0, ' '); + return result; + } + + //DFS algorithm + void helper(const string &num, const int target, //`num` and `target` never change + vector& result, // the array store all of the answers + string solution, //the current potential answer. + int idx, // the current index of `num` array + long long val, // the current value we calculated so far + long long prev, // the lastest value we used for calculation, which used for operation prioirty adjustment + char preop ) // the latest "+" or "-" operation, which used for operation prioirty adjustment + { + + if (target == val && idx == num.size()){ + result.push_back(solution); + return; + } + if (idx == num.size()) return; + + string n; + long long v=0; + for(int i=idx; i Date: Sat, 16 Jan 2016 21:15:22 +0800 Subject: [PATCH 019/105] update readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c4c976e14..6ed7a7ccc 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ LeetCode |285|[Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/) ♥ | [Java](./algorithms/java/src/inorderSuccessorInBST/inorderSuccessorInBST.java)|Medium| |284|[Peeking Iterator](https://leetcode.com/problems/peeking-iterator/) | [C++](./algorithms/cpp/peekingIterator/PeekingIterator.cpp)|Medium| |283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [C++](./algorithms/cpp/moveZeroes/moveZeroes.cpp)|Easy| +|282|[Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./algorithms/cpp/expressionAddOperators/ExpressionAddOperators.cpp)|Hard| |279|[Perfect Squares](https://leetcode.com/problems/perfect-squares/) | [C++](./algorithms/cpp/perfectSquares/PerfectSquares.cpp)|Medium| |278|[First Bad Version](https://leetcode.com/problems/first-bad-version/)| [C++](./algorithms/cpp/firstBadVersion/FirstBadVersion.cpp), [Java](./algorithms/java/src/firstBadVersion/firstBadVersion.java)|Easy| |275|[H-Index II](https://leetcode.com/problems/h-index-ii/)| [C++](./algorithms/cpp/h-Index/h-Index.II.cpp)|Medium| From 1ab20b068dac5d7eff3878ddaa01493719cd81d1 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 16 Jan 2016 22:03:01 +0800 Subject: [PATCH 020/105] New Problem "Odd Even Linked List" --- README.md | 1 + .../oddEvenLinkedList/OddEvenLinkedList.cpp | 53 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp diff --git a/README.md b/README.md index 6ed7a7ccc..42d073936 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [C++](./algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp)|Easy| |327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| |326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| diff --git a/algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp b/algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp new file mode 100644 index 000000000..6a206978e --- /dev/null +++ b/algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp @@ -0,0 +1,53 @@ +// Source : https://leetcode.com/problems/odd-even-linked-list/ +// Author : Hao Chen +// Date : 2016-01-16 + +/*************************************************************************************** + * + * Given a singly linked list, group all odd nodes together followed by the even nodes. + * Please note here we are talking about the node number and not the value in the nodes. + * + * You should try to do it in place. The program should run in O(1) space complexity + * and O(nodes) time complexity. + * + * Example: + * Given 1->2->3->4->5->NULL, + * return 1->3->5->2->4->NULL. + * + * Note: + * The relative order inside both the even and odd groups should remain as it was in + * the input. + * The first node is considered odd, the second node even and so on ... + * + * Credits:Special thanks to @aadarshjajodia for adding this problem and creating all + * test cases. + ***************************************************************************************/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* oddEvenList(ListNode* head) { + if (!head) return head; + ListNode* pOdd = head; + ListNode* p = head->next; + ListNode* pNext = NULL; + while(p && (pNext=p->next)) { + + p->next = pNext->next; + pNext->next = pOdd->next; + pOdd->next = pNext; + + p = p->next; + pOdd = pOdd->next; + + } + return head; + } +}; From 1c8023e53f27cc99b2df4360bd35a0647e490005 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 16 Jan 2016 22:45:04 +0800 Subject: [PATCH 021/105] New Problem "Single Number III" --- README.md | 1 + .../cpp/singleNumber/singleNumber.III.cpp | 94 +++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 algorithms/cpp/singleNumber/singleNumber.III.cpp diff --git a/README.md b/README.md index 42d073936..3dfe34ef6 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ LeetCode |268|[Missing Number](https://leetcode.com/problems/missing-number/)| [C++](./algorithms/cpp/missingNumber/MissingNumber.cpp)|Medium| |264|[Ugly Number II](https://leetcode.com/problems/ugly-number-ii/)| [C++](./algorithms/cpp/uglyNumber/UglyNumber.II.cpp)|Medium| |263|[Ugly Number](https://leetcode.com/problems/ugly-number/)| [C++](./algorithms/cpp/uglyNumber/UglyNumber.cpp)|Easy| +|260|[Single Number III](https://leetcode.com/problems/single-number-iii/)| [C++](./argorithms/cpp/singleNumber/singleNumber.III.cpp)|Medium| |258|[Add Digits](https://leetcode.com/problems/add-digits/)| [C++](./algorithms/cpp/addDigits/addDigits.cpp)|Easy| |257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)| [C++](./algorithms/cpp/binaryTreePaths/binaryTreePaths.cpp)|Easy| |242|[Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./algorithms/cpp/anagrams/ValidAnagram.cpp)|Easy| diff --git a/algorithms/cpp/singleNumber/singleNumber.III.cpp b/algorithms/cpp/singleNumber/singleNumber.III.cpp new file mode 100644 index 000000000..d2f86bd52 --- /dev/null +++ b/algorithms/cpp/singleNumber/singleNumber.III.cpp @@ -0,0 +1,94 @@ +// Source : https://leetcode.com/problems/single-number-iii/ +// Author : Hao Chen +// Date : 2016-01-16 + +/*************************************************************************************** + * + * Given an array of numbers nums, in which exactly two elements appear only once and + * all the other elements appear exactly twice. Find the two elements that appear only + * once. + * + * For example: + * + * Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. + * + * Note: + * + * The order of the result is not important. So in the above example, [5, 3] is also + * correct. + * Your algorithm should run in linear runtime complexity. Could you implement it using + * only constant space complexity? + * + * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating + * all test cases. + ***************************************************************************************/ + + +/* + * For the problem - only one number appears once when all other numbers appears exactly twice. + * + * We know, we can XOR all of the array elements. Since X^X is zero, and X^0 is X, + * so all of the duplicated number will zero themselves out, and the only number would be the result. + * + * However, this solution cannot be applied directly to finding two numbers that appear once each. + * + * Suppose that these numbers that appear once are X and Y, and all other numbers appear twice. + * If we decide to XOR all the array's elements, the overall result would actually be `X^Y`. + * + * Unfortunately, there is no way to extract J and K out of their XOR. + * + * But since X and Y are different, we are sure that X^Y is different than zero. + * + * This information is valuable in sense that we know pieces of information that differ. + * If we pick up any bit that is 1 in X XOR Y, we can use it as a mask to test each element of the array. + * + * Obviously, that mask will be the discriminator between X and Y - + * + * Only one of them will have value 1 at that particular position. + * + * + * Now that we have the mask with exactly one bit set to 1, we can walk through the array once again. + * + * But this time we are going to maintain two XORed results. + * + * - One for numbers that have bit 1 at the mask's position + * - Another for numbers that have bit 0 at that position + * + * In this way, we are sure that all duplicates will go into the same pile. + * + * But likewise, we are sure that X and Y will go into separate piles. + * + * So, the overall result is that + * - the first XORed result will be equal to X + * - and the second XORed result will be equal to Y + * +*/ + +class Solution { +public: + vector singleNumber(vector& nums) { + int allxor = 0; + for (int n : nums) { + allxor ^= n; + } + int mask = 1; + while ( (mask & allxor) == 0 ) { + mask <<= 1; + } + + int zero = 0; + int one = 0; + for (int n : nums) { + if (n & mask ){ + one ^= n; + }else { + zero ^= n; + } + } + + vector result; + result.push_back(zero); + result.push_back(one); + return result; + } +}; From 0d9585f087581fe693abe7075764ebc372e3382c Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 16 Jan 2016 22:46:37 +0800 Subject: [PATCH 022/105] link error --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3dfe34ef6..aa2f240c2 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ LeetCode |268|[Missing Number](https://leetcode.com/problems/missing-number/)| [C++](./algorithms/cpp/missingNumber/MissingNumber.cpp)|Medium| |264|[Ugly Number II](https://leetcode.com/problems/ugly-number-ii/)| [C++](./algorithms/cpp/uglyNumber/UglyNumber.II.cpp)|Medium| |263|[Ugly Number](https://leetcode.com/problems/ugly-number/)| [C++](./algorithms/cpp/uglyNumber/UglyNumber.cpp)|Easy| -|260|[Single Number III](https://leetcode.com/problems/single-number-iii/)| [C++](./argorithms/cpp/singleNumber/singleNumber.III.cpp)|Medium| +|260|[Single Number III](https://leetcode.com/problems/single-number-iii/)| [C++](./algorithms/cpp/singleNumber/singleNumber.III.cpp)|Medium| |258|[Add Digits](https://leetcode.com/problems/add-digits/)| [C++](./algorithms/cpp/addDigits/addDigits.cpp)|Easy| |257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)| [C++](./algorithms/cpp/binaryTreePaths/binaryTreePaths.cpp)|Easy| |242|[Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./algorithms/cpp/anagrams/ValidAnagram.cpp)|Easy| From 1f24b4a199f7cae2a9f46d0b915f72d1b0ef28b5 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sun, 17 Jan 2016 16:12:12 +0800 Subject: [PATCH 023/105] New Problem "Burst Balloons" --- README.md | 1 + .../cpp/burstBalloons/BurstBalloons.cpp | 104 ++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 algorithms/cpp/burstBalloons/BurstBalloons.cpp diff --git a/README.md b/README.md index aa2f240c2..6a9945f68 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ LeetCode |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| +|312|[Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./algorithms/cpp/burstBalloons/BurstBalloons.cpp)|Hard| |307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Mutable/RangeSumQueryMutable.cpp)|Medium| |306|[Additive Number](https://leetcode.com/problems/additive-number/) | [C++](./algorithms/cpp/additiveNumber/AdditiveNumber.cpp)|Medium| |304|[Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/) | [C++](./algorithms/cpp/rangeSumQuery2D-Immutable/RangeSumQuery2dImmutable.cpp)|Medium| diff --git a/algorithms/cpp/burstBalloons/BurstBalloons.cpp b/algorithms/cpp/burstBalloons/BurstBalloons.cpp new file mode 100644 index 000000000..901f2e8eb --- /dev/null +++ b/algorithms/cpp/burstBalloons/BurstBalloons.cpp @@ -0,0 +1,104 @@ +// Source : https://leetcode.com/problems/burst-balloons/ +// Author : Hao Chen +// Date : 2016-01-17 + +/*************************************************************************************** + * + * Given n balloons, indexed from 0 to n-1. Each balloon is painted with a + * number on it represented by array nums. + * + * You are asked to burst all the balloons. If the you burst + * balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left + * and right are adjacent indices of i. After the burst, the left and right + * then becomes adjacent. + * + * Find the maximum coins you can collect by bursting the balloons wisely. + * + * Note: + * (1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can + * not burst them. + * (2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 + * + * Example: + * + * Given [3, 1, 5, 8] + * + * Return 167 + * + * nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] + * coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + + + +class Solution { +public: + int maxCoins(vector& nums) { + //remove all of zero item + nums.erase(remove_if(nums.begin(), nums.end(), [](int n){return n==0;}), nums.end()); + + //add 1 for head and tail + nums.insert(nums.begin(),1); + nums.push_back(1); + + int n = nums.size(); + vector< vector > matrix(n, vector(n,0)); + + return maxCoins_DP(nums, matrix); + return maxCoins_DC(nums, matrix, 0, n-1); + } + + + //Divide and Conquer + // + // If we seprate the array to two part, left part and right part. + // + // Then, we will find in this problem the left and right become adjacent + // and have effects on the maxCoins in the future. + // + // So, if we think reversely, if the balloon i is the last balloon of all to burst, + // the left and right section now has well defined boundary and do not affect each other! + // Therefore we can do either recursive method with memoization + // + int maxCoins_DC(vector& nums, vector>& matrix, int low, int high) { + if (low + 1 == high) return 0; + if (matrix[low][high] > 0) return matrix[low][high]; + int result = 0; + for (int i = low + 1; i < high; ++i){ + result = max(result, nums[low] * nums[i] * nums[high] + + maxCoins_DC(nums, matrix, low, i) + + maxCoins_DC(nums, matrix, i, high)); + } + matrix[low][high] = result; + return result; + } + + //Dynamic Programming + // + // using the same idea of above + // + int maxCoins_DP(vector& nums, vector>& dp) { + int n = nums.size(); + for (int k = 2; k < n; ++k) { + for (int low = 0; low < n - k; low++){ + int high = low + k; + for (int i = low + 1; i < high; ++i) + dp[low][high] = max( dp[low][high], + nums[low] * nums[i] * nums[high] + dp[low][i] + dp[i][high]); + } + } + return dp[0][n - 1]; + } + +private: + void printVector(vector& nums) { + cout << "nums: "; + for (auto n: nums) { + cout << n << ' '; + } + cout << '\n'; + } +}; From 53fe7c9cac47b32b6ee11b6d90193738f100cd45 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 21 Jan 2016 15:13:39 +0800 Subject: [PATCH 024/105] New Problem "Create Maximum Number" --- README.md | 1 + .../CreateMaximumNumber.cpp | 152 ++++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100644 algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp diff --git a/README.md b/README.md index 6a9945f68..6d154e63c 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ LeetCode |327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| |326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| +|321|[Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | [C++](./algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp)|Hard| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| |312|[Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./algorithms/cpp/burstBalloons/BurstBalloons.cpp)|Hard| diff --git a/algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp b/algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp new file mode 100644 index 000000000..dc88f9a41 --- /dev/null +++ b/algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp @@ -0,0 +1,152 @@ +// Source : https://leetcode.com/problems/create-maximum-number/ +// Author : Hao Chen +// Date : 2016-01-21 + +/*************************************************************************************** + * + * Given two arrays of length m and n with digits 0-9 representing two numbers. + * Create the maximum number of length k from digits of the two. The relative + * order of the digits + * from the same array must be preserved. Return an array of the k digits. You + * should try to optimize your time and space complexity. + * + * Example 1: + * + * nums1 = [3, 4, 6, 5] + * nums2 = [9, 1, 2, 5, 8, 3] + * k = 5 + * return [9, 8, 6, 5, 3] + * + * Example 2: + * + * nums1 = [6, 7] + * nums2 = [6, 0, 4] + * k = 5 + * return [6, 7, 6, 0, 4] + * + * Example 3: + * + * nums1 = [3, 9] + * nums2 = [8, 9] + * k = 3 + * return [9, 8, 9] + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + + + +/* + * Solution + * -------- + * + * 1) We split the `K` to two parts : `i` & `k-i` 0<= i <= k + * + * 2) Find the max number for both arrays with giving the length `i` and `k-i` + * - sub1 = FindMaxNumber(num1, len=i); + * - sub2 = FindMaxNumber(num2, len=k-i); + * Here, we need use stack-way to solve find the max number. + * + * 3) Merge two arrays + * - solution = Merge(sub1, sub2); + * Here, we need be careful if a two number are same which one we need to take. For examples: + * [6,7] + * [6,0,4] + * 5 + * + * [2,5,6,4,4,0] + * [7,3,8,0,6,5,7,6,2] + * 15 + * + * 4) compare with the last solution + * - result = max(result, solution); + * + * + */ + + +class Solution { +public: + vector maxNumber(vector& nums1, vector& nums2, int k) { + vector result; + int len1 = nums1.size(); + int len2 = nums2.size(); + for (int i=0; i<=k; i++){ + if (len1 < i || len2 < k-i) continue; + vector sub1 = findMaxSubArray(nums1, i); + vector sub2 = findMaxSubArray(nums2, k-i); + vector merge = mergeTwoArrays(sub1, sub2); + if (compareTwoArray(merge, 0, result, 0)) { + result = merge; + } + } + return result; + } + + + bool compareTwoArray(vector& nums1, int start1, vector& nums2, int start2) { + int n1 = nums1.size(); + int n2 = nums2.size(); + for(; start1 nums2[start2]) return true; + if (nums1[start1] < nums2[start2]) return false; + } + //if num1 still have numbers, return true, else return false + return start1 < nums1.size(); + } + + vector mergeTwoArrays(vector& nums1, vector& nums2) { + vector result; + int len1 = nums1.size(); + int len2 = nums2.size(); + int pos1=0, pos2=0; + while ( pos1 < len1 && pos2 < len2 ){ + // Be careful if two numbers are equal. consider the following case + // case 1: [6,7], [6,0,4] - we have same item - 6 + // case 2: [4,0,2], [2,0,3,1] - we have same item - 0 + // which one we need to merge? + // We need compare the rest of array. + if (nums1[pos1] == nums2[pos2]){ + result.push_back( compareTwoArray(nums1, pos1+1, nums2, pos2+1) ? + nums1[pos1++] : nums2[pos2++]); + }else { + result.push_back(nums1[pos1] > nums2[pos2] ? + nums1[pos1++] : nums2[pos2++]); + } + } + + if (pos1 < len1){ + result.insert(result.end(), nums1.begin()+pos1, nums1.end()); + } + if (pos2 < len2) { + result.insert(result.end(), nums2.begin()+pos2, nums2.end()); + } + + return result; + } + + + // using a stack method to find the max sub-array + // k <= nums.size() + vector findMaxSubArray(vector& nums, int k) { + int len = nums.size(); + if ( k >= len ) return nums; + vector result(k, 0); + int idx = 0; // the postion for result array + for (int i=0; i the last element of result[], + // and we still have enough numbers, + // then pop up the item + while (idx>0 && k - idx < len - i && result[idx-1] < nums[i]) { + idx--; + } + //push the number into the result[] + if (idx < k) { + result[idx++] = nums[i]; + } + } + return result; + } + +}; From 69a1d4b8240ccb64bd456ec26d3452c7cd71669a Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 21 Jan 2016 23:44:42 +0800 Subject: [PATCH 025/105] New Problem "Longest Increasing Path in a Matrix" --- README.md | 1 + .../LongestIncreasingPathInAMatrix.cpp | 81 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp diff --git a/README.md b/README.md index 6d154e63c..8762d1e84 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp)|Medium| |328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [C++](./algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp)|Easy| |327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| |326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| diff --git a/algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp b/algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp new file mode 100644 index 000000000..a7e6a4423 --- /dev/null +++ b/algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp @@ -0,0 +1,81 @@ +// Source : https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ +// Author : Hao Chen +// Date : 2016-01-21 + +/*************************************************************************************** + * + * Given an integer matrix, find the length of the longest increasing path. + * + * From each cell, you can either move to four directions: left, right, up or down. You + * may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not + * allowed). + * + * Example 1: + * + * nums = [ + * [>9, 9, 4], + * [>6, 6, 8], + * [>2,>1, 1] + * ] + * + * Return 4 + * + * The longest increasing path is [1, 2, 6, 9]. + * + * Example 2: + * + * nums = [ + * [>3,>4,>5], + * [ 3, 2,>6], + * [ 2, 2, 1] + * ] + * + * Return 4 + * + * The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + + +class Solution { +public: + int longestIncreasingPath(vector>& matrix) { + int result = 0; + int row = matrix.size(); + int col = row ? matrix[0].size() : 0; + vector> path = vector>(row, vector(col, 0)); + for (int r = 0; r < row; r++) { + for (int c = 0; c < col; c++) { + result = max(result, helper(matrix, path, row, col, r, c)); + } + } + return result; + } + + int helper(vector>& matrix, vector>& path, const int row, const int col, int r, int c) { + + if (path[r][c]>0) return path[r][c]; + + int maxPath = 0; + + int tmp = matrix[r][c]; + matrix[r][c]=INT_MIN; + if (r < row-1 && tmp < matrix[r+1][c]) { + maxPath = max(maxPath, helper(matrix, path, row, col, r+1, c)); + } + if (c < col-1 && tmp < matrix[r][c+1]) { + maxPath = max(maxPath, helper(matrix, path, row, col, r, c+1)); + } + if (r > 0 && tmp < matrix[r-1][c]) { + maxPath = max(maxPath, helper(matrix, path, row, col, r-1, c)); + } + if (c > 0 && tmp < matrix[r][c-1]) { + maxPath = max(maxPath, helper(matrix, path, row, col, r, c-1)); + } + matrix[r][c] = tmp; + path[r][c] = maxPath + 1; + return path[r][c]; + } +}; From 50b9b4ee87d1f0c4cba69c428a7f4ff81d550c19 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sun, 24 Jan 2016 15:27:08 +0800 Subject: [PATCH 026/105] New Problem "Minimum Height Trees" --- README.md | 1 + .../minimumHeightTrees/MinimumHeightTrees.cpp | 98 +++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 algorithms/cpp/minimumHeightTrees/MinimumHeightTrees.cpp diff --git a/README.md b/README.md index 8762d1e84..6d410f75a 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ LeetCode |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| |312|[Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./algorithms/cpp/burstBalloons/BurstBalloons.cpp)|Hard| +|310|[Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/) | [C++](./algorithms/cpp/minimumHeightTrees/MinimumHeightTrees.cpp)|Medium| |307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Mutable/RangeSumQueryMutable.cpp)|Medium| |306|[Additive Number](https://leetcode.com/problems/additive-number/) | [C++](./algorithms/cpp/additiveNumber/AdditiveNumber.cpp)|Medium| |304|[Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/) | [C++](./algorithms/cpp/rangeSumQuery2D-Immutable/RangeSumQuery2dImmutable.cpp)|Medium| diff --git a/algorithms/cpp/minimumHeightTrees/MinimumHeightTrees.cpp b/algorithms/cpp/minimumHeightTrees/MinimumHeightTrees.cpp new file mode 100644 index 000000000..9f3a125f2 --- /dev/null +++ b/algorithms/cpp/minimumHeightTrees/MinimumHeightTrees.cpp @@ -0,0 +1,98 @@ +// Source : https://leetcode.com/problems/minimum-height-trees/ +// Author : Hao Chen +// Date : 2016-01-24 + +/*************************************************************************************** + * + * For a undirected graph with tree characteristics, we can choose any node as the + * root. The result graph is then a rooted tree. Among all possible rooted trees, those + * with minimum height are called minimum height trees (MHTs). + * + * Given such a graph, write a function to find all the MHTs and return a list of + * their root labels. + * + * *Format* + * The graph contains n nodes which are labeled from 0 to n - 1. + * You will be given the number n and a list of undirected edges (each edge is a + * pair of labels). + * + * + * You can assume that no duplicate edges will appear in edges. Since all edges are + * undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. + * + * Example 1: + * + * Given n = 4, edges = [[1, 0], [1, 2], [1, 3]] + * + * 0 + * | + * 1 + * / \ + * 2 3 + * + * return [1] + * + * Example 2: + * + * Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] + * + * 0 1 2 + * \ | / + * 3 + * | + * 4 + * | + * 5 + * + * return [3, 4] + * + * How many MHTs can a graph have at most? + * + * Note: + * + * (1) According to the definition of tree on Wikipedia: https://en.wikipedia.org/wiki/Tree_(graph_theory) + * “a tree is an undirected graph in which any two vertices are connected by exactly one path. + * In other words, any connected graph without simple cycles is a tree.” + * + * (2) The height of a rooted tree is the number of edges on the longest downward path between + * the root and a leaf. + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + +class Solution { +public: + vector findMinHeightTrees(int n, vector>& edges) { + //corner case + if ( n <= 1 ) return {0}; + + //construct a edges search data stucture + vector> graph(n); + for (auto e : edges) { + graph[e.first].insert(e.second); + graph[e.second].insert(e.first); + } + + //find all of leaf nodes + vector current; + for (int i=0; i next; + for (int node : current) { + for (int neighbor : graph[node]) { + graph[neighbor].erase(node); + if (graph[neighbor].size() == 1) next.push_back(neighbor); + } + } + if (next.empty()) break; + current = next; + } + return current; + } + +}; From e594f51689888f6b8d836b5631ec39997c80b3e1 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 25 Jan 2016 14:53:39 +0800 Subject: [PATCH 027/105] another solution for "Bulb Switcher" --- algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp | 38 +++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp b/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp index 04b046391..d4f51736b 100644 --- a/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp +++ b/algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp @@ -1,5 +1,5 @@ // Source : https://leetcode.com/problems/bulb-switcher/ -// Author : Calinescu Valentin +// Author : Calinescu Valentin, Hao Chen // Date : 2015-12-28 /*************************************************************************************** @@ -21,6 +21,42 @@ * So you should return 1, because there is only one bulb is on. * ***************************************************************************************/ + + /* Solution + * -------- + * + * We know, + * - if a bulb can be switched to ON eventually, it must be switched by ODD times + * - Otherwise, if a bulb has been switched by EVEN times, it will be OFF eventually. + * So, + * - If bulb `i` ends up ON if and only if `i` has an ODD numbers of divisors. + * And we know, + * - the divisors come in pairs. for example: + * 12 - [1,12] [2,6] [3,4] [6,2] [12,1] (the 12th bulb would be switched by 1,2,3,4,6,12) + * - the pairs means almost all of the numbers are switched by EVEN times. + * + * But we have a special case - square numbers + * - A square number must have a divisors pair with same number. such as 4 - [2,2], 9 - [3,3] + * - So, a square number has a ODD numbers of divisors. + * + * At last, we figure out the solution is: + * + * Count the number of the squre numbers!! + */ + +class Solution { +public: + int bulbSwitch(int n) { + int cnt = 0; + for (int i=1; i*i<=n; i++) { + cnt++; + } + return cnt; + } +}; + + + /* * Solution 1 - O(1) * ========= From 8469352740f8b23e0d1234af8d88d75ba0a81ebf Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Tue, 26 Jan 2016 23:25:41 +0800 Subject: [PATCH 028/105] another implementation for "Coin Change" --- algorithms/cpp/coinChange/coinChange.cpp | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/algorithms/cpp/coinChange/coinChange.cpp b/algorithms/cpp/coinChange/coinChange.cpp index e8ddc9c51..2b7d9b296 100644 --- a/algorithms/cpp/coinChange/coinChange.cpp +++ b/algorithms/cpp/coinChange/coinChange.cpp @@ -1,5 +1,5 @@ // Source : https://leetcode.com/problems/coin-change/ -// Author : Calinescu Valentin +// Author : Calinescu Valentin, Hao Chen // Date : 2015-12-28 /*************************************************************************************** @@ -60,3 +60,24 @@ class Solution { return -1; } }; + + +//Another DP implmentation, same idea above +class Solution { +public: + int coinChange(vector& coins, int amount) { + const int MAX = amount +1; + vector dp(amount+1, MAX); + dp[0]=0; + + for(int i=1; i<=amount; i++) { + for (int j=0; j= coins[j]) { + dp[i] = min( dp[i], dp[i-coins[j]] + 1 ); + } + } + } + + return dp[amount]==MAX ? -1 : dp[amount]; + } +}; From 79a570c0f246b067f54bccc881420daf2ff4d863 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Wed, 27 Jan 2016 00:07:13 +0800 Subject: [PATCH 029/105] another solution for "Longest Increasing Subsequence" --- .../longestIncreasingSubsequence.cpp | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/algorithms/cpp/longestIncreasingSubsequence/longestIncreasingSubsequence.cpp b/algorithms/cpp/longestIncreasingSubsequence/longestIncreasingSubsequence.cpp index 70a7fadab..30c65e9f4 100644 --- a/algorithms/cpp/longestIncreasingSubsequence/longestIncreasingSubsequence.cpp +++ b/algorithms/cpp/longestIncreasingSubsequence/longestIncreasingSubsequence.cpp @@ -1,5 +1,5 @@ // Source : https://leetcode.com/problems/longest-increasing-subsequence/ -// Author : Calinescu Valentin +// Author : Calinescu Valentin, Hao Chen // Date : 2015-11-06 /*************************************************************************************** @@ -22,6 +22,30 @@ * ***************************************************************************************/ + + +// O(n^2) - dynamic programming +class Solution { +public: + int lengthOfLIS(vector& nums) { + + int len = nums.size(); + int maxLen = 0; + vector dp(len, 1); + + for (int i=0; i Date: Sat, 13 Feb 2016 19:31:53 -0500 Subject: [PATCH 030/105] update --- .DS_Store | Bin 0 -> 8196 bytes algorithms/.DS_Store | Bin 0 -> 10244 bytes algorithms/cpp/.DS_Store | Bin 0 -> 22532 bytes algorithms/cpp/majorityElement/.DS_Store | Bin 0 -> 6148 bytes .../cpp/majorityElement/majorityElement.II.cpp | 2 +- 5 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 .DS_Store create mode 100644 algorithms/.DS_Store create mode 100644 algorithms/cpp/.DS_Store create mode 100644 algorithms/cpp/majorityElement/.DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a88d1f977020681eb1ce37775d2046438f4c31e7 GIT binary patch literal 8196 zcmeI1T}&KR6vxj2TIRAs?-ppcrP4JhQh^FpC?&OBmXEeUQc^yaFI{JMrZ91s!JXL! zB_wE~QR7FnF(y8k2x^VS2Oso7AB-_pV_!5jMvVI6n@=X{L*G1i?ku6e`ec-(bCbE} z-gEDnx$~dj%+1*a0E}m~R)7cqD0B$RLsV^3#JD)Nlp^0#LKZ0=AOi-tFaxvTY?&Q6 z0tEsE0tEsE0tEsEc7g)5XN#f~*!SgVPzMSG3fzP-iXNgLFG0)YZs6%ema8K_{wG}s&S_td;Imon`XjbBgAnTF%Gw5(xKamlXTr3x#f zQc=dk6%P!}*z-fK>Smp|nwj)^hNh?d_Mqy{6s0o zQwhV;?D@EzwKQjHNS-fYXzomsR}W_N9EA?5mOg4YM#?Y^_fbYgVM!iYTx@N>w<+4z zvD6e@Y;9@jXo|LLDo?(Iu*o^|vKx~aNGPVZ4&-AVF24(W9+ZCn0rBzZWkn&~V} z(z{G^$aqY55^3Aa&RWixt1r01GvU}7x7%}$85ApgNxoOeaDL7;Y|9zdGY(l2;ob6m zHHU9Ma`c{#`>s{&;bB(EsuMXOl&O!*3k}CrC#_qWVNFkvvX*OHH1rG$<9BS>QfGA; z6$u?={6l3*qje3~nwX<`BcVvBR#7H}zdNH-E#2(4P#xo{GVIXW*hhO=nl96o}}_zb>;ui_iHf~)vGeuSUORTbrtJR|%0 z8b71fw(lz;>A$ZH86lC)fIoipH%YMdp%hA)U%X^zR$bNmOmnj^#qW2Hrtq^t}6LeSMTlgM+fnVWw zxK5~*Vi@;h1ZxPjTD%h*@Gfk`W^Bjfcmg}|B!Sk4XYm~N<1mg8aASmAnvlDQ(`aA@ z9n4}57w~a>0-waE@M!|@WxRy1;Om>vJDZ12TD)8cz1&d7GHq*`#`DX7H-Q3mR_b}=> literal 0 HcmV?d00001 diff --git a/algorithms/.DS_Store b/algorithms/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a033a0ae6c3097c0d1bd47e0d12c031d4ff9372c GIT binary patch literal 10244 zcmeHMU2GIp6h5adFw=!{m;TW5ySj?S7HknpAwaj=AHYglyKT3Bu+HvG+mY$aIy1Wk zNt0@#QR7dP7!w~%1O%h;!3T}eL}LtSLYo%9jkF6PTQA%#1jfA~OuWb{uc=#5VO zM?7=Dn2lw>T=#OZ_u6E4jg%n%0z^-3Y zk6cp?9M6(X)is6J*M3{m%&|#ZS9>QW9L*h`R~|{Rl}^UC45QC-bXT{`k#T3rnmOod z(+AB7i$=`r+DvbjH#tL^?T}pLGkn-k(wfn0#x2*irbiUpR?JB)ew=A^n&uO> zX;|hYX}EP6JOm2lK}pXz{#^}RO=rbgU&i7}mzS4Ul(TTf;RFGYa1}S_#1(tYtLdti z_RD>WJ5?wTSe8*NE9oJEi&nG4GF?SCHG7`xcv3f2YbMV5;*2Lme@R_+r&6riN4ifj zwISWn)4HL%$7M>AoMN>nPBgb{Z;b3{oo$SqXl`n1ZH%<+YMz~CCnag^<{j;aMzXU{ zpE`Z!^|R;R`1HIFM**fvQ7`5f<^y6l`95)ZRbmwY`L+m%99rI4-PN69EazzbnxVLQ zUh7m`%~?#66bok*Ba;O_WonHQ`koS|hV} zrE!(s>yV{#8`WzG)rK}m(iqow*c#8DqJxy=u2=(sJ9*KP}9pPi&uQ+aRRx@e% zeQmKYy;aA}W+_P{+@oDpH8mRZqb?e25=+bYe~CJ1gniHtqqMh~6kX52vlL;^Q;eO4 zx8NQ45H7%H@C96iFX1vp-1qPU`~tth@9+mAmSYH4U8~Cd>LQEQ+OKR#`o}J@m9rX-Crc2SHMq56yuU; z=*MMA@`g0*uG-)A-_Y=~zxh{H*Z6FV7guw^0?y}>M<2ltk2eKgc+9+>jH_$w)`Zr{ z8*aAjgG4*+n8zcw?2>0q9OVRJlBjM9)l0;2R^nCVhR_zyU{)$xJ!YyhTOwMClbp@0 zOtkKniHkilTPj-HN3&P?t=b_+q;K4cSf+)jlAiU4*aT8~71^hAVKD=(P;P zxEgD5EzxTO-i7seH*NG=umyMGF5HcKh+N&Yv#O>yU^js*r?n3}o y_;tK@FsC;ET<-bBNYDM}g!J60?zxi`xB372$AIAcFYaXj$u(4P{=cQp|9=6g)!oJb literal 0 HcmV?d00001 diff --git a/algorithms/cpp/.DS_Store b/algorithms/cpp/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..4dfe7e1a95e6ba39857547c1dba471dfde0d32b4 GIT binary patch literal 22532 zcmeHPTW?#(5#D3V7A5LJU2MsYohV3(8f}U=vC+5%3RsSvSc&7Pl42Wa3WpMDi7`d0 z6lF;X0{E%$dtUq#0`vzo?=4yv=npUo^sN{FguJESH+v2_vs~(u0!5or2E~hZzMc7Y zc6MgYp`CNdm95fi&dodLa(M8$FocisW(Lpa@yLGocRo6Pj^dL9kH6w^4D!ycxTdSS zhO4+@$LRmQ4~{@3+R%r`l)DF=wf@?R^2<3P#FY)y=AV$Lp- z$y4XXAGIXcMaNbAeit)xEht-ZH=xHRUTe)o)!wfj13d0BD3Rp25<0_T$ZQauO0(E1|kf+iqCAF zIVW{1D#)NheG7G_u22U}b(+?ffeflzBa=f7S_FPsYU^@1M}j)qj32@H70g4KWz^wi z)U-{!mwMdJC3UdYkFsS*Hh{3^UUygBds0bLddJE-*fz1&s-c~;vTsQpy#Q%;0YYA2 zqmeyr=ADDg0_3wQzGSNMZZ$o4Fqo4an6!=(n7X6?b1m7CYQWdnAFNoE1S@Dzj;AQH z*MqUNNYB`hvFxkScWrlzi2&?4aZcIsa%*&3ORg8Z!;$qGVukOv(d*Ma<=#hca29-3 zv9@HpWV&da2RxX0$nzG))!ltOvkzBw4?2B`mK(WYkz0rNGH&f6a-=aQoRKSQB*{Fx zjEpsmHst;WW-LPYJ$?DaW5v&yps+((2O9Srdxs17y$Y7dPvDVaxke}eVH>k!85|I(Mmk>2m@Mj4CBk_w>I57(4Br*f$f!aMI+IX-f=Q# ztfwFFjJXdTxTkA)H!p1X(`Vg!Bdza1;NIGhUB+0#6(r7WJX60Qn$UiOki#e+pVLTW zXQb6;{Bexm2Gi^=huYD;9cAAj#xT0=?%@%%NXtx#A5^gWx1hZ~4;Jx0J6)HcGfwl^ z>Ke4XL8DKQ@z5t|qt;;>d&i$irIf{e^st=CIzLl99lm}j-{AF&lI#LTE}sK2BcfNX2J*1k$Pb8bQSOSY zaM9hj67*jqG1!v0fwd~(U#HJweT_`MCF4Cp_DPt_a22PXDBIdIDNnT8aeo?_0y3To z_P~eGZ8eSf5|^1AKW<=ar4LqTg|vadS3W?RK@fx>$b6-nUIkmNaa;-U?q5hxW~$#Oya7X39JHw zQ<&$6kr+wm@bxxNj;{HG*r#V3PGy(mv{Q27tYVp#%t4a%$f{#*xgL(ET}e*aHI90S z`4Xj8pd(Ljp7y?`NOQG-8(3;EMg@bX;tE!qXe-D%h$(k?SZUg7q)$QG*Y8U}@co`T zwAe!K*ksx6NjT z*Cihp?w%>`&UBGxL=f*d1b-U$xh}ZOl@Gis!ktE)ilQ#S{#9hbP4LCuP1)VTbJ=a% zHRfJSG}>eo?E}<%+$+Sn3SGBj+3S%zio=(pI3J2upJH8CrFuW4-_Rq?EZ%QeA@c4Y z_WEu@KlU?B{Au?Y0_)+225$&jGYTw&HDWfgb6LTJRV`SH%2lC--~a5kY{w$mktd3! zVVRG+uZifvD8zH8OCQ2W9)o6#f2HtFEBc2Sna4=h`s^?>8pZn*v`A|j2a*GTz>*+4YE@Q7`9p|Ipd$BGY7&eHE3BCi`Y~?GR_iSQ+_dQaq`ZZ?X zv?;v>e+`0t%+~cT?4GnM8evXjjVcWoue~MgqQ`bH8PU?u2hxkM-$zgSo!P;#@1AJb z05Y?bdsZ_>2ZOD-;ZE`ST@a5L3HrWP-1vC3h4DOx7NH-{jgp)u!4(~zVn%iXqq!q} z2i0ah%9cQHa-uaDl+&5(%2S$qZ8toB#8xdcC1ZI#h-;Xw9V5Z4_*xB}Vp@^ol0M zGZ7U_z$2~Ia%UmuJHlJ3Pb|nM{*+?Jp4VH5xF&1nuf2BZ?-}Hiz}cY&kY5xJ<;pWx zslvW>XxH7}$cfhS#J*Upjha9X?S zEEKfn=OW%s!z1Z8><;@C;W}hz@>Rhuf)AeI+=an)26}^;;{}CBTt*18M^EDQsY6{0 zr`H_+O0hB8LZ26H?z?N`kp2ezz*EJ3Eq$^jy(H_~adPgl!q_blP1@OM$!1E{i-jev z$)srFrQZWber36b^fi5)&=!Y$^q*6FoCS`r%Ne6;(fn!&tTRUK9k1Xk2Kh9Q=~;{? z-sgzJy~bVuvjifpV)ybBu5w3>oPaZfIf(H^*h+7r&&GBo{K?2nNL=wblRpDksqPme z$@wz;#?*diQgnl;!b(L8Xd@WQDuR)&*}A8o;ZK1GTRV!aF(d2!ILmkA=Qcbc zrx8vF0(Y0ci-Eh~ns|P8%5=FefL>ydyd4&a>&~4Mxp&9Nj<>XE$jY-b<@cYD%%ra$i^aU$wJ8n+<0Sv8?+hWPrD7cI{<;+-t(cr;i^ZF zf1`(Jgq-^X-p`D?Ywj^{M=^04yMnbBuTnN-T{rRGoFw9Bto>RQQNS+z#9&URm^#~z zqZSdR7u}M@qqi8mVTtQ)?e@$)jO25Hq>tH*xQq*o8*_MdU07#jopzS3K0Ij#o+!== zB1r@?M~@+Uv@rGmK%V?)`5BRKVm$XTv#Lm6BfZ;ZULqr7es`|bz6Y1(H}uFL#xQp@v;W}0 zv-3=EN~Xl@+~+x5rG4j=_0bkj1#{j?c|1^^D668;zAtFo5f5jaW8Fi~XAI`px`Ej31Sg_7ky?ezI#L zejp8>&QGI0O1}99PK-HygxTEm>z*XrAg&0=$F^GdOCw{T{$QYtSO8@DT^=Gs!ZcCA`|P_Dh-xKV7D8^7S-rFy-J z0seJy`BtU8eYY_AX1&%dR%+#j;CYOXZdYoh`u3IjR;{%8kp{k7I5FQSKY-|bu~xoS z*{m#As+H!hfTjcG^?b3phRFsBUkv01?iQv$`|Pz#7hjoq{U;Ybe`V&gH{Lk^%FM+J zKmPpl+`vHY><{0$wY>Z5FMjje-~Ij%e|++%zy19mzPwD*?`gP6|GxG6pLn$okq;Id zwQ9Y#ijhPq$fEfRT?`@}hnZbAal=Q-4Tl5yMG3u9Km?L>FD*H(B$-^W(Aj|7_`~l& zX^z1g4Dgt$Y*-z*WsS_qK!(XPTUfrC?gJogkt{zbA~)h&V%QnSsz` zOv{rB|FU4t;85d66jwZan3IAc)8_e5cajW`=%VBrl0osVZ#);&3-^KtQqo+@sr zlg7J_HOsDnrqMQB8=im$gKMKPvaEw{7ctj@%PQl7XWx znPb=ggF@{3O4-FA%WJjFIoT`N1vBkDDcni4(n>S;=H1lnvNZ&&d&dTAZKV5Czm3*n zVx69gqkU(A{i{$jtk=jnW!EsqFc?dxMDmo^Bu|Ony<;Q`9g@rmd1rf5;$0-p8Tru; z`8n)k_TK1wf!?&zNRLU_E+OM!1yDOcKaQ3^R+f(ffva*2vr*?Pqvib3uDOw(gcpQ4 zczJ&<7~2d^A&S#|7mx>S#mT5VBMEyuw9EHsxTC}SlflSnPBAhpSXM3?UAc>m~jlvudTk8x*p{t0q2|2=XvO_u>X3 z^^UA9>+0;f9j{;e`=%lhj=RVpz95L%>EC&^Y7<=0cliHHMegCS`jWS?ONzJWzZH7d z2y3uCi<#!8vud?Uz@m|yHd@UgYPP@sw1G3fN^?{N^j_zz}OnwJj-*Xg|5~j4&q)25wCe~S3v8QGwPN@E3Xc4_^ zOyi6TPS*QjcX%Esyc>a9(RVvoCM)C9iWP5xzXrhZERUl(nUNZi8QM}@?bh{?U|r!S zMs_TajjU{d0J{x>=dV3`wu=5ci|@*veeC50MY`DjNZEcO(4=)eNX{p&M=SHT8ZmZ{ zYb5f)-OTvS>rDIc(UScZ^?$$b0nGFN|G9>^GlYJN`v3nf<9+X^$3TyP?>GZV-_^yd zS72n;vkmR#|FtuN$H#c^hvOdd1%B{a{wp3l%YVg#H~g=7?#Lhg-#=EbAM$k~2z(Y% eJpYIO6QHnj(5wIVKQnRan)ay|9=5k8gy6y literal 0 HcmV?d00001 diff --git a/algorithms/cpp/majorityElement/.DS_Store b/algorithms/cpp/majorityElement/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..2c13c8a8364e9d7d1fa8f26063f53c6c26cb691a GIT binary patch literal 6148 zcmeHK%Sr=55Ukc50$u`wc$}jr!9Q3+BJ9~8(8L^+)eT|}x$Ot~PiximC@!veQbf9; zr+T`ldv*$T9sq2+RO@?{3JC^+fnXpQ z2nK$T0iM~C>5*f!!9Xw&47@X-{UK3>Rl&|NZyjuOeO7!Tl+f1YSeOb{1v^JZDCVg| zPqp&IFi)pHm2p+U&e79hd1lrrGrv7vEYD7V%EMumW3<6QFfe4`(7Q98|4aTdqmTSy zO7wz(VBnuIV3WnwV$MaCv-Q*Rbk-*7HC3W`_4EzEEuY7GR(EtDd literal 0 HcmV?d00001 diff --git a/algorithms/cpp/majorityElement/majorityElement.II.cpp b/algorithms/cpp/majorityElement/majorityElement.II.cpp index 827e97a57..08b675d69 100644 --- a/algorithms/cpp/majorityElement/majorityElement.II.cpp +++ b/algorithms/cpp/majorityElement/majorityElement.II.cpp @@ -36,7 +36,7 @@ class Solution { //the same algorithm as Majority Element I problem int majority1=0, majority2=0, cnt1=0, cnt2=0; for(auto item: nums) { - if (cnt1 == 0) { + if (cnt1 == 0 && majority2 != item ) { majority1 = item; cnt1 = 1; } else if (majority1 == item) { From a28233dd0be4ed11eb2f65815e997e2bb12486b7 Mon Sep 17 00:00:00 2001 From: wilsoncao <275239608@qq.com> Date: Sat, 13 Feb 2016 19:32:31 -0500 Subject: [PATCH 031/105] update --- .DS_Store | Bin 8196 -> 0 bytes algorithms/.DS_Store | Bin 10244 -> 0 bytes algorithms/cpp/.DS_Store | Bin 22532 -> 0 bytes algorithms/cpp/majorityElement/.DS_Store | Bin 6148 -> 0 bytes 4 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store delete mode 100644 algorithms/.DS_Store delete mode 100644 algorithms/cpp/.DS_Store delete mode 100644 algorithms/cpp/majorityElement/.DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index a88d1f977020681eb1ce37775d2046438f4c31e7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeI1T}&KR6vxj2TIRAs?-ppcrP4JhQh^FpC?&OBmXEeUQc^yaFI{JMrZ91s!JXL! zB_wE~QR7FnF(y8k2x^VS2Oso7AB-_pV_!5jMvVI6n@=X{L*G1i?ku6e`ec-(bCbE} z-gEDnx$~dj%+1*a0E}m~R)7cqD0B$RLsV^3#JD)Nlp^0#LKZ0=AOi-tFaxvTY?&Q6 z0tEsE0tEsE0tEsEc7g)5XN#f~*!SgVPzMSG3fzP-iXNgLFG0)YZs6%ema8K_{wG}s&S_td;Imon`XjbBgAnTF%Gw5(xKamlXTr3x#f zQc=dk6%P!}*z-fK>Smp|nwj)^hNh?d_Mqy{6s0o zQwhV;?D@EzwKQjHNS-fYXzomsR}W_N9EA?5mOg4YM#?Y^_fbYgVM!iYTx@N>w<+4z zvD6e@Y;9@jXo|LLDo?(Iu*o^|vKx~aNGPVZ4&-AVF24(W9+ZCn0rBzZWkn&~V} z(z{G^$aqY55^3Aa&RWixt1r01GvU}7x7%}$85ApgNxoOeaDL7;Y|9zdGY(l2;ob6m zHHU9Ma`c{#`>s{&;bB(EsuMXOl&O!*3k}CrC#_qWVNFkvvX*OHH1rG$<9BS>QfGA; z6$u?={6l3*qje3~nwX<`BcVvBR#7H}zdNH-E#2(4P#xo{GVIXW*hhO=nl96o}}_zb>;ui_iHf~)vGeuSUORTbrtJR|%0 z8b71fw(lz;>A$ZH86lC)fIoipH%YMdp%hA)U%X^zR$bNmOmnj^#qW2Hrtq^t}6LeSMTlgM+fnVWw zxK5~*Vi@;h1ZxPjTD%h*@Gfk`W^Bjfcmg}|B!Sk4XYm~N<1mg8aASmAnvlDQ(`aA@ z9n4}57w~a>0-waE@M!|@WxRy1;Om>vJDZ12TD)8cz1&d7GHq*`#`DX7H-Q3mR_b}=> diff --git a/algorithms/.DS_Store b/algorithms/.DS_Store deleted file mode 100644 index a033a0ae6c3097c0d1bd47e0d12c031d4ff9372c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10244 zcmeHMU2GIp6h5adFw=!{m;TW5ySj?S7HknpAwaj=AHYglyKT3Bu+HvG+mY$aIy1Wk zNt0@#QR7dP7!w~%1O%h;!3T}eL}LtSLYo%9jkF6PTQA%#1jfA~OuWb{uc=#5VO zM?7=Dn2lw>T=#OZ_u6E4jg%n%0z^-3Y zk6cp?9M6(X)is6J*M3{m%&|#ZS9>QW9L*h`R~|{Rl}^UC45QC-bXT{`k#T3rnmOod z(+AB7i$=`r+DvbjH#tL^?T}pLGkn-k(wfn0#x2*irbiUpR?JB)ew=A^n&uO> zX;|hYX}EP6JOm2lK}pXz{#^}RO=rbgU&i7}mzS4Ul(TTf;RFGYa1}S_#1(tYtLdti z_RD>WJ5?wTSe8*NE9oJEi&nG4GF?SCHG7`xcv3f2YbMV5;*2Lme@R_+r&6riN4ifj zwISWn)4HL%$7M>AoMN>nPBgb{Z;b3{oo$SqXl`n1ZH%<+YMz~CCnag^<{j;aMzXU{ zpE`Z!^|R;R`1HIFM**fvQ7`5f<^y6l`95)ZRbmwY`L+m%99rI4-PN69EazzbnxVLQ zUh7m`%~?#66bok*Ba;O_WonHQ`koS|hV} zrE!(s>yV{#8`WzG)rK}m(iqow*c#8DqJxy=u2=(sJ9*KP}9pPi&uQ+aRRx@e% zeQmKYy;aA}W+_P{+@oDpH8mRZqb?e25=+bYe~CJ1gniHtqqMh~6kX52vlL;^Q;eO4 zx8NQ45H7%H@C96iFX1vp-1qPU`~tth@9+mAmSYH4U8~Cd>LQEQ+OKR#`o}J@m9rX-Crc2SHMq56yuU; z=*MMA@`g0*uG-)A-_Y=~zxh{H*Z6FV7guw^0?y}>M<2ltk2eKgc+9+>jH_$w)`Zr{ z8*aAjgG4*+n8zcw?2>0q9OVRJlBjM9)l0;2R^nCVhR_zyU{)$xJ!YyhTOwMClbp@0 zOtkKniHkilTPj-HN3&P?t=b_+q;K4cSf+)jlAiU4*aT8~71^hAVKD=(P;P zxEgD5EzxTO-i7seH*NG=umyMGF5HcKh+N&Yv#O>yU^js*r?n3}o y_;tK@FsC;ET<-bBNYDM}g!J60?zxi`xB372$AIAcFYaXj$u(4P{=cQp|9=6g)!oJb diff --git a/algorithms/cpp/.DS_Store b/algorithms/cpp/.DS_Store deleted file mode 100644 index 4dfe7e1a95e6ba39857547c1dba471dfde0d32b4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 22532 zcmeHPTW?#(5#D3V7A5LJU2MsYohV3(8f}U=vC+5%3RsSvSc&7Pl42Wa3WpMDi7`d0 z6lF;X0{E%$dtUq#0`vzo?=4yv=npUo^sN{FguJESH+v2_vs~(u0!5or2E~hZzMc7Y zc6MgYp`CNdm95fi&dodLa(M8$FocisW(Lpa@yLGocRo6Pj^dL9kH6w^4D!ycxTdSS zhO4+@$LRmQ4~{@3+R%r`l)DF=wf@?R^2<3P#FY)y=AV$Lp- z$y4XXAGIXcMaNbAeit)xEht-ZH=xHRUTe)o)!wfj13d0BD3Rp25<0_T$ZQauO0(E1|kf+iqCAF zIVW{1D#)NheG7G_u22U}b(+?ffeflzBa=f7S_FPsYU^@1M}j)qj32@H70g4KWz^wi z)U-{!mwMdJC3UdYkFsS*Hh{3^UUygBds0bLddJE-*fz1&s-c~;vTsQpy#Q%;0YYA2 zqmeyr=ADDg0_3wQzGSNMZZ$o4Fqo4an6!=(n7X6?b1m7CYQWdnAFNoE1S@Dzj;AQH z*MqUNNYB`hvFxkScWrlzi2&?4aZcIsa%*&3ORg8Z!;$qGVukOv(d*Ma<=#hca29-3 zv9@HpWV&da2RxX0$nzG))!ltOvkzBw4?2B`mK(WYkz0rNGH&f6a-=aQoRKSQB*{Fx zjEpsmHst;WW-LPYJ$?DaW5v&yps+((2O9Srdxs17y$Y7dPvDVaxke}eVH>k!85|I(Mmk>2m@Mj4CBk_w>I57(4Br*f$f!aMI+IX-f=Q# ztfwFFjJXdTxTkA)H!p1X(`Vg!Bdza1;NIGhUB+0#6(r7WJX60Qn$UiOki#e+pVLTW zXQb6;{Bexm2Gi^=huYD;9cAAj#xT0=?%@%%NXtx#A5^gWx1hZ~4;Jx0J6)HcGfwl^ z>Ke4XL8DKQ@z5t|qt;;>d&i$irIf{e^st=CIzLl99lm}j-{AF&lI#LTE}sK2BcfNX2J*1k$Pb8bQSOSY zaM9hj67*jqG1!v0fwd~(U#HJweT_`MCF4Cp_DPt_a22PXDBIdIDNnT8aeo?_0y3To z_P~eGZ8eSf5|^1AKW<=ar4LqTg|vadS3W?RK@fx>$b6-nUIkmNaa;-U?q5hxW~$#Oya7X39JHw zQ<&$6kr+wm@bxxNj;{HG*r#V3PGy(mv{Q27tYVp#%t4a%$f{#*xgL(ET}e*aHI90S z`4Xj8pd(Ljp7y?`NOQG-8(3;EMg@bX;tE!qXe-D%h$(k?SZUg7q)$QG*Y8U}@co`T zwAe!K*ksx6NjT z*Cihp?w%>`&UBGxL=f*d1b-U$xh}ZOl@Gis!ktE)ilQ#S{#9hbP4LCuP1)VTbJ=a% zHRfJSG}>eo?E}<%+$+Sn3SGBj+3S%zio=(pI3J2upJH8CrFuW4-_Rq?EZ%QeA@c4Y z_WEu@KlU?B{Au?Y0_)+225$&jGYTw&HDWfgb6LTJRV`SH%2lC--~a5kY{w$mktd3! zVVRG+uZifvD8zH8OCQ2W9)o6#f2HtFEBc2Sna4=h`s^?>8pZn*v`A|j2a*GTz>*+4YE@Q7`9p|Ipd$BGY7&eHE3BCi`Y~?GR_iSQ+_dQaq`ZZ?X zv?;v>e+`0t%+~cT?4GnM8evXjjVcWoue~MgqQ`bH8PU?u2hxkM-$zgSo!P;#@1AJb z05Y?bdsZ_>2ZOD-;ZE`ST@a5L3HrWP-1vC3h4DOx7NH-{jgp)u!4(~zVn%iXqq!q} z2i0ah%9cQHa-uaDl+&5(%2S$qZ8toB#8xdcC1ZI#h-;Xw9V5Z4_*xB}Vp@^ol0M zGZ7U_z$2~Ia%UmuJHlJ3Pb|nM{*+?Jp4VH5xF&1nuf2BZ?-}Hiz}cY&kY5xJ<;pWx zslvW>XxH7}$cfhS#J*Upjha9X?S zEEKfn=OW%s!z1Z8><;@C;W}hz@>Rhuf)AeI+=an)26}^;;{}CBTt*18M^EDQsY6{0 zr`H_+O0hB8LZ26H?z?N`kp2ezz*EJ3Eq$^jy(H_~adPgl!q_blP1@OM$!1E{i-jev z$)srFrQZWber36b^fi5)&=!Y$^q*6FoCS`r%Ne6;(fn!&tTRUK9k1Xk2Kh9Q=~;{? z-sgzJy~bVuvjifpV)ybBu5w3>oPaZfIf(H^*h+7r&&GBo{K?2nNL=wblRpDksqPme z$@wz;#?*diQgnl;!b(L8Xd@WQDuR)&*}A8o;ZK1GTRV!aF(d2!ILmkA=Qcbc zrx8vF0(Y0ci-Eh~ns|P8%5=FefL>ydyd4&a>&~4Mxp&9Nj<>XE$jY-b<@cYD%%ra$i^aU$wJ8n+<0Sv8?+hWPrD7cI{<;+-t(cr;i^ZF zf1`(Jgq-^X-p`D?Ywj^{M=^04yMnbBuTnN-T{rRGoFw9Bto>RQQNS+z#9&URm^#~z zqZSdR7u}M@qqi8mVTtQ)?e@$)jO25Hq>tH*xQq*o8*_MdU07#jopzS3K0Ij#o+!== zB1r@?M~@+Uv@rGmK%V?)`5BRKVm$XTv#Lm6BfZ;ZULqr7es`|bz6Y1(H}uFL#xQp@v;W}0 zv-3=EN~Xl@+~+x5rG4j=_0bkj1#{j?c|1^^D668;zAtFo5f5jaW8Fi~XAI`px`Ej31Sg_7ky?ezI#L zejp8>&QGI0O1}99PK-HygxTEm>z*XrAg&0=$F^GdOCw{T{$QYtSO8@DT^=Gs!ZcCA`|P_Dh-xKV7D8^7S-rFy-J z0seJy`BtU8eYY_AX1&%dR%+#j;CYOXZdYoh`u3IjR;{%8kp{k7I5FQSKY-|bu~xoS z*{m#As+H!hfTjcG^?b3phRFsBUkv01?iQv$`|Pz#7hjoq{U;Ybe`V&gH{Lk^%FM+J zKmPpl+`vHY><{0$wY>Z5FMjje-~Ij%e|++%zy19mzPwD*?`gP6|GxG6pLn$okq;Id zwQ9Y#ijhPq$fEfRT?`@}hnZbAal=Q-4Tl5yMG3u9Km?L>FD*H(B$-^W(Aj|7_`~l& zX^z1g4Dgt$Y*-z*WsS_qK!(XPTUfrC?gJogkt{zbA~)h&V%QnSsz` zOv{rB|FU4t;85d66jwZan3IAc)8_e5cajW`=%VBrl0osVZ#);&3-^KtQqo+@sr zlg7J_HOsDnrqMQB8=im$gKMKPvaEw{7ctj@%PQl7XWx znPb=ggF@{3O4-FA%WJjFIoT`N1vBkDDcni4(n>S;=H1lnvNZ&&d&dTAZKV5Czm3*n zVx69gqkU(A{i{$jtk=jnW!EsqFc?dxMDmo^Bu|Ony<;Q`9g@rmd1rf5;$0-p8Tru; z`8n)k_TK1wf!?&zNRLU_E+OM!1yDOcKaQ3^R+f(ffva*2vr*?Pqvib3uDOw(gcpQ4 zczJ&<7~2d^A&S#|7mx>S#mT5VBMEyuw9EHsxTC}SlflSnPBAhpSXM3?UAc>m~jlvudTk8x*p{t0q2|2=XvO_u>X3 z^^UA9>+0;f9j{;e`=%lhj=RVpz95L%>EC&^Y7<=0cliHHMegCS`jWS?ONzJWzZH7d z2y3uCi<#!8vud?Uz@m|yHd@UgYPP@sw1G3fN^?{N^j_zz}OnwJj-*Xg|5~j4&q)25wCe~S3v8QGwPN@E3Xc4_^ zOyi6TPS*QjcX%Esyc>a9(RVvoCM)C9iWP5xzXrhZERUl(nUNZi8QM}@?bh{?U|r!S zMs_TajjU{d0J{x>=dV3`wu=5ci|@*veeC50MY`DjNZEcO(4=)eNX{p&M=SHT8ZmZ{ zYb5f)-OTvS>rDIc(UScZ^?$$b0nGFN|G9>^GlYJN`v3nf<9+X^$3TyP?>GZV-_^yd zS72n;vkmR#|FtuN$H#c^hvOdd1%B{a{wp3l%YVg#H~g=7?#Lhg-#=EbAM$k~2z(Y% eJpYIO6QHnj(5wIVKQnRan)ay|9=5k8gy6y diff --git a/algorithms/cpp/majorityElement/.DS_Store b/algorithms/cpp/majorityElement/.DS_Store deleted file mode 100644 index 2c13c8a8364e9d7d1fa8f26063f53c6c26cb691a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%Sr=55Ukc50$u`wc$}jr!9Q3+BJ9~8(8L^+)eT|}x$Ot~PiximC@!veQbf9; zr+T`ldv*$T9sq2+RO@?{3JC^+fnXpQ z2nK$T0iM~C>5*f!!9Xw&47@X-{UK3>Rl&|NZyjuOeO7!Tl+f1YSeOb{1v^JZDCVg| zPqp&IFi)pHm2p+U&e79hd1lrrGrv7vEYD7V%EMumW3<6QFfe4`(7Q98|4aTdqmTSy zO7wz(VBnuIV3WnwV$MaCv-Q*Rbk-*7HC3W`_4EzEEuY7GR(EtDd From 4727c83e154ef058b9ff8112bc3210801164e886 Mon Sep 17 00:00:00 2001 From: Siwei Xu Date: Fri, 26 Feb 2016 01:10:40 +0800 Subject: [PATCH 032/105] another solution for "Reverse Words in a String" --- .../reverseWordsInAString.cpp | 32 +++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp b/algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp index b3f4d6147..33e79f882 100644 --- a/algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp +++ b/algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp @@ -1,5 +1,5 @@ // Source : https://oj.leetcode.com/problems/reverse-words-in-a-string/ -// Author : Hao Chen +// Author : Hao Chen, Siwei Xu // Date : 2014-06-16 /********************************************************************************** @@ -71,7 +71,35 @@ void reverseWords(string &s) { } cout << "[" << s << "]" < -- Handwaving +void reverseWords2(string &s) { + if (s.length() == 0) return; + + string result = ""; + if (s[s.length()-1] == ' ') { + int last = s.find_last_not_of(' ') + 1; + s.erase(last, s.length() - last); + } + + int first = s.find_first_not_of(' ', 0); + while (first != string::npos) { + int wend = s.find(' ', first); // word end + if (wend == string::npos) wend = s.length(); + + string word = s.substr(first, wend - first); + reverse(word.begin(), word.end()); + result += word; + + first = s.find_first_not_of(' ', wend); // next word + if (first == string::npos) break; + + result += ' '; + } + reverse(result.begin(), result.end()); + s.swap(result); +} + main() { string s; From 5c5363e9ae15c765e90510b9cd88dcad84e61f69 Mon Sep 17 00:00:00 2001 From: Siwei Xu Date: Fri, 26 Feb 2016 01:11:36 +0800 Subject: [PATCH 033/105] fix typo caused build error --- algorithms/cpp/maximalRectangle/maximalRectangle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/cpp/maximalRectangle/maximalRectangle.cpp b/algorithms/cpp/maximalRectangle/maximalRectangle.cpp index 5e0a8fd81..4f732ed73 100644 --- a/algorithms/cpp/maximalRectangle/maximalRectangle.cpp +++ b/algorithms/cpp/maximalRectangle/maximalRectangle.cpp @@ -56,7 +56,7 @@ int maximalRectangle(vector > &matrix) { if (matrix.size()<=0 || matrix[0].size()<=0) return 0; int row = matrix.size(); int col = matrix[0].size(); - vector< vector > heights(row, vector col); + vector< vector > heights(row, vector(col)); int maxArea = 0; for(int i=0; i Date: Sun, 28 Feb 2016 00:22:11 +0800 Subject: [PATCH 034/105] C solution for "Reverse Words in a String", in O(1) space --- .../reverseWordsInAString.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp b/algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp index 33e79f882..89edd1062 100644 --- a/algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp +++ b/algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp @@ -24,9 +24,13 @@ **********************************************************************************/ #include +#include +#include +#include #include #include #include +#include // for std::reverse using namespace std; void reverseWords(string &s) { @@ -100,6 +104,53 @@ void reverseWords2(string &s) { s.swap(result); } + +// C solution in O(1) space +void reverse(char *b, char *e) { + for (--e; e - b > 0; b++, e--) { + char t = *b; + *b = *e; + *e = t; + } +} + +void reverseWords(char *s) { + char *p = s, *ws = NULL, *last = s; + + while (*p && *p == ' ') p++; // skip leading space + ws = p; + + for ( ; *p; p++) { + while (*p && *p != ' ') p++; // find word end + + reverse(ws, p); + strncpy(last, ws, p-ws); + last += (p-ws); + + while (*p && *p == ' ') p++; // for next word + ws = p; + + if (*p == '\0') break; + *last++ = ' '; + } + reverse(s, last); + *last = '\0'; +} + +void test() { +#define TEST(str) do { \ + char* s = strdup(str); \ + printf("\"%s\" => ", s); \ + reverseWords(s); \ + printf("\"%s\"\n\n", s); \ + free(s); \ + } while (0) + + TEST(" the blue sky is blue "); + TEST(" "); +} + + main() { string s; @@ -113,4 +164,5 @@ main() s="i love cpp"; reverseWords(s); + test(); } From be582a0f5fb5b9e14f098fb031c8a58471b2ab5a Mon Sep 17 00:00:00 2001 From: Vally Date: Sat, 27 Feb 2016 19:40:31 +0200 Subject: [PATCH 035/105] added increasingTripletSubsequence --- README.md | 1 + .../increasingTripletSubsequence.cpp | 43 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp diff --git a/README.md b/README.md index 6d410f75a..47982b36d 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| |329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp)|Medium| |328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [C++](./algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp)|Easy| |327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| diff --git a/algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp b/algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp new file mode 100644 index 000000000..a53f3d7bd --- /dev/null +++ b/algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp @@ -0,0 +1,43 @@ +// Source : https://leetcode.com/problems/increasing-triplet-subsequence/ +// Author : Calinescu Valentin +// Date : 2016-02-27 + +/*************************************************************************************** + * + * Given an unsorted array return whether an increasing subsequence of length 3 exists + * or not in the array. + * + * Formally the function should: + * Return true if there exists i, j, k + * such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. + * Your algorithm should run in O(n) time complexity and O(1) space complexity. + * + * Examples: + * Given [1, 2, 3, 4, 5], + * return true. + * + * Given [5, 4, 3, 2, 1], + * return false. + * + ***************************************************************************************/ +class Solution { +public: + bool increasingTriplet(vector& nums) { + bool solution = false; + if(nums.size()) + { + int first = nums[0]; + int second = 0x7fffffff; //MAX_INT so we can always find something smaller than it + for(int i = 1; i < nums.size() && !solution; i++) + { + if(nums[i] > second) + solution = true; + else if(nums[i] > first && nums[i] < second) + second = nums[i]; + else if(nums[i] < first) + first = nums[i]; + } + } + return solution; + } +}; From e8e1847fb62402771f6a5a48eb4bdbd803fed30c Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 29 Feb 2016 17:38:33 +0800 Subject: [PATCH 036/105] refine the comments --- algorithms/cpp/nextPermutation/nextPermutation.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/algorithms/cpp/nextPermutation/nextPermutation.cpp b/algorithms/cpp/nextPermutation/nextPermutation.cpp index 404c4b86c..8d4ab294e 100644 --- a/algorithms/cpp/nextPermutation/nextPermutation.cpp +++ b/algorithms/cpp/nextPermutation/nextPermutation.cpp @@ -33,11 +33,11 @@ * 2 1 3 4 * ... * - * The pattern as below: + * The pattern can be descripted as below: * - * 1) find the first place which num[i-1] < num[i] - * 2) find the first number from n-1 to i which >= num[i-1] - * 3) swap the 2) num with num[i-1] + * 1) from n-1 to 0, find the first place [i-1] which num[i-1] < num[i] + * 2) from n-1 to i, find the first number from n-1 to i which >= num[i-1] + * 3) swap the 2) num with the num[i-1] * 4) sort the sub-array [i, n) //actuall sort is fine as well * * For example: From 23801d8650fb79bd0d768e3e19f8b19f0d50219e Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 29 Feb 2016 17:43:33 +0800 Subject: [PATCH 037/105] fix #96 --- algorithms/cpp/3Sum/3Sum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/cpp/3Sum/3Sum.cpp b/algorithms/cpp/3Sum/3Sum.cpp index 0b38716e4..711550183 100644 --- a/algorithms/cpp/3Sum/3Sum.cpp +++ b/algorithms/cpp/3Sum/3Sum.cpp @@ -71,7 +71,7 @@ vector > threeSum(vector &num) { result.push_back(v); // Continue search for all triplet combinations summing to zero. //skip the duplication - while(low0 && num[high]==num[high-1]) high--; low++; high--; From da6bc7c890e8d36e3711f8a2d3bccbd2d06ef91a Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Tue, 1 Mar 2016 00:45:30 +0800 Subject: [PATCH 038/105] New Problem "Patching Array" --- README.md | 1 + .../cpp/patchingArray/PatchingArray.cpp | 115 ++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 algorithms/cpp/patchingArray/PatchingArray.cpp diff --git a/README.md b/README.md index 47982b36d..cc9b9f4be 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| +|330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium| |329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp)|Medium| |328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [C++](./algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp)|Easy| |327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| diff --git a/algorithms/cpp/patchingArray/PatchingArray.cpp b/algorithms/cpp/patchingArray/PatchingArray.cpp new file mode 100644 index 000000000..18b7ee51b --- /dev/null +++ b/algorithms/cpp/patchingArray/PatchingArray.cpp @@ -0,0 +1,115 @@ +// Source : https://leetcode.com/problems/patching-array/ +// Author : Hao Chen +// Date : 2016-03-01 + +/*************************************************************************************** + * + * Given a sorted positive integer array nums and an integer n, add/patch elements to + * the array such that any number in range [1, n] inclusive can be formed by the sum of + * some elements in the array. Return the minimum number of patches required. + * + * Example 1: + * nums = [1, 3], n = 6 + * Return 1. + * + * Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. + * Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], + * [1,2,3]. + * Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. + * So we only need 1 patch. + * + * Example 2: + * nums = [1, 5, 10], n = 20 + * Return 2. + * The two patches can be [2, 4]. + * + * Example 3: + * nums = [1, 2, 2], n = 5 + * Return 0. + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + + +class Solution { +public: + int minPatches(vector& nums, int n) { + return minPatches_02(nums, n); + return minPatches_01(nums, n); + } + + + // Greedy Algorithm + // (Assume the array is sorted already) + // + // Let do some observation at first, + // + // 1) if we have [1,2] then we can cover 1, 2, 3 + // 2) if we have [1,2,3] then we can cover 1,2,3,4,5,6 + // So, it looks we can simply add all of nums together, then we can find out max number we can reach. + // + // 3) if we have [1,2,5], we can see + // 3.1) [1,2] can cover 1,2,3, but we cannot reach 4, + // 3.2) then we patch 4, then we have [1,2,4] which can cover 1,2,3(1+2),4,5(1+4),6(2+4), 7(1+2+4) + // 3.3) we can see [1,2,4] can reach to 7 - sum all of them + // 3.4) then [1,2,4,5], we can reach to 12 - 1,2,3,4,5,6,7,8(1+2+5),9(4+5),10(1+4+5), 11(2+4+5), 12(1+2+4+5) + // + // So, we can have figure out our solution + // + // 0) considering the `n` we need to cover. + // 1) maintain a variable we are trying to patch, suppose named `try_patch` + // 2) if `try_patch` >= nums[i] then, we just keep add the current array item, + // and set the `try_patch` to the next patch candidate number - `sum+1` + // 3) if `try_patch` < nums[i], which means we need to patch. + // + int minPatches_01(vector& nums, int n) { + long covered = 0; //avoid integer overflow + int patch_cnt = 0; + int i = 0; + while (i= nums[i]) { + covered += nums[i]; + i++; + } else { // if the `try_patch` cannot cover the current item, then we find the number we need to patch + patch_cnt++; + //cout << "patch " << try_patch << endl; + covered = covered + try_patch; + } + + if (covered >=n) break; + } + //for the case - [1], 7 + //the above while-loop just process all of the numbers in the array, + //but we might not reach the goal, so, we need keep patching. + while (covered < n) { + int try_patch = covered + 1; + patch_cnt++; + //cout << "patch " << try_patch << endl; + covered = covered + try_patch; + } + return patch_cnt; + } + + + //The following solution just re-organizes the solution above, and make it shorter + int minPatches_02(vector& nums, int n) { + long covered = 0; + int patch_cnt = 0; + int i = 0; + while ( covered < n){ + if (i Date: Sat, 12 Mar 2016 22:33:54 +0800 Subject: [PATCH 039/105] union-find solution for "Surrounded Regions", --- .../surroundedRegions/surroundedRegions.cpp | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/algorithms/cpp/surroundedRegions/surroundedRegions.cpp b/algorithms/cpp/surroundedRegions/surroundedRegions.cpp index b7ca43b17..6aec38571 100644 --- a/algorithms/cpp/surroundedRegions/surroundedRegions.cpp +++ b/algorithms/cpp/surroundedRegions/surroundedRegions.cpp @@ -182,7 +182,94 @@ void solve_non_recursively(vector< vector > &board) { } } + +// refers to 4th edition. +class UnionFind { + int count_; // number of components + int* rank_; // to limits tree hights + int* id_; // id[i] parent of i +public: + UnionFind(int n) { + count_ = n; + rank_ = new int[n]; + id_ = new int[n]; + for (int i = 0; i < n; i++) { + id_[i] = i; + rank_[i] = 0; + } + } + + ~UnionFind() { + delete [] rank_; + delete [] id_; + } + + int count() { return count_; } + + int find(int p) { + while (p != id_[p]) { + id_[p] = id_[id_[p]]; // path compression + p = id_[p]; + } + return p; + } + + bool connected(int p, int q) { + return find(p) == find(q); + } + + void connect(int p, int q) { + int i = find(p); + int j = find(q); + if (i == j) return; + if (rank_[i] < rank_[j]) id_[i] = j; + else if (rank_[i] > rank_[j]) id_[j] = i; + else { // == + id_[j] = i; + rank_[i]++; + } + count_--; + } +}; + +class Solution { +public: + void solve(vector >& board) { + int n = board.size(); + if (n == 0) return; + int m = board[0].size(); + + UnionFind uf(n*m+1); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (i == 0 || i == n-1 || j == 0 || j == m-1) { // side case, connect to dummy node + uf.connect(i*m + j, n*m); + continue; + } + char c = board[i][j]; // inner case, connect to same neighbor + if (board[i+1][j] == c) uf.connect((i+1)*m + j, i*m + j); + if (board[i-1][j] == c) uf.connect((i-1)*m + j, i*m + j); + if (board[i][j+1] == c) uf.connect(i*m + (j+1), i*m + j); + if (board[i][j-1] == c) uf.connect(i*m + (j-1), i*m + j); + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (board[i][j] == 'O' && !uf.connected(i*m + j, n*m)) { + board[i][j] = 'X'; + } + } + } + } +}; + + void solve(vector< vector > &board) { + if (rand() % 2) { + Solution().solve(board); + return; + } //Runtime Error for 250 x 250 matrix /* solve_recursively(board); */ solve_non_recursively(board); From 38f46e5e82910e75f92318c232f72af96e7c881b Mon Sep 17 00:00:00 2001 From: Vally Date: Fri, 29 Apr 2016 22:46:45 +0300 Subject: [PATCH 040/105] added houseRobberIII --- README.md | 1 + algorithms/cpp/houseRobber/houseRobberIII.cpp | 88 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 algorithms/cpp/houseRobber/houseRobberIII.cpp diff --git a/README.md b/README.md index cc9b9f4be..8eb0c6e5f 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| |330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium| |329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp)|Medium| diff --git a/algorithms/cpp/houseRobber/houseRobberIII.cpp b/algorithms/cpp/houseRobber/houseRobberIII.cpp new file mode 100644 index 000000000..8bb4aeadf --- /dev/null +++ b/algorithms/cpp/houseRobber/houseRobberIII.cpp @@ -0,0 +1,88 @@ +// Source : https://leetcode.com/problems/house-robber-iii/ +// Author : Calinescu Valentin +// Date : 2016-04-29 + +/*************************************************************************************** + * + * The thief has found himself a new place for his thievery again. There is only one + * entrance to this area, called the "root." Besides the root, each house has one and + * only one parent house. After a tour, the smart thief realized that "all houses in + * this place forms a binary tree". It will automatically contact the police if two + * directly-linked houses were broken into on the same night. + * + * Determine the maximum amount of money the thief can rob tonight without alerting the + * police. + * + * Example 1: + * 3 + * / \ + * 2 3 + * \ \ + * 3 1 + * Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. + * Example 2: + * 3 + * / \ + * 4 5 + * / \ \ + * 1 3 1 + * Maximum amount of money the thief can rob = 4 + 5 = 9. + * Credits: + * Special thanks to @dietpepsi for adding this problem and creating all test cases. + * + ***************************************************************************************/ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + /* + * Solution 1 - O(N log N) + * ========= + * + * We can use a recursive function that computes the solution for every node of the tree + * using the previous solutions calculated for the left and right subtrees. At every step + * we have 2 options: + * + * 1) Take the value of the current node + the solution of the left and right subtrees of + * each of the left and right children of the current node. + * 2) Take the solution of the left and right subtrees of the current node, skipping over + * its value. + * + * This way we can make sure that we do not pick 2 adjacent nodes. + * + * If we implemented this right away we would get TLE. Thus, we need to optimize the + * algorithm. One key observation would be that we only need to compute the solution for + * a certain node once. We can use memoization to calculate every value once and then + * retrieve it when we get subsequent calls. As the header of the recursive function + * doesn't allow additional parameters we can use a map to link every node(a pointer) to + * its solution(an int). For every call the map lookup of an element and its insertion + * take logarithmic time and there are a constant number of calls for each node. Thus, the + * algorithm takes O(N log N) time to finish. + * + */ +class Solution { +public: + map dict; + int rob(TreeNode* root) { + if(root == NULL) + return 0; + else if(dict.find(root) == dict.end()) + { + int lwith = rob(root->left); + int rwith = rob(root->right); + int lwithout = 0, rwithout = 0; + if(root->left != NULL) + lwithout = rob(root->left->left) + rob(root->left->right); + if(root->right != NULL) + rwithout = rob(root->right->left) + rob(root->right->right); + //cout << lwith << " " << rwith << " " << lwithout << " " << rwithout << '\n'; + dict[root] = max(root->val + lwithout + rwithout, lwith + rwith); + } + return dict[root]; + } +}; From d88cc15f7ab30c00d2dfc72d9a6ec0f82f30e8a9 Mon Sep 17 00:00:00 2001 From: Vally Date: Sat, 30 Apr 2016 17:34:02 +0300 Subject: [PATCH 041/105] added reverseVowelsOfAString --- README.md | 1 + .../reverseVowelsOfAString.cpp | 50 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp diff --git a/README.md b/README.md index 8eb0c6e5f..16acd1391 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| |330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium| diff --git a/algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp b/algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp new file mode 100644 index 000000000..f4f63922a --- /dev/null +++ b/algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp @@ -0,0 +1,50 @@ +// Source : https://leetcode.com/problems/reverse-vowels-of-a-string/ +// Author : Calinescu Valentin +// Date : 2016-04-30 + +/*************************************************************************************** + * + * Write a function that takes a string as input and reverse only the vowels of a + * string. + * + * Example 1: + * Given s = "hello", return "holle". + * + * Example 2: + * Given s = "leetcode", return "leotcede". + * + ***************************************************************************************/ +class Solution { +public: + string reverseVowels(string s) { + list vowels; + set vows; + vows.insert('a'); + vows.insert('A'); + vows.insert('e'); + vows.insert('E'); + vows.insert('i'); + vows.insert('I'); + vows.insert('o'); + vows.insert('O'); + vows.insert('u'); + vows.insert('U'); + string result; + for(int i = 0; i < s.size(); i++) + { + if(vows.find(s[i]) != vows.end()) + vowels.push_back(s[i]); + } + for(int i = 0; i < s.size(); i++) + { + if(vows.find(s[i]) != vows.end()) + { + result.push_back(vowels.back()); + vowels.pop_back(); + } + else + result.push_back(s[i]); + } + return result; + } +}; From a127523d15dc047452e1b0a79d167802b6958b3b Mon Sep 17 00:00:00 2001 From: Vally Date: Mon, 2 May 2016 23:13:48 +0300 Subject: [PATCH 042/105] added topKFrequentElements --- README.md | 1 + .../topKFrequentElements.cpp | 65 +++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp diff --git a/README.md b/README.md index 16acd1391..9362904c5 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| diff --git a/algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp b/algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp new file mode 100644 index 000000000..245c3ba0b --- /dev/null +++ b/algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp @@ -0,0 +1,65 @@ +// Source : https://leetcode.com/problems/top-k-frequent-elements/ +// Author : Calinescu Valentin +// Date : 2016-05-02 + +/*************************************************************************************** + * + * Given a non-empty array of integers, return the k most frequent elements. + * + * For example, + * Given [1,1,1,2,2,3] and k = 2, return [1,2]. + * + * Note: + * You may assume k is always valid, 1 ≤ k ≤ number of unique elements. + * Your algorithm's time complexity must be better than O(n log n), where n is the + * array's size. + * + ***************************************************************************************/ + +class Solution { +public: + struct element//structure consisting of every distinct number in the vector, + //along with its frequency + { + int number, frequency; + bool operator < (const element arg) const + { + return frequency < arg.frequency; + } + }; + priority_queue sol;//we use a heap so we have all of the elements sorted + //by their frequency + vector solution; + + vector topKFrequent(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int i = 1; + for(; i < nums.size(); i++) + { + int freq = 1; + while(i < nums.size() && nums[i] == nums[i - 1]) + { + i++; + freq++; + } + element el; + el.number = nums[i - 1]; + el.frequency = freq; + sol.push(el); + } + if(i == nums.size())//if we have 1 distinct element as the last + { + element el; + el.number = nums[nums.size() - 1]; + el.frequency = 1; + sol.push(el); + } + while(k)//we extract the first k elements from the heap + { + solution.push_back(sol.top().number); + sol.pop(); + k--; + } + return solution; + } +}; From 43156ff0bf6a5241b030bb31ea2dc216903b8a3a Mon Sep 17 00:00:00 2001 From: Vally Date: Fri, 20 May 2016 14:46:16 +0300 Subject: [PATCH 043/105] added intersectionOfTwoArrays --- README.md | 1 + .../intersectionOfTwoArrays.cpp | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp diff --git a/README.md b/README.md index 9362904c5..3b6e68aa7 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy| |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| diff --git a/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp b/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp new file mode 100644 index 000000000..da8fe9046 --- /dev/null +++ b/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp @@ -0,0 +1,31 @@ +// Source : https://leetcode.com/problems/intersection-of-two-arrays/ +// Author : Calinescu Valentin +// Date : 2016-05-20 + +/*************************************************************************************** + * + * Given two arrays, write a function to compute their intersection. + * + * Example: + * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. + * + * Note: + * Each element in the result must be unique. + * The result can be in any order. + * + ***************************************************************************************/ +class Solution { +public: + set inter1, inter2;//we use sets so as to avoid duplicates + vector solution; + vector intersection(vector& nums1, vector& nums2) { + for(int i = 0; i < nums1.size(); i++) + inter1.insert(nums1[i]);//get all of the unique elements in nums1 sorted + for(int i = 0; i < nums2.size(); i++) + if(inter1.find(nums2[i]) != inter1.end())//search nums1 in O(logN) + inter2.insert(nums2[i]);//populate the intersection set + for(set::iterator it = inter2.begin(); it != inter2.end(); ++it) + solution.push_back(*it);//copy the set into a vector + return solution; + } +}; From 7d3ec8447afde81fb065499422d37e180b256d85 Mon Sep 17 00:00:00 2001 From: Vally Date: Fri, 20 May 2016 14:48:38 +0300 Subject: [PATCH 044/105] fixed typo --- .../cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp b/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp index da8fe9046..0b20ecc77 100644 --- a/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp +++ b/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp @@ -22,7 +22,7 @@ class Solution { for(int i = 0; i < nums1.size(); i++) inter1.insert(nums1[i]);//get all of the unique elements in nums1 sorted for(int i = 0; i < nums2.size(); i++) - if(inter1.find(nums2[i]) != inter1.end())//search nums1 in O(logN) + if(inter1.find(nums2[i]) != inter1.end())//search inter1 in O(logN) inter2.insert(nums2[i]);//populate the intersection set for(set::iterator it = inter2.begin(); it != inter2.end(); ++it) solution.push_back(*it);//copy the set into a vector From 96f799f843841463d31f6fea6f82be7aed2b9771 Mon Sep 17 00:00:00 2001 From: Vally Date: Sun, 22 May 2016 16:47:42 +0300 Subject: [PATCH 045/105] added intersectionOfTwoArraysII --- README.md | 1 + .../intersectionOfTwoArraysII.cpp | 61 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp diff --git a/README.md b/README.md index 3b6e68aa7..8084bd918 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| |349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy| |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| diff --git a/algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp b/algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp new file mode 100644 index 000000000..3b20ef791 --- /dev/null +++ b/algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp @@ -0,0 +1,61 @@ +// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/ +// Author : Calinescu Valentin +// Date : 2016-05-22 + +/*************************************************************************************** + * + * Given two arrays, write a function to compute their intersection. + * + * Example: + * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. + * + * Note: + * Each element in the result should appear as many times as it shows in both arrays. + * The result can be in any order. + * + * Follow up: + * What if the given array is already sorted? How would you optimize your algorithm? + * What if nums1's size is small compared to num2's size? Which algorithm is better? + * What if elements of nums2 are stored on disk, and the memory is limited such that you + * cannot load all elements into the memory at once? + * + ***************************************************************************************/ + + /* Solution + * -------- + * + * Follow up: + * + * 1)If the given array is already sorted we can skip the sorting. + * + * 2)If nums1 is significantly smaller than nums2 we can only sort nums1 and then binary + * search every element of nums2 in nums1 with a total complexity of (MlogN) or if nums2 + * is already sorted we can search every element of nums1 in nums2 in O(NlogM) + * + * 3)Just like 2), we can search for every element in nums2, thus having an online + * algorithm. + */ + +class Solution { // O(NlogN + MlogM) +public: + vector intersect(vector& nums1, vector& nums2) { + sort(nums1.begin(), nums1.end());//we sort both vectors in order to intersect + sort(nums2.begin(), nums2.end());//them later in O(N + M), where N = nums1.size() + vector solution; //M = nums2.size() + int index = 0; + bool finished = false; + for(int i = 0; i < nums1.size() && !finished; i++) + { + while(index < nums2.size() && nums1[i] > nums2[index])//we skip over the + index++;//smaller elements in nums2 + if(index == nums2.size())//we have reached the end of nums2 so we have no more + finished = true;//elements to add to the intersection + else if(nums1[i] == nums2[index])//we found a common element + { + solution.push_back(nums1[i]); + index++; + } + } + return solution; + } +}; From cf12236261b84d2f965562a227139fa412c4e7d1 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sun, 29 May 2016 15:37:31 +0800 Subject: [PATCH 046/105] the solution of the problem "Reverse String" --- README.md | 1 + .../cpp/reverseString/ReverseString.cpp | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 algorithms/cpp/reverseString/ReverseString.cpp diff --git a/README.md b/README.md index 8084bd918..cf2cb7155 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ LeetCode |349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy| |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| +|345|[Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./algorithms/cpp/reverseString/ReverseString.cpp)|Easy| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| |330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium| diff --git a/algorithms/cpp/reverseString/ReverseString.cpp b/algorithms/cpp/reverseString/ReverseString.cpp new file mode 100644 index 000000000..c0f41088b --- /dev/null +++ b/algorithms/cpp/reverseString/ReverseString.cpp @@ -0,0 +1,24 @@ +// Source : https://leetcode.com/problems/reverse-string/ +// Author : Hao Chen +// Date : 2016-05-29 + +/*************************************************************************************** + * + * Write a function that takes a string as input and returns the string reversed. + * + * Example: + * Given s = "hello", return "olleh". + ***************************************************************************************/ + +class Solution { +public: + string reverseString(string s) { + int len = s.size(); + for (int i=0; i Date: Sun, 29 May 2016 15:58:40 +0800 Subject: [PATCH 047/105] make the script can detect the author name automatically --- scripts/comments.sh | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/scripts/comments.sh b/scripts/comments.sh index 69a6a10b6..6fe2e15f2 100755 --- a/scripts/comments.sh +++ b/scripts/comments.sh @@ -1,7 +1,7 @@ #!/bin/bash set -e -AUTHOR="Hao Chen" +AUTHOR="NOBODY" LEETCODE_URL=https://leetcode.com/problems/ LEETCODE_NEW_URL=https://leetcode.com/problems/ LEETCODE_OLD_URL=https://oj.leetcode.com/problems/ @@ -23,6 +23,18 @@ function usage() echo -e "" } +function get_author_name() +{ + TRUE_CMD=`which true` + git=`type -P git || ${TRUE_CMD}` + if [ ! -z "${git}" ]; then + AUTHOR=`git config --get user.name` + else + AUTHOR=`whoami` + fi +} + + function detect_os() { platform='unknown' @@ -138,6 +150,9 @@ if [ ! -s $source_file ]; then echo "" > $source_file fi +#detect the author name +get_author_name; + #adding the Copyright Comments if ! grep -Fq "${COMMENT_TAG} Author :" $source_file ; then sed -i.bak '1i\'$'\n'"${COMMENT_TAG} Source : ${leetcode_url}"$'\n' $source_file From 13eef8ddee74bd3727e74b911c67925433bea17d Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sun, 29 May 2016 16:13:33 +0800 Subject: [PATCH 048/105] the solution of problem "Power of Four" --- README.md | 3 +- algorithms/cpp/powerOfFour/PowerOfFour.cpp | 37 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 algorithms/cpp/powerOfFour/PowerOfFour.cpp diff --git a/README.md b/README.md index cf2cb7155..b3535e609 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,8 @@ LeetCode |349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy| |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| -|345|[Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./algorithms/cpp/reverseString/ReverseString.cpp)|Easy| +|344|[Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./algorithms/cpp/reverseString/ReverseString.cpp)|Easy| +|342|[Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./algorithms/cpp/powerOfFour/PowerOfFour.cpp)|Easy| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| |330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium| diff --git a/algorithms/cpp/powerOfFour/PowerOfFour.cpp b/algorithms/cpp/powerOfFour/PowerOfFour.cpp new file mode 100644 index 000000000..f66e6d9e2 --- /dev/null +++ b/algorithms/cpp/powerOfFour/PowerOfFour.cpp @@ -0,0 +1,37 @@ +// Source : https://leetcode.com/problems/power-of-four/ +// Author : Hao Chen +// Date : 2016-05-29 + +/*************************************************************************************** + * + * Given an integer (signed 32 bits), write a function to check whether it is a power + * of 4. + * + * Example: + * Given num = 16, return true. + * Given num = 5, return false. + * + * Follow up: Could you solve it without loops/recursion? + * + * Credits:Special thanks to @yukuairoy for adding this problem and creating all test + * cases. + ***************************************************************************************/ + + +class Solution { +public: + bool isPowerOfFour(int num) { + static int mask = 0b01010101010101010101010101010101; + + //edge case + if (num<=0) return false; + + // there are multiple bits are 1 + if ((num & num-1) != 0) return false; + + // check which one bit is zero, if the place is 1 or 3 or 5 or 7 or 9..., + // then it is the power of 4 + if ((num & mask) != 0) return true; + return false; + } +}; From 35ed8b3590b0400b21d42979b2d6f224ce8e2622 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sun, 29 May 2016 16:27:19 +0800 Subject: [PATCH 049/105] the solution of problem "Integer Break" --- README.md | 1 + algorithms/cpp/integerBreak/IntegerBreak.cpp | 46 ++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 algorithms/cpp/integerBreak/IntegerBreak.cpp diff --git a/README.md b/README.md index b3535e609..bc09b594d 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ LeetCode |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| |344|[Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./algorithms/cpp/reverseString/ReverseString.cpp)|Easy| +|343|[Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./algorithms/cpp/integerBreak/IntegerBreak.cpp)|Medium| |342|[Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./algorithms/cpp/powerOfFour/PowerOfFour.cpp)|Easy| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| diff --git a/algorithms/cpp/integerBreak/IntegerBreak.cpp b/algorithms/cpp/integerBreak/IntegerBreak.cpp new file mode 100644 index 000000000..21f78bb82 --- /dev/null +++ b/algorithms/cpp/integerBreak/IntegerBreak.cpp @@ -0,0 +1,46 @@ +// Source : https://leetcode.com/problems/integer-break/ +// Author : Hao Chen +// Date : 2016-05-29 + +/*************************************************************************************** + * + * Given a positive integer n, break it into the sum of at least two positive integers + * and maximize the product of those integers. Return the maximum product you can get. + * + * For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + * + 4). + * + * Note: you may assume that n is not less than 2. + * + * There is a simple O(n) solution to this problem. + * You may check the breaking results of n ranging from 7 to 10 to discover the + * regularities. + * + * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating + * all test cases. + ***************************************************************************************/ + +class Solution { +public: + // As the hint said, checking the n with ranging from 7 to 10 to discover the regularities. + // n = 7, 3*4 = 12 + // n = 8, 3*3*2 = 18 + // n = 9, 3*3*3 = 27 + // n = 10, 3*3*4 = 36 + // n = 11, 3*3*3*2 = 54 + // + // we can see we can break the number by 3 if it is greater than 4; + // + int integerBreak(int n) { + if ( n == 2 ) return 1; + if ( n == 3 ) return 2; + int result = 1; + while( n > 4 ) { + result *= 3; + n -= 3; + } + result *= n; + return result; + } +}; + From ecb178901cd760480b50e38961853f113e95db11 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 30 May 2016 00:42:46 +0800 Subject: [PATCH 050/105] the solution of the problem "Flatten Nested List Iterator" --- README.md | 1 + .../FlattenNestedListIterator.cpp | 74 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp diff --git a/README.md b/README.md index bc09b594d..cb84551d3 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ LeetCode |344|[Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./algorithms/cpp/reverseString/ReverseString.cpp)|Easy| |343|[Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./algorithms/cpp/integerBreak/IntegerBreak.cpp)|Medium| |342|[Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./algorithms/cpp/powerOfFour/PowerOfFour.cpp)|Easy| +|341|[Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/) | [C++](./algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp)|Medium| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| |330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium| diff --git a/algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp b/algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp new file mode 100644 index 000000000..e62484864 --- /dev/null +++ b/algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp @@ -0,0 +1,74 @@ +// Source : https://leetcode.com/problems/flatten-nested-list-iterator/ +// Author : Hao Chen +// Date : 2016-05-30 + +/*************************************************************************************** + * + * Given a nested list of integers, implement an iterator to flatten it. + * + * Each element is either an integer, or a list -- whose elements may also be integers + * or other lists. + * + * Example 1: + * Given the list [[1,1],2,[1,1]], + * + * By calling next repeatedly until hasNext returns false, the order of elements + * returned by next should be: [1,1,2,1,1]. + * + * Example 2: + * Given the list [1,[4,[6]]], + * + * By calling next repeatedly until hasNext returns false, the order of elements + * returned by next should be: [1,4,6]. + ***************************************************************************************/ + +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class NestedIterator { +private: + vector v; + int index; + void flatten(vector &nestedList) { + for (auto item : nestedList){ + if (item.isInteger()){ + v.push_back( item.getInteger() ); + }else{ + flatten( item.getList() ); + } + } + } +public: + NestedIterator(vector &nestedList) { + flatten(nestedList); + index = 0; + } + + int next() { + return v[index++]; + } + + bool hasNext() { + return (index < v.size() ); + } +}; + +/** + * Your NestedIterator object will be instantiated and called as such: + * NestedIterator i(nestedList); + * while (i.hasNext()) cout << i.next(); + */ From eb040df04b9715b274da44e2b1e43ff8c64bb145 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 30 May 2016 01:36:23 +0800 Subject: [PATCH 051/105] the solution of the problem "Counting Bits" --- README.md | 1 + algorithms/cpp/countingBits/CountingBits.cpp | 67 ++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 algorithms/cpp/countingBits/CountingBits.cpp diff --git a/README.md b/README.md index cb84551d3..cfe31bb33 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ LeetCode |343|[Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./algorithms/cpp/integerBreak/IntegerBreak.cpp)|Medium| |342|[Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./algorithms/cpp/powerOfFour/PowerOfFour.cpp)|Easy| |341|[Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/) | [C++](./algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp)|Medium| +|338|[Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./algorithms/cpp/countingBits/CountingBits.cpp)|Medium| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| |330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium| diff --git a/algorithms/cpp/countingBits/CountingBits.cpp b/algorithms/cpp/countingBits/CountingBits.cpp new file mode 100644 index 000000000..0bfe843b1 --- /dev/null +++ b/algorithms/cpp/countingBits/CountingBits.cpp @@ -0,0 +1,67 @@ +// Source : https://leetcode.com/problems/counting-bits/ +// Author : Hao Chen +// Date : 2016-05-30 + +/*************************************************************************************** + * + * Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ + * num calculate the number of 1's in their binary representation and return them as an + * array. + * + * Example: + * For num = 5 you should return [0,1,1,2,1,2]. + * + * Follow up: + * + * It is very easy to come up with a solution with run time O(n*sizeof(integer)). But + * can you do it in linear time O(n) /possibly in a single pass? + * Space complexity should be O(n). + * Can you do it like a boss? Do it without using any builtin function like + * __builtin_popcount in c++ or in any other language. + * + * You should make use of what you have produced already. + * Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to + * generate new range from previous. + * Or does the odd/even status of the number help you in calculating the number of 1s? + * + * Credits:Special thanks to @ syedee for adding this problem and creating all test + * cases. + ***************************************************************************************/ + +class Solution { +public: + /* + * Initialization + * + * bits_cnt[0] => 0000 => 0 + * bits_cnt[1] => 0001 => 1 + * + * if the number has 2 bits (2, 3), then we can split the binary to two parts, + * 2 = 10 + 0 and 3= 10 + 1, then we can reuse the bits_cnt[0] and bits_cnt[1] + * + * bits_cnt[2] => 0010 => 0010 + 0 => 1 + bits_cnt[0]; + * bits_cnt[3] => 0011 => 0010 + 1 => 1 + bits_cnt[1]; + * + * if the number has 3 bits (4,5,6,7), then we can split the binary to two parts, + * 4 = 100 + 0, 5 = 100 + 01, 6= 100 + 10, 7 = 100 +11 + * then we can reuse the bits_cnt[0] and bits_cnt[1] + * + * bits_cnt[4] => 0110 => 0100 + 00 => 1 + bits_cnt[0]; + * bits_cnt[5] => 0101 => 0100 + 01 => 1 + bits_cnt[1]; + * bits_cnt[6] => 0110 => 0100 + 10 => 1 + bits_cnt[2]; + * bits_cnt[7] => 0111 => 0100 + 11 => 1 + bits_cnt[3]; + * + * so, we can have the solution: + * + * bits_cnt[x] = bits_cnt[x & (x-1) ] + 1; + * + */ + vector countBits(int num) { + vector bits_cnt(num+1, 0); + + for (int i=1; i<=num; i++) { + bits_cnt[i] = bits_cnt[i & (i-1)] + 1; + } + return bits_cnt; + } +}; From 94e9e4b090455ff07f6e57d8f73855654f9defb1 Mon Sep 17 00:00:00 2001 From: wuxun Date: Tue, 14 Jun 2016 20:31:43 +0800 Subject: [PATCH 052/105] fix a wrong number in comment --- algorithms/cpp/editDistance/editDistance.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/cpp/editDistance/editDistance.cpp b/algorithms/cpp/editDistance/editDistance.cpp index ec5612658..776e9661a 100644 --- a/algorithms/cpp/editDistance/editDistance.cpp +++ b/algorithms/cpp/editDistance/editDistance.cpp @@ -75,7 +75,7 @@ using namespace std; * "" 0 1 2 3 4 5 * a 1 0 1 2 3 4 * b 2 1 0 1 2 3 - * b 3 2 1 1 1 2 + * b 3 2 1 1 2 2 * */ int min(int x, int y, int z) { From b4e083642db5f9df15d2112cdd199759ed2d9621 Mon Sep 17 00:00:00 2001 From: arctanx Date: Wed, 6 Jul 2016 23:10:13 +0800 Subject: [PATCH 053/105] Update bullsAndCows.cpp --- algorithms/cpp/bullsAndCows/bullsAndCows.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/algorithms/cpp/bullsAndCows/bullsAndCows.cpp b/algorithms/cpp/bullsAndCows/bullsAndCows.cpp index f91550532..feeb1bb89 100644 --- a/algorithms/cpp/bullsAndCows/bullsAndCows.cpp +++ b/algorithms/cpp/bullsAndCows/bullsAndCows.cpp @@ -42,8 +42,8 @@ class Solution { } string getHint01(string secret, string guess) { - int appears_in_secret[10], appears_in_guess[10], bulls[10]; - int total_bulls, total_cows; + int appears_in_secret[10] = {0}, appears_in_guess[10] = {0}, bulls[10] = {0}; + int total_bulls = 0, total_cows = 0; for(int i = 0; i < secret.size(); i++) appears_in_secret[secret[i] - '0']++; for(int i = 0; i < guess.size(); i++) From 227b5749fcf968f51d0290371b3e823c9774b1fc Mon Sep 17 00:00:00 2001 From: Vali Date: Sun, 7 Aug 2016 16:35:33 +0300 Subject: [PATCH 054/105] added combinationSumIV --- README.md | 1 + .../cpp/combinationSumIV/combinationSumIV.cpp | 68 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 algorithms/cpp/combinationSumIV/combinationSumIV.cpp diff --git a/README.md b/README.md index cfe31bb33..cfb9929c2 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| |349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy| |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| diff --git a/algorithms/cpp/combinationSumIV/combinationSumIV.cpp b/algorithms/cpp/combinationSumIV/combinationSumIV.cpp new file mode 100644 index 000000000..d3006375d --- /dev/null +++ b/algorithms/cpp/combinationSumIV/combinationSumIV.cpp @@ -0,0 +1,68 @@ +// Source : https://leetcode.com/problems/combination-sum-iv/ +// Author : Calinescu Valentin +// Date : 2016-08-07 + +/*************************************************************************************** + * + * Given an integer array with all positive numbers and no duplicates, find the number + * of possible combinations that add up to a positive integer target. + * + * Example: + * + * nums = [1, 2, 3] + * target = 4 + * + * The possible combination ways are: + * (1, 1, 1, 1) + * (1, 1, 2) + * (1, 2, 1) + * (1, 3) + * (2, 1, 1) + * (2, 2) + * (3, 1) + * + * Note that different sequences are counted as different combinations. + * + * Therefore the output is 7. + * Follow up: + * What if negative numbers are allowed in the given array? + * How does it change the problem? + * What limitation we need to add to the question to allow negative numbers? + * + ***************************************************************************************/ + + /* Solution + * -------- + * 1) Dynamic Programming - O(N * target) + * + * We notice that any sum S can be written as S_prev + nums[i], where S_prev is a sum of + * elements from nums and nums[i] is one element of the array. S_prev is always smaller + * than S so we can create the array sol, where sol[i] is the number of ways one can + * arrange the elements of the array to obtain sum i, and populate it from 1 to target, + * as the solution for i is made up of previously computed ones for numbers smaller than + * i. The final answer is sol[target], which is returned at the end. + * + * Follow up: + * + * If the array contains negative numbers as well as positive ones we can run into a cycle + * where some subset of the elements have sum 0 so they can always be added to an existing + * sum, leading to an infinite number of solutions. The limitation that we need is a rule + * to be followed by the input data, that which doesn't allow this type of subsets to exist. + */ +class Solution { +public: + int combinationSum4(vector& nums, int target) { + int sol[target + 1]; + sol[0] = 1;//starting point, only 1 way to obtain 0, that is to have 0 elements + for(int i = 1; i <= target; i++) + { + sol[i] = 0; + for(int j = 0; j < nums.size(); j++) + { + if(i >= nums[j])//if there is a previously calculated sum to add nums[j] to + sol[i] += sol[i - nums[j]]; + } + } + return sol[target]; + } +}; From 931ba6a9a7888fdf9e16ddefa16a6d76ecb4a1e0 Mon Sep 17 00:00:00 2001 From: Vali Date: Mon, 8 Aug 2016 11:12:28 +0300 Subject: [PATCH 055/105] added wiggleSubsequence --- README.md | 1 + .../wiggleSubsequence/wiggleSubsequence.cpp | 88 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp diff --git a/README.md b/README.md index cfb9929c2..3091c6a5c 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| +|376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| |349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy| |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| diff --git a/algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp b/algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp new file mode 100644 index 000000000..5631e5713 --- /dev/null +++ b/algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp @@ -0,0 +1,88 @@ +// Source : https://leetcode.com/problems/wiggle-subsequence/ +// Author : Calinescu Valentin +// Date : 2016-08-08 + +/*************************************************************************************** + * + * A sequence of numbers is called a wiggle sequence if the differences between + * successive numbers strictly alternate between positive and negative. The first + * difference (if one exists) may be either positive or negative. A sequence with fewer + * than two elements is trivially a wiggle sequence. + * + * For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) + * are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are + * not wiggle sequences, the first because its first two differences are positive and + * the second because its last difference is zero. + * + * Given a sequence of integers, return the length of the longest subsequence that is a + * wiggle sequence. A subsequence is obtained by deleting some number of elements + * (eventually, also zero) from the original sequence, leaving the remaining elements in + * their original order. + * + * Examples: + * Input: [1,7,4,9,2,5] + * Output: 6 + * The entire sequence is a wiggle sequence. + * + * Input: [1,17,5,10,13,15,10,5,16,8] + * Output: 7 + * There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8]. + * + * Input: [1,2,3,4,5,6,7,8,9] + * Output: 2 + * + * Follow up: + * Can you do it in O(n) time? + * + ***************************************************************************************/ + + /* Solution + * -------- + * 1) O(N) + * + * We notice that adding a new number to an existing subsequence means finding one that + * is smaller or bigger than the previous number, according to the difference between the + * previous number and the number before that as we always need to alternate between increasing + * and decreasing subsequences. If we encounter increasing or decreasing sequences of 2 or + * more consecutive numbers we can treat the entire subsequence as a number, because that way + * we can always be sure we don't miss any solution, as finding a number smaller than any + * number of an increasing subsequence is guaranteed to be smaller than the biggest number + * in the subsequence. Thus, we can only check the difference between consecutive numbers. + * + * Follow up: + * + * The time complexity is already O(N). + */ +class Solution { +public: + int wiggleMaxLength(vector& nums) { + int solution = 0;//if we have an empty vector the solution is 0 + if(nums.size()) + { + solution = 1; + int bigger = 0;//0 is the starting point to be followed by either an increasing or decreasing sequence + for(int i = 1; i < nums.size(); i++) + { + if(nums[i] == nums[i - 1]) + continue;//we can ignore duplicates as they can always be omitted + else if(nums[i] > nums[i - 1]) + { + if(bigger == 0 || bigger == 2) + { + bigger = 1;//1 means we now have an increasing sequence + solution++; + } + } + else //if(nums[i] < nums[i - 1]) + { + if(bigger == 0 || bigger == 1) + { + bigger = 2;//2 means we now have a decreasing sequence + solution++; + } + } + } + } + return solution; + } +}; From ec8013d95483e0659f11a62806d861cc3cc19b36 Mon Sep 17 00:00:00 2001 From: huangxiaofei Date: Thu, 11 Aug 2016 22:43:20 +0800 Subject: [PATCH 056/105] modified: cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp use one set instead of two set --- .../intersectionOfTwoArrays.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp b/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp index 0b20ecc77..88eaccba6 100644 --- a/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp +++ b/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp @@ -29,3 +29,32 @@ class Solution { return solution; } }; + +/* + * This Solution use one unordered_set + */ +class Solution2 { +public: + vector intersection(vector& nums1, vector& nums2) { + unordered_set hash_set(nums1.begin(), nums1.end()); + vector res ; + for (auto it& : nums2) { + if (hash_set.count(it)) { + res.push_back(it); + hash_set.erase(it); + } + } + return res; + } +}; + + + + + + + + + + + From 5e147626a0948f555bcfb578bb4ee1fa2b573761 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Tue, 23 Aug 2016 11:32:06 +0800 Subject: [PATCH 057/105] New Problem "Lexicographical Numbers" --- README.md | 1 + .../LexicographicalNumbers.cpp | 109 ++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp diff --git a/README.md b/README.md index 3091c6a5c..f70960641 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|386|[Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp)|Medium| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| |376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| diff --git a/algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp b/algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp new file mode 100644 index 000000000..f75a423d1 --- /dev/null +++ b/algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp @@ -0,0 +1,109 @@ +// Source : https://leetcode.com/problems/lexicographical-numbers/ +// Author : Hao Chen +// Date : 2016-08-23 + +/*************************************************************************************** + * + * Given an integer n, return 1 - n in lexicographical order. + * + * For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. + * + * Please optimize your algorithm to use less time and space. The input size may be as + * large as 5,000,000. + ***************************************************************************************/ +class Solution { + +//Solution 1: convert the int to string for sort, Time complexity is high (Time Limited Error) +public: + vector lexicalOrder01(int n) { + vector result; + for (int i=1; i<=n; i++) { + result.push_back(i); + } + sort(result.begin(), result.end(), this->myComp); + return result; + } +private: + static bool myComp(int i,int j) { + static char si[32]={0}, sj[32]={0}; + sprintf(si, "%d\0", i); + sprintf(sj, "%d\0", j); + return (strcmp(si, sj)<0); + } + + +//Solution 2 : using recursive way to solution the problem, 540ms +public: + vector lexicalOrder02(int n) { + vector result; + for (int i=1; i<=n && i<=9; i++) { + result.push_back(i); + lexicalOrder_helper(i, n, result); + } + return result; + } + +private: + void lexicalOrder_helper(int num, int& n, vector& result) { + for (int i=0; i<=9; i++) { + int tmp = num * 10 + i; + if (tmp > n) { + break; + } + result.push_back(tmp); + lexicalOrder_helper(tmp, n, result); + } + } + +//Solution 3: no recursive way, but the code is not easy to read +public : + vector lexicalOrder03(int n) { + vector result; + int curr = 1; + while (result.size() lexicalOrder(int n) { + //srand(time(NULL)); + //if (rand()%2) + // return lexicalOrder02(n); // recursive way 560ms + //else + return lexicalOrder03(n); // non-recursive way, 460ms + } + +}; From 5fe30bc76f29f906c95affcafce6b0dcd5aeeeea Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Tue, 23 Aug 2016 12:09:57 +0800 Subject: [PATCH 058/105] New Problem "First Unique Character in a String" --- README.md | 1 + .../FirstUniqueCharacterInAString.cpp | 55 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp diff --git a/README.md b/README.md index f70960641..3de2a519c 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp)|Easy| |386|[Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp)|Medium| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| |376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium| diff --git a/algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp b/algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp new file mode 100644 index 000000000..29081bb3d --- /dev/null +++ b/algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp @@ -0,0 +1,55 @@ +// Source : https://leetcode.com/problems/first-unique-character-in-a-string/ +// Author : Hao Chen +// Date : 2016-08-23 + +/*************************************************************************************** + * + * Given a string, find the first non-repeating character in it and return it's index. + * If it doesn't exist, return -1. + * + * Examples: + * + * s = "leetcode" + * return 0. + * + * s = "loveleetcode", + * return 2. + * + * Note: You may assume the string contain only lowercase letters. + ***************************************************************************************/ + +class Solution { +public: + int firstUniqChar(string s) { + //As the question mentioned, there only have lower case chars, + //so the MAX_CHAR can be defined as 26, but I want this algorithm be more general for all ASCII + #define MAX_CHAR 256 + #define NOT_FOUND -1 + #define DUPLICATION -2 + + // initlize all chars status to NOT_FOUND + int pos_map[MAX_CHAR]; + memset(pos_map, NOT_FOUND,sizeof(pos_map)); + + // if it is the first time to find, set the status to its postion + // if it is the second time to find, set the status to duplication + // if it has already duplicated, do nothing + for (int i=0; i= 0 ) { + pos_map[s[i]] = DUPLICATION; + }else if ( pos_map[s[i]] == NOT_FOUND ) { + pos_map[s[i]] = i; + } + } + + // find the lowest postion + int pos = INT_MAX; + for (auto item : pos_map) { + cout << item << ","; + if (item >= 0 && item < pos) { + pos = item; + } + } + return pos == INT_MAX ? -1 : pos; + } +}; From 25633c1a10df57f01b019de440375a8aa5df2744 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Tue, 23 Aug 2016 13:06:47 +0800 Subject: [PATCH 059/105] add indent --- algorithms/cpp/wordPattern/WordPattern.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/cpp/wordPattern/WordPattern.cpp b/algorithms/cpp/wordPattern/WordPattern.cpp index 8d67a0edb..0d319f110 100644 --- a/algorithms/cpp/wordPattern/WordPattern.cpp +++ b/algorithms/cpp/wordPattern/WordPattern.cpp @@ -34,7 +34,7 @@ private:: string tok; while(getline(ss, tok, delimiter)) { - internal.push_back(tok); + internal.push_back(tok); } return internal; From f9dc6340dfff3e9e17e0d7ff2a284dbb707197d7 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Tue, 23 Aug 2016 14:09:10 +0800 Subject: [PATCH 060/105] New Problem "Longest Absolute File Path" --- README.md | 1 + .../LongestAbsoluteFilePath.cpp | 107 ++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp diff --git a/README.md b/README.md index 3de2a519c..e17e5400d 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +[388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp)|Medium| |387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp)|Easy| |386|[Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp)|Medium| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| diff --git a/algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp b/algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp new file mode 100644 index 000000000..bf7f6ce33 --- /dev/null +++ b/algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp @@ -0,0 +1,107 @@ +// Source : https://leetcode.com/problems/longest-absolute-file-path/ +// Author : Hao Chen +// Date : 2016-08-23 + +/*************************************************************************************** + * + * Suppose we abstract our file system by a string in the following manner: + * + * The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: + * + * dir + * subdir1 + * subdir2 + * file.ext + * + * The directory dir contains an empty sub-directory subdir1 and a sub-directory + * subdir2 containing a file file.ext. + * + * The string + * "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile + * 2.ext" represents: + * + * dir + * subdir1 + * file1.ext + * subsubdir1 + * subdir2 + * subsubdir2 + * file2.ext + * + * The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains + * a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 + * contains a second-level sub-directory subsubdir2 containing a file file2.ext. + * + * We are interested in finding the longest (number of characters) absolute path to a + * file within our file system. For example, in the second example above, the longest + * absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not + * including the double quotes). + * + * Given a string representing the file system in the above format, return the length + * of the longest absolute path to file in the abstracted file system. If there is no + * file in the system, return 0. + * + * Note: + * + * The name of a file contains at least a . and an extension. + * The name of a directory or sub-directory will not contain a .. + * + * Time complexity required: O(n) where n is the size of the input string. + * + * Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another + * path aaaaaaaaaaaaaaaaaaaaa/sth.png. + ***************************************************************************************/ + +class Solution { +public: + // Solution + // -------- + // We can see the input formation has the order + // so, we can maintain an array which states the current level's path length + // + // For example: + // dir + // subdir1 <- length[ level1 = len("dir")+len("/"), + // level2 = len("dir")+len("/")+len("subdir1")+len("/") ] + // file.ext + // subdir2 + // file.ext + // subsubdir1 <- length[ level1 = len("dir")+len("/"), + // level2 = len("dir")+len("/")+len("subdir2")+len("/"), + // level3 = len("dir")+len("/")+len("subdir2")+len("/")+len("subsubdir1")+len("/") ] + // file.ext + // + int lengthLongestPath(string input) { + + stringstream ss(input); + string line; + int result = 0; + + vector length; + length.push_back(0); //initialize top dummy level's length is zero + + while (getline(ss, line, '\n')) { + //get current level, start from 1 + int level = 0; + while ( line[level++] == '\t'); // get the level + int len = line.size() - level + 1; + + //if is a file, then cacualte the total length. + if (line.find('.') != string::npos) { + if ( length[level-1] + len > result ) { + result = length[level-1] + len; + } + } else { + + if (length.size() <= level) { + length.push_back(0); + } + + // if it a folder, then update the current level's length + length[level] = length[level-1] + len + 1; // 1 for "/" path delimiter + } + + } + return result; + } +}; From bfeb664e07f0854561a4dc72bfd7ef7dac1950af Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Tue, 23 Aug 2016 14:11:46 +0800 Subject: [PATCH 061/105] typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e17e5400d..121c7ca1d 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | -[388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp)|Medium| +|388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp)|Medium| |387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp)|Easy| |386|[Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp)|Medium| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| From 729eec6f0973a78eb9cbd33262d847a89076bc2c Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Wed, 24 Aug 2016 11:06:07 +0800 Subject: [PATCH 062/105] uncomment the code --- .../cpp/lexicographicalNumbers/LexicographicalNumbers.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp b/algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp index f75a423d1..779e61077 100644 --- a/algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp +++ b/algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp @@ -99,10 +99,10 @@ public : //start point public: vector lexicalOrder(int n) { - //srand(time(NULL)); - //if (rand()%2) - // return lexicalOrder02(n); // recursive way 560ms - //else + srand(time(NULL)); + if (rand()%2) + return lexicalOrder02(n); // recursive way 560ms + else return lexicalOrder03(n); // non-recursive way, 460ms } From d076c2c3daa9eaa8349cdb230b8faa2a0a340b14 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Wed, 24 Aug 2016 12:30:18 +0800 Subject: [PATCH 063/105] New Problem Solution - "Mini Parser" --- README.md | 1 + algorithms/cpp/miniParser/MiniParser.cpp | 116 +++++++++++++++++++++++ 2 files changed, 117 insertions(+) create mode 100644 algorithms/cpp/miniParser/MiniParser.cpp diff --git a/README.md b/README.md index 121c7ca1d..3913fb8f2 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ LeetCode |388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp)|Medium| |387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp)|Easy| |386|[Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp)|Medium| +|385|[Mini Parser](https://leetcode.com/problems/mini-parser/) | [C++](./algorithms/cpp/miniParser/MiniParser.cpp)|Medium| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| |376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| diff --git a/algorithms/cpp/miniParser/MiniParser.cpp b/algorithms/cpp/miniParser/MiniParser.cpp new file mode 100644 index 000000000..8c126e958 --- /dev/null +++ b/algorithms/cpp/miniParser/MiniParser.cpp @@ -0,0 +1,116 @@ +// Source : https://leetcode.com/problems/mini-parser/ +// Author : Hao Chen +// Date : 2016-08-24 + +/*************************************************************************************** + * + * Given a nested list of integers represented as a string, implement a parser to + * deserialize it. + * + * Each element is either an integer, or a list -- whose elements may also be integers + * or other lists. + * + * Note: + * You may assume that the string is well-formed: + * + * String is non-empty. + * String does not contain white spaces. + * String contains only digits 0-9, [, - ,, ]. + * + * Example 1: + * + * Given s = "324", + * + * You should return a NestedInteger object which contains a single integer 324. + * + * Example 2: + * + * Given s = "[123,[456,[789]]]", + * + * Return a NestedInteger object containing a nested list with 2 elements: + * + * 1. An integer containing value 123. + * 2. A nested list containing two elements: + * i. An integer containing value 456. + * ii. A nested list with one element: + * a. An integer containing value 789. + ***************************************************************************************/ + + +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Constructor initializes an empty nested list. + * NestedInteger(); + * + * // Constructor initializes a single integer. + * NestedInteger(int value); + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Set this NestedInteger to hold a single integer. + * void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * void add(const NestedInteger &ni); + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class Solution { +public: + NestedInteger deserialize(string s) { + if (s.size()==0) return NestedInteger(); + int pos = 0; + if (s[pos]!='[') return atoni(s, pos); + + return helper(s, ++pos); + } +private: + NestedInteger helper(string& s, int& pos) { + + NestedInteger ni; + + while ( s[pos] != ']' && pos < s.size() ) { + + if (s[pos]=='-' || isnum(s[pos])){ + ni.add(atoni(s, pos)); + }else if (s[pos] == '[') { + pos++; + ni.add(helper(s, pos)); + }else { + pos++; + } + } + pos++; + return ni; + } + NestedInteger atoni(string& s, int& pos) { + int sign = 1; + int num = 0; + if (s[pos]=='-') { + sign = -1; + pos++; + } + for (; pos < s.size(); pos++) { + if (isnum(s[pos])) { + num = num * 10 + s[pos] - '0'; + }else{ + break; + } + } + return NestedInteger(sign * num); + } + bool isnum(char& c) { + return (c >='0' && c <='9'); + } +}; From d666cbfcafd7f157acca45a904a3ed569602ada7 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Wed, 24 Aug 2016 13:22:08 +0800 Subject: [PATCH 064/105] New Problem Solution - "Shuffle an Array" --- README.md | 1 + .../cpp/shuffleAnArray/ShuffleAnArray.cpp | 59 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp diff --git a/README.md b/README.md index 3913fb8f2..477d66c84 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ LeetCode |387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp)|Easy| |386|[Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp)|Medium| |385|[Mini Parser](https://leetcode.com/problems/mini-parser/) | [C++](./algorithms/cpp/miniParser/MiniParser.cpp)|Medium| +|384|[Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp)|Medium| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| |376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| diff --git a/algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp b/algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp new file mode 100644 index 000000000..681a77519 --- /dev/null +++ b/algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp @@ -0,0 +1,59 @@ +// Source : https://leetcode.com/problems/shuffle-an-array/ +// Author : Hao Chen +// Date : 2016-08-24 + +/*************************************************************************************** + * + * Shuffle a set of numbers without duplicates. + * + * Example: + * + * // Init an array with set 1, 2, and 3. + * int[] nums = {1,2,3}; + * Solution solution = new Solution(nums); + * + * // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must + * equally likely to be returned. + * solution.shuffle(); + * + * // Resets the array back to its original configuration [1,2,3]. + * solution.reset(); + * + * // Returns the random shuffling of array [1,2,3]. + * solution.shuffle(); + ***************************************************************************************/ + +class Solution { +public: + Solution(vector nums) : _nums(nums), _solution(nums) { + srand(time(NULL)); + } + + /** Resets the array to its original configuration and return it. */ + vector reset() { + return _solution = _nums; + } + + /** Returns a random shuffling of the array. */ + vector shuffle() { + //Fisher Yates + //https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle + + int i = _solution.size(); + + while ( --i > 0 ) { + int j = rand() % (i+1); + swap(_solution[i], _solution[j]); + } + return _solution; + } +private: + vector _nums, _solution; +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(nums); + * vector param_1 = obj.reset(); + * vector param_2 = obj.shuffle(); + */ From 6906cda1138081f68298521884006c22321b4988 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Wed, 24 Aug 2016 13:24:30 +0800 Subject: [PATCH 065/105] New Problem Solution - "Ransom Note" --- README.md | 1 + algorithms/cpp/ransomNote/RansomNote.cpp | 38 ++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 algorithms/cpp/ransomNote/RansomNote.cpp diff --git a/README.md b/README.md index 477d66c84..d9e0f38aa 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ LeetCode |386|[Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp)|Medium| |385|[Mini Parser](https://leetcode.com/problems/mini-parser/) | [C++](./algorithms/cpp/miniParser/MiniParser.cpp)|Medium| |384|[Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp)|Medium| +|383|[Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./algorithms/cpp/ransomNote/RansomNote.cpp)|Easy| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| |376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| diff --git a/algorithms/cpp/ransomNote/RansomNote.cpp b/algorithms/cpp/ransomNote/RansomNote.cpp new file mode 100644 index 000000000..c13922ea1 --- /dev/null +++ b/algorithms/cpp/ransomNote/RansomNote.cpp @@ -0,0 +1,38 @@ +// Source : https://leetcode.com/problems/ransom-note/ +// Author : Hao Chen +// Date : 2016-08-24 + +/*************************************************************************************** + * + * 
Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing + * 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true + * 
if 
the 
ransom 
 + * note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return + * 
false. 

 + * + * Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your + * 
ransom
 note. + * + * Note: + * You may assume that both strings contain only lowercase letters. + * + * canConstruct("a", "b") -> false + * canConstruct("aa", "ab") -> false + * canConstruct("aa", "aab") -> true + ***************************************************************************************/ + +class Solution { +public: + bool canConstruct(string ransomNote, string magazine) { + unordered_map m; + for(int i=0; i Date: Wed, 24 Aug 2016 14:10:53 +0800 Subject: [PATCH 066/105] New Problem Solution - "Linked List Random Node" --- README.md | 1 + .../LinkedListRandomNode.cpp | 61 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 algorithms/cpp/linkedListRandomNode/LinkedListRandomNode.cpp diff --git a/README.md b/README.md index d9e0f38aa..41bce4906 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ LeetCode |385|[Mini Parser](https://leetcode.com/problems/mini-parser/) | [C++](./algorithms/cpp/miniParser/MiniParser.cpp)|Medium| |384|[Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp)|Medium| |383|[Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./algorithms/cpp/ransomNote/RansomNote.cpp)|Easy| +|382|[Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./algorithms/cpp/linkedListRandomNode/LinkedListRandomNode.cpp)|Medium| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| |376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| diff --git a/algorithms/cpp/linkedListRandomNode/LinkedListRandomNode.cpp b/algorithms/cpp/linkedListRandomNode/LinkedListRandomNode.cpp new file mode 100644 index 000000000..8cc97117c --- /dev/null +++ b/algorithms/cpp/linkedListRandomNode/LinkedListRandomNode.cpp @@ -0,0 +1,61 @@ +// Source : https://leetcode.com/problems/linked-list-random-node/ +// Author : Hao Chen +// Date : 2016-08-24 + +/*************************************************************************************** + * + * Given a singly linked list, return a random node's value from the linked list. Each + * node must have the same probability of being chosen. + * + * Follow up: + * What if the linked list is extremely large and its length is unknown to you? Could + * you solve this efficiently without using extra space? + * + * Example: + * + * // Init a singly linked list [1,2,3]. + * ListNode head = new ListNode(1); + * head.next = new ListNode(2); + * head.next.next = new ListNode(3); + * Solution solution = new Solution(head); + * + * // getRandom() should return either 1, 2, or 3 randomly. Each element should have + * equal probability of returning. + * solution.getRandom(); + ***************************************************************************************/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + /** @param head The linked list's head. + Note that the head is guaranteed to be not null, so it contains at least one node. */ + Solution(ListNode* head) { + this->head = head; + this->len = 0; + for(ListNode*p = head; p!=NULL; p=p->next, len++); + srand(time(NULL)); + } + + /** Returns a random node's value. */ + int getRandom() { + int pos = rand() % len; + ListNode *p = head; + for (; pos > 0; pos--, p=p->next); + return p->val; + } + ListNode* head; + int len; +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(head); + * int param_1 = obj.getRandom(); + */ From 2c9f3c241bb3c28ad303cab164d7f438ebd8253c Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 25 Aug 2016 18:01:24 +0800 Subject: [PATCH 067/105] Two Problems Solutions - "Insert Delete GetRandom O(1)" --- README.md | 2 + .../InsertDeleteGetrandomO1.cpp | 98 +++++++++++++++++ ...sertDeleteGetrandomO1DuplicatesAllowed.cpp | 102 ++++++++++++++++++ 3 files changed, 202 insertions(+) create mode 100644 algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1.cpp create mode 100644 algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1DuplicatesAllowed.cpp diff --git a/README.md b/README.md index 41bce4906..4c74c0ea1 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,8 @@ LeetCode |384|[Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp)|Medium| |383|[Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./algorithms/cpp/ransomNote/RansomNote.cpp)|Easy| |382|[Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./algorithms/cpp/linkedListRandomNode/LinkedListRandomNode.cpp)|Medium| +|381|[Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1DuplicatesAllowed.cpp)|Hard| +|380|[Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1.cpp)|Hard| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| |376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| diff --git a/algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1.cpp b/algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1.cpp new file mode 100644 index 000000000..07a0bde1d --- /dev/null +++ b/algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1.cpp @@ -0,0 +1,98 @@ +// Source : https://leetcode.com/problems/insert-delete-getrandom-o1/ +// Author : Hao Chen +// Date : 2016-08-25 + +/*************************************************************************************** + * + * Design a data structure that supports all following operations in average O(1) time. + * + * insert(val): Inserts an item val to the set if not already present. + * remove(val): Removes an item val from the set if present. + * getRandom: Returns a random element from current set of elements. Each element must + * have the same probability of being returned. + * + * Example: + * + * // Init an empty set. + * RandomizedSet randomSet = new RandomizedSet(); + * + * // Inserts 1 to the set. Returns true as 1 was inserted successfully. + * randomSet.insert(1); + * + * // Returns false as 2 does not exist in the set. + * randomSet.remove(2); + * + * // Inserts 2 to the set, returns true. Set now contains [1,2]. + * randomSet.insert(2); + * + * // getRandom should return either 1 or 2 randomly. + * randomSet.getRandom(); + * + * // Removes 1 from the set, returns true. Set now contains [2]. + * randomSet.remove(1); + * + * // 2 was already in the set, so return false. + * randomSet.insert(2); + * + * // Since 1 is the only number in the set, getRandom always return 1. + * randomSet.getRandom(); + ***************************************************************************************/ + + +class RandomizedSet { +public: + /** Initialize your data structure here. */ + RandomizedSet() { + srand(time(NULL)); + } + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + bool insert(int val) { + if ( find(val) ) return false; + data.push_back(val); + valpos[val] = data.size() - 1; + return true; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + bool remove(int val) { + if ( !find(val) ) return false; + + /* + * Tricky + * ------ + * 1) Copy the data from the last one to the place need be removed. + * 2) Remove the last one. + */ + int _idx = valpos[val]; + int _val = data.back(); + + data[_idx] = _val; + valpos[_val] = _idx; + + valpos.erase(val); + data.pop_back(); + return true; + } + + /** Get a random element from the set. */ + int getRandom() { + return data[ rand() % data.size() ]; + } + +private: + unordered_map valpos; //value position map + vector data; + bool find(int val) { + return (valpos.find(val) != valpos.end()); + } + +}; + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet obj = new RandomizedSet(); + * bool param_1 = obj.insert(val); + * bool param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ diff --git a/algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1DuplicatesAllowed.cpp b/algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1DuplicatesAllowed.cpp new file mode 100644 index 000000000..3ae8de9b2 --- /dev/null +++ b/algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1DuplicatesAllowed.cpp @@ -0,0 +1,102 @@ +// Source : https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/ +// Author : Hao Chen +// Date : 2016-08-25 + +/*************************************************************************************** + * + * Design a data structure that supports all following operations in average O(1) time. + * Note: Duplicate elements are allowed. + * + * insert(val): Inserts an item val to the collection. + * remove(val): Removes an item val from the collection if present. + * getRandom: Returns a random element from current collection of elements. The + * probability of each element being returned is linearly related to the number of same + * value the collection contains. + * + * Example: + * + * // Init an empty collection. + * RandomizedCollection collection = new RandomizedCollection(); + * + * // Inserts 1 to the collection. Returns true as the collection did not contain 1. + * collection.insert(1); + * + * // Inserts another 1 to the collection. Returns false as the collection contained 1. + * Collection now contains [1,1]. + * collection.insert(1); + * + * // Inserts 2 to the collection, returns true. Collection now contains [1,1,2]. + * collection.insert(2); + * + * // getRandom should return 1 with the probability 2/3, and returns 2 with the + * probability 1/3. + * collection.getRandom(); + * + * // Removes 1 from the collection, returns true. Collection now contains [1,2]. + * collection.remove(1); + * + * // getRandom should return 1 and 2 both equally likely. + * collection.getRandom(); + ***************************************************************************************/ + +class RandomizedCollection { +public: + /** Initialize your data structure here. */ + RandomizedCollection() { + srand(time(NULL)); + } + + /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ + bool insert(int val) { + data.push_back(val); + valpos[val].insert( data.size() - 1 ); + return (valpos[val].size() == 1); + } + + /** Removes a value from the collection. Returns true if the collection contained the specified element. */ + bool remove(int val) { + // not found + if (!find(val)) return false; + + + //same idea with non-duplication version, but need be careful with some edge case + int _idx = *(valpos[val].begin()); + int _val = data.back(); + + valpos[_val].insert(_idx); + data[_idx] = _val; + + valpos[val].erase(_idx); + if (valpos[val].size()==0){ + valpos.erase(val); + } + + data.pop_back(); + if ( _idx < data.size() ){ + valpos[_val].erase(data.size()); + valpos[_val].insert(_idx); + } + + return true; + } + + /** Get a random element from the collection. */ + int getRandom() { + return data[ rand() % data.size() ]; + } +private: + unordered_map> valpos; //value position map + vector data; + bool find(int val) { + return (valpos.find(val) != valpos.end()); + } + +}; + +/** + * Your RandomizedCollection object will be instantiated and called as such: + * RandomizedCollection obj = new RandomizedCollection(); + * bool param_1 = obj.insert(val); + * bool param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ From 4eb48060d3ef468f9463b7a7e99729223fd37e1a Mon Sep 17 00:00:00 2001 From: huangxiaofei Date: Wed, 31 Aug 2016 10:47:51 +0800 Subject: [PATCH 068/105] =?UTF-8?q?=09modified:=20=20=20algorithms/cpp/max?= =?UTF-8?q?imumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp=20=09?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=20max=20=E5=87=BD=E6=95=B0=E4=BB=A5=E5=8F=8A?= =?UTF-8?q?=E9=80=92=E5=BD=92=20=E7=B2=BE=E7=AE=80=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/algorithms/cpp/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp b/algorithms/cpp/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp index e33d6020d..c80336281 100644 --- a/algorithms/cpp/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp +++ b/algorithms/cpp/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp @@ -40,3 +40,11 @@ class Solution { } }; + +class Solution2 { +public: + int maxDepth(TreeNode *root) { + if (root==NULL) return 0; + return max(maxDepth(root->left), maxDepth(root->right)) + 1; + } +}; From 7f16adf18c6957452ac840b0833483ce78bcd0bf Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 8 Sep 2016 01:11:56 +0800 Subject: [PATCH 069/105] add readme.sh script to help to generate the content in README.md for each problem --- scripts/README.md | 13 +++++++++++++ scripts/readme.sh | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100755 scripts/readme.sh diff --git a/scripts/README.md b/scripts/README.md index 6972133fa..6349e5f00 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -44,3 +44,16 @@ The comments would be generated by above examples as below: ``` + +### readme.sh + +`readme.sh` - it's used to generate the table item in README.md + +For example: + +``` +$ ./readme.sh ../algorithms/cpp/nextPermutation/nextPermutation.cpp +|31|[Next Permutation](https://oj.leetcode.com/problems/next-permutation/) | [C++](./algorithms/cpp/nextPermutation/nextPermutation.cpp)|Medium| +``` + + diff --git a/scripts/readme.sh b/scripts/readme.sh new file mode 100755 index 000000000..356c9613c --- /dev/null +++ b/scripts/readme.sh @@ -0,0 +1,33 @@ +#!/bin/bash + + +function usage() +{ + + echo -e "Usage: ${0} [file]" + echo -e "" + echo -e "Example:" + echo -e "" + echo -e " ${0} ./LargestNumber.cpp" + echo -e "" +} + + + +if [ $# -lt 1 ] || [[ ! -f ${1} ]]; then + usage + exit 255 +fi + +DIR=`cd $(dirname ${1}) && pwd -P` +FILE=${DIR}/$(basename ${1}) + +URL=`grep Source ${FILE} | awk '{print $4}'` +title_str=`xidel ${URL} -q -e "css('div.question-title h3')"` +NUM=`echo ${title_str} | awk -F '.' '{print $1}'` +TITLE=`echo ${title_str} | awk -F '.' '{print $2}' | sed -e 's/^[[:space:]]*//'` +DIFFCULT=`xidel ${URL} -q -e "css('.question-info')" | grep Difficulty | awk '{print $2}'` + +FILE=`echo ${FILE} | sed "s/.*\/algorithms/\.\/algorithms/"` + +echo "|${NUM}|[${TITLE}](${URL}) | [C++](${FILE})|${DIFFCULT}|" From 1714519c336cdd5d8e7a316a92a4d1423f468122 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 8 Sep 2016 01:15:02 +0800 Subject: [PATCH 070/105] New Problem Solution - "Find the Difference" --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 4c74c0ea1..6e67769b3 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./algorithms/cpp/findTheDifference/FindTheDifference.cpp)|Easy| |388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp)|Medium| |387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp)|Easy| |386|[Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp)|Medium| From a4b191a6451e1d02afc476c078f4c093e3895dde Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 8 Sep 2016 01:36:50 +0800 Subject: [PATCH 071/105] New Problem Solution "Elimination Game" --- README.md | 1 + .../cpp/eliminationGame/EliminationGame.cpp | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 algorithms/cpp/eliminationGame/EliminationGame.cpp diff --git a/README.md b/README.md index 6e67769b3..a4299d170 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|390|[Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium| |389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./algorithms/cpp/findTheDifference/FindTheDifference.cpp)|Easy| |388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp)|Medium| |387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp)|Easy| diff --git a/algorithms/cpp/eliminationGame/EliminationGame.cpp b/algorithms/cpp/eliminationGame/EliminationGame.cpp new file mode 100644 index 000000000..3ec31cccb --- /dev/null +++ b/algorithms/cpp/eliminationGame/EliminationGame.cpp @@ -0,0 +1,41 @@ +// Source : https://leetcode.com/contest/2/problems/elimination-game/ +// Author : Hao Chen +// Date : 2016-09-07- + +/********************************************************************************** + * + * There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other + * number afterward until you reach the end of the list. + * + * Repeat the previous step again, but this time from right to left, remove the right most number and every other number + * from the remaining numbers. + * + * We keep repeating the steps again, alternating left to right and right to left, until a single number remains. + * + * Find the last number that remains starting with a list of length n. + * + * Example: + * + * Input: + * n = 9, + * 1 2 3 4 5 6 7 8 9 + * 2 4 6 8 + * 2 6 + * 6 + * + * Output: + * 6 +**********************************************************************************/ + +class Solution { +public: + int lastRemaining(int n) { + int start = 1, step = 1; + while (n > 1) { + start += step + (n-2)/2 * 2*step; + n /= 2; + step *= -2; + } + return start; + } +}; From 626efee459e33278a094efe945a25e2fac9ae2eb Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 8 Sep 2016 01:39:42 +0800 Subject: [PATCH 072/105] New Problem Solution "Perfect Rectangle" --- README.md | 1 + .../cpp/perfectRectangle/PerfectRectangle.cpp | 80 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 algorithms/cpp/perfectRectangle/PerfectRectangle.cpp diff --git a/README.md b/README.md index a4299d170..a713f20fc 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./algorithms/cpp/perfectRectangle/PerfectRectangle.cpp)|Hard| |390|[Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium| |389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./algorithms/cpp/findTheDifference/FindTheDifference.cpp)|Easy| |388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp)|Medium| diff --git a/algorithms/cpp/perfectRectangle/PerfectRectangle.cpp b/algorithms/cpp/perfectRectangle/PerfectRectangle.cpp new file mode 100644 index 000000000..453020c6e --- /dev/null +++ b/algorithms/cpp/perfectRectangle/PerfectRectangle.cpp @@ -0,0 +1,80 @@ +// Source : https://leetcode.com/problems/perfect-rectangle/ +// Author : Hao Chen +// Date : 2016-09-08 + +/*************************************************************************************** + * + * Given N axis-aligned rectangles where N > 0, determine if they all together form an + * exact cover of a rectangular region. + * + * Each rectangle is represented as a bottom-left point and a top-right point. For + * example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point + * is (1, 1) and top-right point is (2, 2)). + * + * Example 1: + * + * rectangles = [ + * [1,1,3,3], + * [3,1,4,2], + * [3,2,4,4], + * [1,3,2,4], + * [2,3,3,4] + * ] + * + * Return true. All 5 rectangles together form an exact cover of a rectangular region. + * + * Example 2: + * + * rectangles = [ + * [1,1,2,3], + * [1,3,2,4], + * [3,1,4,2], + * [3,2,4,4] + * ] + * + * Return false. Because there is a gap between the two rectangular regions. + * + * Example 3: + * + * rectangles = [ + * [1,1,3,3], + * [3,1,4,2], + * [1,3,2,4], + * [3,2,4,4] + * ] + * + * Return false. Because there is a gap in the top center. + * + * Example 4: + * + * rectangles = [ + * [1,1,3,3], + * [3,1,4,2], + * [1,3,2,4], + * [2,2,4,4] + * ] + * + * Return false. Because two of the rectangles overlap with each other. + ***************************************************************************************/ + + +class Solution { +public: + bool isRectangleCover(vector>& rectangles) { + unordered_map mp; + string corners[4]; + for(auto v: rectangles) + for(int i = 0; i<4; ++i){ + corners[i] = to_string(v[i/2*2]) + "," + to_string(v[(i%2)*2+1]); + if(mp[corners[i]] & int(pow(2,i))) return false; + else mp[corners[i]] |= int(pow(2,i)); + } + int corner = 0; + for(auto i=mp.begin(); i!=mp.end(); ++i){ + int val = i->second; + if(!(val & (val-1)) && (++corner >4)) return false; + if((val & (val-1)) && !(val == 3 || val==12 || val==10 || val==5 || val==15)) return false; + } + return true; + } +}; From ea1a2130970c01484a69ce9cae3c436075c6e0ac Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 8 Sep 2016 01:42:00 +0800 Subject: [PATCH 073/105] New Problem "Is Subsequence" --- README.md | 1 + .../cpp/isSubsequence/IsSubsequence.cpp | 50 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 algorithms/cpp/isSubsequence/IsSubsequence.cpp diff --git a/README.md b/README.md index a713f20fc..245b5ca9d 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp)|Medium| |391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./algorithms/cpp/perfectRectangle/PerfectRectangle.cpp)|Hard| |390|[Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium| |389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./algorithms/cpp/findTheDifference/FindTheDifference.cpp)|Easy| diff --git a/algorithms/cpp/isSubsequence/IsSubsequence.cpp b/algorithms/cpp/isSubsequence/IsSubsequence.cpp new file mode 100644 index 000000000..e2cd88371 --- /dev/null +++ b/algorithms/cpp/isSubsequence/IsSubsequence.cpp @@ -0,0 +1,50 @@ +// Source : https://leetcode.com/problems/is-subsequence/ +// Author : Hao Chen +// Date : 2016-09-08 + +/*************************************************************************************** + * + * Given a string s and a string t, check if s is subsequence of t. + * + * You may assume that there is only lower case English letters in both s and t. t is + * potentially a very long (length ~= 500,000) string, and s is a short string ( + * + * A subsequence of a string is a new string which is formed from the original string + * by deleting some (can be none) of the characters without disturbing the relative + * positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while + * "aec" is not). + * + * Example 1: + * s = "abc", t = "ahbgdc" + * + * Return true. + * + * Example 2: + * s = "axc", t = "ahbgdc" + * + * Return false. + * + * Follow up: + * If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to + * check one by one to see if T has its subsequence. In this scenario, how would you + * change your code? + ***************************************************************************************/ + +class Solution { +public: + bool isSubsequence(string s, string t) { + if (s.size() <= 0) return true; + + int ps=0, pt=0; + while (pt < t.size()) { + if (s[ps] == t[pt]) { + ps++; pt++; + if (ps >= s.size()) return true; + }else { + pt++; + } + } + + return false; + } +}; From cfe88095df073fee7f44cf2b9a02cf294861dc58 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 8 Sep 2016 01:44:30 +0800 Subject: [PATCH 074/105] New Problem Solution "UTF-8 Validation" --- README.md | 1 + .../cpp/UTF8Validation/UTF8Validation.cpp | 86 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 algorithms/cpp/UTF8Validation/UTF8Validation.cpp diff --git a/README.md b/README.md index 245b5ca9d..f35d70e5f 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./algorithms/cpp/UTF8Validation/UTF8Validation.cpp)|Medium| |392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp)|Medium| |391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./algorithms/cpp/perfectRectangle/PerfectRectangle.cpp)|Hard| |390|[Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium| diff --git a/algorithms/cpp/UTF8Validation/UTF8Validation.cpp b/algorithms/cpp/UTF8Validation/UTF8Validation.cpp new file mode 100644 index 000000000..619b8ab63 --- /dev/null +++ b/algorithms/cpp/UTF8Validation/UTF8Validation.cpp @@ -0,0 +1,86 @@ +// Source : https://leetcode.com/problems/utf-8-validation/ +// Author : Hao Chen +// Date : 2016-09-08 + +/*************************************************************************************** + * + * A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: + * + * For 1-byte character, the first bit is a 0, followed by its unicode code. + * For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by + * n-1 bytes with most significant 2 bits being 10. + * + * This is how the UTF-8 encoding would work: + * + * Char. number range | UTF-8 octet sequence + * --------------------+--------------------------------------------- + * 0000 0000-0000 007F | 0xxxxxxx + * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + * + * Given an array of integers representing the data, return whether it is a valid utf-8 + * encoding. + * + * Note: + * The input is an array of integers. Only the least significant 8 bits of each integer + * is used to store the data. This means each integer represents only 1 byte of data. + * + * Example 1: + * + * data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 + * 00000001. + * + * Return true. + * It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. + * + * Example 2: + * + * data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 + * 00000100. + * + * Return false. + * The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. + * The next byte is a continuation byte which starts with 10 and that's correct. + * But the second continuation byte does not start with 10, so it is invalid. + ***************************************************************************************/ + + +class Solution { +public: + bool validUtf8(vector& data) { + int i = 0; + while ( i < data.size() ) { + if ( (data[i] & 0x80) == 0 ){ + i++; + continue; + } + + int len = 0; + if ( (data[i] & 0xE0) == 0xC0 ) { // checking 110xxxxx + len = 2; + }else if ( (data[i] & 0xF0) == 0xE0) { // checking 1110xxxx + len = 3; + }else if ( (data[i] & 0xF8) == 0xF0) { // checking 11110xxx + len = 4; + }else { + return false; + } + + + for (int j=i+1; j < i+len; j++) { //checking 10xxxxxx + if ( (data[j] & 0xC0) != 0x80 ) { + return false; + } + } + + i += len ; + + if (i > data.size()) { + return false; + } + + } + return true; + } +}; From 2f3a77de45a6addf7aae3fb6988e8422a7a3eb6c Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 8 Sep 2016 01:48:16 +0800 Subject: [PATCH 075/105] New Problem Solution"Longest Substring with At Least K Repeating Characters" --- README.md | 2 + algorithms/cpp/decodeString/DecodeString.cpp | 105 +++++++++++++++++ ...bstringWithAtLeastKRepeatingCharacters.cpp | 109 ++++++++++++++++++ 3 files changed, 216 insertions(+) create mode 100644 algorithms/cpp/decodeString/DecodeString.cpp create mode 100644 algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp diff --git a/README.md b/README.md index f35d70e5f..2e477c439 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|395|[Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp)|Medium| +|394|[Decode String](https://leetcode.com/problems/decode-string/) | [C++](./algorithms/cpp/decodeString/DecodeString.cpp)|Medium| |393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./algorithms/cpp/UTF8Validation/UTF8Validation.cpp)|Medium| |392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp)|Medium| |391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./algorithms/cpp/perfectRectangle/PerfectRectangle.cpp)|Hard| diff --git a/algorithms/cpp/decodeString/DecodeString.cpp b/algorithms/cpp/decodeString/DecodeString.cpp new file mode 100644 index 000000000..677818981 --- /dev/null +++ b/algorithms/cpp/decodeString/DecodeString.cpp @@ -0,0 +1,105 @@ +// Source : https://leetcode.com/problems/decode-string/ +// Author : Hao Chen +// Date : 2016-09-08 + +/*************************************************************************************** + * + * Given an encoded string, return it's decoded string. + * + * The encoding rule is: k[encoded_string], where the encoded_string inside the square + * brackets is being repeated exactly k times. Note that k is guaranteed to be a + * positive integer. + * + * You may assume that the input string is always valid; No extra white spaces, square + * brackets are well-formed, etc. + * + * Furthermore, you may assume that the original data does not contain any digits and + * that digits are only for those repeat numbers, k. For example, there won't be input + * like 3a or 2[4]. + * + * Examples: + * + * s = "3[a]2[bc]", return "aaabcbc". + * s = "3[a2[c]]", return "accaccacc". + * s = "2[abc]3[cd]ef", return "abcabccdcdcdef". + ***************************************************************************************/ + +class Solution { +public: + string decodeString(string s) { + if (!isValid(s)) return ""; + + stack _stack; + stack _nstack; + + string result; + string tmp; + int n=0; + for (int i=0; i0; n--) { + tmp += _stack.top(); + } + _stack.pop(); + _nstack.pop(); + if ( ! _stack.empty() ) { + _stack.top() += tmp; + }else { + result += tmp; + } + } else { + if ( ! _stack.empty() ) { + _stack.top() += s[i]; + } else { + result += s[i]; + } + + } + } + + return result; + } + +private: + + //only check the following rules: + // 1) the number must be followed by '[' + // 2) the '[' and ']' must be matched. + bool isValid(string& s) { + stack _stack; + for (int i=0; i='0' && ch<='9'); + } +}; + diff --git a/algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp b/algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp new file mode 100644 index 000000000..59c8c4f32 --- /dev/null +++ b/algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp @@ -0,0 +1,109 @@ +// Source : https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ +// Author : Hao Chen +// Date : 2016-09-08 + +/*************************************************************************************** + * + * Find the length of the longest substring T of a given string (consists of lowercase + * letters only) such that every character in T appears no less than k times. + * + * Example 1: + * + * Input: + * s = "aaabb", k = 3 + * + * Output: + * 3 + * + * The longest substring is "aaa", as 'a' is repeated 3 times. + * + * Example 2: + * + * Input: + * s = "ababbc", k = 2 + * + * Output: + * 5 + * + * The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 + * times. + ***************************************************************************************/ + +const int NO_OF_CHARS = 256; + +/* if every character appears at least k times, the whole string is ok. + * Otherwise split by a least frequent character. + * + * Because it will always be too infrequent and thus can't be part of any ok substring + * and make the most out of the splits. + */ + + +class Solution { +public: + int longestSubstring(string s, int k) { + + //deal with edge cases + if (s.size() == 0 || s.size() < k) return 0; + if (k==1) return s.size(); + + //declare a map for every char's counter + int count[NO_OF_CHARS]; + memset(count , 0, sizeof(count)); + + //counting every char + for (char ch : s) { + count[ch]++; + } + + int i=0; + for ( i=0; i= NO_OF_CHARS ) return s.size(); + + // find the most infrequent char + char least = 0; + for (int c = 0; c < NO_OF_CHARS; c++) { + if (count[c] == 0) continue; + if (least == 0) { + least = c; + } else if ( count[c] < count[least]) { + least = c; + } + } + + //split the string and run them recursively + vector subs; + split(s, least, subs); + + int res = 0; + for (string str: subs) { + res = max(res, longestSubstring(str, k)); + } + return res; + return 0; + } + +private: + + inline int max(int x, int y) { return x>y? x:y; } + + inline void split(const string &s, char delim, vector &elems) { + stringstream ss; + ss.str(s); + string item; + while (getline(ss, item, delim)) { + cout << item << endl; + elems.push_back(item); + } + } + + + inline vector split(const string &s, char delim) { + vector elems; + split(s, delim, elems); + return elems; + } +}; From 2d433dd8ddf22e4235cbdea3517f03be7dfd382e Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Wed, 2 Nov 2016 23:35:39 +0800 Subject: [PATCH 076/105] correct the URL of "Elimination Game" --- README.md | 2 +- algorithms/cpp/eliminationGame/EliminationGame.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2e477c439..cca69ca28 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ LeetCode |393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./algorithms/cpp/UTF8Validation/UTF8Validation.cpp)|Medium| |392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp)|Medium| |391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./algorithms/cpp/perfectRectangle/PerfectRectangle.cpp)|Hard| -|390|[Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium| +|390|[Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium| |389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./algorithms/cpp/findTheDifference/FindTheDifference.cpp)|Easy| |388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp)|Medium| |387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp)|Easy| diff --git a/algorithms/cpp/eliminationGame/EliminationGame.cpp b/algorithms/cpp/eliminationGame/EliminationGame.cpp index 3ec31cccb..386c985fd 100644 --- a/algorithms/cpp/eliminationGame/EliminationGame.cpp +++ b/algorithms/cpp/eliminationGame/EliminationGame.cpp @@ -1,4 +1,4 @@ -// Source : https://leetcode.com/contest/2/problems/elimination-game/ +// Source : https://leetcode.com/problems/elimination-game // Author : Hao Chen // Date : 2016-09-07- From 421189eaa41682111e5295b0ff877b07c8eeac5f Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 3 Nov 2016 00:21:41 +0800 Subject: [PATCH 077/105] New Problem Solution "Rotate Function" --- README.md | 1 + .../cpp/rotateFunction/RotateFunction.cpp | 75 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 algorithms/cpp/rotateFunction/RotateFunction.cpp diff --git a/README.md b/README.md index cca69ca28..17b4791e9 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|396|[Rotate Function](https://leetcode.com/problems/rotate-function/) | [C++](./algorithms/cpp/rotateFunction/RotateFunction.cpp)|Easy| |395|[Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp)|Medium| |394|[Decode String](https://leetcode.com/problems/decode-string/) | [C++](./algorithms/cpp/decodeString/DecodeString.cpp)|Medium| |393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./algorithms/cpp/UTF8Validation/UTF8Validation.cpp)|Medium| diff --git a/algorithms/cpp/rotateFunction/RotateFunction.cpp b/algorithms/cpp/rotateFunction/RotateFunction.cpp new file mode 100644 index 000000000..c8897dd27 --- /dev/null +++ b/algorithms/cpp/rotateFunction/RotateFunction.cpp @@ -0,0 +1,75 @@ +// Source : https://leetcode.com/problems/rotate-function/ +// Author : Hao Chen +// Date : 2016-11-03 + +/*************************************************************************************** + * + * Given an array of integers A and let n to be its length. + * + * Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we + * define a "rotation function" F on A as follow: + * + * F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]. + * + * Calculate the maximum value of F(0), F(1), ..., F(n-1). + * + * Note: + * n is guaranteed to be less than 105. + * + * Example: + * + * A = [4, 3, 2, 6] + * + * F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 + * F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 + * F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 + * F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 + * + * So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. + ***************************************************************************************/ + + +// +// Asumming we have 4 numbers: a, b, c, d, then +// F(0) = 0a + 1b + 2c + 3d +// F(1) = 3a + 0b + 1c + 2d +// F(2) = 2a + 3b + 0c + 1d +// F(3) = 1a + 2b + 3c + 0d +// +// We can see how F(n) transfrom to F(n+1) +// F(0) - F(1) = -3a + b + c + d +// F(1) - F(2) = a + -3b + c + d +// F(2) - F(3) = a + b + -3c + d +// F(3) - F(0) = a + b + c + -3d +// +// So, we can tansfrom to the following experssion: +// +// F(1) = F(0) - (a+b+c+d) + 4a +// F(2) = F[1] - (a+b+c+d) + 4b +// F(3) = F[2] - (a+b+c+d) + 4c +// +// Then, we can see this fomular: +// +// F(n) = F(n-1) - sum(array) + len(array) * array[n-1] +// +class Solution { +public: + int maxRotateFunction(vector& A) { + int sum = 0; + int F = 0; + for (int i=0; i < A.size(); i++) { + sum += A[i]; + F += (i * A[i]); + } + int maxF = F; + int len = A.size(); + //cout << "F(0) = " << maxF < 4 -> 2 -> 1 + * + * Example 2: + * + * Input: + * 7 + * + * Output: + * 4 + * + * Explanation: + * 7 -> 8 -> 4 -> 2 -> 1 + * or + * 7 -> 6 -> 3 -> 2 -> 1 + ***************************************************************************************/ + +class Solution { +public: + + + int integerReplacement_recursion(int n) { + if ( n <= 1) return 0; // recursive exited point + if ( n == INT_MAX ) return 32; // special case to avoid integer overflow. + if ( n % 2 == 0 ) return integerReplacement(n/2) + 1; + return min( integerReplacement(n+1), integerReplacement(n-1) ) + 1; + } + + int integerReplacement_recursionWithCache(int n) { + static unordered_map cache; + //if hitted the cache, just return the result + if (cache.find(n) != cache.end()) return cache[n]; + + int result; + if ( n <= 1) return 0; // recursive exited point + if ( n == INT_MAX ) return 32; // special case to avoid integer overflow. + if ( n % 2 == 0 ) result = integerReplacement(n/2) + 1; + else result = min( integerReplacement(n+1), integerReplacement(n-1) ) + 1; + + //add into cache + cache[n] = result; + return result; + } + + int integerReplacement(int n) { + return integerReplacement_recursionWithCache(n); + } +}; From 51a06242815f98fd443869ac9b909d1d1797d1ba Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 4 Nov 2016 08:36:43 +0800 Subject: [PATCH 079/105] New Problem Solution "Random Pick Index" --- README.md | 1 + .../cpp/randomPickIndex/RandomPickIndex.cpp | 54 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 algorithms/cpp/randomPickIndex/RandomPickIndex.cpp diff --git a/README.md b/README.md index 35eb1acb7..dd68c3dc4 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|398|[Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./algorithms/cpp/randomPickIndex/RandomPickIndex.cpp)|Medium| |397|[Integer Replacement](https://leetcode.com/problems/integer-replacement/) | [C++](./algorithms/cpp/integerReplacement/IntegerReplacement.cpp)|Medium| |396|[Rotate Function](https://leetcode.com/problems/rotate-function/) | [C++](./algorithms/cpp/rotateFunction/RotateFunction.cpp)|Easy| |395|[Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp)|Medium| diff --git a/algorithms/cpp/randomPickIndex/RandomPickIndex.cpp b/algorithms/cpp/randomPickIndex/RandomPickIndex.cpp new file mode 100644 index 000000000..f06f43ab3 --- /dev/null +++ b/algorithms/cpp/randomPickIndex/RandomPickIndex.cpp @@ -0,0 +1,54 @@ +// Source : https://leetcode.com/problems/random-pick-index/ +// Author : Hao Chen +// Date : 2016-11-04 + +/*************************************************************************************** + * + * Given an array of integers with possible duplicates, randomly output the index of a + * given target number. You can assume that the given target number must exist in the + * array. + * + * Note: + * The array size can be very large. Solution that uses too much extra space will not + * pass the judge. + * + * Example: + * + * int[] nums = new int[] {1,2,3,3,3}; + * Solution solution = new Solution(nums); + * + * // pick(3) should return either index 2, 3, or 4 randomly. Each index should have + * equal probability of returning. + * solution.pick(3); + * + * // pick(1) should return 0. Since in the array only nums[0] is equal to 1. + * solution.pick(1); + ***************************************************************************************/ + +class Solution { +private: + vector nums; +public: + Solution(vector nums) { + srand(time(0)); + this->nums = nums; + } + + int pick(int target) { + // we just randomly pick a number from the array, + // if the number is target just return the index. + // otherwise, keep picking the number randomly. + while(true) { + int idx = rand() % nums.size(); + if ( target == nums[idx] ) { + return idx; + } + } + } +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(nums); + * int param_1 = obj.pick(target); + */ From f9e16a7fa7e362dfc4b0721a59625a4cc2dbe5ca Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 5 Nov 2016 00:51:36 +0800 Subject: [PATCH 080/105] New Problem Solution "Evaluate Division" --- README.md | 1 + .../cpp/evaluateDivision/EvaluateDivision.cpp | 93 +++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 algorithms/cpp/evaluateDivision/EvaluateDivision.cpp diff --git a/README.md b/README.md index dd68c3dc4..78eecabf2 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|399|[Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./algorithms/cpp/evaluateDivision/EvaluateDivision.cpp)|Medium| |398|[Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./algorithms/cpp/randomPickIndex/RandomPickIndex.cpp)|Medium| |397|[Integer Replacement](https://leetcode.com/problems/integer-replacement/) | [C++](./algorithms/cpp/integerReplacement/IntegerReplacement.cpp)|Medium| |396|[Rotate Function](https://leetcode.com/problems/rotate-function/) | [C++](./algorithms/cpp/rotateFunction/RotateFunction.cpp)|Easy| diff --git a/algorithms/cpp/evaluateDivision/EvaluateDivision.cpp b/algorithms/cpp/evaluateDivision/EvaluateDivision.cpp new file mode 100644 index 000000000..bd6d06ba8 --- /dev/null +++ b/algorithms/cpp/evaluateDivision/EvaluateDivision.cpp @@ -0,0 +1,93 @@ +// Source : https://leetcode.com/problems/evaluate-division/ +// Author : Hao Chen +// Date : 2016-11-05 + +/*************************************************************************************** + * + * Equations are given in the format A / B = k, where A and B are variables + * represented as strings, and k is a real number (floating point number). Given some + * queries, return the answers. If the answer does not exist, return -1.0. + * + * Example: + * Given a / b = 2.0, b / c = 3.0. queries are: a / c = ?, b / a = ?, a / e = ?, a + * / a = ?, x / x = ? . return [6.0, 0.5, -1.0, 1.0, -1.0 ]. + * + * The input is: vector> equations, vector& values, + * vector> queries , where equations.size() == values.size(), and + * the values are positive. This represents the equations. Return vector. + * + * According to the example above: + * equations = [ ["a", "b"], ["b", "c"] ], + * values = [2.0, 3.0], + * queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. + * + * The input is always valid. You may assume that evaluating the queries will result in + * no division by zero and there is no contradiction. + ***************************************************************************************/ + +class Solution { +private: + bool dfs( unordered_map>& m, + unordered_map& visited, + string& start, string& end, double& res ) { + + if ( m.find(start) == m.end() || m.find(end) == m.end() ) return false; + if ( start == end ) return true; + + for (auto it = m[start].begin(); it != m[start].end(); ++it) { + + auto key = it->first; + auto value = it->second; + + // already visited, skip it. + if (visited.find(key) != visited.end() ) { + continue; + } + + visited[key] = true; + double old = res; + res *= value; + + if (dfs(m, visited, key, end, res)) { + return true; + } + //didn't find the result, reset the current result, and go to next one + res = old; + visited.erase(key); + } + + return false; + } +public: + vector calcEquation(vector> equations, + vector& values, + vector> queries) { + + unordered_map> m; + for(int i=0; i result; + for(auto q : queries) { + string start = q.first; + string end = q.second; + + unordered_map visited; + visited[start] = true; + double res = 1.0; + + if(dfs(m, visited, start, end, res)) { + result.push_back(res); + } else { + result.push_back(-1.0); + } + } + + return result; + } +}; From fa4d3f6424d403a3e798d475ff326ffdec90a615 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 5 Nov 2016 14:57:57 +0800 Subject: [PATCH 081/105] New Problem Solution "Nth Digit" --- README.md | 1 + algorithms/cpp/nthDigit/NthDigit.cpp | 99 ++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 algorithms/cpp/nthDigit/NthDigit.cpp diff --git a/README.md b/README.md index 78eecabf2..eb3488d53 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|400|[Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./algorithms/cpp/nthDigit/NthDigit.cpp)|Easy| |399|[Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./algorithms/cpp/evaluateDivision/EvaluateDivision.cpp)|Medium| |398|[Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./algorithms/cpp/randomPickIndex/RandomPickIndex.cpp)|Medium| |397|[Integer Replacement](https://leetcode.com/problems/integer-replacement/) | [C++](./algorithms/cpp/integerReplacement/IntegerReplacement.cpp)|Medium| diff --git a/algorithms/cpp/nthDigit/NthDigit.cpp b/algorithms/cpp/nthDigit/NthDigit.cpp new file mode 100644 index 000000000..1351f2a84 --- /dev/null +++ b/algorithms/cpp/nthDigit/NthDigit.cpp @@ -0,0 +1,99 @@ +// Source : https://leetcode.com/problems/nth-digit/ +// Author : Hao Chen +// Date : 2016-11-05 + +/*************************************************************************************** + * + * Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + * 11, ... + * + * Note: + * n is positive and will fit within the range of a 32-bit signed integer (n 31). + * + * Example 1: + * + * Input: + * 3 + * + * Output: + * 3 + * + * Example 2: + * + * Input: + * 11 + * + * Output: + * 0 + * + * Explanation: + * The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which + * is part of the number 10. + ***************************************************************************************/ + + +#include +using namespace std; + +class Solution { +public: + int findNthDigit(int n) { + + // We can see the following pattern: + // + // 1, 2, .... 9 : there are 9 * 1 digits. + // 10, 11, ..., 99: there are 90 * 2 digits. + // 101, 102, 103, ..., 999: there are 900 * 3. + // ... + + + //we can count the digits with the above pattern + long digits_cnt = 0; + long digits_cnt_prev = 0; + int base = 0; + for ( ; digits_cnt < n; base++) { + digits_cnt_prev = digits_cnt; + digits_cnt = digits_cnt + 9 * pow(10 , base) * ( base + 1 ); + } + + + // Now, we got `digits_cnt_prev`, `digits_cnt` and `base` + // + // For examples: + // n = 20; digits_cnt_prev = 9, digits_cnt = 9+90*2 = 189, base = 2; + // n = 500; digits_cnt_prev = 9+90*2 = 189, digits_cnt = 9+90*2+900*3 = 2889, base = 3; + // n = 2000; digits_cnt_prev = 9+90*2 = 189, digits_cnt = 9+90*2+900*3 = 2889, base = 3; + // + // It means, we found the range where the number it is + // n = 20, the number located in the range 10 -- 99 + // n = 500, the number located in the range 100 - 999 + // + // and we can use `digits_cnt_prev` to know the previous rangs produce how many digits. + // n = 20, the previous ranges produce 9 digits, so there needs 20-9 = 11 digits in [10 - 99] + // n = 500, the previous ranges produce 189 digits, so there needs 500-189 = 311 digits in [100-999] + // + // the `base` told us in current ranges, each number can have how many digits. + // then we can locate the target number. + // n = 20, + // (n - digits_cnt_prev) / base = (20 - 9 ) / 2 = 5, so, [10 - 14] produces 10 digits (ZERO-based), + // now, we have 1 digits left, it is the first digit of the target number 15. + // + // n = 500, + // (n - digits_cnt_prev) / base = (500 - 189) / 3 = 103, so, [100 - 202] produces 309 digits(ZERO-based). + // now, we have (500 - 189 - 309) = 2 digits left, it is the second digit of the target number 203. + // + // We can write the code now... + // + int target = pow(10, base-1) + (n - digits_cnt_prev) / base - 1; + int left = n - digits_cnt_prev - (n - digits_cnt_prev) / base * base; + + //cout << "target = " << target << ", left = " << left << endl; + + //no digits left + if ( left == 0 ) return (target) % 10; + + //still have some digits left, it should be in next number. + target++; + return int( target / pow(10, base - left) ) % 10; + } +}; From 4285701161157918ec90e1842edf275d0c7470cb Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 5 Nov 2016 22:23:05 +0800 Subject: [PATCH 082/105] New Problem Solution "Binary Watch" --- README.md | 1 + algorithms/cpp/binaryWatch/BinaryWatch.cpp | 111 +++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 algorithms/cpp/binaryWatch/BinaryWatch.cpp diff --git a/README.md b/README.md index eb3488d53..38d910633 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|401|[Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./algorithms/cpp/binaryWatch/BinaryWatch.cpp)|Easy| |400|[Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./algorithms/cpp/nthDigit/NthDigit.cpp)|Easy| |399|[Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./algorithms/cpp/evaluateDivision/EvaluateDivision.cpp)|Medium| |398|[Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./algorithms/cpp/randomPickIndex/RandomPickIndex.cpp)|Medium| diff --git a/algorithms/cpp/binaryWatch/BinaryWatch.cpp b/algorithms/cpp/binaryWatch/BinaryWatch.cpp new file mode 100644 index 000000000..14fce05c3 --- /dev/null +++ b/algorithms/cpp/binaryWatch/BinaryWatch.cpp @@ -0,0 +1,111 @@ +// Source : https://leetcode.com/problems/binary-watch/ +// Author : Hao Chen +// Date : 2016-11-05 + +/*************************************************************************************** + * + * A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 + * LEDs on the bottom represent the minutes (0-59). + * Each LED represents a zero or one, with the least significant bit on the right. + * + * For example, the above binary watch reads "3:25". + * + * Given a non-negative integer n which represents the number of LEDs that are + * currently on, return all possible times the watch could represent. + * + * Example: + * Input: n = 1Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", + * "0:16", "0:32"] + * + * Note: + * + * The order of output does not matter. + * The hour must not contain a leading zero, for example "01:00" is not valid, it + * should be "1:00". + * The minute must be consist of two digits and may contain a leading zero, for example + * "10:2" is not valid, it should be "10:02". + ***************************************************************************************/ + +class Solution { +private: + void combination(int len, int n, int max, bool zero, + int start, int k, int solution, + vector>& result) { + if (solution > max){ + return; + } + if (k == 0) { + char tmp[5] = ""; + if (zero) { + sprintf(tmp, "%02d", solution); + }else{ + sprintf(tmp, "%d", solution); + } + result[n].push_back(tmp); + return; + } + for (int i=start; i<=len-k; i++) { + solution += pow(2, i); + combination(len, n, max, zero, i+1, k-1, solution, result); + solution -= pow(2, i); + } + } + + void generate_combination(int nLED, int max, bool zero, vector>& result) { + for (int i=0; i>& vv) { + for(auto v : vv) { + cout << "[ "; + for (auto i : v) { + cout << i << " "; + } + cout << "]" << endl; + } + } + +private: + vector> hour; + vector> mins; + +public: + + Solution():hour(4, vector()), mins(6, vector()){ + generate_combination(4, 11, false, hour); + //print(hour); + //[ 0 ] + //[ 1 2 4 8 ] + //[ 3 5 9 6 10 ] + //[ 7 11 ] + + + generate_combination(6, 59, true, mins); + //print(mins); + //[ 00 ] + //[ 01 02 04 08 16 32 ] + //[ 03 05 09 17 33 06 10 18 34 12 20 36 24 40 48 ] + //[ 07 11 19 35 13 21 37 25 41 49 14 22 38 26 42 50 28 44 52 56 ] + //[ 15 23 39 27 43 51 29 45 53 57 30 46 54 58 ] + //[ 31 47 55 59 ] + } + + vector readBinaryWatch(int num) { + + vector result; + for (int i = 0; i <= 3 && i <= num; i++) { + if (num - i > 5) { + continue; + } + for (auto h : hour[i]) { + for (auto m : mins[num - i]) { + result.push_back( h + ":" + m ); + } + } + + } + return result; + } +}; From fff0041eae96ddec8619f7a4f3c2a27c0e73005c Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 5 Nov 2016 22:31:23 +0800 Subject: [PATCH 083/105] make the variables name more sense --- algorithms/cpp/binaryWatch/BinaryWatch.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/algorithms/cpp/binaryWatch/BinaryWatch.cpp b/algorithms/cpp/binaryWatch/BinaryWatch.cpp index 14fce05c3..26c59425c 100644 --- a/algorithms/cpp/binaryWatch/BinaryWatch.cpp +++ b/algorithms/cpp/binaryWatch/BinaryWatch.cpp @@ -28,7 +28,7 @@ class Solution { private: - void combination(int len, int n, int max, bool zero, + void combination(int nLED, int nLight, int max, bool zero, int start, int k, int solution, vector>& result) { if (solution > max){ @@ -41,12 +41,12 @@ class Solution { }else{ sprintf(tmp, "%d", solution); } - result[n].push_back(tmp); + result[nLight].push_back(tmp); return; } - for (int i=start; i<=len-k; i++) { + for (int i=start; i<=nLED-k; i++) { solution += pow(2, i); - combination(len, n, max, zero, i+1, k-1, solution, result); + combination(nLED, nLight, max, zero, i+1, k-1, solution, result); solution -= pow(2, i); } } From a991e748671c06ff395873133eda01fd2affe945 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 11 Nov 2016 23:54:58 +0800 Subject: [PATCH 084/105] New Problem Solution - "Remove K Digits" --- README.md | 1 + .../cpp/removeKDigits/RemoveKDigits.cpp | 107 ++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 algorithms/cpp/removeKDigits/RemoveKDigits.cpp diff --git a/README.md b/README.md index 38d910633..60796f490 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|402|[Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./algorithms/cpp/removeKDigits/RemoveKDigits.cpp)|Medium| |401|[Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./algorithms/cpp/binaryWatch/BinaryWatch.cpp)|Easy| |400|[Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./algorithms/cpp/nthDigit/NthDigit.cpp)|Easy| |399|[Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./algorithms/cpp/evaluateDivision/EvaluateDivision.cpp)|Medium| diff --git a/algorithms/cpp/removeKDigits/RemoveKDigits.cpp b/algorithms/cpp/removeKDigits/RemoveKDigits.cpp new file mode 100644 index 000000000..9b33cf5c4 --- /dev/null +++ b/algorithms/cpp/removeKDigits/RemoveKDigits.cpp @@ -0,0 +1,107 @@ +// Source : https://leetcode.com/problems/remove-k-digits/ +// Author : Hao Chen +// Date : 2016-11-11 + +/*************************************************************************************** + * + * Given a non-negative integer num represented as a string, remove k digits from the + * number so that the new number is the smallest possible. + * + * Note: + * + * The length of num is less than 10002 and will be ≥ k. + * The given num does not contain any leading zero. + * + * Example 1: + * + * Input: num = "1432219", k = 3 + * Output: "1219" + * Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which + * is the smallest. + * + * Example 2: + * + * Input: num = "10200", k = 1 + * Output: "200" + * Explanation: Remove the leading 1 and the number is 200. Note that the output must + * not contain leading zeroes. + * + * Example 3: + * + * Input: num = "10", k = 2 + * Output: "0" + * Explanation: Remove all the digits from the number and it is left with nothing which + * is 0. + ***************************************************************************************/ + +class Solution { +public: + string removeKdigits_pick(string& num, int k) { + + int len = num.size(); + string result; + + int idx = 0; + for (int i=0; i < len - k; i++) { + int min_idx = idx; + for (int j=min_idx; j<=i+k; j++) { + if (num[min_idx] > num[j]) min_idx = j; + } + + //don't put zero at the beginning + if ( !(result.empty() && num[min_idx]=='0') ){ + result.push_back(num[min_idx]); + } + + //select the number started from next one, to make the order correctness. + idx = min_idx + 1; + } + + if (result.empty()) result = "0"; + return result; + } + + string removeKdigits_remove(string& num, int k) { + if ( num.size() <= k ) return "0"; + int left_len = num.size() - k; + int idx = 0; + for (int i=0; i num[j+1] ) { + num.erase(j, 1); + idx = j; + break; + } + } + } + + //remove all of ZEROs at the beginning. + for (int i=0; i<= num.size(); i++) { + if (num[i] != '0' || i == num.size()) { + num.erase(0, i); + break; + } + } + + // if the digits in the array are sorted, + // then, we need remove the digits at the ends. + if (num.size() > left_len ) { + num.erase(num.begin() + left_len, num.end()); + } + + if (num.empty()) num = "0"; + return num; + } + + string removeKdigits(string num, int k) { + srand(time(0)); + if (rand() % 2 ) { + return removeKdigits_pick(num, k); + } else { + return removeKdigits_remove(num, k); + } + } +}; From 24839cef7046bd94e519ad8f6a080f35cdecc433 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 12 Nov 2016 00:17:28 +0800 Subject: [PATCH 085/105] New Problem Solution "Sum of Left Leaves" --- README.md | 1 + .../sumOfLeftLeaves/SumOfLeftLeaves.cpp | 71 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 algorithms/cpp/removeKDigits/sumOfLeftLeaves/SumOfLeftLeaves.cpp diff --git a/README.md b/README.md index 60796f490..2e63a75ac 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/removeKDigits/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| |402|[Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./algorithms/cpp/removeKDigits/RemoveKDigits.cpp)|Medium| |401|[Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./algorithms/cpp/binaryWatch/BinaryWatch.cpp)|Easy| |400|[Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./algorithms/cpp/nthDigit/NthDigit.cpp)|Easy| diff --git a/algorithms/cpp/removeKDigits/sumOfLeftLeaves/SumOfLeftLeaves.cpp b/algorithms/cpp/removeKDigits/sumOfLeftLeaves/SumOfLeftLeaves.cpp new file mode 100644 index 000000000..3db0ad26c --- /dev/null +++ b/algorithms/cpp/removeKDigits/sumOfLeftLeaves/SumOfLeftLeaves.cpp @@ -0,0 +1,71 @@ +// Source : https://leetcode.com/problems/sum-of-left-leaves/ +// Author : Hao Chen +// Date : 2016-11-12 + +/*************************************************************************************** + * + * Find the sum of all left leaves in a given binary tree. + * + * Example: + * + * 3 + * / \ + * 9 20 + * / \ + * 15 7 + * + * There are two left leaves in the binary tree, with values 9 and 15 respectively. + * Return 24. + ***************************************************************************************/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + + + void sumOfLeftLeaves_recursion_v1(TreeNode* root, int& result) { + if (root == NULL ) { + return; + } + + if (root->left && root->left->left == NULL && root->left->right == NULL) { + result += root->left->val; + } + sumOfLeftLeaves_recursion_v1(root->left, result); + sumOfLeftLeaves_recursion_v1(root->right, result); + + } + + int sumOfLeftLeaves_recursion_v2(TreeNode* root) { + if (root == NULL ) { + return 0; + } + int result = 0; + if (root->left && root->left->left == NULL && root->left->right == NULL) { + result = root->left->val; + } + result += sumOfLeftLeaves_recursion_v2(root->left) + sumOfLeftLeaves_recursion_v2(root->right); + return result; + } + + + int sumOfLeftLeaves(TreeNode* root) { + srand(time(NULL)); + if (rand()%2) { + int result = 0; + sumOfLeftLeaves_recursion_v1(root, result); + return result; + } else { + return sumOfLeftLeaves_recursion_v2(root); + } + + } +}; From 51e3e7ff5d8e51e37e460a5d8656cb1e071637bb Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 12 Nov 2016 00:31:03 +0800 Subject: [PATCH 086/105] fix: change the direcotry --- README.md | 2 +- .../cpp/{removeKDigits => }/sumOfLeftLeaves/SumOfLeftLeaves.cpp | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename algorithms/cpp/{removeKDigits => }/sumOfLeftLeaves/SumOfLeftLeaves.cpp (100%) diff --git a/README.md b/README.md index 2e63a75ac..36e9af9fa 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | -|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/removeKDigits/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| +|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| |402|[Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./algorithms/cpp/removeKDigits/RemoveKDigits.cpp)|Medium| |401|[Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./algorithms/cpp/binaryWatch/BinaryWatch.cpp)|Easy| |400|[Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./algorithms/cpp/nthDigit/NthDigit.cpp)|Easy| diff --git a/algorithms/cpp/removeKDigits/sumOfLeftLeaves/SumOfLeftLeaves.cpp b/algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp similarity index 100% rename from algorithms/cpp/removeKDigits/sumOfLeftLeaves/SumOfLeftLeaves.cpp rename to algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp From 79617041ea029a773d2816af13ca740589e863a9 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 12 Nov 2016 00:38:26 +0800 Subject: [PATCH 087/105] New Problem Solution "Convert a Number to Hexadecimal" --- README.md | 1 + .../ConvertANumberToHexadecimal.cpp | 56 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp diff --git a/README.md b/README.md index 36e9af9fa..a236a7b2a 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy| |404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| |402|[Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./algorithms/cpp/removeKDigits/RemoveKDigits.cpp)|Medium| |401|[Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./algorithms/cpp/binaryWatch/BinaryWatch.cpp)|Easy| diff --git a/algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp b/algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp new file mode 100644 index 000000000..654e50e40 --- /dev/null +++ b/algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp @@ -0,0 +1,56 @@ +// Source : https://leetcode.com/problems/convert-a-number-to-hexadecimal/ +// Author : Hao Chen +// Date : 2016-11-12 + +/*************************************************************************************** + * + * Given an integer, write an algorithm to convert it to hexadecimal. For negative + * integer, two’s complement method is used. + * + * Note: + * + * All letters in hexadecimal (a-f) must be in lowercase. + * The hexadecimal string must not contain extra leading 0s. If the number is zero, it + * is represented by a single zero character '0'; otherwise, the first character in the + * hexadecimal string will not be the zero character. + * The given number is guaranteed to fit within the range of a 32-bit signed integer. + * You must not use any method provided by the library which converts/formats the + * number to hex directly. + * + * Example 1: + * + * Input: + * 26 + * + * Output: + * "1a" + * + * Example 2: + * + * Input: + * -1 + * + * Output: + * "ffffffff" + ***************************************************************************************/ + +class Solution { +public: + + string toHex(int num) { + + if (num == 0) return "0"; + + unsigned int x = num; + + string result; + for(;x > 0; x/=16) { + int n = x % 16; + char c; + if (n < 10) c = n + '0'; + else c = 'a' + n - 10 ; + result = c + result; + } + return result; + } +}; From 0e3f0e28901953c8fa5989ed9ae27f60a8a5d236 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 12 Nov 2016 17:20:19 +0800 Subject: [PATCH 088/105] New Problem Solution "Frog Jump" --- README.md | 1 + algorithms/cpp/frogJump/FrogJump.cpp | 125 +++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 algorithms/cpp/frogJump/FrogJump.cpp diff --git a/README.md b/README.md index a236a7b2a..cfcfa97e0 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ LeetCode |---| ----- | -------- | ---------- | |405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy| |404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| +|403|[Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./algorithms/cpp/frogJump/FrogJump.cpp)|Hard| |402|[Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./algorithms/cpp/removeKDigits/RemoveKDigits.cpp)|Medium| |401|[Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./algorithms/cpp/binaryWatch/BinaryWatch.cpp)|Easy| |400|[Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./algorithms/cpp/nthDigit/NthDigit.cpp)|Easy| diff --git a/algorithms/cpp/frogJump/FrogJump.cpp b/algorithms/cpp/frogJump/FrogJump.cpp new file mode 100644 index 000000000..8bd302b89 --- /dev/null +++ b/algorithms/cpp/frogJump/FrogJump.cpp @@ -0,0 +1,125 @@ +// Source : https://leetcode.com/problems/frog-jump/ +// Author : Hao Chen +// Date : 2016-11-12 + +/*************************************************************************************** + * + * A frog is crossing a river. The river is divided into x units and at each unit there + * may or may not exist a stone. The frog can jump on a stone, but it must not jump + * into the water. + * + * Given a list of stones' positions (in units) in sorted ascending order, determine if + * the frog is able to cross the river by landing on the last stone. Initially, the + * frog is on the first stone and assume the first jump must be 1 unit. + * + * If the frog's last jump was k units, then its next jump must be either k - 1, k, or + * k + 1 units. Note that the frog can only jump in the forward direction. + * + * Note: + * + * The number of stones is ≥ 2 and is + * Each stone's position will be a non-negative integer 31. + * The first stone's position is always 0. + * + * Example 1: + * + * [0,1,3,5,6,8,12,17] + * + * There are a total of 8 stones. + * The first stone at the 0th unit, second stone at the 1st unit, + * third stone at the 3rd unit, and so on... + * The last stone at the 17th unit. + * + * Return true. The frog can jump to the last stone by jumping + * 1 unit to the 2nd stone, then 2 units to the 3rd stone, then + * 2 units to the 4th stone, then 3 units to the 6th stone, + * 4 units to the 7th stone, and 5 units to the 8th stone. + * + * Example 2: + * + * [0,1,2,3,4,8,9,11] + * + * Return false. There is no way to jump to the last stone as + * the gap between the 5th and 6th stone is too large. + ***************************************************************************************/ + +class Solution { +public: + bool canCross_recursion(vector& stones, int curr, int last_jump) { + for(int i=curr+1; i last_jump + 1) return false; + + if (i == stones.size() - 1 || canCross_recursion(stones, i, next_jump)) return true; + } + return false; + } + + bool canCross_recursion_with_cache(vector& stones, int curr, int last_jump, + unordered_map>& cache) + { + //check the cache is hitted ? + if (cache.find(curr) != cache.end() && cache[curr].find(last_jump)!=cache[curr].end()) { + return cache[curr][last_jump]; + } + + for(int i=curr+1; i last_jump + 1) break; + if (i == stones.size() - 1 || canCross_recursion_with_cache(stones, i, next_jump, cache)) { + cache[curr][last_jump] = true; + return true; + } + } + cache[curr][last_jump] = false; + return false; + } + + bool canCross_non_recursion(vector& stones) { + + // the `jumps` map store the all possible `last jumps` + unordered_map> jumps = {{0, {0}}}; + + for(int i=0; i& stones) { + + //Burst Force solution -- accepted ~500ms + return canCross_non_recursion(stones); + + //DFS with cache solution - accepted ~160ms + unordered_map> cache; + return canCross_recursion_with_cache(stones, 0, 0, cache); + + // Time Limit Error + return canCross_recursion(stones, 0, 0); + + } +}; From 7fb99ce3bf2d3b8800e5f930539c9cf681d46d58 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 12 Nov 2016 18:20:11 +0800 Subject: [PATCH 089/105] New Problem Solution "Queue Reconstruction by Height" --- README.md | 1 + .../QueueReconstructionByHeight.cpp | 73 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp diff --git a/README.md b/README.md index cfcfa97e0..07d9c7dc4 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp)|Medium| |405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy| |404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| |403|[Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./algorithms/cpp/frogJump/FrogJump.cpp)|Hard| diff --git a/algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp b/algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp new file mode 100644 index 000000000..e648683a1 --- /dev/null +++ b/algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp @@ -0,0 +1,73 @@ +// Source : https://leetcode.com/problems/queue-reconstruction-by-height/ +// Author : Hao Chen +// Date : 2016-11-12 + +/*************************************************************************************** + * + * Suppose you have a random list of people standing in a queue. Each person is + * described by a pair of integers (h, k), where h is the height of the person and k is + * the number of people in front of this person who have a height greater than or equal + * to h. Write an algorithm to reconstruct the queue. + * + * Note: + * The number of people is less than 1,100. + * + * Example + * + * Input: + * [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] + * + * Output: + * [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] + ***************************************************************************************/ + +class Solution { + +public: + vector> reconstructQueue(vector>& people) { + //sort function + auto comp = [](const pair& p1, const pair& p2) + { return p1.first == p2.first ? p1.second < p2.second : p1.first > p2.first; }; + //sort the people with their height with descending order + // and if the height is same then sort by K with ascending order + sort(people.begin(), people.end(), comp); + + // For example: + // Original Queue: [7,0], [4,4], [7,1], [5,0], [6,1], [5,2] + // Sorted Queue: [7,0], [7,1], [6,1], [5,0], [5,2], [4,4] + + + // Why do we need to sort like this? + // + // ** The position of shorter people is ZERO impacted with higher people. ** + // + // and, the shortest people has no impacts to all of people. we can simpley insert it to the Kth position + // + // So, we sorted the people from highest to the shortest, then when we insert the people to another array, + // + // we always can guarantee the people is going to be inserted has nothing to do with the people has been inserted. + // + // Let's continue the about example above + // + // [7,0] => [] then [7,0] + // [7,1] => [7,0] then [7,0], [7,1] + // [6,1] => [7,0], [7,1] then [7,0], [6,1], [7,1] + // [5,0] => [7,0], [6,1], [7,1] then [5,0], [7,0], [6,1], [7,1] + // [5,2] => [5,0], [7,0], [6,1], [7,1] then [5,0], [7,0], [5,2], [6,1], [7,1] + // [4,4] => [5,0], [7,0], [5,2], [6,1], [7,1] then [5,0], [7,0], [5,2], [6,1], [4,4], [7,1] + // + // We alway can see, the people is going to be inserted has NO IMPACT with the current people. + // + // [6,1] => [7,0], [7,1] + // + // Whatever the people[6,1] placed, it has nothing to do with the people [7,0] [7,1], + // So, we can just insert the people to the place he like - the `Kth` place. + // + // + vector> res; + for (auto& p : people) { + res.insert(res.begin() + p.second, p); + } + return res; + } +}; From 9f00ad162bfb977def5a4f2643af060e5d6964c8 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 12 Nov 2016 18:50:43 +0800 Subject: [PATCH 090/105] New Problem Solution "Add Strings" --- README.md | 1 + algorithms/cpp/addStrings/AddStrings.cpp | 48 ++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 algorithms/cpp/addStrings/AddStrings.cpp diff --git a/README.md b/README.md index 07d9c7dc4..13a46274a 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|415|[Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./algorithms/cpp/addStrings/AddStrings.cpp)|Easy| |406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp)|Medium| |405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy| |404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| diff --git a/algorithms/cpp/addStrings/AddStrings.cpp b/algorithms/cpp/addStrings/AddStrings.cpp new file mode 100644 index 000000000..32b6734bb --- /dev/null +++ b/algorithms/cpp/addStrings/AddStrings.cpp @@ -0,0 +1,48 @@ +// Source : https://leetcode.com/problems/add-strings/ +// Author : Hao Chen +// Date : 2016-11-12 + +/*************************************************************************************** + * + * Given two non-negative numbers num1 and num2 represented as string, return the sum + * of num1 and num2. + * + * Note: + * + * The length of both num1 and num2 is + * Both num1 and num2 contains only digits 0-9. + * Both num1 and num2 does not contain any leading zero. + * You must not use any built-in BigInteger library or convert the inputs to integer + * directly. + ***************************************************************************************/ + +class Solution { +public: + string addStrings(string num1, string num2) { + string& longstr = ( num1.size() >= num2.size() ? num1 : num2 ); + string& shortstr = ( num1.size() < num2.size() ? num1 : num2 ); + + int longlen = longstr.size(); + int shortlen = shortstr.size(); + + char carry = 0; + int i, j; + + string result; + for (i = longlen-1, j=shortlen-1; i>=0; i--, j--) { + int add = 0; + if (j>=0) { + add = longstr[i] + shortstr[j] - 2 * '0' + carry; + }else{ + add = longstr[i] - '0' + carry; + } + carry = add/10; + result = char('0' + add % 10) + result; + } + + if (carry) { + result = '1' + result; + } + return result; + } +}; From c54086b33b24643d5d1a59ef2e86d3a0b6e71b80 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 12 Nov 2016 18:57:20 +0800 Subject: [PATCH 091/105] adjust the file's directory --- README.md | 2 +- .../intersectionOfTwoArraysII.cpp | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename algorithms/cpp/{intersectionOfTwoArraysII => intersectionOfTwoArrays}/intersectionOfTwoArraysII.cpp (100%) diff --git a/README.md b/README.md index 13a46274a..fbe369a29 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ LeetCode |380|[Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1.cpp)|Hard| |377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium| |376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium| -|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp)|Easy| +|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArraysII.cpp)|Easy| |349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy| |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| diff --git a/algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp b/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArraysII.cpp similarity index 100% rename from algorithms/cpp/intersectionOfTwoArraysII/intersectionOfTwoArraysII.cpp rename to algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArraysII.cpp From e7e12523cf231ae1b40dc8c92a23a1cb7788b239 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sun, 13 Nov 2016 11:59:17 +0800 Subject: [PATCH 092/105] New Problem "Arithmetic Slices" --- README.md | 2 + .../cpp/arithmeticSlices/ArithmeticSlices.cpp | 72 +++++++++++++++++++ .../thirdMaximumNumber/ThirdMaximumNumber.cpp | 51 +++++++++++++ 3 files changed, 125 insertions(+) create mode 100644 algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp create mode 100644 algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp diff --git a/README.md b/README.md index fbe369a29..0611bfdcb 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | |415|[Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./algorithms/cpp/addStrings/AddStrings.cpp)|Easy| +|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp)|Easy| +|413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium| |406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp)|Medium| |405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy| |404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| diff --git a/algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp b/algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp new file mode 100644 index 000000000..dc7c9fa05 --- /dev/null +++ b/algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp @@ -0,0 +1,72 @@ +// Source : https://leetcode.com/problems/arithmetic-slices/ +// Author : Hao Chen +// Date : 2016-11-13 + +/*************************************************************************************** + * + * A sequence of number is called arithmetic if it consists of at least three elements + * and if the difference between any two consecutive elements is the same. + * + * For example, these are arithmetic sequence: + * 1, 3, 5, 7, 9 + * 7, 7, 7, 7 + * 3, -1, -5, -9 + * + * The following sequence is not arithmetic. 1, 1, 2, 5, 7 + * + * A zero-indexed array A consisting of N numbers is given. A slice of that array is + * any pair of integers (P, Q) such that 0 + * + * A slice (P, Q) of array A is called arithmetic if the sequence: + * A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means + * that P + 1 + * + * The function should return the number of arithmetic slices in the array A. + * + * Example: + * + * A = [1, 2, 3, 4] + * + * return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] + * itself. + ***************************************************************************************/ + +class Solution { +public: + // + // It's easy to find out how many 3-length slices in an arithmetic array with N length. + // + // len = 3, then 1 slices, sum(1) + // len = 4, then 3 slices, sum(1,2) - TWO 3-length slices + ONE 4-length slice + // len = 5, then 6 slices, sum(1,2,3) - THREE 3-length slices + TWO 4-length slices + ONE 5-length slice + // len = 6, then 10 slices, sum(1,2,3,4) - ... + // len = 7, then 15 slices, sum(1,2,3,4,5) - .. + // + // So, with N length arithmetic array, there are Sum[1, N-3+1] 3-length slices + // + // And, we know the formula sum from 1 to n is: + // + // n * ( n + 1 ) + // sum [1, n] = --------------- + // 2 + // Then, we could have the solution - O(n) Time with O(1) Space + // + + int sum1toN(int n) { + return n * (n+1) / 2; + } + + int numberOfArithmeticSlices(vector& A) { + int result = 0; + int len = 0; // the current length of arithmetic + for (int i=2; i& nums, int n) { + set topN; + for(auto num : nums) { + topN.insert(num); + if (topN.size() > n) topN.erase(topN.begin()); + } + return (topN.size() >= n) ? *(topN.begin()) : *(topN.rbegin()); + } + int thirdMax(vector& nums) { + return nMax(nums, 3); + } +}; From 48978d84a83d324e7b94138bd9aa92b7df27fa3b Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sun, 13 Nov 2016 12:28:51 +0800 Subject: [PATCH 093/105] New Problem Solution "Fizz Buzz" --- README.md | 1 + algorithms/cpp/fizzBuzz/FizzBuzz.cpp | 91 ++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 algorithms/cpp/fizzBuzz/FizzBuzz.cpp diff --git a/README.md b/README.md index 0611bfdcb..0845d31b5 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ LeetCode |415|[Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./algorithms/cpp/addStrings/AddStrings.cpp)|Easy| |414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp)|Easy| |413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium| +|412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./algorithms/cpp/fizzBuzz/FizzBuzz.cpp)|Easy| |406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp)|Medium| |405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy| |404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| diff --git a/algorithms/cpp/fizzBuzz/FizzBuzz.cpp b/algorithms/cpp/fizzBuzz/FizzBuzz.cpp new file mode 100644 index 000000000..f4ec548e7 --- /dev/null +++ b/algorithms/cpp/fizzBuzz/FizzBuzz.cpp @@ -0,0 +1,91 @@ +// Source : https://leetcode.com/problems/fizz-buzz/ +// Author : Hao Chen +// Date : 2016-11-13 + +/*************************************************************************************** + * + * Write a program that outputs the string representation of numbers from 1 to n. + * + * But for multiples of three it should output “Fizz” instead of the number and for the + * multiples of five output “Buzz”. For numbers which are multiples of both three and + * five output “FizzBuzz”. + * + * Example: + * + * n = 15, + * + * Return: + * [ + * "1", + * "2", + * "Fizz", + * "4", + * "Buzz", + * "Fizz", + * "7", + * "8", + * "Fizz", + * "Buzz", + * "11", + * "Fizz", + * "13", + * "14", + * "FizzBuzz" + * ] + ***************************************************************************************/ + +class Solution { +public: + vector fizzBuzz_old_school_way(int n) { + vector result; + for (int i=1; i<=n; i++) { + if ( i%3 == 0 && i%5 ==0 ) { + result.push_back("FizzBuzz"); + }else if (i%3 == 0) { + result.push_back("Fizz"); + }else if (i%5 == 0) { + result.push_back("Buzz"); + }else{ + result.push_back(std::to_string(i)); + } + } + return result; + } + + + class FizzBuzz { + public: + FizzBuzz() : x(0) {} + + string operator()() { + x++; + if ( x%3 == 0 && x%5 ==0 ) { + return ("FizzBuzz"); + }else if (x%3 == 0) { + return ("Fizz"); + }else if (x%5 == 0) { + return("Buzz"); + } + return std::to_string(x); + } + + private: + int x; + }; + + vector fizzBuzz_cpp_way(int n) { + vector result(n); + generate(result.begin(), result.end(), FizzBuzz()); + return result; + } + + vector fizzBuzz(int n) { + + //both method has same performance + + if (rand() % 2 == 0) { + return fizzBuzz_cpp_way(n); + } + return fizzBuzz_old_school_way(n); + } +}; From 4d68a1318afed990ac3ee83a770a29e86fb7703f Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sun, 13 Nov 2016 22:42:48 +0800 Subject: [PATCH 094/105] New Problem Solution "Longest Palindrome" --- README.md | 1 + .../longestPalindrome/LongestPalindrome.cpp | 50 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 algorithms/cpp/longestPalindrome/LongestPalindrome.cpp diff --git a/README.md b/README.md index 0845d31b5..09bdeb498 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ LeetCode |414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp)|Easy| |413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium| |412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./algorithms/cpp/fizzBuzz/FizzBuzz.cpp)|Easy| +|409|[Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./algorithms/cpp/longestPalindrome/LongestPalindrome.cpp)|Easy| |406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp)|Medium| |405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy| |404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy| diff --git a/algorithms/cpp/longestPalindrome/LongestPalindrome.cpp b/algorithms/cpp/longestPalindrome/LongestPalindrome.cpp new file mode 100644 index 000000000..402486c02 --- /dev/null +++ b/algorithms/cpp/longestPalindrome/LongestPalindrome.cpp @@ -0,0 +1,50 @@ +// Source : https://leetcode.com/problems/longest-palindrome/ +// Author : Hao Chen +// Date : 2016-11-13 + +/*************************************************************************************** + * + * Given a string which consists of lowercase or uppercase letters, find the length of + * the longest palindromes that can be built with those letters. + * + * This is case sensitive, for example "Aa" is not considered a palindrome here. + * + * Note: + * Assume the length of given string will not exceed 1,010. + * + * Example: + * + * Input: + * "abccccdd" + * + * Output: + * 7 + * + * Explanation: + * One longest palindrome that can be built is "dccaccd", whose length is 7. + ***************************************************************************************/ + +class Solution { +public: + int longestPalindrome(string s) { + + int hashtable[128]; + memset(hashtable, 0, sizeof(hashtable)); + + for(char ch : s) { + hashtable[ch]++; + } + int result = 0; + bool hasOdd = false; + for (int n : hashtable) { + if ( n%2 == 0 ) { + result += n; + } else { + result += n -1; + hasOdd = true; + } + } + + return hasOdd ? result + 1 : result; + } +}; From 09410736efba5aed18a6fa98a44615979ce720f7 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sun, 13 Nov 2016 23:42:51 +0800 Subject: [PATCH 095/105] New Problem Soluiton "Split Array Largest Sum" --- README.md | 1 + .../SplitArrayLargestSum.cpp | 69 +++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp diff --git a/README.md b/README.md index 09bdeb498..271b14882 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ LeetCode |414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp)|Easy| |413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium| |412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./algorithms/cpp/fizzBuzz/FizzBuzz.cpp)|Easy| +|410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) | [C++](./algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp)|Hard| |409|[Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./algorithms/cpp/longestPalindrome/LongestPalindrome.cpp)|Easy| |406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp)|Medium| |405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy| diff --git a/algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp b/algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp new file mode 100644 index 000000000..450dda91d --- /dev/null +++ b/algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp @@ -0,0 +1,69 @@ +// Source : https://leetcode.com/problems/split-array-largest-sum/ +// Author : Hao Chen +// Date : 2016-11-13 + +/*************************************************************************************** + * + * Given an array which consists of non-negative integers and an integer m, you can + * split the array into m non-empty continuous subarrays. Write an algorithm to + * minimize the largest sum among these m subarrays. + * + * Note: + * Given m satisfies the following constraint: 1 ≤ m ≤ length(nums) ≤ 14,000. + * + * Examples: + * + * Input: + * nums = [7,2,5,10,8] + * m = 2 + * + * Output: + * 18 + * + * Explanation: + * There are four ways to split nums into two subarrays. + * The best way is to split it into [7,2,5] and [10,8], + * where the largest sum among the two subarrays is only 18. + ***************************************************************************************/ + +class Solution { +public: + // Idea + // 1) The max of the result is the sum of the whole array. + // 2) The min of the result is the max num among the array. + // 3) Then, we use Binary Search to find the resullt between the `min` and the `max` + + int splitArray(vector& nums, int m) { + int min = 0, max = 0; + for (int n : nums) { + min = std::max(min, n); + max += n; + } + while (min < max) { + int mid = min + (max - min) / 2; + if (hasSmallerSum(nums, m, mid)) max = mid; + else min = mid + 1; + } + return min; + } + + + // Using a specific `sum` to check wheter we can get `smaller sum` + // The idea here as below: + // find all of possible `sub array` whose sum greater than `sum` + // 1) if the number of `sub array` > m, whcih means the actual result is greater than `sum` + // 2) if the number of `sub array` <= m, whcih means we can have `smaller sum` + // + bool hasSmallerSum(vector& nums, int m, int sum) { + int cnt = 1, curSum = 0; + for (int n : nums) { + curSum += n; + if (curSum > sum) { + curSum = n; + cnt++; + if (cnt > m) return false; + } + } + return true; + } +}; From 879e9e6513013aa1e4d453b8ba2ad91cb86a4ae2 Mon Sep 17 00:00:00 2001 From: omengye Date: Mon, 26 Dec 2016 22:23:55 +0800 Subject: [PATCH 096/105] array index out of bounds, fix to low > threeSum(vector &num) { high--; } else{ //skip the duplication - while(low Date: Mon, 2 Jan 2017 10:20:53 +0800 Subject: [PATCH 097/105] New Problem Solution - "Super Ugly Number" --- README.md | 1 + .../cpp/superUglyNumber/SuperUglyNumber.cpp | 69 +++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 algorithms/cpp/superUglyNumber/SuperUglyNumber.cpp diff --git a/README.md b/README.md index 271b14882..b7244b06a 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ LeetCode |321|[Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | [C++](./algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp)|Hard| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| +|313|[Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | [C++](./algorithms/cpp/superUglyNumber/SuperUglyNumber.cpp)|Medium| |312|[Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./algorithms/cpp/burstBalloons/BurstBalloons.cpp)|Hard| |310|[Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/) | [C++](./algorithms/cpp/minimumHeightTrees/MinimumHeightTrees.cpp)|Medium| |307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Mutable/RangeSumQueryMutable.cpp)|Medium| diff --git a/algorithms/cpp/superUglyNumber/SuperUglyNumber.cpp b/algorithms/cpp/superUglyNumber/SuperUglyNumber.cpp new file mode 100644 index 000000000..66438fd46 --- /dev/null +++ b/algorithms/cpp/superUglyNumber/SuperUglyNumber.cpp @@ -0,0 +1,69 @@ +// Source : https://leetcode.com/problems/super-ugly-number/ +// Author : Hao Chen +// Date : 2017-01-02 + +/*************************************************************************************** + * + * Write a program to find the nth super ugly number. + * + * Super ugly numbers are positive numbers whose all prime factors are in the given + * prime list + * primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] + * is the sequence of the first 12 super ugly numbers given primes + * = [2, 7, 13, 19] of size 4. + * + * Note: + * (1) 1 is a super ugly number for any given primes. + * (2) The given numbers in primes are in ascending order. + * (3) 0 k ≤ 100, 0 n ≤ 106, 0 primes[i] + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + +// As the solution we have for the ugly number II problem +// +// int nthUglyNumber(int n) { +// +// int i=0, j=0, k=0; +// vector ugly(1,1); +// +// while(ugly.size() < n){ +// int next = min(ugly[i]*2, ugly[j]*3, ugly[k]*5); +// if (next == ugly[i]*2) i++; +// if (next == ugly[j]*3) j++; +// if (next == ugly[k]*5) k++; +// ugly.push_back(next); +// } +// return ugly.back(); +// } +// +// The logic of solution is exacly same for both., except that instead of 3 numbers you have k numbers to consider. +// +// +// +class Solution { + +public: + int nthSuperUglyNumber(int n, vector& primes) { + vector ugly(1, 1); + int len = primes.size(); + vector pos(len, 0); + + while( ugly.size() < n ) { + int next = INT_MAX; + for(int i=0; i Date: Mon, 2 Jan 2017 10:22:14 +0800 Subject: [PATCH 098/105] fix: forgot commit the "Find the Difference" --- .../findTheDifference/FindTheDifference.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 algorithms/cpp/findTheDifference/FindTheDifference.cpp diff --git a/algorithms/cpp/findTheDifference/FindTheDifference.cpp b/algorithms/cpp/findTheDifference/FindTheDifference.cpp new file mode 100644 index 000000000..5e51e4f0e --- /dev/null +++ b/algorithms/cpp/findTheDifference/FindTheDifference.cpp @@ -0,0 +1,38 @@ +// Source : https://leetcode.com/problems/find-the-difference/ +// Author : Hao Chen +// Date : 2016-09-08 + +/*************************************************************************************** + * + * Given two strings s and t which consist of only lowercase letters. + * + * String t is generated by random shuffling string s and then add one more letter at a + * random position. + * + * Find the letter that was added in t. + * + * Example: + * + * Input: + * s = "abcd" + * t = "abcde" + * + * Output: + * e + * + * Explanation: + * 'e' is the letter that was added. + ***************************************************************************************/ + +class Solution { +public: + char findTheDifference(string s, string t) { + unordered_map m; + for(auto c : s) m[c]++; + for(auto c : t) { + m[c]--; + if (m[c] < 0) return c; + } + return '\0'; + } +}; From 9c3eac7992c8c10075f2b3d73897b3ef9a34ddf8 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 2 Jan 2017 15:39:10 +0800 Subject: [PATCH 099/105] New Problem Solution "Remove Duplicate Letters" --- README.md | 1 + .../RemoveDuplicateLetters.cpp | 52 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 algorithms/cpp/removeDuplicateLetters/RemoveDuplicateLetters.cpp diff --git a/README.md b/README.md index b7244b06a..443973758 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ LeetCode |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |321|[Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | [C++](./algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp)|Hard| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| +|316|[Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./algorithms/cpp/removeDuplicateLetters/RemoveDuplicateLetters.cpp)|Hard| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| |313|[Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | [C++](./algorithms/cpp/superUglyNumber/SuperUglyNumber.cpp)|Medium| |312|[Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./algorithms/cpp/burstBalloons/BurstBalloons.cpp)|Hard| diff --git a/algorithms/cpp/removeDuplicateLetters/RemoveDuplicateLetters.cpp b/algorithms/cpp/removeDuplicateLetters/RemoveDuplicateLetters.cpp new file mode 100644 index 000000000..e3ae9f3f4 --- /dev/null +++ b/algorithms/cpp/removeDuplicateLetters/RemoveDuplicateLetters.cpp @@ -0,0 +1,52 @@ +// Source : https://leetcode.com/problems/remove-duplicate-letters/ +// Author : Hao Chen +// Date : 2017-01-02 + +/*************************************************************************************** + * + * Given a string which contains only lowercase letters, remove duplicate letters so + * that every letter appear once and only once. You must make sure your result is the + * smallest in lexicographical order among all possible results. + * + * Example: + * + * Given "bcabc" + * Return "abc" + * + * Given "cbacdcbc" + * Return "acdb" + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + + +class Solution { +public: + string removeDuplicateLetters(string s) { + const int ASCII_LEN = 256; + int counter[ASCII_LEN] = {0}; + bool visited[ASCII_LEN] = {false}; + + for (char ch : s) { + counter[ch]++; + } + + string result; + for (char ch : s) { + counter[ch]--; + // if the current `ch` has already put into the result. + if (visited[ch]) continue; + + // if the current `ch` is smaller than the last one char in result. + // and we still have duplicated last-one char behind, so we can remove the current one. + while ( !result.empty() && ch < result.back() && counter[result.back()] ) { + visited[result.back()] = false; + result.pop_back(); + } + result.push_back(ch); + visited[ch] = true; + } + return result; + } +}; From f3c62b342d407159c60ba6c6e0a7416511caf6d8 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 2 Jan 2017 17:30:54 +0800 Subject: [PATCH 100/105] New Problem Solution - "Maximum Product of Word Lengths" --- README.md | 1 + .../MaximumProductOfWordLengths.cpp | 72 +++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 algorithms/cpp/maximumProductOfWordLengths/MaximumProductOfWordLengths.cpp diff --git a/README.md b/README.md index 443973758..990801653 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ LeetCode |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |321|[Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | [C++](./algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp)|Hard| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| +|318|[Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./algorithms/cpp/maximumProductOfWordLengths/MaximumProductOfWordLengths.cpp)|Medium| |316|[Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./algorithms/cpp/removeDuplicateLetters/RemoveDuplicateLetters.cpp)|Hard| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard| |313|[Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | [C++](./algorithms/cpp/superUglyNumber/SuperUglyNumber.cpp)|Medium| diff --git a/algorithms/cpp/maximumProductOfWordLengths/MaximumProductOfWordLengths.cpp b/algorithms/cpp/maximumProductOfWordLengths/MaximumProductOfWordLengths.cpp new file mode 100644 index 000000000..8e9ecf4e0 --- /dev/null +++ b/algorithms/cpp/maximumProductOfWordLengths/MaximumProductOfWordLengths.cpp @@ -0,0 +1,72 @@ +// Source : https://leetcode.com/problems/maximum-product-of-word-lengths/ +// Author : Hao Chen +// Date : 2017-01-02 + +/*************************************************************************************** + * + * Given a string array words, find the maximum value of length(word[i]) * + * length(word[j]) where the two words do not share common letters. + * You may assume that each word will contain only lower case letters. + * If no such two words exist, return 0. + * + * Example 1: + * + * Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] + * Return 16 + * The two words can be "abcw", "xtfn". + * + * Example 2: + * + * Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] + * Return 4 + * The two words can be "ab", "cd". + * + * Example 3: + * + * Given ["a", "aa", "aaa", "aaaa"] + * Return 0 + * No such pair of words. + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + +class Solution { +public: + // + // there are two algorithms: + // + // 1) compare two words is same or not + // - we can use bit-mask to solve that. + // - we need be careful about one word is subset of another one, such as: "abc" is subset of "abcabc" + // + // 2) find out the max product - that needs O(N^2) time complexity algorithm. + // + + int maxProduct(vector& words) { + //Key is the word's bitmask, and the value the max length of that bit mask + unordered_map maxLens; + //constructing the bitmask. + for(auto& w: words) { + int mask = 0; + for (auto& c: w) { + mask = mask | ( 1 << (c-'a') ); + } + if ( maxLens.find(mask) == maxLens.end() || maxLens[mask] < w.size() ) { + maxLens[mask] = w.size(); + } + } + + //find out the max product + int result = 0; + for (auto a : maxLens) { + for (auto b: maxLens) { + // if `a` and `b` is same, then just simply continue + if (a.first & b.first) continue; // there are common letters + result = max( result, a.second * b.second ); + } + } + + return result; + } +}; From 7fc247a63b8c31b2cbba3cc4509ad0b298749eb2 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 2 Jan 2017 22:24:20 +0800 Subject: [PATCH 101/105] New Problem Solution "Wiggle Sort II" --- README.md | 1 + algorithms/cpp/wiggleSort/WiggleSort.II.cpp | 93 +++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 algorithms/cpp/wiggleSort/WiggleSort.II.cpp diff --git a/README.md b/README.md index 990801653..07e3f2a5f 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ LeetCode |328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [C++](./algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp)|Easy| |327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| |326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| +|324|[Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./algorithms/cpp/wiggleSort/WiggleSort.II.cpp)|Medium| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |321|[Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | [C++](./algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp)|Hard| |319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium| diff --git a/algorithms/cpp/wiggleSort/WiggleSort.II.cpp b/algorithms/cpp/wiggleSort/WiggleSort.II.cpp new file mode 100644 index 000000000..a225c19b7 --- /dev/null +++ b/algorithms/cpp/wiggleSort/WiggleSort.II.cpp @@ -0,0 +1,93 @@ +// Source : https://leetcode.com/problems/wiggle-sort-ii/ +// Author : Hao Chen +// Date : 2017-01-02 + +/*************************************************************************************** + * + * Given an unsorted array nums, reorder it such that + * nums[0] nums[2] . + * + * Example: + * (1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. + * (2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2]. + * + * Note: + * You may assume all input has valid answer. + * + * Follow Up: + * Can you do it in O(n) time and/or in-place with O(1) extra space? + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + +class Solution { + +public: + // + // Solution - O(N*logN) + // -------------------- + // 1) Sorting the array with descending order + // + // 2) Split the sorted array into two parts, + // and insert the 2nd half array into the 1st half array + // + // For example: [ 9 8 7 6 5 4 3 2 1 0 ] + // + // + // 1st Large half: . 9 . 8 . 7 . 6 . 5 + // 2nd Small half: 4 . 3 . 2 . 1 . 0 . + // --------------------------------------- + // Result: 4 9 3 8 2 7 1 6 0 5 + // + // Be careful if the length of array is odd number, + // Such as: [5 4 3 2 1], + // The 2nd half is [3 2 1] instead of [2 1] + // + + void wiggleSort01(vector& nums) { + sort(nums.begin(), nums.end(), [](int x, int y) { return x > y; }); + int half = (nums.size() / 2); + + for (int i=0; i& nums) { + int n = nums.size(); + + // Find a median. + auto midptr = nums.begin() + n / 2; + nth_element(nums.begin(), midptr, nums.end()); + int mid = *midptr; + + // Index-rewiring. + #define A(i) nums[(1+2*(i)) % (n|1)] + + // 3-way-partition-to-wiggly in O(n) time with O(1) space. + int i = 0, j = 0, k = n - 1; + while (j <= k) { + if (A(j) > mid) + swap(A(i++), A(j++)); + else if (A(j) < mid) + swap(A(j), A(k--)); + else + j++; + } + } + void wiggleSort(vector& nums) { + return wiggleSort02(nums); //~140ms + return wiggleSort01(nums); //~230ms + } +}; From 86f94976841d01428cfc224c110a2421f19d06ee Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 6 Jan 2017 09:57:06 +0800 Subject: [PATCH 102/105] New Problem Solution "Verify Preorder Serialization of a Binary Tree" --- README.md | 1 + ...rifyPreorderSerializationOfABinaryTree.cpp | 85 +++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 algorithms/cpp/verifyPreorderSerializationOfABinaryTree/VerifyPreorderSerializationOfABinaryTree.cpp diff --git a/README.md b/README.md index 07e3f2a5f..bb0a3d8cf 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ LeetCode |338|[Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./algorithms/cpp/countingBits/CountingBits.cpp)|Medium| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| +|331|[Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/) | [C++](./algorithms/cpp/verifyPreorderSerializationOfABinaryTree/VerifyPreorderSerializationOfABinaryTree.cpp)|Medium| |330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium| |329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp)|Medium| |328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [C++](./algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp)|Easy| diff --git a/algorithms/cpp/verifyPreorderSerializationOfABinaryTree/VerifyPreorderSerializationOfABinaryTree.cpp b/algorithms/cpp/verifyPreorderSerializationOfABinaryTree/VerifyPreorderSerializationOfABinaryTree.cpp new file mode 100644 index 000000000..04e6c6c1d --- /dev/null +++ b/algorithms/cpp/verifyPreorderSerializationOfABinaryTree/VerifyPreorderSerializationOfABinaryTree.cpp @@ -0,0 +1,85 @@ +// Source : https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ +// Author : Hao Chen +// Date : 2017-01-06 + +/*************************************************************************************** + * + * One way to serialize a binary tree is to use pre-order traversal. When we encounter + * a non-null node, we record the node's value. If it is a null node, we record using a + * sentinel value such as #. + * + * _9_ + * / \ + * 3 2 + * / \ / \ + * 4 1 # 6 + * / \ / \ / \ + * # # # # # # + * + * For example, the above binary tree can be serialized to the string + * "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node. + * + * Given a string of comma separated values, verify whether it is a correct preorder + * traversal serialization of a binary tree. Find an algorithm without reconstructing + * the tree. + * + * Each comma separated value in the string must be either an integer or a character + * '#' representing null pointer. + * + * You may assume that the input format is always valid, for example it could never + * contain two consecutive commas such as "1,,3". + * + * Example 1: + * "9,3,4,#,#,1,#,#,2,#,6,#,#" + * Return true + * Example 2: + * "1,#" + * Return false + * Example 3: + * "9,#,#,1" + * Return false + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + +class Solution { +public: + + // we know the following facts: + // 1) if we met a non-null node, then this node will generate two child node. + // 2) if we met a null node, then this node will generate zero child node. + // + // so the idea is, + // 1) we can have a counter to calculate how many node we are going to expect + // 2) once we have the expected node, then we can decrease the counter. + // 3) finally, we will check the counter is zero or not. + // + // the algorithm as below: + // 1) when we meet a non-null node, just simply do `counter++`. because: + // 1.1) we will expect 2 more node after, then we do `counter += 2`. + // 1.2) but the current node also meet the expection of parent node , so, it need remove 1 in counter. + // finally, the `counter = counbter + 2 -1` + // 2) when we meet a null node, just simply do `counter--`. + + bool isValidSerialization(string preorder) { + vector list; + split(preorder, ',', list); + //we initailize the counter as 1, + //because we expect at lease 1 node in the tree. + int node_expected = 1; + for (auto node : list) { + if (node_expected == 0) return false; + node == "#" ? node_expected-- : node_expected++; + } + return node_expected == 0; + } + + void split(const string &s, char delim, vector &elems) { + stringstream ss(s); + string item; + while (getline(ss, item, delim)) { + elems.push_back(item); + } + } +}; From 121b458ffc38177faca8813d70668a068ca9973e Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 6 Jan 2017 11:00:43 +0800 Subject: [PATCH 103/105] New Problem Solution "Reconstruct Itinerary" --- README.md | 1 + .../ReconstructItinerary.cpp | 78 +++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 algorithms/cpp/reconstructItinerary/ReconstructItinerary.cpp diff --git a/README.md b/README.md index bb0a3d8cf..31777f982 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ LeetCode |338|[Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./algorithms/cpp/countingBits/CountingBits.cpp)|Medium| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| +|332|[Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [C++](./algorithms/cpp/reconstructItinerary/ReconstructItinerary.cpp)|Medium| |331|[Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/) | [C++](./algorithms/cpp/verifyPreorderSerializationOfABinaryTree/VerifyPreorderSerializationOfABinaryTree.cpp)|Medium| |330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium| |329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp)|Medium| diff --git a/algorithms/cpp/reconstructItinerary/ReconstructItinerary.cpp b/algorithms/cpp/reconstructItinerary/ReconstructItinerary.cpp new file mode 100644 index 000000000..a80974833 --- /dev/null +++ b/algorithms/cpp/reconstructItinerary/ReconstructItinerary.cpp @@ -0,0 +1,78 @@ +// Source : https://leetcode.com/problems/reconstruct-itinerary/ +// Author : Hao Chen +// Date : 2017-01-06 + +/*************************************************************************************** + * + * Given a list of airline tickets represented by pairs of departure and arrival + * airports [from, to], reconstruct the itinerary in order. All of the tickets belong + * to a man who departs from JFK. Thus, the itinerary must begin with JFK. + * + * Note: + * + * If there are multiple valid itineraries, you should return the itinerary that has + * the smallest lexical order when read as a single string. For example, the itinerary + * ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. + * All airports are represented by three capital letters (IATA code). + * You may assume all tickets form at least one valid itinerary. + * + * Example 1: + * tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] + * Return ["JFK", "MUC", "LHR", "SFO", "SJC"]. + * + * Example 2: + * tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] + * Return ["JFK","ATL","JFK","SFO","ATL","SFO"]. + * Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it + * is larger in lexical order. + * + * Credits:Special thanks to @dietpepsi for adding this problem and creating all test + * cases. + ***************************************************************************************/ + +/* + This problem's description really confuse me. + + for examples: + 1) [["JFK", "PEK"], ["JFK", "SHA"], ["SHA", "JFK"]], which has two itineraries: + a) JFK -> PEK, + b) JFK -> SHA -> JFK -> PEK + The a) is smaller than b), because PEK < SHA, however the b) is correct answer. + So, it means we need use all of tickets. + + 2) [["JFK", "PEK"], ["JFK", "SHA"]], which also has two itineraries: + a) JFK -> PEK + b) JFK -> SHA + for my understanding, the JFK -> SHA is the correct one, + however, the correct answer is JFK -> SHA -> PEK. + I don't understand, why the correct answer is not JFK -> PEK -> SHA + That really does not make sense to me. + + All right, we need assume all of the tickets can be connected in one itinerary. + Then, it's easy to have a DFS algorithm. +*/ + + +class Solution { +public: + //DFS + void travel(string& start, unordered_map>& map, vector& result) { + while (map[start].size() > 0 ) { + string next = *(map[start].begin()); + map[start].erase(map[start].begin()); + travel(next, map, result); + } + result.insert(result.begin(), start); + } + + vector findItinerary(vector> tickets) { + unordered_map> map; + for(auto t : tickets) { + map[t.first].insert(t.second); + } + vector result; + string start = "JFK"; + travel(start, map, result); + return result; + } +}; From 271fb95e6fddb59d335508564b9f397b86a679cf Mon Sep 17 00:00:00 2001 From: Vali Date: Mon, 9 Jan 2017 14:02:59 +0200 Subject: [PATCH 104/105] added totalHammingDistance --- README.md | 1 + .../totalHammingDistance.cpp | 56 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp diff --git a/README.md b/README.md index 31777f982..594d50bb1 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|477|[Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp)|Medium| |415|[Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./algorithms/cpp/addStrings/AddStrings.cpp)|Easy| |414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp)|Easy| |413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium| diff --git a/algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp b/algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp new file mode 100644 index 000000000..27971e2b0 --- /dev/null +++ b/algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp @@ -0,0 +1,56 @@ +// Source : https://leetcode.com/problems/total-hamming-distance/ +// Author : Calinescu Valentin +// Date : 2017-01-09 + +/*************************************************************************************** + * + * The Hamming distance between two integers is the number of positions at which the + * corresponding bits are different. + * + * Now your job is to find the total Hamming distance between all pairs of the given + * numbers. + * + * Example: + * Input: 4, 14, 2 + * + * Output: 6 + * + * Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just + * showing the four bits relevant in this case). So the answer will be: + * HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. + * + * Note: + * Elements of the given array are in the range of 0 to 10^9 + * Length of the array will not exceed 10^4. + ***************************************************************************************/ + +/* +* Solution 1 - O(N) +* +* The total Hamming Distance is equal to the sum of all individual Hamming Distances +* between every 2 numbers. However, given that this depends on the individual bits of +* each number, we can see that we only need to compute the number of 1s and 0s for each +* bit position. For example, we look at the least significant bit. Given that we need to +* calculate the Hamming Distance for each pair of 2 numbers, we see that the answer is +* equal to the number of 1s at this position * the number of 0s(which is the total number +* of numbers - the number of 1s), because for each 1 we need to have a 0 to form a pair. +* Thus, the solution is the sum of all these distances at every position. +*/ +class Solution { +public: + int totalHammingDistance(vector& nums) { + long long solution = 0; + int ones[31]; + for(int i = 0; i < 31; i++) + ones[i] = 0; + for(vector::iterator it = nums.begin(); it != nums.end(); ++it) + { + for(int i = 0; (1 << i) <= *it; i++) //i is the position of the bit + if((1 << i) & *it)//to see if the bit at i-position is a 1 + ones[i]++; + } + for(int i = 0; i < 31; i++) + solution += ones[i] * (nums.size() - ones[i]); + return solution; + } +}; From 9f88e7c1397c2a8169a2c60af577971e7110cb15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E8=82=B1?= Date: Sun, 26 Feb 2017 18:11:48 +0800 Subject: [PATCH 105/105] add: twoSum solution. --- algorithms/js/twoSum/twoSum.js | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 algorithms/js/twoSum/twoSum.js diff --git a/algorithms/js/twoSum/twoSum.js b/algorithms/js/twoSum/twoSum.js new file mode 100644 index 000000000..3a33d13e2 --- /dev/null +++ b/algorithms/js/twoSum/twoSum.js @@ -0,0 +1,36 @@ +// Source : https://oj.leetcode.com/problems/two-sum/ +// Author : Albin Zeng. +// Date : 2017-02-26 + +/********************************************************************************** +* +* Given an array of integers, find two numbers such that they add up to a specific target number. +* +* The function twoSum should return indices of the two numbers such that they add up to the target, +* where index1 must be less than index2. Please note that your returned answers (both index1 and index2) +* are not zero-based. +* +* You may assume that each input would have exactly one solution. +* +* Input: numbers={2, 7, 11, 15}, target=9 +* Output: index1=1, index2=2 +* +* +**********************************************************************************/ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function(nums, target) { + const map = {}; + let i = 0; + for (; i < nums.length; i++) { + if (undefined === map[target - nums[i]]) { + map[nums[i]] = i; + } else { + return [map[target - nums[i]], i]; + } + } +};