From 6f08c06c4f89456ba2817594b5a1eb47e940ed5c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Jan 2015 13:27:27 +0800 Subject: [PATCH 0001/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c7c3ea16e..ebdd7e29d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-13), there are total `180` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-16), there are total `181` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `180` problems. +Here is the classification of all `181` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -717,6 +717,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | +[Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | [Second Highest Salary] | [second-highest-salary.sql] | _O(n)_ | _O(1)_ | Easy | @@ -725,6 +726,8 @@ Problem | Solution | Time | Space | Difficul [combine-two-tables.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/combine-two-tables.sql [Consecutive Numbers]:https://oj.leetcode.com/problems/consecutive-numbers/ [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql +[Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ +[employees-earning-more-than-their-managers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/employees-earning-more-than-their-managers.sql [Nth Highest Salary]:https://oj.leetcode.com/problems/nth-highest-salary/ [nth-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/nth-highest-salary.sql [Rank Scores]:https://oj.leetcode.com/problems/rank-scores/ From bc454a270b4b3de317cf1d30a9c7fbe0e015bb52 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Jan 2015 13:33:46 +0800 Subject: [PATCH 0002/1939] Create employees-earning-more-than-their-managers.sql --- ...oyees-earning-more-than-their-managers.sql | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 MySQL/employees-earning-more-than-their-managers.sql diff --git a/MySQL/employees-earning-more-than-their-managers.sql b/MySQL/employees-earning-more-than-their-managers.sql new file mode 100644 index 000000000..414f87f53 --- /dev/null +++ b/MySQL/employees-earning-more-than-their-managers.sql @@ -0,0 +1,37 @@ +# Time: O(n^2) +# Space: O(1) +# +# The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id. +# +# +----+-------+--------+-----------+ +# | Id | Name | Salary | ManagerId | +# +----+-------+--------+-----------+ +# | 1 | Joe | 70000 | 3 | +# | 2 | Henry | 80000 | 4 | +# | 3 | Sam | 60000 | NULL | +# | 4 | Max | 90000 | NULL | +# +----+-------+--------+-----------+ +# Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager. +# +# +----------+ +# | Employee | +# +----------+ +# | Joe | +# +----------+ +# + +# Time: O(n^2) +# Space: O(n) +# Write your MySQL query statement below +SELECT e.Name AS Employee FROM Employee e LEFT JOIN Employee b + ON e.ManagerId=b.Id + WHERE e.Salary > b.Salary + +# Time: O(n^2) +# Space: O(1) +# Write your MySQL query statement below +SELECT Name AS Employee + FROM Employee e + WHERE e.Salary > (SELECT Salary + FROM Employee + WHERE e.ManagerId = Id) From 5a5f2618d14a9da61287e225815077c611c5fb58 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Jan 2015 13:36:23 +0800 Subject: [PATCH 0003/1939] Update employees-earning-more-than-their-managers.sql --- MySQL/employees-earning-more-than-their-managers.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/employees-earning-more-than-their-managers.sql b/MySQL/employees-earning-more-than-their-managers.sql index 414f87f53..eaafe2a00 100644 --- a/MySQL/employees-earning-more-than-their-managers.sql +++ b/MySQL/employees-earning-more-than-their-managers.sql @@ -32,6 +32,6 @@ SELECT e.Name AS Employee FROM Employee e LEFT JOIN Employee b # Write your MySQL query statement below SELECT Name AS Employee FROM Employee e - WHERE e.Salary > (SELECT Salary + WHERE e.ManagerId IS NOT NULL AND e.Salary > (SELECT Salary FROM Employee WHERE e.ManagerId = Id) From 7eb2f366b5d64b4f97809080db57644c28510ccb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Jan 2015 23:45:38 +0800 Subject: [PATCH 0004/1939] Create duplicate-emails.sql --- Python/duplicate-emails.sql | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/duplicate-emails.sql diff --git a/Python/duplicate-emails.sql b/Python/duplicate-emails.sql new file mode 100644 index 000000000..836ad0490 --- /dev/null +++ b/Python/duplicate-emails.sql @@ -0,0 +1,24 @@ +# Time: O(n^2) +# Space: O(n) +# +# Write a SQL query to find all duplicate emails in a table named Person. +# +# +----+---------+ +# | Id | Email | +# +----+---------+ +# | 1 | a@b.com | +# | 2 | c@d.com | +# | 3 | a@b.com | +# +----+---------+ +# For example, your query should return the following for the above table: +# +# +---------+ +# | Email | +# +---------+ +# | a@b.com | +# +---------+ +# Note: All emails are in lowercase. +# + +# Write your MySQL query statement below +SELECT Email FROM Person GROUP BY Email HAVING COUNT(*) > 1 From c36d86db0554b1fc1b709bf6a0d28733f5bbccca Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 18 Jan 2015 23:46:24 +0800 Subject: [PATCH 0005/1939] update --- {Python => MySQL}/duplicate-emails.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Python => MySQL}/duplicate-emails.sql (100%) diff --git a/Python/duplicate-emails.sql b/MySQL/duplicate-emails.sql similarity index 100% rename from Python/duplicate-emails.sql rename to MySQL/duplicate-emails.sql From c5534064db2f597aa1fa6403848a7d21b7c29c05 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 18 Jan 2015 23:50:36 +0800 Subject: [PATCH 0006/1939] update --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ebdd7e29d..3f8e2ccea 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-16), there are total `181` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-18), there are total `182` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `181` problems. +Here is the classification of all `182` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -717,6 +717,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | +[Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | @@ -726,6 +727,8 @@ Problem | Solution | Time | Space | Difficul [combine-two-tables.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/combine-two-tables.sql [Consecutive Numbers]:https://oj.leetcode.com/problems/consecutive-numbers/ [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql +[Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ +[duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql [Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ [employees-earning-more-than-their-managers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/employees-earning-more-than-their-managers.sql [Nth Highest Salary]:https://oj.leetcode.com/problems/nth-highest-salary/ From d857776f65ecbac0785c7c46a908b95db689222a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Jan 2015 13:41:08 +0800 Subject: [PATCH 0007/1939] Rename surrounded-region.py to surrounded-regions.py --- Python/{surrounded-region.py => surrounded-regions.py} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename Python/{surrounded-region.py => surrounded-regions.py} (99%) diff --git a/Python/surrounded-region.py b/Python/surrounded-regions.py similarity index 99% rename from Python/surrounded-region.py rename to Python/surrounded-regions.py index a16bbee0b..bec979730 100644 --- a/Python/surrounded-region.py +++ b/Python/surrounded-regions.py @@ -57,4 +57,4 @@ def solve(self, board): ['X', 'X', 'O', 'X'], ['X', 'O', 'X', 'X']] Solution().solve(board) - print board \ No newline at end of file + print board From beae3d588f120f990f8ecb745f771b6ed193d5c5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 13:46:27 +0800 Subject: [PATCH 0008/1939] Create customers-who-never-order.sql --- MySQL/customers-who-never-order.sql | 42 +++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 MySQL/customers-who-never-order.sql diff --git a/MySQL/customers-who-never-order.sql b/MySQL/customers-who-never-order.sql new file mode 100644 index 000000000..c63d41aaa --- /dev/null +++ b/MySQL/customers-who-never-order.sql @@ -0,0 +1,42 @@ +# Time: O(n^2) +# Space: O(1) +# +# Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything. +# +# Table: Customers. +# +# +----+-------+ +# | Id | Name | +# +----+-------+ +# | 1 | Joe | +# | 2 | Henry | +# | 3 | Sam | +# | 4 | Max | +# +----+-------+ +# Table: Orders. +# +# +----+------------+ +# | Id | CustomerId | +# +----+------------+ +# | 1 | 3 | +# | 2 | 1 | +# +----+------------+ +# Using the above tables as example, return the following: +# +# +-----------+ +# | Customers | +# +-----------+ +# | Henry | +# | Max | +# +-----------+ +# + +# Time: O(n^2) +# Space: O(1) +# Write your MySQL query statement below +SELECT Name AS Customers FROM Customers WHERE Id NOT IN (SELECT CustomerId FROM Orders) + +# Time: O(n^2) +# Space: O(n) +# Write your MySQL query statement below +SELECT Customers.Name AS Customers FROM (Customers LEFT JOIN Orders ON Customers.Id = Orders.CustomerId) WHERE Orders.CustomerId IS NULL From 6cfd88163c5678bd2a22d29b2aab2cae084c4ac2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 13:48:41 +0800 Subject: [PATCH 0009/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3f8e2ccea..bbf33b400 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-18), there are total `182` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-21), there are total `183` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `182` problems. +Here is the classification of all `183` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -717,6 +717,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | +[Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | [Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | @@ -727,6 +728,8 @@ Problem | Solution | Time | Space | Difficul [combine-two-tables.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/combine-two-tables.sql [Consecutive Numbers]:https://oj.leetcode.com/problems/consecutive-numbers/ [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql +[Customers Who Never Order]:https://oj.leetcode.com/problems/customers-who-never-order/ +[customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql [Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ [duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql [Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ From 21025462833cc33578e7308c622cb28d4715cb38 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 14:50:28 +0800 Subject: [PATCH 0010/1939] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 47 +++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 47f6c6862..644f74927 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -1,11 +1,52 @@ # Time: O(log(m + n)) -# Space: O(log(m + n)) +# Space: O(1) # # There are two sorted arrays A and B of size m and n respectively. # Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). # class Solution: + # @return a float + def findMedianSortedArrays(self, A, B): + lenA, lenB = len(A), len(B) + if (lenA + lenB) % 2 == 1: + return self.getKth(A, B, (lenA + lenB)/2 + 1) + else: + return (self.getKth(A, B, (lenA + lenB)/2) + self.getKth(A, B, (lenA + lenB)/2 + 1)) * 0.5 + + def getKth(self, A, B, k): + b = max(0, k - len(B)) + t = min(len(A), k) + while b < t: + x = b + (t - b) / 2 + A_x_1, A_x, B_k_x_1, B_k_x = float("-inf"), float("inf"), float("-inf"), float("inf") + if x > 0: + A_x_1 = A[x - 1] + if x < len(A): + A_x = A[x] + if k - x > 0: + B_k_x_1 = B[k - x - 1] + if k - x < len(B): + B_k_x = B[k - x] + + if A_x < B_k_x_1: + b = x + 1 + elif A_x_1 > B_k_x: + t = x - 1 + else: + return max(A_x_1, B_k_x_1) + + A_b_1, B_k_b_1 = float("-inf"), float("-inf") + if b > 0: + A_b_1 = A[b - 1] + if k - b - 1 >= 0: + B_k_b_1 = B[k - b - 1] + + return max(A_b_1, B_k_b_1) + +# Time: O(log(m + n)) +# Space: O(log(m + n)) +class Solution2: # @return a float def findMedianSortedArrays(self, A, B): lenA, lenB = len(A), len(B) @@ -36,7 +77,7 @@ def getKth(self, A, i, B, j, k): return A[i + pa - 1] # using list slicing (O(k)) may be slower than solution1 -class Solution2: +class Solution3: # @return a float def findMedianSortedArrays(self, A, B): lenA, lenB = len(A), len(B) @@ -69,4 +110,4 @@ def getKth(self, A, B, k): if __name__ == "__main__": print Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6]) print Solution().findMedianSortedArrays([1, 3, 5], [2, 4, 6]) - \ No newline at end of file + From d72a56643b64e8c268c59ac96a5c7152a995ca93 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 14:51:30 +0800 Subject: [PATCH 0011/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bbf33b400..31a3d155e 100644 --- a/README.md +++ b/README.md @@ -496,7 +496,7 @@ Problem | Solution | Time | Space | Difficul [Find Minimum in Rotated Sorted Array] | [find-minimum-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Medium | [Find Minimum in Rotated Sorted Array II] | [find-minimum-in-rotated-sorted-array-ii.py] | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard | [Find Peak Element] | [find-peak-element.py] | _O(logn)_ | _O(1)_ | Medium | -[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n)_ | _O(log(m + n)_ | Hard | +[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n)_ | _O(1)_ | Hard | [Pow(x, n)] | [powx-n.py] | _O(logn)_ | _O(logn)_ | Medium | [Search a 2D Matrix] | [search-a-2d-matrix.py] | _O(log m + logn)_ | _O(1)_ | Medium | [Search for a Range] | [search-for-a-range.py] | _O(logn)_ | _O(1)_ | Medium | From cae03ab91f32a0a6bc846aefb81f4cc78277bfb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 22:54:54 +0800 Subject: [PATCH 0012/1939] Create department-highest-salary --- MySQL/department-highest-salary | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 MySQL/department-highest-salary diff --git a/MySQL/department-highest-salary b/MySQL/department-highest-salary new file mode 100644 index 000000000..1c5670253 --- /dev/null +++ b/MySQL/department-highest-salary @@ -0,0 +1,42 @@ +# Time: O(n^2) +# Space: O(n) +# +# The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id. +# +# +----+-------+--------+--------------+ +# | Id | Name | Salary | DepartmentId | +# +----+-------+--------+--------------+ +# | 1 | Joe | 70000 | 1 | +# | 2 | Henry | 80000 | 2 | +# | 3 | Sam | 60000 | 2 | +# | 4 | Max | 90000 | 1 | +# +----+-------+--------+--------------+ +# The Department table holds all departments of the company. +# +# +----+----------+ +# | Id | Name | +# +----+----------+ +# | 1 | IT | +# | 2 | Sales | +# +----+----------+ +# Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department. +# +# +------------+----------+--------+ +# | Department | Employee | Salary | +# +------------+----------+--------+ +# | IT | Max | 90000 | +# | Sales | Henry | 80000 | +# +------------+----------+--------+ +# +# Write your MySQL query statement below +SELECT d.Department AS Department, e.Name AS Employee, d.Salary AS Salary +FROM (SELECT Department.Id AS DepartmentId, Department.Name AS Department, emp.Salary AS Salary + FROM Department JOIN (SELECT DepartmentId, MAX(Salary) AS Salary FROM Employee GROUP BY Employee.DepartmentId) emp + ON Department.Id = emp.DepartmentId) d + JOIN Employee e + ON e.DepartmentId = d.DepartmentId and e.Salary = d.Salary + +# Write your MySQL query statement below +SELECT Department.Name AS Department, Employee.Name AS Employee, Employee.Salary AS Salary +FROM Department JOIN Employee ON Employee.DepartmentId = Department.Id +WHERE Employee.Salary IN (SELECT MAX(e.Salary) FROM Employee e WHERE e.DepartmentId = Employee.DepartmentId) From 00103491530d2495f4118070ee1b011f783e1909 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 22:57:33 +0800 Subject: [PATCH 0013/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 31a3d155e..323a2a7fd 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-21), there are total `183` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-21), there are total `184` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `183` problems. +Here is the classification of all `184` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -718,6 +718,7 @@ Problem | Solution | Time | Space | Difficul [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | [Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | +[Department Highest Salary] | [department-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | @@ -730,6 +731,8 @@ Problem | Solution | Time | Space | Difficul [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql [Customers Who Never Order]:https://oj.leetcode.com/problems/customers-who-never-order/ [customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql +[Department Highest Salary]:https://oj.leetcode.com/problems/department-highest-salary/ +[department-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-highest-salary.sql [Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ [duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql [Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ From fa62b597a6db1f38d67ff07e68f1625a2ed99533 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 22:58:20 +0800 Subject: [PATCH 0014/1939] Rename department-highest-salary to department-highest-salary.sql --- .../{department-highest-salary => department-highest-salary.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename MySQL/{department-highest-salary => department-highest-salary.sql} (100%) diff --git a/MySQL/department-highest-salary b/MySQL/department-highest-salary.sql similarity index 100% rename from MySQL/department-highest-salary rename to MySQL/department-highest-salary.sql From 34052c1ffd070951e71c09ad8a6bed3ed3903e70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jan 2015 22:59:54 +0800 Subject: [PATCH 0015/1939] Update department-highest-salary.sql --- MySQL/department-highest-salary.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/department-highest-salary.sql b/MySQL/department-highest-salary.sql index 1c5670253..69c88f734 100644 --- a/MySQL/department-highest-salary.sql +++ b/MySQL/department-highest-salary.sql @@ -31,7 +31,7 @@ # Write your MySQL query statement below SELECT d.Department AS Department, e.Name AS Employee, d.Salary AS Salary FROM (SELECT Department.Id AS DepartmentId, Department.Name AS Department, emp.Salary AS Salary - FROM Department JOIN (SELECT DepartmentId, MAX(Salary) AS Salary FROM Employee GROUP BY Employee.DepartmentId) emp + FROM Department JOIN (SELECT DepartmentId, MAX(Salary) AS Salary FROM Employee GROUP BY DepartmentId) emp ON Department.Id = emp.DepartmentId) d JOIN Employee e ON e.DepartmentId = d.DepartmentId and e.Salary = d.Salary From f29dca95c593bcfd229bf618da20de1f6050c58b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jan 2015 00:21:22 +0800 Subject: [PATCH 0016/1939] Update single-number-ii.py --- Python/single-number-ii.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Python/single-number-ii.py b/Python/single-number-ii.py index e725ccf8a..a9fe759e6 100644 --- a/Python/single-number-ii.py +++ b/Python/single-number-ii.py @@ -8,6 +8,15 @@ # class Solution: + # @param A, a list of integer + # @return an integer + def singleNumber(self, A): + one, two, carry = 0, 0, 0 + for x in A: + one, two = (~x & one) | (x & ~one & ~two), (~x & two) | (x & one) + return one + +class Solution2: # @param A, a list of integer # @return an integer def singleNumber(self, A): @@ -21,4 +30,4 @@ def singleNumber(self, A): return one if __name__ == "__main__": - print Solution().singleNumber([1, 1, 1, 2, 2, 2, 3]) \ No newline at end of file + print Solution().singleNumber([1, 1, 1, 2, 2, 2, 3]) From 413554178979ef2b9da521896550da8dcbdfc687 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jan 2015 22:00:23 +0800 Subject: [PATCH 0017/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 323a2a7fd..676d6f50b 100644 --- a/README.md +++ b/README.md @@ -273,7 +273,7 @@ Problem | Solution | Time | Space | Difficul [Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | -[Minimum Window Substring] | [minimum-window-substring.py] | _O(n^2)_ | _O(n)_ | Hard | +[Minimum Window Substring] | [minimum-window-substring.py] | _O(n)_ | _O(k)_ | Hard | [Substring with Concatenation of All Words] | [substring-with-concatenation-of-all-words.py] | _O(m * n * k)_ | _O(n * k)_ | Hard | [Two Sum] | [two-sum.py] | _O(n)_ | _O(n)_ | Medium | [Two Sum III - Data structure design] | [two-sum-iii-data-structure-design.py] | _O(n)_ | _O(n)_ | Easy | From ee9bc351caa2b52519485fb1093a0d37a610c975 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jan 2015 22:15:24 +0800 Subject: [PATCH 0018/1939] Update minimum-window-substring.py --- Python/minimum-window-substring.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/minimum-window-substring.py b/Python/minimum-window-substring.py index 37a001902..03c52ff64 100644 --- a/Python/minimum-window-substring.py +++ b/Python/minimum-window-substring.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(1) +# Space: O(k), k is # # Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). # From 2cbf418847ef9943e032d33e74fb591e74eab89d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jan 2015 22:16:28 +0800 Subject: [PATCH 0019/1939] Update minimum-window-substring.py --- Python/minimum-window-substring.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/minimum-window-substring.py b/Python/minimum-window-substring.py index 03c52ff64..687402e30 100644 --- a/Python/minimum-window-substring.py +++ b/Python/minimum-window-substring.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(k), k is +# Space: O(k), k is the number of different characters # # Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). # From 9dbf6e76b8b0ee555d0a43325bb1aa7991ac1eca Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Jan 2015 00:22:59 +0800 Subject: [PATCH 0020/1939] Create department-top-three-salaries.sql --- MySQL/department-top-three-salaries.sql | 41 +++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 MySQL/department-top-three-salaries.sql diff --git a/MySQL/department-top-three-salaries.sql b/MySQL/department-top-three-salaries.sql new file mode 100644 index 000000000..337c3ff81 --- /dev/null +++ b/MySQL/department-top-three-salaries.sql @@ -0,0 +1,41 @@ +# Time: O(n^2) +# Space: O(n) +# +# The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id. +# +# +----+-------+--------+--------------+ +# | Id | Name | Salary | DepartmentId | +# +----+-------+--------+--------------+ +# | 1 | Joe | 70000 | 1 | +# | 2 | Henry | 80000 | 2 | +# | 3 | Sam | 60000 | 2 | +# | 4 | Max | 90000 | 1 | +# | 5 | Janet | 69000 | 1 | +# | 6 | Randy | 85000 | 1 | +# +----+-------+--------+--------------+ +# The Department table holds all departments of the company. +# +# +----+----------+ +# | Id | Name | +# +----+----------+ +# | 1 | IT | +# | 2 | Sales | +# +----+----------+ +# Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows. +# +# +------------+----------+--------+ +# | Department | Employee | Salary | +# +------------+----------+--------+ +# | IT | Max | 90000 | +# | IT | Randy | 85000 | +# | IT | Joe | 70000 | +# | Sales | Henry | 80000 | +# | Sales | Sam | 60000 | +# +------------+----------+--------+ + +# Write your MySQL query statement below +SELECT D.Name AS Department, E.Name AS Employee, E.Salary AS Salary +FROM Employee E INNER JOIN Department D ON E.DepartmentId = D.Id +WHERE (SELECT COUNT(DISTINCT(Salary)) FROM Employee + WHERE DepartmentId = E.DepartmentId AND Salary > E.Salary) < 3 +ORDER by E.DepartmentId, E.Salary DESC; From 41b185d9251660903c68396ea27d2fe61834d1c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Jan 2015 00:26:25 +0800 Subject: [PATCH 0021/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 676d6f50b..a30f18cdc 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-21), there are total `184` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-01-24), there are total `185` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `184` problems. +Here is the classification of all `185` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -719,6 +719,7 @@ Problem | Solution | Time | Space | Difficul [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | [Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | [Department Highest Salary] | [department-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | +[Department Top Three Salaries] | [department-top-three-salaries.sql] | _O(n^2)_ | _O(n)_ | Hard | [Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | @@ -733,6 +734,8 @@ Problem | Solution | Time | Space | Difficul [customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql [Department Highest Salary]:https://oj.leetcode.com/problems/department-highest-salary/ [department-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-highest-salary.sql +[Department Top Three Salaries]:https://oj.leetcode.com/problems/department-top-three-salaries/ +[department-top-three-salaries.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-top-three-salaries.sql [Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ [duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql [Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ From 7d880f9e79e690078dbbed8283ddd6a83ce6db91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 29 Jan 2015 11:42:36 +0800 Subject: [PATCH 0022/1939] Update wildcard-matching.py --- Python/wildcard-matching.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index ebd9f1c49..cf2d464b8 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -48,7 +48,9 @@ def isMatch(self, s, p): return p_ptr == len(p) -# dp +# dp with rolling window +# Time: O(m * n) +# Space: O(m + n) class Solution2: # @return a boolean def isMatch(self, s, p): @@ -120,4 +122,4 @@ def isMatch(self, s, p): print Solution().isMatch("aa", "a*") print Solution().isMatch("aa", "?*") print Solution().isMatch("ab", "?*") - print Solution().isMatch("aab", "c*a*b") \ No newline at end of file + print Solution().isMatch("aab", "c*a*b") From 282f51f19ebec2d10b85a417c8fa34987d1e2dc8 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Fri, 30 Jan 2015 00:25:39 +0800 Subject: [PATCH 0023/1939] fix solution3 bug --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index f6c6d2746..5c6b31a3e 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -74,7 +74,7 @@ def isMatch(self, s, p): return len(s) == 0 if len(p) == 1 or p[1] != '*': - if len(s) == 0 or (p[0] == s[0] or p[0] == '.'): + if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): return self.isMatch(s[1:], p[1:]) else: return False From b349f841bdbb8cf6ae3722128c93d433c77ea72a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 30 Jan 2015 00:26:25 +0800 Subject: [PATCH 0024/1939] Update regular-expression-matching.py --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 5c6b31a3e..28ff51e67 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -74,7 +74,7 @@ def isMatch(self, s, p): return len(s) == 0 if len(p) == 1 or p[1] != '*': - if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): + if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): return self.isMatch(s[1:], p[1:]) else: return False From 25867bf77aeb6c5f8f4eddc6eab92aa7a2bad54f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Fri, 30 Jan 2015 01:04:21 +0800 Subject: [PATCH 0025/1939] add extended solution --- Python/single-number-ii.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Python/single-number-ii.py b/Python/single-number-ii.py index a9fe759e6..0e97ce970 100644 --- a/Python/single-number-ii.py +++ b/Python/single-number-ii.py @@ -11,7 +11,7 @@ class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): - one, two, carry = 0, 0, 0 + one, two = 0, 0 for x in A: one, two = (~x & one) | (x & ~one & ~two), (~x & two) | (x & one) return one @@ -29,5 +29,16 @@ def singleNumber(self, A): two &= ~carry return one +# every element appears 4 times except for one with 2 times +class SolutionEX: + # @param A, a list of integer + # @return an integer + # [1, 1, 1, 1, 2, 2, 2, 2, 3, 3] + def singleNumber(self, A): + one, two, three = 0, 0, 0 + for x in A: + one, two, three = (~x & one) | (x & ~one & ~two & ~three), (~x & two) | (x & one), (~x & three) | (x & two) + return two + if __name__ == "__main__": print Solution().singleNumber([1, 1, 1, 2, 2, 2, 3]) From a84d9dbac6704320b5f52c52271d8791d7d0dfa0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Feb 2015 01:24:08 +0800 Subject: [PATCH 0026/1939] Update word-ladder.py --- Python/word-ladder.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/word-ladder.py b/Python/word-ladder.py index 8ed2f6c97..c8aebed3d 100644 --- a/Python/word-ladder.py +++ b/Python/word-ladder.py @@ -1,5 +1,5 @@ -# Time: O((25n)^n) -# Space: O((25n)^n) +# Time: O(nd), n is length of string, d is size of dictionary +# Space: O(d) # # Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: # From fe953af8f1c08efb804f3cde02c58bcc3f2b605a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Feb 2015 01:27:23 +0800 Subject: [PATCH 0027/1939] Update word-ladder-ii.py --- Python/word-ladder-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/word-ladder-ii.py b/Python/word-ladder-ii.py index 501fd94fa..2838f1da5 100644 --- a/Python/word-ladder-ii.py +++ b/Python/word-ladder-ii.py @@ -1,5 +1,5 @@ -# Time: O((25n)^n) -# Space: O((25n)^n) +# Time: O(n * d), n is length of string, d is size of dictionary +# Space: O(d) # # Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: # From 0d8cb9da1242bf9aa918d16c0f0f3a6d5cdba91d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Feb 2015 01:27:45 +0800 Subject: [PATCH 0028/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a30f18cdc..54689951b 100644 --- a/README.md +++ b/README.md @@ -539,7 +539,7 @@ Problem | Solution | Time | Space | Difficul [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | [Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | -[Word Ladder] |[word-ladder.py] | _O((25n)^n)_ | _O((25n)^n)_ | Medium | +[Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | [Binary Tree Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ [binary-tree-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal.py @@ -671,7 +671,7 @@ Problem | Solution | Time | Space | Difficul ##Backtracking Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Word Ladder II] |[word-ladder-ii.py] | _O((25n)^n)_ | _O((25n)^n)_ | Hard | +[Word Ladder II] |[word-ladder-ii.py] | _O(n * d)_ | _O(d)_ | Hard | [Word Ladder II]:https://oj.leetcode.com/problems/word-ladder-ii/ [word-ladder-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-ladder-ii.py From 08be9fdf8a962b30192aabc58babd03a0a83eb6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Feb 2015 01:28:08 +0800 Subject: [PATCH 0029/1939] Update word-ladder.py --- Python/word-ladder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-ladder.py b/Python/word-ladder.py index c8aebed3d..17cdb9a77 100644 --- a/Python/word-ladder.py +++ b/Python/word-ladder.py @@ -1,4 +1,4 @@ -# Time: O(nd), n is length of string, d is size of dictionary +# Time: O(n * d), n is length of string, d is size of dictionary # Space: O(d) # # Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: From d5b052b849bde7a38d4a46edb4f3d0bc769dd4a0 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 3 Feb 2015 22:05:40 +0800 Subject: [PATCH 0030/1939] update --- Python/reverse-words-in-a-string-ii.py | 34 ++++++++++++++++++++++++++ README.md | 7 ++++-- 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 Python/reverse-words-in-a-string-ii.py diff --git a/Python/reverse-words-in-a-string-ii.py b/Python/reverse-words-in-a-string-ii.py new file mode 100644 index 000000000..09bd7f87b --- /dev/null +++ b/Python/reverse-words-in-a-string-ii.py @@ -0,0 +1,34 @@ +# Time: O(n) +# Space:O(1) +# +# Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. +# +# The input string does not contain leading or trailing spaces and the words are always separated by a single space. +# +# For example, +# Given s = "the sky is blue", +# return "blue is sky the". +# +# Could you do it in-place without allocating extra space? +# + +class Solution: + # @param s, a list of 1 length strings, e.g., s = ['h','e','l','l','o'] + # @return nothing + def reverseWords(self, s): + self.reverse(s, 0, len(s)) + + i = 0 + for j in xrange(len(s) + 1): + if j == len(s) or s[j] == ' ': + self.reverse(s, i, j) + i = j + 1 + + def reverse(self, s, begin, end): + for i in xrange((end - begin) / 2): + s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i] + +if __name__ == '__main__': + s = ['h','e','l','l','o', ' ', 'w', 'o', 'r', 'l', 'd'] + Solution().reverseWords(s) + print s \ No newline at end of file diff --git a/README.md b/README.md index 54689951b..0bb89d4e1 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-01-24), there are total `185` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-02-03), there are total `186` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `185` problems. +Here is the classification of all `186` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -136,6 +136,7 @@ Problem | Solution | Time | Space | Difficul [Multiply Strings] | [multiply-strings.py] | _O(m * n)_ | _O(m + n)_ | Medium | [One Edit Distance] | [one-edit-distance.py] | _O(m + n)_ | _O(1)_ | Medium | [Reverse Words in a String] | [reverse-words-in-a-string.py] | _O(n)_ | _O(n)_ | Medium | +[Reverse Words in a String II] | [reverse-words-in-a-string-ii.py] | _O(n)_ | _O(1)_ | Medium | [String to Integer (atoi)] | [string-to-integer-atoi.py] | _O(n)_ | _O(1)_ | Easy | [Text Justification] | [text-justification.py] | _O(n)_ | _O(1)_ | Hard | [Valid Palindrome] | [valid-palindrome.py] | _O(n)_ | _O(1)_ | Easy | @@ -164,6 +165,8 @@ Problem | Solution | Time | Space | Difficul [one-edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/one-edit-distance.py [Reverse Words in a String]:https://oj.leetcode.com/problems/reverse-words-in-a-string/ [reverse-words-in-a-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-words-in-a-string.py +[Reverse Words in a String II]:https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/ +[reverse-words-in-a-string-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-words-in-a-string-ii.py [String to Integer (atoi)]:https://oj.leetcode.com/problems/string-to-integer-atoi/ [string-to-integer-atoi.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/string-to-integer-atoi.py [Text Justification]:https://oj.leetcode.com/problems/text-justification/ From 6281b0043dffb06d4c3150bd7105e6e8ccf37a76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Feb 2015 22:56:50 +0800 Subject: [PATCH 0031/1939] Update first-missing-positive.py --- Python/first-missing-positive.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/first-missing-positive.py b/Python/first-missing-positive.py index b2fa788f0..134baa714 100644 --- a/Python/first-missing-positive.py +++ b/Python/first-missing-positive.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(n) +# Space: O(1) # # Given an unsorted integer array, find the first missing positive integer. # @@ -28,4 +28,4 @@ def firstMissingPositive(self, A): if __name__ == "__main__": print Solution().firstMissingPositive([1,2,0]) - print Solution().firstMissingPositive([3,4,-1,1]) \ No newline at end of file + print Solution().firstMissingPositive([3,4,-1,1]) From 8fbe5a62645c21bc6ff0e40861506166d4fd3a96 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 4 Feb 2015 00:38:52 +0800 Subject: [PATCH 0032/1939] update --- Python/best-time-to-buy-and-sell-stock-iii.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 7b08da290..d55083324 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -13,6 +13,29 @@ # class Solution: + # @param prices, a list of integer + # @return an integer + def maxProfit(self, prices): + return self.maxKPairsProfit(prices, 2) + + def maxKPairsProfit(self, prices, k): + k_sum = [float("-inf") for _ in xrange(2 * k)] + for i in xrange(len(prices)): + pre_k_sum = list(k_sum) + j, sign = 0, -1 + while j < len(k_sum) and j <= i: + diff = sign * prices[i] + + if j > 0: + diff += pre_k_sum[j - 1] + + k_sum[j] = max(diff, pre_k_sum[j]) + j += 1 + sign *= -1 + + return k_sum[-1] + +class Solution2: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): From 0195c8a9ea680e18a568391dc1a53721074b6195 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 4 Feb 2015 00:52:57 +0800 Subject: [PATCH 0033/1939] update --- Python/best-time-to-buy-and-sell-stock-iii.py | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index d55083324..c7c3504b9 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -12,29 +12,33 @@ # (ie, you must sell the stock before you buy again). # +# Time: O(k^2 * n) +# Space: O(k) class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): - return self.maxKPairsProfit(prices, 2) - + result = 0 + for k in xrange(3): + result = max(result, self.maxKPairsProfit(prices, k)) + return result + def maxKPairsProfit(self, prices, k): + if k == 0 or len(prices) < 2: + return 0 + k_sum = [float("-inf") for _ in xrange(2 * k)] for i in xrange(len(prices)): - pre_k_sum = list(k_sum) - j, sign = 0, -1 + j, sign, pre_k_sum = 0, -1, list(k_sum) while j < len(k_sum) and j <= i: diff = sign * prices[i] - if j > 0: diff += pre_k_sum[j - 1] - k_sum[j] = max(diff, pre_k_sum[j]) - j += 1 - sign *= -1 + j, sign = j + 1, sign * -1 return k_sum[-1] - + class Solution2: # @param prices, a list of integer # @return an integer From 01d27c7b9578dc399bcb9a33255e5c43b6f4b903 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 4 Feb 2015 01:01:02 +0800 Subject: [PATCH 0034/1939] update --- Python/best-time-to-buy-and-sell-stock-iii.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index c7c3504b9..441daa3a2 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -12,9 +12,24 @@ # (ie, you must sell the stock before you buy again). # +# Time: O(n) +# Space: O(1) +class Solution: + # @param prices, a list of integer + # @return an integer + def maxProfit(self, prices): + hold1, hold2 = float("-inf"), float("-inf") + release1, release2 = 0, 0 + for i in prices: + release2 = max(release2, hold2 + i) + hold2 = max(hold2, release1 - i) + release1 = max(release1, hold1 + i) + hold1 = max(hold1, -i); + return release2 + # Time: O(k^2 * n) # Space: O(k) -class Solution: +class Solution2: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): @@ -39,7 +54,7 @@ def maxKPairsProfit(self, prices, k): return k_sum[-1] -class Solution2: +class Solution3: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): From ef31d85742060d53c08be9c6fc70942128b8dc85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 10:57:24 +0800 Subject: [PATCH 0035/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 441daa3a2..3cb8d7b86 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -29,20 +29,31 @@ def maxProfit(self, prices): # Time: O(k^2 * n) # Space: O(k) -class Solution2: +class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): - result = 0 - for k in xrange(3): - result = max(result, self.maxKPairsProfit(prices, k)) - return result + return self.maxAtMostKPairsProfit(prices, 2) - def maxKPairsProfit(self, prices, k): - if k == 0 or len(prices) < 2: - return 0 + def maxAtMostKPairsProfit(self, prices, k): + k_sum = [float("-inf") for _ in xrange(2 * k)] + for i in xrange(1, len(k_sum), 2): + k_sum[i] = 0 + for i in xrange(len(prices)): + j, sign, pre_k_sum = 0, -1, list(k_sum) + while j < len(k_sum): + diff = sign * prices[i] + if j > 0: + diff += pre_k_sum[j - 1] + k_sum[j] = max(diff, pre_k_sum[j]) + j, sign = j + 1, sign * -1 + + return k_sum[-1] + + def maxExatclyKPairsProfit(self, prices, k): k_sum = [float("-inf") for _ in xrange(2 * k)] + for i in xrange(len(prices)): j, sign, pre_k_sum = 0, -1, list(k_sum) while j < len(k_sum) and j <= i: @@ -53,7 +64,7 @@ def maxKPairsProfit(self, prices, k): j, sign = j + 1, sign * -1 return k_sum[-1] - + class Solution3: # @param prices, a list of integer # @return an integer From cef98212de4da499abb696433193fb4a515e4e2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 11:00:09 +0800 Subject: [PATCH 0036/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 3cb8d7b86..7ba442fad 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -29,7 +29,7 @@ def maxProfit(self, prices): # Time: O(k^2 * n) # Space: O(k) -class Solution: +class Solution2: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): From 74b08301a1b39adf60b6688c1d3602defa2e071c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 21:22:44 +0800 Subject: [PATCH 0037/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0bb89d4e1..4ecd3760d 100644 --- a/README.md +++ b/README.md @@ -280,7 +280,7 @@ Problem | Solution | Time | Space | Difficul [Substring with Concatenation of All Words] | [substring-with-concatenation-of-all-words.py] | _O(m * n * k)_ | _O(n * k)_ | Hard | [Two Sum] | [two-sum.py] | _O(n)_ | _O(n)_ | Medium | [Two Sum III - Data structure design] | [two-sum-iii-data-structure-design.py] | _O(n)_ | _O(n)_ | Easy | -[Valid Sudoku] | [valid-sudoku.py] | _O(n)_ | _O(n)_ | Easy | +[Valid Sudoku] | [valid-sudoku.py] | _O(n^2)_ | _O(n)_ | Easy | [4 Sum]: https://oj.leetcode.com/problems/4sum/ [4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py From ab5cf0020f12317e065e18104908413079721aa1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 23:53:00 +0800 Subject: [PATCH 0038/1939] Update letter-combinations-of-a-phone-number.py --- Python/letter-combinations-of-a-phone-number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/letter-combinations-of-a-phone-number.py b/Python/letter-combinations-of-a-phone-number.py index a818ce42b..a4bbfebc8 100644 --- a/Python/letter-combinations-of-a-phone-number.py +++ b/Python/letter-combinations-of-a-phone-number.py @@ -1,4 +1,4 @@ -# Time: O(4^n) +# Time: O(n * 4^n) # Space: O(1) # # Given a digit string, return all possible letter combinations that the number could represent. @@ -29,7 +29,7 @@ def letterCombinations(self, digits): return result -# Time: O(4^n) +# Time: O(n * 4^n) # Space: O(n) # Recursive Solution class Solution2: From 0a8379ee61a49d19d2fba4c0cc61b01ff0da8d3d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 23:53:58 +0800 Subject: [PATCH 0039/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4ecd3760d..bf94b13ce 100644 --- a/README.md +++ b/README.md @@ -420,7 +420,7 @@ Problem | Solution | Time | Space | Difficul ##Brute Force Search Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(4^n)_ | _O(1)_ | Medium | +[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(1)_ | Medium | [Permutations]| [permutations.py] | _O(n!)_ | _O(n)_ | Medium | [Permutations II]| [permutations-ii.py] | _O(n!)_ | _O(n)_ | Hard | [Subsets] | [subsets.py] | _O(2^n)_ | _O(1)_ | Medium | From 452da7d7b6916950349b802e42f284a09596cb94 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 23:54:53 +0800 Subject: [PATCH 0040/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bf94b13ce..a917dbbed 100644 --- a/README.md +++ b/README.md @@ -420,7 +420,7 @@ Problem | Solution | Time | Space | Difficul ##Brute Force Search Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(1)_ | Medium | +[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(n)_ | Medium | [Permutations]| [permutations.py] | _O(n!)_ | _O(n)_ | Medium | [Permutations II]| [permutations-ii.py] | _O(n!)_ | _O(n)_ | Hard | [Subsets] | [subsets.py] | _O(2^n)_ | _O(1)_ | Medium | From 91926d22a5eeea5c4ece96292e1eb37c96e03949 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Feb 2015 23:55:09 +0800 Subject: [PATCH 0041/1939] Update letter-combinations-of-a-phone-number.py --- Python/letter-combinations-of-a-phone-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/letter-combinations-of-a-phone-number.py b/Python/letter-combinations-of-a-phone-number.py index a4bbfebc8..c3d5e7779 100644 --- a/Python/letter-combinations-of-a-phone-number.py +++ b/Python/letter-combinations-of-a-phone-number.py @@ -1,5 +1,5 @@ # Time: O(n * 4^n) -# Space: O(1) +# Space: O(n) # # Given a digit string, return all possible letter combinations that the number could represent. # From 41f76710b33dbc4b76e98a9cc97d923ed619e6e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Feb 2015 00:01:26 +0800 Subject: [PATCH 0042/1939] Update count-and-say.py --- Python/count-and-say.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/count-and-say.py b/Python/count-and-say.py index 5b55c29a4..325fdc8e5 100644 --- a/Python/count-and-say.py +++ b/Python/count-and-say.py @@ -1,5 +1,5 @@ -# Time: O(n^2) -# Space: O(n) +# Time: O(n * 2^n) +# Space: O(2^n) # # The count-and-say sequence is the sequence of integers beginning as follows: # 1, 11, 21, 1211, 111221, ... From 2caf3e52ea41eb9bfb6e09aea5dab23a4693ba71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Feb 2015 00:02:28 +0800 Subject: [PATCH 0043/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a917dbbed..4931a5c02 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ Problem | Solution | Time | Space | Difficul [Add Binary] | [add-binary.py] | _O(n)_ | _O(1)_ | Easy | [Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | [Compare Version Numbers] | [compare-version-numbers.py] | _O(n)_ | _O(1)_ | Easy | -[Count and Say] | [count-and-say.py]| _O(n^2)_ | _O(n)_ | Easy | +[Count and Say] | [count-and-say.py]| _O(n * 2^n)_ | _O(2^n)_ | Easy | [Implement strStr()] | [implement-strstr.py] | _O(n + m)_ | _O(m)_ | Easy | `KMP Algorithm` [Length of Last Word] | [length-of-last-word.py] | _O(n)_ | _O(1)_ | Easy | [Longest Common Prefix] | [longest-common-prefix.py] | _O(n1 + n2 + ...)_ | _O(1)_ | Easy | From eeecfe5a6624a9a349e679dd2cea1a3942abff72 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 5 Feb 2015 01:51:17 +0800 Subject: [PATCH 0044/1939] update --- Python/text-justification.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/text-justification.py b/Python/text-justification.py index c1a18d1e9..5ccab0e51 100644 --- a/Python/text-justification.py +++ b/Python/text-justification.py @@ -48,18 +48,18 @@ def fullJustify(self, words, L): # count space number spaceCount = L - size if i - begin - 1 > 0 and i < len(words): - everyCount = spaceCount / (i - begin - 1) + everyCount = spaceCount / (i - begin - 1) + 1 spaceCount %= i - begin - 1 else: - everyCount = 0 - + everyCount = 1 + # add space j = begin while j < i: if j == begin: s = words[j] else: - s += ' ' * (everyCount + 1) + s += ' ' * everyCount if spaceCount > 0 and i < len(words): s += ' ' spaceCount -= 1 From 302bc80c3db717627217eea3d669bf790026fb17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Feb 2015 17:13:51 +0800 Subject: [PATCH 0045/1939] Create repeated-dna-sequences --- Python/repeated-dna-sequences | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/repeated-dna-sequences diff --git a/Python/repeated-dna-sequences b/Python/repeated-dna-sequences new file mode 100644 index 000000000..f93278c7f --- /dev/null +++ b/Python/repeated-dna-sequences @@ -0,0 +1,39 @@ +# Time: O(n) +# Space: O(n) +# +# All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, +# for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. +# +# Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. +# +# For example, +# +# Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", +# +# Return: +# ["AAAAACCCCC", "CCCCCAAAAA"]. +# + +class Solution: + # @param s, a string + # @return a list of strings + def findRepeatedDnaSequences(self, s): + hash_table = {} + rolling_hash = 0 + res = [] + + for i in xrange(len(s)): + rolling_hash = rolling_hash << 3 & 0x3fffffff | ord(s[i]) & 7 + if hash_table.get(rolling_hash, None) != None: + if hash_table[rolling_hash]: + res.append(s[i - 9: i + 1]) + hash_table[rolling_hash] = False + else: + hash_table[rolling_hash] = True + + return res + +if __name__ == "__main__": + print Solution().findRepeatedDnaSequences("AAAAAAAAAA") + print Solution().findRepeatedDnaSequences("") + print Solution().findRepeatedDnaSequences("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT") From 5184f59eec1cde1a140141fb7618de97f7c81580 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Feb 2015 17:17:01 +0800 Subject: [PATCH 0046/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4931a5c02..11d38db85 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-02-03), there are total `186` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-02-06), there are total `187` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `186` problems. +Here is the classification of all `187` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -277,6 +277,7 @@ Problem | Solution | Time | Space | Difficul [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | [Minimum Window Substring] | [minimum-window-substring.py] | _O(n)_ | _O(k)_ | Hard | +[Repeated DNA Sequences] | [repeated-dna-sequences.py] | _O(n)_ | _O(n)_ | Medium | [Substring with Concatenation of All Words] | [substring-with-concatenation-of-all-words.py] | _O(m * n * k)_ | _O(n * k)_ | Hard | [Two Sum] | [two-sum.py] | _O(n)_ | _O(n)_ | Medium | [Two Sum III - Data structure design] | [two-sum-iii-data-structure-design.py] | _O(n)_ | _O(n)_ | Easy | @@ -292,6 +293,8 @@ Problem | Solution | Time | Space | Difficul [max-points-on-a-line.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/max-points-on-a-line.py [Minimum Window Substring]:https://oj.leetcode.com/problems/minimum-window-substring/ [minimum-window-substring.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/minimum-window-substring.py +[Repeated DNA Sequences]:https://oj.leetcode.com/problems/repeated-dna-sequences/ +[repeated-dna-sequences.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/repeated-dna-sequences.py [Substring with Concatenation of All Words]:https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/ [substring-with-concatenation-of-all-words.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/substring-with-concatenation-of-all-words.py [Two Sum]:https://oj.leetcode.com/problems/two-sum/ From 8844caa3d8022e94f181252ee2c3d44d58f30673 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Feb 2015 17:18:52 +0800 Subject: [PATCH 0047/1939] Update and rename repeated-dna-sequences to repeated-dna-sequences.py --- ...ated-dna-sequences => repeated-dna-sequences.py} | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) rename Python/{repeated-dna-sequences => repeated-dna-sequences.py} (81%) diff --git a/Python/repeated-dna-sequences b/Python/repeated-dna-sequences.py similarity index 81% rename from Python/repeated-dna-sequences rename to Python/repeated-dna-sequences.py index f93278c7f..79c6fc5c3 100644 --- a/Python/repeated-dna-sequences +++ b/Python/repeated-dna-sequences.py @@ -18,19 +18,18 @@ class Solution: # @param s, a string # @return a list of strings def findRepeatedDnaSequences(self, s): - hash_table = {} + dict = {} rolling_hash = 0 res = [] for i in xrange(len(s)): rolling_hash = rolling_hash << 3 & 0x3fffffff | ord(s[i]) & 7 - if hash_table.get(rolling_hash, None) != None: - if hash_table[rolling_hash]: - res.append(s[i - 9: i + 1]) - hash_table[rolling_hash] = False + if dict.get(rolling_hash, None) is None: + dict[rolling_hash] = True else: - hash_table[rolling_hash] = True - + if dict[rolling_hash]: + res.append(s[i - 9: i + 1]) + dict[rolling_hash] = False return res if __name__ == "__main__": From 286405821b497a03d83b41d64fd36a85b7d400b4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Feb 2015 17:20:02 +0800 Subject: [PATCH 0048/1939] Update repeated-dna-sequences.py --- Python/repeated-dna-sequences.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/repeated-dna-sequences.py b/Python/repeated-dna-sequences.py index 79c6fc5c3..b3b926173 100644 --- a/Python/repeated-dna-sequences.py +++ b/Python/repeated-dna-sequences.py @@ -24,7 +24,7 @@ def findRepeatedDnaSequences(self, s): for i in xrange(len(s)): rolling_hash = rolling_hash << 3 & 0x3fffffff | ord(s[i]) & 7 - if dict.get(rolling_hash, None) is None: + if dict.get(rolling_hash) is None: dict[rolling_hash] = True else: if dict[rolling_hash]: From 799f29e5ea99f409191cc1ca9a1891140eafc02d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Feb 2015 00:04:57 +0800 Subject: [PATCH 0049/1939] Update binary-tree-inorder-traversal.py --- Python/binary-tree-inorder-traversal.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index 5972f569b..5f68d1e39 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -72,9 +72,25 @@ def inorderTraversal(self, root): current = parent.right return result +class Solution3: + # @param root, a tree node + # @return a list of integers + def inorderTraversal(self, root): + result, stack, current, last_traversed = [], [], root, None + while stack or current: + if current: + stack.append(current) + current = current.left + else: + current = stack[-1] + stack.pop() + result.append(current.val) + current = current.right + return result + if __name__ == "__main__": root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) result = Solution().inorderTraversal(root) - print result \ No newline at end of file + print result From 8b17249f535770e0341e2388c3894954cec1741c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Feb 2015 00:05:28 +0800 Subject: [PATCH 0050/1939] Update binary-tree-preorder-traversal.py --- Python/binary-tree-preorder-traversal.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Python/binary-tree-preorder-traversal.py b/Python/binary-tree-preorder-traversal.py index 2cf998dcd..51146c7bd 100644 --- a/Python/binary-tree-preorder-traversal.py +++ b/Python/binary-tree-preorder-traversal.py @@ -70,9 +70,25 @@ def preorderTraversal(self, root): current = parent.right return result +class Solution3: + # @param root, a tree node + # @return a list of integers + def preorderTraversal(self, root): + result, stack, current, last_traversed = [], [], root, None + while stack or current: + if current: + result.append(current.val) + stack.append(current) + current = current.left + else: + current = stack[-1] + stack.pop() + current = current.right + return result + if __name__ == "__main__": root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) result = Solution().preorderTraversal(root) - print result \ No newline at end of file + print result From dc0a2d2fc524d30351b55cacf20b1a6c31f062ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Feb 2015 17:00:16 +0800 Subject: [PATCH 0051/1939] Update populating-next-right-pointers-in-each-node.py --- ...lating-next-right-pointers-in-each-node.py | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/Python/populating-next-right-pointers-in-each-node.py b/Python/populating-next-right-pointers-in-each-node.py index 5223f28fb..79b50a7d8 100644 --- a/Python/populating-next-right-pointers-in-each-node.py +++ b/Python/populating-next-right-pointers-in-each-node.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(1) # # Given a binary tree # @@ -45,6 +45,23 @@ def __repr__(self): return "{} -> {}".format(self.val, repr(self.next)) class Solution: + # @param root, a tree node + # @return nothing + def connect(self, root): + head = root + while head: + prev, cur, next_head = None, head, None + while cur and cur.left: + cur.left.next = cur.right + if cur.next: + cur.right.next = cur.next.left + cur = cur.next + head = head.left + +# Time: O(n) +# Space: O(logn) +# recusion +class Solution2: # @param root, a tree node # @return nothing def connect(self, root): @@ -64,4 +81,4 @@ def connect(self, root): print root print root.left print root.left.left - \ No newline at end of file + From a93725ff75dade6a30546324cdab7f6f547e82e4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Feb 2015 17:01:03 +0800 Subject: [PATCH 0052/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 11d38db85..ea9ea9ec4 100644 --- a/README.md +++ b/README.md @@ -455,7 +455,7 @@ Problem | Solution | Time | Space | Difficul [Flatten Binary Tree to Linked List]|[flatten-binary-tree-to-linked-list.py]| _O(n)_ | _O(logn)_ | Medium | [Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(logn)_ | Easy | [Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(logn)_ | Easy | -[Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(logn)_ | Medium | +[Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(1)_ | Medium | [Same Tree] |[same-tree.py] | _O(n)_ | _O(logn)_ | Easy | [Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(logn)_ | Medium | [Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | From 93d3af8baff4c122d9f46fecffdb97d362e065cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Feb 2015 00:41:48 +0800 Subject: [PATCH 0053/1939] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ea9ea9ec4..2cfb8a562 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,6 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Add Binary] | [add-binary.py] | _O(n)_ | _O(1)_ | Easy | -[Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | [Compare Version Numbers] | [compare-version-numbers.py] | _O(n)_ | _O(1)_ | Easy | [Count and Say] | [count-and-say.py]| _O(n * 2^n)_ | _O(2^n)_ | Easy | [Implement strStr()] | [implement-strstr.py] | _O(n + m)_ | _O(m)_ | Easy | `KMP Algorithm` @@ -144,8 +143,6 @@ Problem | Solution | Time | Space | Difficul [Add Binary]:https://oj.leetcode.com/problems/add-binary/ [add-binary.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/add-binary.py -[Anagrams]:https://oj.leetcode.com/problems/anagrams/ -[anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py [Count and Say]:https://oj.leetcode.com/problems/count-and-say/ [count-and-say.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/count-and-say.py [Compare Version Numbers]:https://oj.leetcode.com/problems/compare-version-numbers/ @@ -273,6 +270,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [4 Sum] |[4sum.py] | _O(n^2)_ ~ _O(n^4)_ | _O(n^2)_ | Medium | +[Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | [Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | @@ -285,6 +283,8 @@ Problem | Solution | Time | Space | Difficul [4 Sum]: https://oj.leetcode.com/problems/4sum/ [4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py +[Anagrams]:https://oj.leetcode.com/problems/anagrams/ +[anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py [Longest Substring with At Most Two Distinct Characters]:https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ [longest-substring-with-at-most-two-distinct-characters.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-with-at-most-two-distinct-characters.py [Longest Substring Without Repeating Characters]:https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ From a5e814f51e611c12fe23d73e9b1ed0b23a9302ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 00:16:57 +0800 Subject: [PATCH 0054/1939] Update merge-intervals.py --- Python/merge-intervals.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/merge-intervals.py b/Python/merge-intervals.py index 49641bb7d..436bbd5d3 100644 --- a/Python/merge-intervals.py +++ b/Python/merge-intervals.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(nlogn) # Space: O(1) # # Given a collection of intervals, merge all overlapping intervals. From 79719297a394ba3e0fe3038fc04be5d2b45d2105 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 00:17:32 +0800 Subject: [PATCH 0055/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2cfb8a562..e375f0f0e 100644 --- a/README.md +++ b/README.md @@ -368,7 +368,7 @@ Problem | Solution | Time | Space | Difficul [Insertion Sort List]|[insertion-sort-list.py] | _O(n^2)_ | _O(1)_ | Medium | [Largest Number] | [largest-number.py] | _O(n^2)_ | _O(n)_ | Medium | [Maximum Gap] | [maximum-gap.py]| _O(n)_ | _O(n)_ | Hard | Tricky -[Merge Intervals]| [merge-intervals.py] | _O(n^2)_ | _O(1)_ | Hard | +[Merge Intervals]| [merge-intervals.py] | _O(nlogn)_ | _O(1)_ | Hard | [Merge Sorted Array]| [merge-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | [Merge Two Sorted Lists]| [merge-two-sorted-lists.py] | _O(n)_ | _O(1)_ | Easy | [Sort Colors] | [sort-colors.py] | _O(n)_ | _O(1)_ | Medium | From 566a0f27d8f2cc10a81ce4f2a1ac2f01529cc9e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 01:42:53 +0800 Subject: [PATCH 0056/1939] Update sort-list.py --- Python/sort-list.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/sort-list.py b/Python/sort-list.py index bd56db074..5427a88bd 100644 --- a/Python/sort-list.py +++ b/Python/sort-list.py @@ -1,5 +1,5 @@ # Time: O(nlogn) -# Space: O(1) +# Space: O(logn) for stack call # # Sort a linked list in O(n log n) time using constant space complexity. # @@ -53,4 +53,4 @@ def mergeTwoLists(self, l1, l2): head.next = ListNode(4) head.next.next = ListNode(1) head.next.next.next= ListNode(2) - print Solution().sortList(head) \ No newline at end of file + print Solution().sortList(head) From 57ae6e9464729b27886fd510a683530effa5791a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 01:43:25 +0800 Subject: [PATCH 0057/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e375f0f0e..5b7338dfb 100644 --- a/README.md +++ b/README.md @@ -372,7 +372,7 @@ Problem | Solution | Time | Space | Difficul [Merge Sorted Array]| [merge-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | [Merge Two Sorted Lists]| [merge-two-sorted-lists.py] | _O(n)_ | _O(1)_ | Easy | [Sort Colors] | [sort-colors.py] | _O(n)_ | _O(1)_ | Medium | -[Sort List] | [sort-list.py] | _O(nlogn)_ | _O(1)_ | Medium | +[Sort List] | [sort-list.py] | _O(nlogn)_ | _O(logn)_ | Medium | [Insert Interval]:https://oj.leetcode.com/problems/insert-interval/ [insert-interval.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/insert-interval.py From 40980253f3ea8dd03e8f14d25f9098c8c910d989 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 03:01:43 +0800 Subject: [PATCH 0058/1939] Update validate-binary-search-tree.py --- Python/validate-binary-search-tree.py | 35 +++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/Python/validate-binary-search-tree.py b/Python/validate-binary-search-tree.py index 9af8db35d..7e329c4cf 100644 --- a/Python/validate-binary-search-tree.py +++ b/Python/validate-binary-search-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(1) # # Given a binary tree, determine if it is a valid binary search tree (BST). # @@ -17,7 +17,38 @@ def __init__(self, x): self.left = None self.right = None +# Morris Traversal Solution class Solution: + # @param root, a tree node + # @return a list of integers + def isValidBST(self, root): + prev, cur = None, root + while cur: + if cur.left is None: + if prev and prev.val >= cur.val: + return False + prev = cur + cur = cur.right + else: + node = cur.left + while node.right and node.right != cur: + node = node.right + + if node.right is None: + node.right = cur + cur = cur.left + else: + if prev and prev.val >= cur.val: + return False + node.right = None + prev = cur + cur = cur.right + + return True + +# Time: O(n) +# Space: O(logn) +class Solution2: # @param root, a tree node # @return a boolean def isValidBST(self, root): @@ -35,4 +66,4 @@ def isValidBSTRecu(self, root, low, high): root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) - print Solution().isValidBST(root) \ No newline at end of file + print Solution().isValidBST(root) From a4472ba47d30156400c969857a4258cd2cd47dc0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Feb 2015 03:02:12 +0800 Subject: [PATCH 0059/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5b7338dfb..a35067773 100644 --- a/README.md +++ b/README.md @@ -459,7 +459,7 @@ Problem | Solution | Time | Space | Difficul [Same Tree] |[same-tree.py] | _O(n)_ | _O(logn)_ | Easy | [Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(logn)_ | Medium | [Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | -[Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(logn)_ | Medium | +[Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(1)_ | Medium | [Balanced Binary Tree]:https://oj.leetcode.com/problems/balanced-binary-tree/ [balanced-binary-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/balanced-binary-tree.py @@ -489,7 +489,7 @@ Problem | Solution | Time | Space | Difficul [sum-root-to-leaf-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sum-root-to-leaf-numbers.py [Unique Binary Search Trees II]:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ [unique-binary-search-trees-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-binary-search-trees-ii.py -[Validate Binary Search Tree]:https://oj.leetcode.com/problems/validate-binary-search-tree.py/ +[Validate Binary Search Tree]:https://oj.leetcode.com/problems/validate-binary-search-tree/ [validate-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/validate-binary-search-tree.py From 8510bf50dedb8e76ba386be1ef9996ecf66f8fd4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:10:30 +0800 Subject: [PATCH 0060/1939] Update flatten-binary-tree-to-linked-list.py --- Python/flatten-binary-tree-to-linked-list.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/flatten-binary-tree-to-linked-list.py b/Python/flatten-binary-tree-to-linked-list.py index 8d081290a..579f2e319 100644 --- a/Python/flatten-binary-tree-to-linked-list.py +++ b/Python/flatten-binary-tree-to-linked-list.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, flatten it to a linked list in-place. # @@ -74,4 +74,4 @@ def flatten(self, root): print result.right.right.val print result.right.right.right.val print result.right.right.right.right.val - print result.right.right.right.right.right.val \ No newline at end of file + print result.right.right.right.right.right.val From d492f17edc1e7d464242942f2c786337d8687304 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:11:31 +0800 Subject: [PATCH 0061/1939] Update binary-tree-maximum-path-sum.py --- Python/binary-tree-maximum-path-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/binary-tree-maximum-path-sum.py b/Python/binary-tree-maximum-path-sum.py index 2c2705aa1..d71f6eeba 100644 --- a/Python/binary-tree-maximum-path-sum.py +++ b/Python/binary-tree-maximum-path-sum.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, find the maximum path sum. # From 372807aa57a6695f3cf835076bcb5e598cc56a41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:12:44 +0800 Subject: [PATCH 0062/1939] Update binary-search-tree-iterator.py --- Python/binary-search-tree-iterator.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/binary-search-tree-iterator.py b/Python/binary-search-tree-iterator.py index c198f87ec..428c8d4a3 100644 --- a/Python/binary-search-tree-iterator.py +++ b/Python/binary-search-tree-iterator.py @@ -1,5 +1,5 @@ # Time: O(1) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Implement an iterator over a binary search tree (BST). # Your iterator will be initialized with the root node of a BST. @@ -47,4 +47,4 @@ def next(self): i, v = BSTIterator(root), [] while i.hasNext(): v.append(i.next()) - print v \ No newline at end of file + print v From a0657c7fb32001f1726e11fbbebb56b14a493065 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:13:29 +0800 Subject: [PATCH 0063/1939] Update symmetric-tree.py --- Python/symmetric-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/symmetric-tree.py b/Python/symmetric-tree.py index 6b2a1c991..709864217 100644 --- a/Python/symmetric-tree.py +++ b/Python/symmetric-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). # # For example, this binary tree is symmetric: @@ -77,4 +77,4 @@ def isSymmetricRecu(self, left, right): root.left.left, root.right.right = TreeNode(3), TreeNode(3) root.left.right, root.right.left = TreeNode(4), TreeNode(4) print Solution().isSymmetric(root) - \ No newline at end of file + From 29f8dadfd5684e33b7a8689410e89557c27b38f7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:14:55 +0800 Subject: [PATCH 0064/1939] Update balanced-binary-tree.py --- Python/balanced-binary-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/balanced-binary-tree.py b/Python/balanced-binary-tree.py index 532657698..fbf1326ab 100644 --- a/Python/balanced-binary-tree.py +++ b/Python/balanced-binary-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, determine if it is height-balanced. # From 827c6715f9dc468183cc0cd11260b02b7fe3c2c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:15:15 +0800 Subject: [PATCH 0065/1939] Update convert-sorted-array-to-binary-search-tree.py --- Python/convert-sorted-array-to-binary-search-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/convert-sorted-array-to-binary-search-tree.py b/Python/convert-sorted-array-to-binary-search-tree.py index 946a2a163..2d0635d83 100644 --- a/Python/convert-sorted-array-to-binary-search-tree.py +++ b/Python/convert-sorted-array-to-binary-search-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given an array where elements are sorted in ascending order, # convert it to a height balanced BST. From 303e940f629bcbae2f8cc4b8ed9d822f460e5109 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:15:50 +0800 Subject: [PATCH 0066/1939] Update maximum-depth-of-binary-tree.py --- Python/maximum-depth-of-binary-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/maximum-depth-of-binary-tree.py b/Python/maximum-depth-of-binary-tree.py index 14c258da1..016f720a6 100644 --- a/Python/maximum-depth-of-binary-tree.py +++ b/Python/maximum-depth-of-binary-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, find its maximum depth. # @@ -27,4 +27,4 @@ def maxDepth(self, root): root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) - print Solution().maxDepth(root) \ No newline at end of file + print Solution().maxDepth(root) From 9d6c6ffc9ffc9e00d2a1a849e76ffe6f29d346ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:16:05 +0800 Subject: [PATCH 0067/1939] Update minimum-depth-of-binary-tree.py --- Python/minimum-depth-of-binary-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/minimum-depth-of-binary-tree.py b/Python/minimum-depth-of-binary-tree.py index 5494074ec..2833dcaab 100644 --- a/Python/minimum-depth-of-binary-tree.py +++ b/Python/minimum-depth-of-binary-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree, find its minimum depth. # @@ -28,4 +28,4 @@ def minDepth(self, root): if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) - print Solution().minDepth(root) \ No newline at end of file + print Solution().minDepth(root) From 1f7514c0703cd9b9731b7cfddac2586dd53a1372 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:16:20 +0800 Subject: [PATCH 0068/1939] Update same-tree.py --- Python/same-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/same-tree.py b/Python/same-tree.py index b73333130..c7e799c94 100644 --- a/Python/same-tree.py +++ b/Python/same-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given two binary trees, write a function to check if they are equal or not. # @@ -29,4 +29,4 @@ def isSameTree(self, p, q): if __name__ == "__main__": root1, root1.left, root1.right = TreeNode(1), TreeNode(2), TreeNode(3) root2, root2.left, root2.right = TreeNode(1), TreeNode(2), TreeNode(3) - print Solution().isSameTree(root1, root2) \ No newline at end of file + print Solution().isSameTree(root1, root2) From 39d0711fe60eac932499a75e7157a2f99e9a3d1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:16:35 +0800 Subject: [PATCH 0069/1939] Update sum-root-to-leaf-numbers.py --- Python/sum-root-to-leaf-numbers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/sum-root-to-leaf-numbers.py b/Python/sum-root-to-leaf-numbers.py index 763a9faba..775c1920b 100644 --- a/Python/sum-root-to-leaf-numbers.py +++ b/Python/sum-root-to-leaf-numbers.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. # @@ -44,4 +44,4 @@ def sumNumbersRecu(self, root, num): root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) - print Solution().sumNumbers(root) \ No newline at end of file + print Solution().sumNumbers(root) From 6db2b8b13dfa530ace7dba518a50e871085d893a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:17:41 +0800 Subject: [PATCH 0070/1939] Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index a35067773..7d7db04b9 100644 --- a/README.md +++ b/README.md @@ -212,12 +212,12 @@ Problem | Solution | Time | Space | Difficul ##Stack Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Binary Search Tree Iterator] | [binary-search-tree-iterator.py] | _O(1)_| _O(logn)_| Medium +[Binary Search Tree Iterator] | [binary-search-tree-iterator.py] | _O(1)_| _O(h)_| Medium [Evaluate Reverse Polish Notation]| [evaluate-reverse-polish-notation.py]| _O(n)_| _O(n)_| Medium | [Longest Valid Parentheses]| [longest-valid-parentheses.py] | _O(n)_ | _O(1)_ | Hard | [Min Stack] | [min-stack.py] | _O(n)_ | _O(1)_ | Easy | [Simplify Path]| [simplify-path.py] | _O(n)_ | _O(n)_ | Medium | -[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(logn)_ | Easy | +[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(h )_ | Easy | [Valid Parentheses]| [valid-parentheses.py] | _O(n)_ | _O(n)_ | Easy | [Binary Search Tree Iterator]:https://oj.leetcode.com/problems/binary-search-tree-iterator/ @@ -445,19 +445,19 @@ Problem | Solution | Time | Space | Difficul ##Divide and Conquer Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Balanced Binary Tree] | [balanced-binary-tree.py] | _O(n)_| _O(logn)_| Easy | +[Balanced Binary Tree] | [balanced-binary-tree.py] | _O(n)_| _O(h)_ | Easy | [Binary Tree Maximum Path Sum]| [binary-tree-maximum-path-sum.py] | _O(n)_| _O(logn)_| Hard | [Binary Tree Upside Down] | [binary-tree-upside-down.py] | _O(n)_ | _O(1)_ | Medium | [Construct Binary Tree from Inorder and Postorder Traversal] | [construct-binary-tree-from-inorder-and-postorder-traversal.py] | _O(n)_ | _O(n)_ | Medium | [Construct Binary Tree from Preorder and Inorder Traversal] | [construct-binary-tree-from-preorder-and-inorder-traversal.py] | _O(n)_ | _O(n)_ | Medium [Convert Sorted Array to Binary Search Tree] | [convert-sorted-array-to-binary-search-tree.py] | _O(n)_ | _O(logn)_ | Medium | [Convert Sorted List to Binary Search Tree] | [convert-sorted-list-to-binary-search-tree.py] | _O(n)_ | _O(logn)_ | Medium | -[Flatten Binary Tree to Linked List]|[flatten-binary-tree-to-linked-list.py]| _O(n)_ | _O(logn)_ | Medium | -[Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(logn)_ | Easy | -[Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(logn)_ | Easy | +[Flatten Binary Tree to Linked List]|[flatten-binary-tree-to-linked-list.py]| _O(n)_ | _O(h)_ | Medium | +[Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | +[Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | [Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(1)_ | Medium | [Same Tree] |[same-tree.py] | _O(n)_ | _O(logn)_ | Easy | -[Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(logn)_ | Medium | +[Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(h)_ | Medium | [Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | [Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(1)_ | Medium | From b79ac662b71b31991bccf2eb30be96e7652b9640 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:18:20 +0800 Subject: [PATCH 0071/1939] Update convert-sorted-array-to-binary-search-tree.py --- Python/convert-sorted-array-to-binary-search-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/convert-sorted-array-to-binary-search-tree.py b/Python/convert-sorted-array-to-binary-search-tree.py index 2d0635d83..946a2a163 100644 --- a/Python/convert-sorted-array-to-binary-search-tree.py +++ b/Python/convert-sorted-array-to-binary-search-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(h), h is height of binary tree +# Space: O(logn) # # Given an array where elements are sorted in ascending order, # convert it to a height balanced BST. From e2b8204c87c04e2a137e90bc78e211a9091fdcca Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:19:07 +0800 Subject: [PATCH 0072/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7d7db04b9..7d2259b8f 100644 --- a/README.md +++ b/README.md @@ -456,7 +456,7 @@ Problem | Solution | Time | Space | Difficul [Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | [Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | [Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(1)_ | Medium | -[Same Tree] |[same-tree.py] | _O(n)_ | _O(logn)_ | Easy | +[Same Tree] |[same-tree.py] | _O(n)_ | _O(h)_ | Easy | [Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(h)_ | Medium | [Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | [Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(1)_ | Medium | From 9fc931e9b31082d3ae3b5f874dbfa8d0391bda1e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:20:12 +0800 Subject: [PATCH 0073/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7d2259b8f..725800682 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,7 @@ Problem | Solution | Time | Space | Difficul [Longest Valid Parentheses]| [longest-valid-parentheses.py] | _O(n)_ | _O(1)_ | Hard | [Min Stack] | [min-stack.py] | _O(n)_ | _O(1)_ | Easy | [Simplify Path]| [simplify-path.py] | _O(n)_ | _O(n)_ | Medium | -[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(h )_ | Easy | +[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(h)_ | Easy | [Valid Parentheses]| [valid-parentheses.py] | _O(n)_ | _O(n)_ | Easy | [Binary Search Tree Iterator]:https://oj.leetcode.com/problems/binary-search-tree-iterator/ From f0363d91e49438391dd8d0a45463911d8a6141a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:22:03 +0800 Subject: [PATCH 0074/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 725800682..42922fbf4 100644 --- a/README.md +++ b/README.md @@ -446,7 +446,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Balanced Binary Tree] | [balanced-binary-tree.py] | _O(n)_| _O(h)_ | Easy | -[Binary Tree Maximum Path Sum]| [binary-tree-maximum-path-sum.py] | _O(n)_| _O(logn)_| Hard | +[Binary Tree Maximum Path Sum]| [binary-tree-maximum-path-sum.py] | _O(n)_| _O(h)_| Hard | [Binary Tree Upside Down] | [binary-tree-upside-down.py] | _O(n)_ | _O(1)_ | Medium | [Construct Binary Tree from Inorder and Postorder Traversal] | [construct-binary-tree-from-inorder-and-postorder-traversal.py] | _O(n)_ | _O(n)_ | Medium | [Construct Binary Tree from Preorder and Inorder Traversal] | [construct-binary-tree-from-preorder-and-inorder-traversal.py] | _O(n)_ | _O(n)_ | Medium From 07327bd22032832ca33da6c2ea6477d55981fc4b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:23:16 +0800 Subject: [PATCH 0075/1939] Update path-sum.py --- Python/path-sum.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/path-sum.py b/Python/path-sum.py index 0f686ec7f..b24c951a1 100644 --- a/Python/path-sum.py +++ b/Python/path-sum.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree and a sum, determine if the tree has a root-to-leaf path # such that adding up all the values along the path equals the given sum. @@ -42,4 +42,4 @@ def hasPathSum(self, root, sum): root.right = TreeNode(8) root.left.left = TreeNode(11) root.left.left.right = TreeNode(2) - print Solution().hasPathSum(root, 22) \ No newline at end of file + print Solution().hasPathSum(root, 22) From f8f6c8ab5eb6d84fd6460cd86e05f1d95ed8982e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:23:36 +0800 Subject: [PATCH 0076/1939] Update path-sum-ii.py --- Python/path-sum-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/path-sum-ii.py b/Python/path-sum-ii.py index a6e835dcb..df35acde8 100644 --- a/Python/path-sum-ii.py +++ b/Python/path-sum-ii.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(logn) +# Space: O(h), h is height of binary tree # # Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. # @@ -51,4 +51,4 @@ def pathSumRecu(self, result, cur, root, sum): if __name__ == "__main__": root = TreeNode(5) - print Solution().pathSum(root, 5) \ No newline at end of file + print Solution().pathSum(root, 5) From 500896c1bb9eca29a5432e8fe073b60745c40707 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Feb 2015 00:24:05 +0800 Subject: [PATCH 0077/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 42922fbf4..aca3ab489 100644 --- a/README.md +++ b/README.md @@ -574,8 +574,8 @@ Problem | Solution | Time | Space | Difficul [N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | [N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | [Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | -[Path Sum] | [path-sum.py] | _O(n)_ | _O(logn)_ | Easy | -[Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(logn)_ | Medium | +[Path Sum] | [path-sum.py] | _O(n)_ | _O(h)_ | Easy | +[Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | [Restore IP Addresses] | [restore-ip-addresses.py] | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium | [Sudoku Solver] | [sudoku-solver.py] | _O((9!)^9)_ | _O(1)_ | Hard | [Word Search] | [word-search.py] | _O(m * n * 3^p)_ | _O(m * n * p)_ | Medium | From 65a49f563243567653cf3e0c4b1a9d5ba30f5123 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Feb 2015 01:35:47 +0800 Subject: [PATCH 0078/1939] Update subsets-ii.py --- Python/subsets-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/subsets-ii.py b/Python/subsets-ii.py index a22bedb27..7690e96a8 100644 --- a/Python/subsets-ii.py +++ b/Python/subsets-ii.py @@ -1,4 +1,4 @@ -# Time: O(2^n) +# Time: O(n * 2^n) # Space: O(1) # # Given a collection of integers that might contain duplicates, S, return all possible subsets. @@ -54,4 +54,4 @@ def subsetsWithDupRecu(self, result, cur, S): self.subsetsWithDupRecu(result, cur + [S[0]], S[1:]) if __name__ == "__main__": - print Solution().subsetsWithDup([1, 2, 2]) \ No newline at end of file + print Solution().subsetsWithDup([1, 2, 2]) From ba0212c301353374ad016f210d96ee914998b736 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Feb 2015 01:36:08 +0800 Subject: [PATCH 0079/1939] Update subsets.py --- Python/subsets.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/subsets.py b/Python/subsets.py index 5143a2d62..0d274aabf 100644 --- a/Python/subsets.py +++ b/Python/subsets.py @@ -1,4 +1,4 @@ -# Time: O(2^n) +# Time: O(n * 2^n) # Space: O(1) # # Given a set of distinct integers, S, return all possible subsets. @@ -52,4 +52,4 @@ def subsetsRecu(self, cur, S): return self.subsetsRecu(cur, S[1:]) + self.subsetsRecu(cur + [S[0]], S[1:]) if __name__ == "__main__": - print Solution().subsets([1, 2, 3]) \ No newline at end of file + print Solution().subsets([1, 2, 3]) From fec46131226db1549333d548c686c7bdb20dec4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Feb 2015 01:36:42 +0800 Subject: [PATCH 0080/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index aca3ab489..6092464c7 100644 --- a/README.md +++ b/README.md @@ -426,8 +426,8 @@ Problem | Solution | Time | Space | Difficul [Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(n)_ | Medium | [Permutations]| [permutations.py] | _O(n!)_ | _O(n)_ | Medium | [Permutations II]| [permutations-ii.py] | _O(n!)_ | _O(n)_ | Hard | -[Subsets] | [subsets.py] | _O(2^n)_ | _O(1)_ | Medium | -[Subsets II] | [subsets-ii.py] | _O(2^n)_ | _O(1)_ | Medium | +[Subsets] | [subsets.py] | _O(n * 2^n)_ | _O(1)_ | Medium | +[Subsets II] | [subsets-ii.py] | _O(n * 2^n)_ | _O(1)_ | Medium | [Letter Combinations of a Phone Number]:https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ [letter-combinations-of-a-phone-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/letter-combinations-of-a-phone-number.py From 09ad1158ca026cc2d8ea49c77879fc7b75c5e5f8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Feb 2015 01:42:22 +0800 Subject: [PATCH 0081/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6092464c7..52d4e211f 100644 --- a/README.md +++ b/README.md @@ -570,7 +570,7 @@ Problem | Solution | Time | Space | Difficul [Combination Sum]| [combination-sum.py] | _O(n^m)_ | _O(m)_ | Medium | [Combination Sum II]| [combination-sum-ii.py]| _O(n! / m!(n-m)!)_| _O(m)_ | Medium | [Combinations] | [combinations.py] | _O(n!)_ | _O(n)_ | Medium | -[Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2)_ | _O(n)_ | Medium | +[Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2))_ | _O(n)_ | Medium | [N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | [N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | [Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | From 036f65f07ed59d8301127f9e4237129e90c85109 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Feb 2015 16:58:19 +0800 Subject: [PATCH 0082/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 7ba442fad..59c6c2081 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -64,7 +64,9 @@ def maxExatclyKPairsProfit(self, prices, k): j, sign = j + 1, sign * -1 return k_sum[-1] - + +# Time: O(n) +# Space: O(n) class Solution3: # @param prices, a list of integer # @return an integer From 5a16320b622f1be5925834544a767a80fb0fd6ac Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 16 Feb 2015 23:06:14 +0800 Subject: [PATCH 0083/1939] update --- Python/implement-strstr.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index 543835dd4..9b7149b10 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -14,17 +14,17 @@ class Solution: # @param needle, a string # @return a string or None def strStr(self, haystack, needle): + if not needle: + return 0 + if len(haystack) < len(needle): - return None - - if len(needle) == 0: - return haystack + return -1 i = self.KMP(haystack, needle) if i > -1: - return haystack[i:] + return i else: - return None + return -1 def KMP(self, text, pattern): prefix = self.getPrefix(pattern) From 035f018dfc9ce0fcc32cbd10d753623833a2000b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:08:22 +0800 Subject: [PATCH 0084/1939] Update insert-interval.py --- Python/insert-interval.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/insert-interval.py b/Python/insert-interval.py index f108a7078..82e27eb9a 100644 --- a/Python/insert-interval.py +++ b/Python/insert-interval.py @@ -31,11 +31,11 @@ def insert(self, intervals, newInterval): return self.merge(intervals + [newInterval]) def merge(self, intervals): - if len(intervals) == 0: + if not intervals: return intervals intervals.sort(key = lambda x: x.start) result = [intervals[0]] - for i in range(1, len(intervals)): + for i in xrange(1, len(intervals)): prev, current = result[-1], intervals[i] if current.start <= prev.end: prev.end = max(prev.end, current.end) @@ -44,4 +44,4 @@ def merge(self, intervals): return result if __name__ == "__main__": - print Solution().insert([Interval(1, 2), Interval(3, 5), Interval(6, 7), Interval(8, 10), Interval(12, 16)], Interval(4, 9)) \ No newline at end of file + print Solution().insert([Interval(1, 2), Interval(3, 5), Interval(6, 7), Interval(8, 10), Interval(12, 16)], Interval(4, 9)) From 89d1f419f0d414cc4e62fc7264e07ab90c3af969 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:10:12 +0800 Subject: [PATCH 0085/1939] Update largest-rectangle-in-histogram.py --- Python/largest-rectangle-in-histogram.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/largest-rectangle-in-histogram.py b/Python/largest-rectangle-in-histogram.py index 2313b011f..e3dea568b 100644 --- a/Python/largest-rectangle-in-histogram.py +++ b/Python/largest-rectangle-in-histogram.py @@ -16,12 +16,12 @@ class Solution: def largestRectangleArea(self, height): increasing, area, i = [], 0, 0 while i <= len(height): - if len(increasing) == 0 or (i < len(height) and height[i] > height[increasing[-1]]): + if not increasing or (i < len(height) and height[i] > height[increasing[-1]]): increasing.append(i) i += 1 else: last = increasing.pop() - if len(increasing) == 0: + if not increasing: area = max(area, height[last] * i) else: area = max(area, height[last] * (i - increasing[-1] - 1 )) @@ -30,4 +30,4 @@ def largestRectangleArea(self, height): if __name__ == "__main__": print Solution().largestRectangleArea([2, 0, 2]) print Solution().largestRectangleArea([2, 1, 5, 6, 2, 3]) - \ No newline at end of file + From 45b4cf15128e0b422a55b905ef936ca24f7cafe5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:11:29 +0800 Subject: [PATCH 0086/1939] Update longest-common-prefix.py --- Python/longest-common-prefix.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/longest-common-prefix.py b/Python/longest-common-prefix.py index 2ffa96cfb..5c39975ab 100644 --- a/Python/longest-common-prefix.py +++ b/Python/longest-common-prefix.py @@ -7,7 +7,7 @@ class Solution: # @return a string def longestCommonPrefix(self, strs): - if len(strs) == 0: + if not strs: return "" longest = strs[0] for string in strs[1:]: @@ -19,4 +19,4 @@ def longestCommonPrefix(self, strs): if __name__ == "__main__": print Solution().longestCommonPrefix(["hello", "heaven", "heavy"]) - \ No newline at end of file + From dcd822a6e9ceeb25f85b492fff049f673ceb2a6b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:13:46 +0800 Subject: [PATCH 0087/1939] Update longest-palindromic-substring.py --- Python/longest-palindromic-substring.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/longest-palindromic-substring.py b/Python/longest-palindromic-substring.py index e882d6bf6..79abaf5af 100644 --- a/Python/longest-palindromic-substring.py +++ b/Python/longest-palindromic-substring.py @@ -35,7 +35,7 @@ def longestPalindrome(self, s): return s[start : start + max_len] def preProcess(self, s): - if len(s) == 0: + if not s: return "^$" string = "^" for i in s: @@ -44,4 +44,4 @@ def preProcess(self, s): return string if __name__ == "__main__": - print Solution().longestPalindrome("abb") \ No newline at end of file + print Solution().longestPalindrome("abb") From c07a51d19e377fa3f276f8d0958cc814778d60f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:18:16 +0800 Subject: [PATCH 0088/1939] Update longest-valid-parentheses.py --- Python/longest-valid-parentheses.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/longest-valid-parentheses.py b/Python/longest-valid-parentheses.py index 8d8b1647e..559ce3e30 100644 --- a/Python/longest-valid-parentheses.py +++ b/Python/longest-valid-parentheses.py @@ -49,11 +49,11 @@ def longestValidParentheses(self, s): for i in xrange(len(s)): if s[i] == '(': indices.append(i) - elif len(indices) == 0: + elif not indices: last = i else: indices.pop() - if len(indices) == 0: + if not indices: longest = max(longest, i - last) else: longest = max(longest, i - indices[-1]) From 81ef6529fa65e74bebf2f63b107a9707704c72e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:19:47 +0800 Subject: [PATCH 0089/1939] Update maximal-rectangle.py --- Python/maximal-rectangle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximal-rectangle.py b/Python/maximal-rectangle.py index 05a99c943..f667a4de2 100644 --- a/Python/maximal-rectangle.py +++ b/Python/maximal-rectangle.py @@ -9,7 +9,7 @@ class Solution: # @param matrix, a list of lists of 1 length string # @return an integer def maximalRectangle(self, matrix): - if len(matrix) == 0: + if not matrix: return 0 result = 0 From 21d3dd598687bb2ae66f937f8eea803f9a438d0f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:20:57 +0800 Subject: [PATCH 0090/1939] Update merge-intervals.py --- Python/merge-intervals.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/merge-intervals.py b/Python/merge-intervals.py index 436bbd5d3..f62b3f0a1 100644 --- a/Python/merge-intervals.py +++ b/Python/merge-intervals.py @@ -21,7 +21,7 @@ class Solution: # @param intervals, a list of Interval # @return a list of Interval def merge(self, intervals): - if len(intervals) == 0: + if not intervals: return intervals intervals.sort(key = lambda x: x.start) result = [intervals[0]] From 6d1fafd95eeb2762e012b7cd421ecf012d6d1019 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:22:12 +0800 Subject: [PATCH 0091/1939] Update min-stack.py --- Python/min-stack.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/min-stack.py b/Python/min-stack.py index 4036555b5..12df16163 100644 --- a/Python/min-stack.py +++ b/Python/min-stack.py @@ -17,7 +17,7 @@ def __init__(self): # @param x, an integer # @return an integer def push(self, x): - if len(self.stack) == 0: + if not self.stack: self.stack.append(0) self.min = x else: @@ -80,4 +80,4 @@ def getMin(self): stack = MinStack() stack.push(-1) print [stack.top(), stack.getMin()] - \ No newline at end of file + From d0aa70a9225e587473747b7227adf1eebbce29a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:24:24 +0800 Subject: [PATCH 0092/1939] Update regular-expression-matching.py --- Python/regular-expression-matching.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 28ff51e67..969a92981 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -70,8 +70,8 @@ def isMatch(self, s, p): class Solution3: # @return a boolean def isMatch(self, s, p): - if len(p) == 0: - return len(s) == 0 + if not p: + return not s if len(p) == 1 or p[1] != '*': if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): From caf713d24e8ced505226a4d5bc2b867f47fac187 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:25:21 +0800 Subject: [PATCH 0093/1939] Update remove-duplicates-from-sorted-array-ii.py --- Python/remove-duplicates-from-sorted-array-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/remove-duplicates-from-sorted-array-ii.py b/Python/remove-duplicates-from-sorted-array-ii.py index 527416e7f..794b192ae 100644 --- a/Python/remove-duplicates-from-sorted-array-ii.py +++ b/Python/remove-duplicates-from-sorted-array-ii.py @@ -14,7 +14,7 @@ class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): - if len(A) == 0: + if not A: return 0 last, i, same = 0, 1, False @@ -28,4 +28,4 @@ def removeDuplicates(self, A): return last + 1 if __name__ == "__main__": - print Solution().removeDuplicates([1, 1, 1, 2, 2, 3]) \ No newline at end of file + print Solution().removeDuplicates([1, 1, 1, 2, 2, 3]) From 9b54997ae5271b55e59cefffa0bc55db7b1129bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:25:57 +0800 Subject: [PATCH 0094/1939] Update remove-duplicates-from-sorted-array.py --- Python/remove-duplicates-from-sorted-array.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/remove-duplicates-from-sorted-array.py b/Python/remove-duplicates-from-sorted-array.py index 473e645fc..7ea358680 100644 --- a/Python/remove-duplicates-from-sorted-array.py +++ b/Python/remove-duplicates-from-sorted-array.py @@ -15,7 +15,7 @@ class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): - if len(A) == 0: + if not A: return 0 last, i = 0, 1 @@ -28,4 +28,4 @@ def removeDuplicates(self, A): return last + 1 if __name__ == "__main__": - print Solution().removeDuplicates([1, 1, 2]) \ No newline at end of file + print Solution().removeDuplicates([1, 1, 2]) From 6a363e57b7f52e12ec37f4c97eaf81159b8ae814 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:26:40 +0800 Subject: [PATCH 0095/1939] Update scramble-string.py --- Python/scramble-string.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/scramble-string.py b/Python/scramble-string.py index f75325daf..5d7d4feeb 100644 --- a/Python/scramble-string.py +++ b/Python/scramble-string.py @@ -47,7 +47,7 @@ class Solution: def isScramble(self, s1, s2): if not s1 or not s2 or len(s1) != len(s2): return False - if len(s1) == 0: + if not s1: return True result = [[[False for j in xrange(len(s2))] for i in xrange(len(s1))] for n in xrange(len(s1) + 1)] for i in xrange(len(s1)): @@ -67,4 +67,4 @@ def isScramble(self, s1, s2): return result[n][0][0] if __name__ == "__main__": - print Solution().isScramble("rgtae", "great") \ No newline at end of file + print Solution().isScramble("rgtae", "great") From ff9cf4d376b69580b4a5aa392af04d14c32f6048 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:28:20 +0800 Subject: [PATCH 0096/1939] Update string-to-integer-atoi.py --- Python/string-to-integer-atoi.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py index b10431638..17b23e886 100644 --- a/Python/string-to-integer-atoi.py +++ b/Python/string-to-integer-atoi.py @@ -33,7 +33,7 @@ def atoi(self, str): INT_MIN = -2147483648 result = 0 - if len(str) == 0: + if not str: return result i = 0 @@ -65,4 +65,4 @@ def atoi(self, str): print Solution().atoi("2147483647") print Solution().atoi("2147483648") print Solution().atoi("-2147483648") - print Solution().atoi("-2147483649") \ No newline at end of file + print Solution().atoi("-2147483649") From f96bc5771e3b529dc5cb057ff45ae373b5655d8c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:29:34 +0800 Subject: [PATCH 0097/1939] Update subsets.py --- Python/subsets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/subsets.py b/Python/subsets.py index 0d274aabf..eefdb0a55 100644 --- a/Python/subsets.py +++ b/Python/subsets.py @@ -46,7 +46,7 @@ def subsets(self, S): return self.subsetsRecu([], sorted(S)) def subsetsRecu(self, cur, S): - if len(S) == 0: + if not S: return [cur] return self.subsetsRecu(cur, S[1:]) + self.subsetsRecu(cur + [S[0]], S[1:]) From d6d78190abd4559839aaca65723ae0c92b622cfd Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:30:43 +0800 Subject: [PATCH 0098/1939] Update surrounded-regions.py --- Python/surrounded-regions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/surrounded-regions.py b/Python/surrounded-regions.py index bec979730..a0badb16c 100644 --- a/Python/surrounded-regions.py +++ b/Python/surrounded-regions.py @@ -23,7 +23,7 @@ class Solution: # Capture all regions by modifying the input board in-place. # Do not return any value. def solve(self, board): - if len(board) == 0: + if not board: return current = [] From 4c426b44b47922a707ce4efcc5e20d30d353a0c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:31:39 +0800 Subject: [PATCH 0099/1939] Update triangle.py --- Python/triangle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/triangle.py b/Python/triangle.py index 40cf9c627..e05906104 100644 --- a/Python/triangle.py +++ b/Python/triangle.py @@ -20,7 +20,7 @@ class Solution: # @param triangle, a list of lists of integers # @return an integer def minimumTotal(self, triangle): - if len(triangle) == 0: + if not triangle: return 0 cur = triangle[0] + [float("inf")] @@ -35,4 +35,4 @@ def minimumTotal(self, triangle): if __name__ == "__main__": print Solution().minimumTotal([[-1], [2, 3], [1, -1, -3]]) - \ No newline at end of file + From ff1efcc3333eeb27ef2ae5667b5de8a4c6c3eb4f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:33:33 +0800 Subject: [PATCH 0100/1939] Update wildcard-matching.py --- Python/wildcard-matching.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index cf2d464b8..d930727d7 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -98,11 +98,11 @@ def isMatch(self, s, p): class Solution4: # @return a boolean def isMatch(self, s, p): - if len(p) == 0: - return len(s) == 0 + if not p: + return not s if p[0] != '*': - if len(s) == 0 or (p[0] == s[0] or p[0] == '?'): + if not s or (p[0] == s[0] or p[0] == '?'): return self.isMatch(s[1:], p[1:]) else: return False From 044de2a7d4e27152512e79c0b86fa0945861971f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Feb 2015 23:34:43 +0800 Subject: [PATCH 0101/1939] Update word-ladder-ii.py --- Python/word-ladder-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-ladder-ii.py b/Python/word-ladder-ii.py index 2838f1da5..8d47c5806 100644 --- a/Python/word-ladder-ii.py +++ b/Python/word-ladder-ii.py @@ -55,7 +55,7 @@ def findLadders(self, start, end, dict): return result def backtrack(self, result, trace, path, word): - if len(trace[word]) == 0: + if not trace[word]: result.append([word] + path) else: for prev in trace[word]: From 25c255b5f54ccad611ee34fd273396a6d9732c1f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 17 Feb 2015 23:25:37 +0800 Subject: [PATCH 0102/1939] add new solution --- Python/best-time-to-buy-and-sell-stock-iv.py | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/best-time-to-buy-and-sell-stock-iv.py diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py new file mode 100644 index 000000000..77cf015aa --- /dev/null +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -0,0 +1,46 @@ +# Time: O(k * n) +# Space: O(k) +# +# Say you have an array for which the ith element is the price of a given stock on day i. +# +# Design an algorithm to find the maximum profit. You may complete at most k transactions. +# +# Note: +# You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). +# + +class Solution: + # @return an integer as the maximum profit + def maxProfit(self, k, prices): + if k >= len(prices): + return self.maxUnlimitPairProfit(prices) + + return self.maxAtMostKPairsProfit(prices, k) + + def maxUnlimitPairProfit(self, prices): + profit = 0 + for i in xrange(len(prices) - 1): + profit += max(0, prices[i + 1] - prices[i]) + return profit + + def maxAtMostKPairsProfit(self, prices, k): + if k == 0: + return 0 + + k_sum = [float("-inf") for _ in xrange(2 * k)] + for i in xrange(1, len(k_sum), 2): + k_sum[i] = 0 + + for i in xrange(len(prices)): + j, sign, pre_k_sum = 0, -1, 0 + while j < len(k_sum): + diff = sign * prices[i] + if j > 0: + diff += pre_k_sum + pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) + j, sign = j + 1, sign * -1 + + return k_sum[-1] + +if __name__ == "__main__": + print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) \ No newline at end of file From a5494d473d36bd987fa7dbf43208c6a4c019ab97 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:27:16 +0800 Subject: [PATCH 0103/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 52d4e211f..2cc361fc9 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-02-06), there are total `187` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-02-17), there are total `188` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `187` problems. +Here is the classification of all `188` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -611,6 +611,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iii.py] | _O(n)_ | _O(1)_ | Hard | +[Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iv.py] | _O(k * n)_ | _O(k)_ | Hard | [Climbing Stairs]| [climbing-stairs.py] | _O(n)_ | _O(1)_ | Easy | [Decode Ways] | [decode-ways.py]| _O(n)_ | _O(1)_ | Medium | [Distinct Subsequences]|[distinct-subsequences.py]| _O(n^2)_ | _O(n)_ | Hard | @@ -633,6 +634,8 @@ Problem | Solution | Time | Space | Difficul [Best Time to Buy and Sell Stock III]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ [best-time-to-buy-and-sell-stock-iii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-iii.py +[Best Time to Buy and Sell Stock IV]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ +[best-time-to-buy-and-sell-stock-iv.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-iv.py [Climbing Stairs]:https://oj.leetcode.com/problems/climbing-stairs/ [climbing-stairs.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/climbing-stairs.py [Decode Ways]:https://oj.leetcode.com/problems/decode-ways/ From baac19f3908dcb2114231f31a38d98eeb2752bbb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:28:05 +0800 Subject: [PATCH 0104/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2cc361fc9..7d73c3dfe 100644 --- a/README.md +++ b/README.md @@ -611,7 +611,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iii.py] | _O(n)_ | _O(1)_ | Hard | -[Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iv.py] | _O(k * n)_ | _O(k)_ | Hard | +[Best Time to Buy and Sell Stock IV]| [best-time-to-buy-and-sell-stock-iv.py] | _O(k * n)_ | _O(k)_ | Hard | [Climbing Stairs]| [climbing-stairs.py] | _O(n)_ | _O(1)_ | Easy | [Decode Ways] | [decode-ways.py]| _O(n)_ | _O(1)_ | Medium | [Distinct Subsequences]|[distinct-subsequences.py]| _O(n^2)_ | _O(n)_ | Hard | From 3ec86226809d5b795b583ea2519e9a121d18b36f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:29:47 +0800 Subject: [PATCH 0105/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 59c6c2081..1a0d89613 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -35,18 +35,21 @@ class Solution2: def maxProfit(self, prices): return self.maxAtMostKPairsProfit(prices, 2) - def maxAtMostKPairsProfit(self, prices, k): + def maxAtMostKPairsProfit(self, prices, k): + if k == 0: + return 0 + k_sum = [float("-inf") for _ in xrange(2 * k)] for i in xrange(1, len(k_sum), 2): k_sum[i] = 0 for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, list(k_sum) + j, sign, pre_k_sum = 0, -1, 0 while j < len(k_sum): diff = sign * prices[i] if j > 0: - diff += pre_k_sum[j - 1] - k_sum[j] = max(diff, pre_k_sum[j]) + diff += pre_k_sum + pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) j, sign = j + 1, sign * -1 return k_sum[-1] From 46c69fb182dcd5222950a3c182e89232eada3454 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:45:01 +0800 Subject: [PATCH 0106/1939] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index 77cf015aa..0579a43b3 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -34,13 +34,11 @@ def maxAtMostKPairsProfit(self, prices, k): for i in xrange(len(prices)): j, sign, pre_k_sum = 0, -1, 0 while j < len(k_sum): - diff = sign * prices[i] - if j > 0: - diff += pre_k_sum + diff = pre_k_sum + sign * prices[i] pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) j, sign = j + 1, sign * -1 return k_sum[-1] if __name__ == "__main__": - print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) \ No newline at end of file + print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) From ea40b2b40e85f86dcc417ae33fd7ac186b606af8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Feb 2015 23:48:54 +0800 Subject: [PATCH 0107/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 1a0d89613..8fb42ff88 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -46,9 +46,7 @@ def maxAtMostKPairsProfit(self, prices, k): for i in xrange(len(prices)): j, sign, pre_k_sum = 0, -1, 0 while j < len(k_sum): - diff = sign * prices[i] - if j > 0: - diff += pre_k_sum + diff = pre_k_sum + sign * prices[i] pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) j, sign = j + 1, sign * -1 @@ -58,12 +56,10 @@ def maxExatclyKPairsProfit(self, prices, k): k_sum = [float("-inf") for _ in xrange(2 * k)] for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, list(k_sum) + j, sign, pre_k_sum = 0, -1, 0 while j < len(k_sum) and j <= i: - diff = sign * prices[i] - if j > 0: - diff += pre_k_sum[j - 1] - k_sum[j] = max(diff, pre_k_sum[j]) + diff = pre_k_sum + sign * prices[i] + pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) j, sign = j + 1, sign * -1 return k_sum[-1] From 0710d947c631e059f499b8added443ef9a73d7e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 00:03:29 +0800 Subject: [PATCH 0108/1939] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index 0579a43b3..685325fb1 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -12,7 +12,7 @@ class Solution: # @return an integer as the maximum profit def maxProfit(self, k, prices): - if k >= len(prices): + if k >= len(prices) / 2: return self.maxUnlimitPairProfit(prices) return self.maxAtMostKPairsProfit(prices, k) From d750bd1859345864ba97b49dbbe81cd51779bc21 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 18 Feb 2015 01:10:07 +0800 Subject: [PATCH 0109/1939] update --- Python/best-time-to-buy-and-sell-stock-iv.py | 31 ++++++++++---------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index 685325fb1..c1ce236cf 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -13,32 +13,31 @@ class Solution: # @return an integer as the maximum profit def maxProfit(self, k, prices): if k >= len(prices) / 2: - return self.maxUnlimitPairProfit(prices) + return self.maxAtMostNPairsProfit(prices) return self.maxAtMostKPairsProfit(prices, k) - - def maxUnlimitPairProfit(self, prices): + + def maxAtMostNPairsProfit(self, prices): profit = 0 for i in xrange(len(prices) - 1): profit += max(0, prices[i + 1] - prices[i]) return profit - + def maxAtMostKPairsProfit(self, prices, k): if k == 0: return 0 - - k_sum = [float("-inf") for _ in xrange(2 * k)] - for i in xrange(1, len(k_sum), 2): - k_sum[i] = 0 - + + max_buy = [float("-inf") for _ in xrange(k + 1)] + max_sell = [0 for _ in xrange(k + 1)] + for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, 0 - while j < len(k_sum): - diff = pre_k_sum + sign * prices[i] - pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) - j, sign = j + 1, sign * -1 - - return k_sum[-1] + j = 1 + while j <= k: + max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) + max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) + j = j + 1 + + return max_sell[k] if __name__ == "__main__": print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) From 9bf205ea3fa164a59c4a8f59892992395a6b4e16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 01:16:55 +0800 Subject: [PATCH 0110/1939] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index c1ce236cf..ad3582488 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -24,9 +24,6 @@ def maxAtMostNPairsProfit(self, prices): return profit def maxAtMostKPairsProfit(self, prices, k): - if k == 0: - return 0 - max_buy = [float("-inf") for _ in xrange(k + 1)] max_sell = [0 for _ in xrange(k + 1)] From 955e7e3cfb41298ed678fc77db60f9042b61f4cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 01:20:24 +0800 Subject: [PATCH 0111/1939] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index ad3582488..f776524e4 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -28,11 +28,9 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - j = 1 - while j <= k: + for j in xrange(1, k+1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) - j = j + 1 return max_sell[k] From b325cfdd1955b5d734b2b5b91bc4b874d40ea4ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:03:35 +0800 Subject: [PATCH 0112/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 36 ++++++------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 8fb42ff88..6b207e701 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -36,33 +36,17 @@ def maxProfit(self, prices): return self.maxAtMostKPairsProfit(prices, 2) def maxAtMostKPairsProfit(self, prices, k): - if k == 0: - return 0 - - k_sum = [float("-inf") for _ in xrange(2 * k)] - for i in xrange(1, len(k_sum), 2): - k_sum[i] = 0 - - for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, 0 - while j < len(k_sum): - diff = pre_k_sum + sign * prices[i] - pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) - j, sign = j + 1, sign * -1 - - return k_sum[-1] - - def maxExatclyKPairsProfit(self, prices, k): - k_sum = [float("-inf") for _ in xrange(2 * k)] - + max_buy = [float("-inf") for _ in xrange(k + 1)] + max_sell = [0 for _ in xrange(k + 1)] + for i in xrange(len(prices)): - j, sign, pre_k_sum = 0, -1, 0 - while j < len(k_sum) and j <= i: - diff = pre_k_sum + sign * prices[i] - pre_k_sum, k_sum[j] = k_sum[j], max(diff, k_sum[j]) - j, sign = j + 1, sign * -1 - - return k_sum[-1] + j = 1 + while j <= k and j <= i + 1: + max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) + max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) + j += 1 + + return max_sell[k] # Time: O(n) # Space: O(n) From 6577659a0c270dc7f3ecd7bb2d1558dac2a97928 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:06:48 +0800 Subject: [PATCH 0113/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 6b207e701..4027266ff 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -40,11 +40,10 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - j = 1 - while j <= k and j <= i + 1: + for j in xrange(1, min(k, i+1) + 1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) - j += 1 + return max_sell[k] From 70d1178714e335a714c45ea3b50d87e55991a5c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:07:03 +0800 Subject: [PATCH 0114/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 4027266ff..72eeaf173 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -44,7 +44,6 @@ def maxAtMostKPairsProfit(self, prices, k): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) - return max_sell[k] # Time: O(n) From 5fee5f2f77d527dbe49f1ba5529523c0b64e631f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:07:50 +0800 Subject: [PATCH 0115/1939] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index f776524e4..e5ee06a0b 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -28,9 +28,9 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - for j in xrange(1, k+1): + for j in xrange(1, min(k, i+1) + 1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) - max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) + max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) return max_sell[k] From a608d30f92752f2f75c0c6560833a45e0a126efc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 03:33:01 +0800 Subject: [PATCH 0116/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 72eeaf173..52a837896 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -27,7 +27,7 @@ def maxProfit(self, prices): hold1 = max(hold1, -i); return release2 -# Time: O(k^2 * n) +# Time: O(k * n) # Space: O(k) class Solution2: # @param prices, a list of integer From de58235ea9751d5845149e74be8e344774afe191 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 15:20:18 +0800 Subject: [PATCH 0117/1939] Update best-time-to-buy-and-sell-stock-iv.py --- Python/best-time-to-buy-and-sell-stock-iv.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py index e5ee06a0b..0235f07df 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -28,7 +28,7 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - for j in xrange(1, min(k, i+1) + 1): + for j in xrange(1, min(k, i/2+1) + 1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) From 842b24e9a282ded39cd2a8b7e9adaa7ba28391a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Feb 2015 15:28:18 +0800 Subject: [PATCH 0118/1939] Update best-time-to-buy-and-sell-stock-iii.py --- Python/best-time-to-buy-and-sell-stock-iii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py index 52a837896..114c1b321 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -40,7 +40,7 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): - for j in xrange(1, min(k, i+1) + 1): + for j in xrange(1, min(k, i/2+1) + 1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) From 795870e0760a985bbc10cf05aa1b16c87f464c0f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Feb 2015 22:32:39 +0800 Subject: [PATCH 0119/1939] Update and rename Python to Python/rotate-array.py --- Python/rotate-array.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/rotate-array.py diff --git a/Python/rotate-array.py b/Python/rotate-array.py new file mode 100644 index 000000000..0dbfb6528 --- /dev/null +++ b/Python/rotate-array.py @@ -0,0 +1,31 @@ +# Time: O(n) +# Space: O(1) +# +# Rotate an array of n elements to the right by k steps. +# +# For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. +# +# Note: +# Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. +# + +class Solution: + # @param nums, a list of integer + # @param k, num of steps + # @return nothing, please modify the nums list in-place. + def rotate(self, nums, k): + k %= len(nums) + self.reverse(nums, 0, len(nums)) + self.reverse(nums, 0, k) + self.reverse(nums, k, len(nums)) + + def reverse(self, nums, start, end): + while start < end: + nums[start], nums[end-1] = nums[end-1], nums[start] + start += 1 + end -= 1 + +if __name__ == '__main__': + nums = [1,2,3,4,5,6,7] + Solution().rotate(nums, 3) + print nums From 3b93cf00f6e42f4e2029cee03fb2dcc07a4581b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Feb 2015 22:37:36 +0800 Subject: [PATCH 0120/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7d73c3dfe..9ef16ae91 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-02-17), there are total `188` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-02-24), there are total `189` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `188` problems. +Here is the classification of all `189` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -72,6 +72,7 @@ Problem | Solution | Time | Space | Difficul [Remove Duplicates from Sorted Array]| [remove-duplicates-from-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | [Remove Duplicates from Sorted Array II]| [remove-duplicates-from-sorted-array-ii.py] | _O(n)_ | _O(1)_ | Medium | [Remove Element] | [remove-element.py] | _O(n)_ | _O(1)_ | Easy | +[Rotate Array] | [rotate-array.py] | _O(n)_ | _O(1)_ | Easy | [Rotate Image] | [rotate-image.py] | _O(n^2)_ | _O(1)_ | Medium | [Set Matrix Zeroes] | [set-matrix-zeroes.py] | _O(m * n)_ | _O(1)_ | Medium | [Spiral Matrix] | [spiral-matrix.py] | _O(m * n)_ | _O(1)_ | Medium | @@ -110,6 +111,8 @@ Problem | Solution | Time | Space | Difficul [remove-duplicates-from-sorted-array-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-array-ii.py [Remove Element]:https://oj.leetcode.com/problems/remove-element/ [remove-element.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-element.py +[Rotate Array]:https://oj.leetcode.com/problems/rotate-array/ +[rotate-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-array.py [Rotate Image]:https://oj.leetcode.com/problems/rotate-image/ [rotate-image.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-image.py [Set Matrix Zeroes]:https://oj.leetcode.com/problems/set-matrix-zeroes/ From 4ce140ffa15a7f038882aaea5719dbab89ec438b Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 24 Feb 2015 23:08:44 +0800 Subject: [PATCH 0121/1939] add solution --- Python/rotate-array.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Python/rotate-array.py b/Python/rotate-array.py index 0dbfb6528..2041672a9 100644 --- a/Python/rotate-array.py +++ b/Python/rotate-array.py @@ -24,7 +24,26 @@ def reverse(self, nums, start, end): nums[start], nums[end-1] = nums[end-1], nums[start] start += 1 end -= 1 - + +from fractions import gcd + +class Solution2: + # @param nums, a list of integer + # @param k, num of steps + # @return nothing, please modify the nums list in-place. + def rotate(self, nums, k): + k %= len(nums) + num_cycles = gcd(len(nums), k) + cycle_len = len(nums) / num_cycles + for i in xrange(num_cycles): + self.apply_cycle_permutation(k, i, cycle_len, nums) + + def apply_cycle_permutation(self, k, offset, cycle_len, nums): + tmp = nums[offset] + for i in xrange(1, cycle_len): + nums[(offset+i*k) % len(nums)], tmp = tmp, nums[(offset+i*k) % len(nums)] + nums[offset] = tmp + if __name__ == '__main__': nums = [1,2,3,4,5,6,7] Solution().rotate(nums, 3) From 72371e24d338a5c054ce414b4d11fa3a6965ec78 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Mar 2015 22:48:02 +0800 Subject: [PATCH 0122/1939] Create reverse-bits.py --- Python/reverse-bits.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/reverse-bits.py diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py new file mode 100644 index 000000000..aac560942 --- /dev/null +++ b/Python/reverse-bits.py @@ -0,0 +1,29 @@ +# Time : O(n) +# Space: O(1) +# +# Reverse bits of a given 32 bits unsigned integer. +# +# For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). +# +# Follow up: +# If this function is called many times, how would you optimize it? +# +# Related problem: Reverse Integer +# +# Credits: +# Special thanks to @ts for adding this problem and creating all test cases. +# + +class Solution: + # @param n, an integer + # @return an integer + def reverseBits(self, n): + result = 0 + for i in xrange(32): + result <<= 1 + result |= n & 1 + n >>= 1 + return result + +if __name__ == '__main__': + print Solutoin().reverseBits(1) From 4548514f463e8e0731836984538c64d053ed85da Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Mar 2015 22:49:00 +0800 Subject: [PATCH 0123/1939] Update reverse-bits.py --- Python/reverse-bits.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py index aac560942..4c8a0f36d 100644 --- a/Python/reverse-bits.py +++ b/Python/reverse-bits.py @@ -26,4 +26,4 @@ def reverseBits(self, n): return result if __name__ == '__main__': - print Solutoin().reverseBits(1) + print Solution().reverseBits(1) From c0051b6832f0a0a8d7732f38ac065fec8140db9f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Mar 2015 22:51:35 +0800 Subject: [PATCH 0124/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9ef16ae91..a0ef8a773 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-02-24), there are total `189` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-03-08), there are total `190` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `189` problems. +Here is the classification of all `190` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -42,9 +42,12 @@ Database ##Bit Manipulation Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Reverse Bits] | [reverse-bits.py] | _O(n)_ | _O(1)_ | Easy | [Single Number] | [single-number.py] | _O(n)_ | _O(1)_ | Medium | [Single Number II] | [single-number-ii.py] | _O(n)_ | _O(1)_ | Medium | +[Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ +[reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py [Single Number]: https://oj.leetcode.com/problems/single-number/ [single-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number.py [Single Number II]: https://oj.leetcode.com/problems/single-number-ii/ From a74fdffab75f94f0af84d9c0cee435ea61bae7ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Mar 2015 22:56:17 +0800 Subject: [PATCH 0125/1939] Create number-of-1-bits.py --- Python/number-of-1-bits.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/number-of-1-bits.py diff --git a/Python/number-of-1-bits.py b/Python/number-of-1-bits.py new file mode 100644 index 000000000..3be9aa774 --- /dev/null +++ b/Python/number-of-1-bits.py @@ -0,0 +1,24 @@ +# Time: O(m) +# Space: O(1) +# +# Write a function that takes an unsigned integer +# and returns the number of ’1' bits it has (also known as the Hamming weight). +# +# For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, +# so the function should return 3. +# +# Credits: +# Special thanks to @ts for adding this problem and creating all test cases. +# +class Solution: + # @param n, an integer + # @return an integer + def hammingWeight(self, n): + result = 0 + while n: + n &= n - 1 + result += 1 + return result + +if __name__ == '__main__': + print Solution().hammingWeight(11) From 690930bb80e5dcc8656e1c788d83490c3df7838c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Mar 2015 22:58:51 +0800 Subject: [PATCH 0126/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a0ef8a773..92e4e7225 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-03-08), there are total `190` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-03-10), there are total `191` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `190` problems. +Here is the classification of all `191` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -42,10 +42,13 @@ Database ##Bit Manipulation Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Number of 1 Bits] | [number-of-1-bits.py] | _O(m)_ | _O(1)_ | Easy | [Reverse Bits] | [reverse-bits.py] | _O(n)_ | _O(1)_ | Easy | [Single Number] | [single-number.py] | _O(n)_ | _O(1)_ | Medium | [Single Number II] | [single-number-ii.py] | _O(n)_ | _O(1)_ | Medium | +[Number of 1 Bits]: https://oj.leetcode.com/problems/number-of-1-bits/ +[number-of-1-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-1-bits.py [Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ [reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py [Single Number]: https://oj.leetcode.com/problems/single-number/ From db8fb0a8503588f2e7d01f79f6b13bfb8af11f3c Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 10 Mar 2015 23:00:52 +0800 Subject: [PATCH 0127/1939] update --- Python/number-of-1-bits.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/number-of-1-bits.py b/Python/number-of-1-bits.py index 3be9aa774..2b34a304f 100644 --- a/Python/number-of-1-bits.py +++ b/Python/number-of-1-bits.py @@ -2,9 +2,9 @@ # Space: O(1) # # Write a function that takes an unsigned integer -# and returns the number of ’1' bits it has (also known as the Hamming weight). +# and returns the number of '1' bits it has (also known as the Hamming weight). # -# For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, +# For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, # so the function should return 3. # # Credits: From a852298c50d7129625e4f493a3bef2edb7c77dda Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Mar 2015 00:18:02 +0800 Subject: [PATCH 0128/1939] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 37 +++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 644f74927..89caa92dc 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -14,6 +14,39 @@ def findMedianSortedArrays(self, A, B): else: return (self.getKth(A, B, (lenA + lenB)/2) + self.getKth(A, B, (lenA + lenB)/2 + 1)) * 0.5 + def getKth(self, A, B, k): + m, n = len(A), len(B) + if m > n: + return self.getKth(B, A, k) + + left, right = 0, m + while left < right: + mid = left + (right - left) / 2 + j = k - 1 - mid + if j >= n or A[mid] < B[j]: + left = mid + 1 + else: + right = mid + + Ai_minus_1, Bj = float("-inf"), float("-inf") + if left - 1 >= 0: + Ai_minus_1 = A[left - 1] + if k - 1 - left >= 0: + Bj = B[k - 1 - left] + + return max(Ai_minus_1, Bj) + +# Time: O(log(m + n)) +# Space: O(1) +class Solution2: + # @return a float + def findMedianSortedArrays(self, A, B): + lenA, lenB = len(A), len(B) + if (lenA + lenB) % 2 == 1: + return self.getKth(A, B, (lenA + lenB)/2 + 1) + else: + return (self.getKth(A, B, (lenA + lenB)/2) + self.getKth(A, B, (lenA + lenB)/2 + 1)) * 0.5 + def getKth(self, A, B, k): b = max(0, k - len(B)) t = min(len(A), k) @@ -46,7 +79,7 @@ def getKth(self, A, B, k): # Time: O(log(m + n)) # Space: O(log(m + n)) -class Solution2: +class Solution3: # @return a float def findMedianSortedArrays(self, A, B): lenA, lenB = len(A), len(B) @@ -77,7 +110,7 @@ def getKth(self, A, i, B, j, k): return A[i + pa - 1] # using list slicing (O(k)) may be slower than solution1 -class Solution3: +class Solution4: # @return a float def findMedianSortedArrays(self, A, B): lenA, lenB = len(A), len(B) From 6fcc8dcb117d18c7478c19dce252a0c940344b14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:01:07 +0800 Subject: [PATCH 0129/1939] Create house-robber.py --- Python/house-robber.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/house-robber.py diff --git a/Python/house-robber.py b/Python/house-robber.py new file mode 100644 index 000000000..db2379811 --- /dev/null +++ b/Python/house-robber.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(1) +# +# You are a professional robber planning to rob houses along a street. +# Each house has a certain amount of money stashed, the only constraint stopping you +# from robbing each of them is that adjacent houses have security system connected +# and it will automatically contact the police if two adjacent houses were broken into on the same night. +# +# Given a list of non-negative integers representing the amount of money of each house, +# determine the maximum amount of money you can rob tonight without alerting the police. +# +class Solution: + # @param num, a list of integer + # @return an integer + def rob(self, num): + if len(num) == 0: + return 0 + + if len(num) == 1: + return num[0] + + num_i, num_i_1 = max(num[1], num[0]), num[0] + for i in xrange(2, len(num)): + num_i_1, num_i_2 = num_i, num_i_1 + num_i = max(num[i] + num_i_2, num_i_1); + + return num_i + +if __name__ == '__main__': + print Solution().rob([8,4,8,5,9,6,5,4,4,10]) From 0d02f04547445ad424cb087731123e6fb3f4e97f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:03:58 +0800 Subject: [PATCH 0130/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 92e4e7225..ee2828151 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-03-10), there are total `191` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-01), there are total `198` problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `191` problems. +Here is the classification of all `192` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -626,6 +626,7 @@ Problem | Solution | Time | Space | Difficul [Distinct Subsequences]|[distinct-subsequences.py]| _O(n^2)_ | _O(n)_ | Hard | [Dungeon Game] | [dungeon-game.py]| _O(m * n)_ | _O(m + n)_ | Hard | [Edit Distance]|[edit-distance.py]| _O(m * n)_ | _O(m + n)_ | Hard | +[House Robber]| [house-robber.py] | _O(n)_ | _O(1)_ | Easy | [Interleaving String]|[interleaving-string.py]| _O(m * n)_ | _O(m + n)_ | Hard | [Maximal Rectangle]|[maximal-rectangle.py]| _O(n^2)_ | _O(n)_ | Hard | [Maximum Product Subarray]|[maximum-product-subarray.py]| _O(n)_ | _O(1)_ | Medium | @@ -655,6 +656,8 @@ Problem | Solution | Time | Space | Difficul [dungeon-game.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/dungeon-game.py [Edit Distance]:https://oj.leetcode.com/problems/edit-distance/ [edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/edit-distance.py +[House Robber]:https://oj.leetcode.com/problems/house-robber/ +[house-robber.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/house-robber.py [Interleaving String]:https://oj.leetcode.com/problems/interleaving-string/ [interleaving-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/interleaving-string.py [Maximal Rectangle]:https://oj.leetcode.com/problems/maximal-rectangle/ From 4913a84c928eb82c72c462a4f1c6efe992307f3a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:21:40 +0800 Subject: [PATCH 0131/1939] Create rising-temperature.sql --- MySQL/rising-temperature.sql | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 MySQL/rising-temperature.sql diff --git a/MySQL/rising-temperature.sql b/MySQL/rising-temperature.sql new file mode 100644 index 000000000..91c25d228 --- /dev/null +++ b/MySQL/rising-temperature.sql @@ -0,0 +1,28 @@ +# Time: O(n^2) +# Space: O(n) +# +# Given a Weather table, write a SQL query to find all dates' +# Ids with higher temperature compared to its previous (yesterday's) dates. +# +# +---------+------------+------------------+ +# | Id(INT) | Date(DATE) | Temperature(INT) | +# +---------+------------+------------------+ +# | 1 | 2015-01-01 | 10 | +# | 2 | 2015-01-02 | 25 | +# | 3 | 2015-01-03 | 20 | +# | 4 | 2015-01-04 | 30 | +# +---------+------------+------------------+ +# For example, return the following Ids for the above Weather table: +# +----+ +# | Id | +# +----+ +# | 2 | +# | 4 | +# +----+ +# + +# Write your MySQL query statement below +SELECT wt1.Id +FROM Weather wt1, Weather wt2 +WHERE wt1.Temperature > wt2.Temperature AND + TO_DAYS(wt1.DATE)-TO_DAYS(wt2.DATE)=1; From e9bff6a2eb0efb239ddd26c0329794946cc800fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:23:39 +0800 Subject: [PATCH 0132/1939] Create delete-duplicate-emails.sql --- MySQL/delete-duplicate-emails.sql | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 MySQL/delete-duplicate-emails.sql diff --git a/MySQL/delete-duplicate-emails.sql b/MySQL/delete-duplicate-emails.sql new file mode 100644 index 000000000..b098426ca --- /dev/null +++ b/MySQL/delete-duplicate-emails.sql @@ -0,0 +1,28 @@ +# Time: O(n^2) +# Space: O(n) +# +# Write a SQL query to delete all duplicate email entries in a table named Person, +# keeping only unique emails based on its smallest Id. +# +# +----+------------------+ +# | Id | Email | +# +----+------------------+ +# | 1 | john@example.com | +# | 2 | bob@example.com | +# | 3 | john@example.com | +# +----+------------------+ +# Id is the primary key column for this table. +# For example, after running your query, the above Person table should have the following rows: +# +# +----+------------------+ +# | Id | Email | +# +----+------------------+ +# | 1 | john@example.com | +# | 2 | bob@example.com | +# +----+------------------+ +# + +# Write your MySQL query statement below +DELETE p1 +FROM Person p1, Person p2 +WHERE p1.Email = p2.Email AND p1.Id > p2.Id From abc2545d9f961708c351c75c5dff7786d2c931fe Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 1 Apr 2015 23:35:30 +0800 Subject: [PATCH 0133/1939] add more solutions --- Shell/tenth-line.sh | 26 ++++++++++++++++++++++++++ Shell/transpose-file.sh | 35 +++++++++++++++++++++++++++++++++++ Shell/valid-phone-numbers.sh | 33 +++++++++++++++++++++++++++++++++ Shell/word-frequency.sh | 29 +++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+) create mode 100644 Shell/tenth-line.sh create mode 100644 Shell/transpose-file.sh create mode 100644 Shell/valid-phone-numbers.sh create mode 100644 Shell/word-frequency.sh diff --git a/Shell/tenth-line.sh b/Shell/tenth-line.sh new file mode 100644 index 000000000..b8ca175d2 --- /dev/null +++ b/Shell/tenth-line.sh @@ -0,0 +1,26 @@ +# Time: O(n) +# Space: O(1) +# +# How would you print just the 10th line of a file? +# +# For example, assume that file.txt has the following content: +# +# Line 1 +# Line 2 +# Line 3 +# Line 4 +# Line 5 +# Line 6 +# Line 7 +# Line 8 +# Line 9 +# Line 10 +# Your script should output the tenth line, which is: +# Line 10 +# +# Hint: +# 1. If the file contains less than 10 lines, what should you output? +# 2. There's at least three different solutions. Try to explore all possibilities. +# +# Read from the file file.txt and output the tenth line to stdout. +awk '{if(NR==10) print $0}' file.txt diff --git a/Shell/transpose-file.sh b/Shell/transpose-file.sh new file mode 100644 index 000000000..e912f219d --- /dev/null +++ b/Shell/transpose-file.sh @@ -0,0 +1,35 @@ +# Time: O(n^2) +# Space: O(n^2) +# +# Given a text file file.txt, transpose its content. +# +# You may assume that each row has the same number of +# columns and each field is separated by the ' ' character. +# +# For example, if file.txt has the following content: +# +# name age +# alice 21 +# ryan 30 +# Output the following: +# +# name alice ryan +# age 21 30 +# + +# Read from the file file.txt and print its transposed content to stdout. +awk ' +{ + for (i = 1; i <= NF; i++) { + if(NR == 1) { + s[i] = $i; + } else { + s[i] = s[i] " " $i; + } + } +} +END { + for (i = 1; s[i] != ""; i++) { + print s[i]; + } +}' file.txt diff --git a/Shell/valid-phone-numbers.sh b/Shell/valid-phone-numbers.sh new file mode 100644 index 000000000..561fde3a0 --- /dev/null +++ b/Shell/valid-phone-numbers.sh @@ -0,0 +1,33 @@ +# Time: O(n) +# Space: O(1) +# +# Given a text file file.txt that contains list of +# phone numbers (one per line), write a one liner +# bash script to print all valid phone numbers. +# +# You may assume that a valid phone number must +# appear in one of the following two formats: +# (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit) +# +# You may also assume each line in the text file +# must not contain leading or trailing white spaces. +# +# For example, assume that file.txt has the following content: +# +# 987-123-4567 +# 123 456 7890 +# (123) 456-7890 +# Your script should output the following valid phone numbers: +# 987-123-4567 +# (123) 456-7890 +# +# +# Read from the file file.txt and output all valid phone numbers to stdout. +# Using grep: +grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt + +# Using sed: +sed -n -E '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt + +# Using awk: +awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt diff --git a/Shell/word-frequency.sh b/Shell/word-frequency.sh new file mode 100644 index 000000000..1775f0504 --- /dev/null +++ b/Shell/word-frequency.sh @@ -0,0 +1,29 @@ +# Time: O(n) +# Space: O(k), k is number of words +# +# Write a bash script to calculate the frequency of each word in a text file words.txt. +# +# For simplicity sake, you may assume: +# +# words.txt contains only lowercase characters and +# space ' ' characters. +# Each word must consist of lowercase characters only. +# Words are separated by one or more whitespace characters. +# For example, assume that words.txt has the following content: +# +# the day is sunny the the +# the sunny is is +# Your script should output the following, +# sorted by descending frequency: +# the 4 +# is 3 +# sunny 2 +# day 1 +# Note: +# Don't worry about handling ties, +# it is guaranteed that each word's frequency count is unique. +# + +# Read from the file words.txt and output the word frequency list to stdout. +awk '{for(i=1;i<=NF;i++) a[$i]++} END {for(k in a) print k,a[k]}' words.txt | sort -k2 -nr + From cadd4ce23b19aa8e2473c18e2ae437dd02d125de Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:51:55 +0800 Subject: [PATCH 0134/1939] Update README.md --- README.md | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ee2828151..724f12754 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-01), there are total `198` problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-01), there are 182 algorithm / 12 database / 4 shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `192` problems. +Here is the classification of all `198` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -37,6 +37,12 @@ Database * [SQL](https://github.com/kamyu104/LeetCode#sql) + +Shell +=== + +* [Shell](https://github.com/kamyu104/LeetCode#shell) + --- ##Bit Manipulation @@ -768,3 +774,21 @@ Problem | Solution | Time | Space | Difficul [Second Highest Salary]:https://oj.leetcode.com/problems/second-highest-salary/ [second-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/second-highest-salary.sql +--- + +##Shell +Problem | Solution | Time | Space | Difficulty | Notes +--------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Tenth Line] | [tenth-line.sh] | _O(n)_ | _O(1)_ | Easy | +[Transpose File] | [transpose-file.sh] | _O(n^2)_ | _O(n^2)_ | Medium | +[Valid Phone Numbers] | [valid-phone-numbers.sh] | _O(n)_ | _O(1)_ | Easy | +[Word Frequency] | [word-frequency.sh] | _O(n)_ | _O(k)_ | Medium | + +[Tenth Line]:https://oj.leetcode.com/problems/tenth-line/ +[tenth-line.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/tenth-line.sh +[Transpose File]:https://oj.leetcode.com/problems/transpose-file/ +[transpose-file.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/transpose-file.sh +[Valid Phone Numbers]:https://oj.leetcode.com/problems/valid-phone-numbers/ +[valid-phone-numbers.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/valid-phone-numbers.sh +[Word Frequency]:https://oj.leetcode.com/problems/word-frequency/ +[word-frequency.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/word-frequency.sh From 6b219f9cbd5dd56cf870a12d7c7d2c9d9f7d8954 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:58:36 +0800 Subject: [PATCH 0135/1939] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 724f12754..3e3840a83 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-04-01), there are 182 algorithm / 12 database / 4 shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-01), there are `182` Algorithm / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. Here is the classification of all `198` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -745,12 +745,14 @@ Problem | Solution | Time | Space | Difficul [Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | [Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | [Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | +[Delete Duplicate Emails] | [delete-duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Department Highest Salary] | [department-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Department Top Three Salaries] | [department-top-three-salaries.sql] | _O(n^2)_ | _O(n)_ | Hard | [Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | +[Rising Temperature] | [customers-who-never-order.sql] | _O(n^2)_ | _O(n)_ | Easy | [Second Highest Salary] | [second-highest-salary.sql] | _O(n)_ | _O(1)_ | Easy | [Combine Two Tables]:https://oj.leetcode.com/problems/combine-two-tables/ @@ -759,6 +761,8 @@ Problem | Solution | Time | Space | Difficul [consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql [Customers Who Never Order]:https://oj.leetcode.com/problems/customers-who-never-order/ [customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql +[Delete Duplicate Emails]:https://oj.leetcode.com/problems/delete-duplicate-emails/ +[delete-duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/delete-duplicate-emails.sql [Department Highest Salary]:https://oj.leetcode.com/problems/department-highest-salary/ [department-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-highest-salary.sql [Department Top Three Salaries]:https://oj.leetcode.com/problems/department-top-three-salaries/ @@ -771,6 +775,8 @@ Problem | Solution | Time | Space | Difficul [nth-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/nth-highest-salary.sql [Rank Scores]:https://oj.leetcode.com/problems/rank-scores/ [rank-scores.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/rank-scores.sql +[Rising Temperature]:https://oj.leetcode.com/problems/rising-temperature/ +[rising-temperature.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/rising-temperature.sql [Second Highest Salary]:https://oj.leetcode.com/problems/second-highest-salary/ [second-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/second-highest-salary.sql From f77426926da5c877a4ee82e7e77ddfe901304e70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Apr 2015 23:59:27 +0800 Subject: [PATCH 0136/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e3840a83..47e32f3bd 100644 --- a/README.md +++ b/README.md @@ -752,7 +752,7 @@ Problem | Solution | Time | Space | Difficul [Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | [Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | [Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | -[Rising Temperature] | [customers-who-never-order.sql] | _O(n^2)_ | _O(n)_ | Easy | +[Rising Temperature] | [rising-temperature.sql] | _O(n^2)_ | _O(n)_ | Easy | [Second Highest Salary] | [second-highest-salary.sql] | _O(n)_ | _O(1)_ | Easy | [Combine Two Tables]:https://oj.leetcode.com/problems/combine-two-tables/ From e27043c0459fe8047296ae74fd42555b0e69e9b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Apr 2015 00:02:31 +0800 Subject: [PATCH 0137/1939] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 47e32f3bd..457ae57e5 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ LeetCode ======== -Up to date (2015-04-01), there are `182` Algorithm / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-01), there are `182` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. Here is the classification of all `198` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- -Algorithm +Algorithms ==== * [Bit Manipulation](https://github.com/kamyu104/LeetCode#bit-manipulation) @@ -41,7 +41,7 @@ Database Shell === -* [Shell](https://github.com/kamyu104/LeetCode#shell) +* [Bash](https://github.com/kamyu104/LeetCode#bash) --- @@ -782,7 +782,7 @@ Problem | Solution | Time | Space | Difficul --- -##Shell +##Bash Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Tenth Line] | [tenth-line.sh] | _O(n)_ | _O(1)_ | Easy | From b71dd3e94eb5d7a73ee50f9cb997d112f6e76e76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Apr 2015 00:03:47 +0800 Subject: [PATCH 0138/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 457ae57e5..c82e22458 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Database Shell === -* [Bash](https://github.com/kamyu104/LeetCode#bash) +* [Shell Script](https://github.com/kamyu104/LeetCode#shell-script) --- @@ -782,7 +782,7 @@ Problem | Solution | Time | Space | Difficul --- -##Bash +##Shell Script Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Tenth Line] | [tenth-line.sh] | _O(n)_ | _O(1)_ | Easy | From 8ed1e1828223ed2a198b93172b615c1ff4b4904e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:14:32 +0800 Subject: [PATCH 0139/1939] Create binary-tree-right-side-view.py --- Python/binary-tree-right-side-view.py | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/binary-tree-right-side-view.py diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py new file mode 100644 index 000000000..17805d36f --- /dev/null +++ b/Python/binary-tree-right-side-view.py @@ -0,0 +1,43 @@ +# Time: O(n) +# Space: O(n) +# +# Given a binary tree, imagine yourself standing on the right side of it, +# return the values of the nodes you can see ordered from top to bottom. +# +# For example: +# Given the following binary tree, +# 1 <--- +# / \ +# 2 3 <--- +# \ \ +# 5 4 <--- +# You should return [1, 3, 4]. +# + +# Definition for a binary tree node +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param root, a tree node + # @return a list of integers + def rightSideView(self, root): + if root is None: + return [] + + result, current = [], [root] + while current: + next_level = [] + for i, node in enumerate(current): + if node.left: + next_level.append(node.left) + if node.right: + next_level.append(node.right) + if i == len(current) - 1: + result.append(node.val) + current = next_level + + return result From 0d7ce51e998e31dc7dbf7762ac4b75b346eba28d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:21:56 +0800 Subject: [PATCH 0140/1939] Update binary-tree-right-side-view.py --- Python/binary-tree-right-side-view.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py index 17805d36f..5af646f51 100644 --- a/Python/binary-tree-right-side-view.py +++ b/Python/binary-tree-right-side-view.py @@ -41,3 +41,12 @@ def rightSideView(self, root): current = next_level return result + +if __name__ == "__main__": + root = TreeNode(1) + root.left = TreeNode(2) + root.right = TreeNode(3) + root.left.right = TreeNode(5) + root.right.right = TreeNode(4) + result = Solution().rightSideView(root) + print result From 57823681dcb5505c661bd2e632508bf484cabe7a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:27:43 +0800 Subject: [PATCH 0141/1939] Update README.md --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c82e22458..1925a6adb 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-01), there are `182` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-04), there are `183` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `198` problems. +Here is the classification of all `199` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -555,7 +555,8 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Binary Tree Level Order Traversal]| [binary-tree-level-order-traversal.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | +[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | +[Binary Tree Right Side View] | [binary-tree-right-side-view.py] | _O(n)_ | _O(n)_ | Medium | [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | @@ -564,6 +565,8 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ [binary-tree-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal.py +[Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ +[binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py [Binary Tree Level Order Traversal II]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ [binary-tree-level-order-traversal-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal-ii.py [Binary Tree Zigzag Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ From 8111d7abba4663f2db6262d30d894776a3fb3b24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:39:16 +0800 Subject: [PATCH 0142/1939] Update binary-tree-right-side-view.py --- Python/binary-tree-right-side-view.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py index 5af646f51..460ccf9ee 100644 --- a/Python/binary-tree-right-side-view.py +++ b/Python/binary-tree-right-side-view.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(n) +# Space: O(h) # # Given a binary tree, imagine yourself standing on the right side of it, # return the values of the nodes you can see ordered from top to bottom. @@ -22,6 +22,27 @@ # self.right = None class Solution: + # @param root, a tree node + # @return a list of integers + def rightSideView(self, root): + result = [] + self.rightSideViewDFS(root, 1, result) + return result + + def rightSideViewDFS(self, node, depth, result): + if not node: + return + + if depth > len(result): + result.append(node.val) + + self.rightSideViewDFS(node.right, depth+1, result) + self.rightSideViewDFS(node.left, depth+1, result) + +# BFS solution +# Time: O(n) +# Space: O(n) +class Solution2: # @param root, a tree node # @return a list of integers def rightSideView(self, root): From 66b8cdaaf23f0e24b4d3ffcc60cd8aeacaa608b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Apr 2015 23:41:35 +0800 Subject: [PATCH 0143/1939] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1925a6adb..c5c84a491 100644 --- a/README.md +++ b/README.md @@ -555,8 +555,7 @@ Problem | Solution | Time | Space | Difficul Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Binary Tree Level Order Traversal]| [binary-tree-level-order-traversal.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Right Side View] | [binary-tree-right-side-view.py] | _O(n)_ | _O(n)_ | Medium | +[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | @@ -565,8 +564,6 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ [binary-tree-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal.py -[Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ -[binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py [Binary Tree Level Order Traversal II]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ [binary-tree-level-order-traversal-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal-ii.py [Binary Tree Zigzag Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ @@ -585,6 +582,7 @@ Problem | Solution | Time | Space | Difficul ##Depth-First Search Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Binary Tree Right Side View] | [binary-tree-right-side-view.py] | _O(n)_ | _O(h)_ | Medium | [Combination Sum]| [combination-sum.py] | _O(n^m)_ | _O(m)_ | Medium | [Combination Sum II]| [combination-sum-ii.py]| _O(n! / m!(n-m)!)_| _O(m)_ | Medium | [Combinations] | [combinations.py] | _O(n!)_ | _O(n)_ | Medium | @@ -598,6 +596,8 @@ Problem | Solution | Time | Space | Difficul [Sudoku Solver] | [sudoku-solver.py] | _O((9!)^9)_ | _O(1)_ | Hard | [Word Search] | [word-search.py] | _O(m * n * 3^p)_ | _O(m * n * p)_ | Medium | +[Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ +[binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py [Combination Sum]:https://oj.leetcode.com/problems/combination-sum/ [combination-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/combination-sum.py [Combination Sum II]:https://oj.leetcode.com/problems/combination-sum-ii/ From 857272724b2706245a8ab5de972a505a661b1050 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 7 Apr 2015 20:24:15 +0800 Subject: [PATCH 0144/1939] update --- Python/binary-tree-right-side-view.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py index 460ccf9ee..56d5e3db2 100644 --- a/Python/binary-tree-right-side-view.py +++ b/Python/binary-tree-right-side-view.py @@ -15,11 +15,11 @@ # # Definition for a binary tree node -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None class Solution: # @param root, a tree node From 6b74d22e50304937a4ec029c5ea0020d97e3538e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Apr 2015 21:45:48 +0800 Subject: [PATCH 0145/1939] Create number-of-islands.py --- Python/number-of-islands.py | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/number-of-islands.py diff --git a/Python/number-of-islands.py b/Python/number-of-islands.py new file mode 100644 index 000000000..2528d6887 --- /dev/null +++ b/Python/number-of-islands.py @@ -0,0 +1,56 @@ +# Time: O(m * n) +# Space: O(m * n) +# +# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. +# An island is surrounded by water and is formed by connecting adjacent lands horizontally +# or vertically. You may assume all four edges of the grid are all surrounded by water. +# +# Example 1: +# +# 11110 +# 11010 +# 11000 +# 00000 +# Answer: 1 +# +# Example 2: +# +# 11000 +# 11000 +# 00100 +# 00011 +# Answer: 3 +# + +class Solution: + # @param grid, a list of list of characters + # @return an integer + def numIslands(self, grid): + if grid == []: + return 0 + + row = len(grid) + col = len(grid[0]) + used = [[False for j in xrange(col)] for i in xrange(row)] + + count = 0 + for i in xrange(row): + for j in xrange(col): + if grid[i][j] == '1' and not used[i][j]: + self.dfs(grid, used, row, col, i, j) + count += 1 + return count + + def dfs(self, grid, used, row, col, x, y): + if grid[x][y] == '0' or used[x][y]: + return 0 + used[x][y] = True + + if x != 0: + self.dfs(grid, used, row, col, x - 1, y) + if x != row - 1: + self.dfs(grid, used, row, col, x + 1, y) + if y != 0: + self.dfs(grid, used, row, col, x, y - 1) + if y != col - 1: + self.dfs(grid, used, row, col, x, y + 1) From 09382fb2a69d6f1b4199fad0aca1279b87f9aaee Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Apr 2015 21:51:25 +0800 Subject: [PATCH 0146/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c5c84a491..88b0b5a44 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-04), there are `183` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-09), there are `184` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `199` problems. +Here is the classification of all `200` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -589,6 +589,7 @@ Problem | Solution | Time | Space | Difficul [Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2))_ | _O(n)_ | Medium | [N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | [N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | +[Number of Islands] | [number-of-islands.py] | _O(n)_ | _O(n)_ | Medium | [Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | [Path Sum] | [path-sum.py] | _O(n)_ | _O(h)_ | Easy | [Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | @@ -610,6 +611,8 @@ Problem | Solution | Time | Space | Difficul [n-queens.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/n-queens.py [N-Queens-II]:https://oj.leetcode.com/problems/n-queens-ii/ [n-queens-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/n-queens-ii.py +[Number of Islands]:https://leetcode.com/problems/number-of-islands/ +[number-of-islands.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-islands.py [Palindrome Partitioning]:https://oj.leetcode.com/problems/palindrome-partitioning/ [palindrome-partitioning.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/palindrome-partitioning.py [Path Sum]:https://oj.leetcode.com/problems/path-sum/ From c42f0d7c6337184454224778d85ae9f974f8623d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Apr 2015 22:31:53 +0800 Subject: [PATCH 0147/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88b0b5a44..be5284031 100644 --- a/README.md +++ b/README.md @@ -589,7 +589,7 @@ Problem | Solution | Time | Space | Difficul [Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2))_ | _O(n)_ | Medium | [N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | [N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | -[Number of Islands] | [number-of-islands.py] | _O(n)_ | _O(n)_ | Medium | +[Number of Islands] | [number-of-islands.py] | _O(m * n)_ | _O(m * n)_| Medium | [Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | [Path Sum] | [path-sum.py] | _O(n)_ | _O(h)_ | Easy | [Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | From beec39a47e9d83c2ebf5ba60f3c52e42e9670f4c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Apr 2015 02:19:28 +0800 Subject: [PATCH 0148/1939] Create bitwise-and-of-numbers-range.py --- Python/bitwise-and-of-numbers-range.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/bitwise-and-of-numbers-range.py diff --git a/Python/bitwise-and-of-numbers-range.py b/Python/bitwise-and-of-numbers-range.py new file mode 100644 index 000000000..156dbbb3a --- /dev/null +++ b/Python/bitwise-and-of-numbers-range.py @@ -0,0 +1,21 @@ +# Time: O(1) +# Space: O(1) +# +# Given a range [m, n] where 0 <= m <= n <= 2147483647, +# return the bitwise AND of all numbers in this range, inclusive. +# +# For example, given the range [5, 7], you should return 4. +# + +class Solution: + # @param m, an integer + # @param n, an integer + # @return an integer + def rangeBitwiseAnd(self, m, n): + i = 0 + while n-m >> i: + i += 1 + return n&m >> i << i + +if __name__ == '__main__': + print Solution().rangeBitwiseAnd(5, 7) From 3b3ac47f1d51fcaf67169da95661ab9d118ad89b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Apr 2015 02:23:23 +0800 Subject: [PATCH 0149/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index be5284031..0f705a401 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-09), there are `184` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-17), there are `185` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `200` problems. +Here is the classification of all `201` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -50,6 +50,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Number of 1 Bits] | [number-of-1-bits.py] | _O(m)_ | _O(1)_ | Easy | [Reverse Bits] | [reverse-bits.py] | _O(n)_ | _O(1)_ | Easy | +[Bitwise AND of Numbers Range] | [bitwise-and-of-numbers-range.py] | _O(1)_ | _O(1)_ | Medium | [Single Number] | [single-number.py] | _O(n)_ | _O(1)_ | Medium | [Single Number II] | [single-number-ii.py] | _O(n)_ | _O(1)_ | Medium | @@ -57,6 +58,8 @@ Problem | Solution | Time | Space | Difficul [number-of-1-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-1-bits.py [Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ [reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py +[Bitwise AND of Numbers Range]: https://leetcode.com/problems/bitwise-and-of-numbers-range/ +[bitwise-and-of-numbers-range.py]: https://github.com/kamyu104/LeetCode/blob/master/bitwise-and-of-numbers-range.py [Single Number]: https://oj.leetcode.com/problems/single-number/ [single-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number.py [Single Number II]: https://oj.leetcode.com/problems/single-number-ii/ From 161b1b2f54222d1bf6cb8e2235ef888516b7dbf7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Apr 2015 02:24:56 +0800 Subject: [PATCH 0150/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f705a401..50db28a69 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Problem | Solution | Time | Space | Difficul [Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ [reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py [Bitwise AND of Numbers Range]: https://leetcode.com/problems/bitwise-and-of-numbers-range/ -[bitwise-and-of-numbers-range.py]: https://github.com/kamyu104/LeetCode/blob/master/bitwise-and-of-numbers-range.py +[bitwise-and-of-numbers-range.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/bitwise-and-of-numbers-range.py [Single Number]: https://oj.leetcode.com/problems/single-number/ [single-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number.py [Single Number II]: https://oj.leetcode.com/problems/single-number-ii/ From 596cb4ab4338b13a38af28ab8bc14e0b2e3ea09b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Apr 2015 02:29:10 +0800 Subject: [PATCH 0151/1939] Update bitwise-and-of-numbers-range.py --- Python/bitwise-and-of-numbers-range.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/bitwise-and-of-numbers-range.py b/Python/bitwise-and-of-numbers-range.py index 156dbbb3a..f8b269d22 100644 --- a/Python/bitwise-and-of-numbers-range.py +++ b/Python/bitwise-and-of-numbers-range.py @@ -12,8 +12,9 @@ class Solution: # @param n, an integer # @return an integer def rangeBitwiseAnd(self, m, n): - i = 0 - while n-m >> i: + i, diff = 0, n-m + while diff: + diff >>= 1 i += 1 return n&m >> i << i From f4ebc5058985946f692512a24d01d4b6763bb7cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 15:10:55 +0800 Subject: [PATCH 0152/1939] Update find-peak-element.py --- Python/find-peak-element.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py index 84eb19221..1fe1ac83b 100644 --- a/Python/find-peak-element.py +++ b/Python/find-peak-element.py @@ -30,10 +30,9 @@ def findPeakElement(self, num): high = mid - 1 else: low = mid + 1 - mid = low + (high - low) / 2 return low if __name__ == "__main__": # print Solution().findPeakElement([1,2,1]) - print Solution().findPeakElement([1,2,3, 1]) \ No newline at end of file + print Solution().findPeakElement([1,2,3, 1]) From 8367b081a8151a1cf202027eb8ed7ac49ef8ebb2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 16:15:34 +0800 Subject: [PATCH 0153/1939] Update search-for-a-range.py --- Python/search-for-a-range.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 505961eed..3ac30c348 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -17,10 +17,12 @@ class Solution: # @param target, an integer to be searched # @return a list of length 2, [index1, index2] def searchRange(self, A, target): - left = self.binarySearch(lambda x, y: x > y, A, target) + # Find the first index where target <= A[idx] + left = self.binarySearch(lambda x, y: x <= y, A, target) if left >= len(A) or A[left] != target: return [-1, -1] - right = self.binarySearch(lambda x, y: x >= y, A, target) + # Find the first index where target < A[idx] + right = self.binarySearch(lambda x, y: x < y, A, target) return [left, right - 1] def binarySearch(self, compare, A, target): @@ -28,11 +30,21 @@ def binarySearch(self, compare, A, target): while start < end: mid = start + (end - start) / 2 if compare(target, A[mid]): + end = mid + else: start = mid + 1 + return start + + def binarySearch2(self, compare, A, target): + start, end = 0, len(A) - 1 + while start <= end: + mid = start + (end - start) / 2 + if compare(target, A[mid]): + end = mid - 1 else: - end = mid + start = mid + 1 return start if __name__ == "__main__": print Solution().searchRange([2, 2], 3) - print Solution().searchRange([5, 7, 7, 8, 8, 10], 8) \ No newline at end of file + print Solution().searchRange([5, 7, 7, 8, 8, 10], 8) From 0ad1d70d3ae1e7efae953945d227000f61e902a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 22:55:19 +0800 Subject: [PATCH 0154/1939] Update search-for-a-range.py --- Python/search-for-a-range.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 3ac30c348..6e6c84d7b 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -44,6 +44,16 @@ def binarySearch2(self, compare, A, target): else: start = mid + 1 return start + + def binarySearch3(self, compare, A, target): + start, end = -1, len(A) + while end - start > 1: + mid = start + (end - start) / 2 + if compare(target, A[mid]): + end = mid + else: + start = mid + return end if __name__ == "__main__": print Solution().searchRange([2, 2], 3) From 5ef7272ac213bb33824de84508c0f5e567e3f5e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 22:55:57 +0800 Subject: [PATCH 0155/1939] Update search-for-a-range.py --- Python/search-for-a-range.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 6e6c84d7b..3a77a0a9e 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -46,7 +46,7 @@ def binarySearch2(self, compare, A, target): return start def binarySearch3(self, compare, A, target): - start, end = -1, len(A) + start, end = -1, len(A) - 1 while end - start > 1: mid = start + (end - start) / 2 if compare(target, A[mid]): From cdfc802af6226c7d9be48b789c6e6f878c970da7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 23:18:46 +0800 Subject: [PATCH 0156/1939] Update search-for-a-range.py --- Python/search-for-a-range.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 3a77a0a9e..4bc2e72cb 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -17,6 +17,9 @@ class Solution: # @param target, an integer to be searched # @return a list of length 2, [index1, index2] def searchRange(self, A, target): + # This is main For binarySearch3() + A += [float("inf")] + # Find the first index where target <= A[idx] left = self.binarySearch(lambda x, y: x <= y, A, target) if left >= len(A) or A[left] != target: From 9e83351f1f8d54eedf133b4cfef5886034644159 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Apr 2015 23:34:25 +0800 Subject: [PATCH 0157/1939] Update search-for-a-range.py --- Python/search-for-a-range.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 4bc2e72cb..6e6c84d7b 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -17,9 +17,6 @@ class Solution: # @param target, an integer to be searched # @return a list of length 2, [index1, index2] def searchRange(self, A, target): - # This is main For binarySearch3() - A += [float("inf")] - # Find the first index where target <= A[idx] left = self.binarySearch(lambda x, y: x <= y, A, target) if left >= len(A) or A[left] != target: @@ -49,7 +46,7 @@ def binarySearch2(self, compare, A, target): return start def binarySearch3(self, compare, A, target): - start, end = -1, len(A) - 1 + start, end = -1, len(A) while end - start > 1: mid = start + (end - start) / 2 if compare(target, A[mid]): From e81f4462c54578cdbaf4c8e1e8a80521ffa90105 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Apr 2015 03:28:05 +0800 Subject: [PATCH 0158/1939] Create happy-number.py --- Python/happy-number.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/happy-number.py diff --git a/Python/happy-number.py b/Python/happy-number.py new file mode 100644 index 000000000..7ea4a5675 --- /dev/null +++ b/Python/happy-number.py @@ -0,0 +1,34 @@ +# Time: O(k), where k is the steps to be happy number +# Space: O(k) +# +# Write an algorithm to determine if a number is "happy". +# +# A happy number is a number defined by the following process: +# Starting with any positive integer, replace the number by the sum +# of the squares of its digits, and repeat the process until +# the number equals 1 (where it will stay), or it loops endlessly +# in a cycle which does not include 1. Those numbers for which +# this process ends in 1 are happy numbers. +# +# Example: 19 is a happy number +# +# 1^2 + 9^2 = 82 +# 8^2 + 2^2 = 68 +# 6^2 + 8^2 = 100 +# 1^2 + 0^2 + 0^2 = 1 +# +class Solution: + # @param {integer} n + # @return {boolean} + def isHappy(self, n): + lookup = {} + while n != 1 and n not in lookup: + lookup[n] = True + n = self.nextNumber(n) + return n == 1 + + def nextNumber(self, n): + new = 0 + for char in str(n): + new += int(char)**2 + return new From 4a7a0e8611e1889c08905060e76de9d469739975 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Apr 2015 03:30:22 +0800 Subject: [PATCH 0159/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 50db28a69..e31adb967 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-17), there are `185` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-22), there are `186` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `201` problems. +Here is the classification of all `202` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -289,6 +289,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [4 Sum] |[4sum.py] | _O(n^2)_ ~ _O(n^4)_ | _O(n^2)_ | Medium | [Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | +[Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | [Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | @@ -303,6 +304,8 @@ Problem | Solution | Time | Space | Difficul [4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py [Anagrams]:https://oj.leetcode.com/problems/anagrams/ [anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py +[Happy Number]:https://oj.leetcode.com/problems/happy-number/ +[happy-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/happy-number.py [Longest Substring with At Most Two Distinct Characters]:https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ [longest-substring-with-at-most-two-distinct-characters.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-with-at-most-two-distinct-characters.py [Longest Substring Without Repeating Characters]:https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ From eceacfc149948c6d5c618e8ec609c05de66d939d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Apr 2015 04:07:42 +0800 Subject: [PATCH 0160/1939] Update largest-number.py --- Python/largest-number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/largest-number.py b/Python/largest-number.py index ab28367cf..8317a617b 100644 --- a/Python/largest-number.py +++ b/Python/largest-number.py @@ -1,5 +1,5 @@ -# Time: O(n^2) -# Space: O(n) +# Time: O(nlogn) +# Space: O(1) # # Given a list of non negative integers, arrange them such that they form the largest number. # From 9481800a9393b961609bbc5fdeb3683c93b43a63 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Apr 2015 04:08:18 +0800 Subject: [PATCH 0161/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e31adb967..27106b673 100644 --- a/README.md +++ b/README.md @@ -387,7 +387,7 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [Insert Interval]| [insert-interval.py] | _O(n)_ | _O(1)_ | Hard | [Insertion Sort List]|[insertion-sort-list.py] | _O(n^2)_ | _O(1)_ | Medium | -[Largest Number] | [largest-number.py] | _O(n^2)_ | _O(n)_ | Medium | +[Largest Number] | [largest-number.py] | _O(nlogn)_ | _O(1)_ | Medium | [Maximum Gap] | [maximum-gap.py]| _O(n)_ | _O(n)_ | Hard | Tricky [Merge Intervals]| [merge-intervals.py] | _O(nlogn)_ | _O(1)_ | Hard | [Merge Sorted Array]| [merge-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | From 3bd7a31356e6cca1d82f71985ad886c93277989d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Apr 2015 04:14:37 +0800 Subject: [PATCH 0162/1939] Create remove-linked-list-elements.py --- Python/remove-linked-list-elements.py | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/remove-linked-list-elements.py diff --git a/Python/remove-linked-list-elements.py b/Python/remove-linked-list-elements.py new file mode 100644 index 000000000..347370e88 --- /dev/null +++ b/Python/remove-linked-list-elements.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(1) +# +# Remove all elements from a linked list of integers that have value val. +# +# Example +# Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 +# Return: 1 --> 2 --> 3 --> 4 --> 5 +# +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param {ListNode} head + # @param {integer} val + # @return {ListNode} + def removeElements(self, head, val): + dummy = ListNode(float("-inf")) + dummy.next = head + prev, curr = dummy, dummy.next + + while curr: + if curr.val == val: + prev.next = curr.next + else: + prev = curr + + curr = curr.next + + return dummy.next + + From ae67deebec189752db71b6aa62391751d7690e6c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Apr 2015 04:18:13 +0800 Subject: [PATCH 0163/1939] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 27106b673..078e12d4b 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-22), there are `186` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-24), there are `187` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `202` problems. +Here is the classification of all `203` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -201,6 +201,7 @@ Problem | Solution | Time | Space | Difficul [Intersection of Two Linked Lists]| [intersection-of-two-linked-lists.py] | _O(m + n)_ | _O(1)_ | Easy | [Remove Duplicates from Sorted List]| [remove-duplicates-from-sorted-list.py] | _O(n)_ | _O(1)_ | Easy | [Remove Duplicates from Sorted List II]| [remove-duplicates-from-sorted-list-ii.py] | _O(n)_ | _O(1)_ | Medium | +[Remove Linked List Elements]| [remove-linked-list-elements.py] | _O(n)_ | _O(1)_ | Easy | [Reverse Linked List II]| [reverse-linked-list-ii.py] | _O(n)_ | _O(1)_ | Medium | [Reverse Nodes in k-Group]| [reverse-nodes-in-k-group.py] | _O(n)_ | _O(1)_ | Hard | [Rotate List]| [rotate-list.py] | _O(n)_ | _O(1)_ | Medium | @@ -216,6 +217,8 @@ Problem | Solution | Time | Space | Difficul [remove-duplicates-from-sorted-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list.py [Remove Duplicates from Sorted List II]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ [remove-duplicates-from-sorted-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list-ii.py +[Remove Linked List Elements]:https://oj.leetcode.com/problems/remove-linked-list-elements/ +[remove-linked-list-elements.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-linked-list-elements.py [Reverse Linked List II]:https://oj.leetcode.com/problems/reverse-linked-list-ii/ [reverse-linked-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list-ii.py [Reverse Nodes in k-Group]:https://oj.leetcode.com/problems/reverse-nodes-in-k-group/ From e889814bec5c085141a4529f099060e1aa2a1187 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Apr 2015 21:44:52 +0800 Subject: [PATCH 0164/1939] Create count-primes.py --- Python/count-primes.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/count-primes.py diff --git a/Python/count-primes.py b/Python/count-primes.py new file mode 100644 index 000000000..8c3337efd --- /dev/null +++ b/Python/count-primes.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(n) +# Description: +# +# Count the number of prime numbers less than a non-negative number, n +# +# Hint: The number n could be in the order of 100,000 to 5,000,000. +# + +from math import sqrt + +class Solution: + # @param {integer} n + # @return {integer} + def countPrimes(self, n): + if n <= 2: + return 0 + + is_prime = [True] * n + sqr = sqrt(n - 1) + + num = 0 + for i in xrange(2, n): + if is_prime[i]: + num += 1 + for j in xrange(i+i, n, i): + is_prime[j] = False + + return num + From 80e8090b39c58b9d784c216196a8e6236f98e06d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Apr 2015 21:48:43 +0800 Subject: [PATCH 0165/1939] Create count-primes.cpp --- C++/count-primes.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/count-primes.cpp diff --git a/C++/count-primes.cpp b/C++/count-primes.cpp new file mode 100644 index 000000000..dcafc14bf --- /dev/null +++ b/C++/count-primes.cpp @@ -0,0 +1,36 @@ +// Time: O(n) +// Space: O(n) +// +// Description: +// +// Count the number of prime numbers less than a non-negative number, n +// +// Hint: The number n could be in the order of 100,000 to 5,000,000. +// + +class Solution { +public: + int countPrimes(int n) { + if (2 >= n) { + return 0; + } + bool* primes = new bool[n]; + for (int i = 2; i < n; ++i) + primes[i] = true; + + int sqr = sqrt(n - 1); + int sum = 0; + for (int i = 2; i < n; ++i) { + if (primes[i]) { + ++sum; + for (int j = i + i; j < n; j += i) { + primes[j] = false; + } + } + } + + delete[] primes; + + return sum; + } +}; From 4822a69867ca74b48f242f51058b7971dea51280 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Apr 2015 21:52:23 +0800 Subject: [PATCH 0166/1939] Update README.md --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 078e12d4b..487d225a9 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-24), there are `187` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-27), there are `188` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `203` problems. +Here is the classification of all `204` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -292,7 +292,8 @@ Problem | Solution | Time | Space | Difficul --------------- | --------------- | --------------- | --------------- | -------------- | ----- [4 Sum] |[4sum.py] | _O(n^2)_ ~ _O(n^4)_ | _O(n^2)_ | Medium | [Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | -[Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | +[Count Primes] | [count-primes.py] | _O(n)_ | _O(n)_ | Easy | +[Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | [Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | [Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | [Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | @@ -307,6 +308,8 @@ Problem | Solution | Time | Space | Difficul [4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py [Anagrams]:https://oj.leetcode.com/problems/anagrams/ [anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py +[Count Primes]:https://oj.leetcode.com/problems/count-primes/ +[count-primes.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/count-primes.py [Happy Number]:https://oj.leetcode.com/problems/happy-number/ [happy-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/happy-number.py [Longest Substring with At Most Two Distinct Characters]:https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ From 93ab11c2e4dd104b13ecbe5cf4fa0aec700f62ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:41:48 +0800 Subject: [PATCH 0167/1939] Create isomorphic-strings.py --- Python/isomorphic-strings.py | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/isomorphic-strings.py diff --git a/Python/isomorphic-strings.py b/Python/isomorphic-strings.py new file mode 100644 index 000000000..d65bdb00d --- /dev/null +++ b/Python/isomorphic-strings.py @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(1) +# +# Given two strings s and t, determine if they are isomorphic. +# +# Two strings are isomorphic if the characters in s can be replaced to get t. +# +# All occurrences of a character must be replaced with another character +# while preserving the order of characters. No two characters may map to +# the same character but a character may map to itself. +# +# For example, +# Given "egg", "add", return true. +# +# Given "foo", "bar", return false. +# +# Given "paper", "title", return true. +# +# Note: +# You may assume both s and t have the same length. +# + +class Solution: + # @param {string} s + # @param {string} t + # @return {boolean} + def isIsomorphic(self, s, t): + if len(s) != len(t): + return False + + return self.halfIsom(s, t) and self.halfIsom(t, s) + + def halfIsom(self, s, t): + res = {} + for i in xrange(len(s)): + if s[i] not in res: + res[s[i]] = t[i] + elif res[s[i]] != t[i]: + return False + return True From a37f346f73ebd97a799898c93d46a6d5014e3044 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:45:20 +0800 Subject: [PATCH 0168/1939] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 487d225a9..e6761ef74 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-27), there are `188` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-04-29), there are `189` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `204` problems. +Here is the classification of all `205` problems. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- @@ -147,6 +147,7 @@ Problem | Solution | Time | Space | Difficul [Compare Version Numbers] | [compare-version-numbers.py] | _O(n)_ | _O(1)_ | Easy | [Count and Say] | [count-and-say.py]| _O(n * 2^n)_ | _O(2^n)_ | Easy | [Implement strStr()] | [implement-strstr.py] | _O(n + m)_ | _O(m)_ | Easy | `KMP Algorithm` +[Isomorphic Strings] | [isomorphic-strings.py] | _O(n)_ | _O(1)_ | Easy | [Length of Last Word] | [length-of-last-word.py] | _O(n)_ | _O(1)_ | Easy | [Longest Common Prefix] | [longest-common-prefix.py] | _O(n1 + n2 + ...)_ | _O(1)_ | Easy | [Longest Palindromic Substring] | [longest-palindromic-substring.py] | _O(n)_ | _O(n)_ | Medium | `Manacher's Algorithm` @@ -167,6 +168,8 @@ Problem | Solution | Time | Space | Difficul [compare-version-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/compare-version-numbers.py [Implement strStr()]:https://oj.leetcode.com/problems/implement-strstr/ [implement-strstr.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/implement-strstr.py +[Isomorphic Strings]:https://oj.leetcode.com/problems/isomorphic-strings/ +[isomorphic-strings.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/isomorphic-strings.py [Length of Last Word]:https://oj.leetcode.com/problems/length-of-last-word/ [length-of-last-word.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/length-of-last-word.py [Longest Common Prefix]:https://oj.leetcode.com/problems/longest-common-prefix/ @@ -175,7 +178,6 @@ Problem | Solution | Time | Space | Difficul [longest-palindromic-substring.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-palindromic-substring.py [Multiply Strings]:https://oj.leetcode.com/problems/multiply-strings/ [multiply-strings.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/multiply-strings.py - [One Edit Distance]:https://oj.leetcode.com/problems/one-edit-distance/ [one-edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/one-edit-distance.py [Reverse Words in a String]:https://oj.leetcode.com/problems/reverse-words-in-a-string/ From 1495953a6f7aa2f468a0d3d3366e760e6f8ad1f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:47:17 +0800 Subject: [PATCH 0169/1939] Create isomorphic-strings.cpp --- C++/isomorphic-strings.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/isomorphic-strings.cpp diff --git a/C++/isomorphic-strings.cpp b/C++/isomorphic-strings.cpp new file mode 100644 index 000000000..da3e0d495 --- /dev/null +++ b/C++/isomorphic-strings.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool isIsomorphic(string s, string t) { + vector m1(256, 0); + vector m2(256, 0); + int n = s.size(); + for (int i = 0; i < n; ++i) { + if (m1[s[i]] != m2[t[i]]) return false; + m1[s[i]] = i + 1; + m2[t[i]] = i + 1; + } + return true; + } +}; From 913fd43a08fce1419e92d2b2cfc79c1ddd9a3b2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:47:54 +0800 Subject: [PATCH 0170/1939] Update isomorphic-strings.cpp --- C++/isomorphic-strings.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/isomorphic-strings.cpp b/C++/isomorphic-strings.cpp index da3e0d495..e766cc2b2 100644 --- a/C++/isomorphic-strings.cpp +++ b/C++/isomorphic-strings.cpp @@ -1,6 +1,9 @@ class Solution { public: bool isIsomorphic(string s, string t) { + if (s.length() != t.length()) { + return 0; + } vector m1(256, 0); vector m2(256, 0); int n = s.size(); From fa26f59010dab83a124dea28ba59d9157f60c43d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Apr 2015 16:48:34 +0800 Subject: [PATCH 0171/1939] Update isomorphic-strings.cpp --- C++/isomorphic-strings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/isomorphic-strings.cpp b/C++/isomorphic-strings.cpp index e766cc2b2..de37015b8 100644 --- a/C++/isomorphic-strings.cpp +++ b/C++/isomorphic-strings.cpp @@ -2,7 +2,7 @@ class Solution { public: bool isIsomorphic(string s, string t) { if (s.length() != t.length()) { - return 0; + return false; } vector m1(256, 0); vector m2(256, 0); From f13b445489774bfa19a3cd26f2324c1144c8f481 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 30 Apr 2015 03:23:33 +0800 Subject: [PATCH 0172/1939] Update word-search.py --- Python/word-search.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/word-search.py b/Python/word-search.py index 434f5dbda..3166d0b00 100644 --- a/Python/word-search.py +++ b/Python/word-search.py @@ -1,5 +1,5 @@ -# Time: O(m * n * 3^p) -# Space: O(m * n + p) +# Time: O(m * n * l) +# Space: O(l) # # Given a 2D board and a word, find if the word exists in the grid. # From d3e2d00d2b6f2bd002d5af48396a542969717f6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 30 Apr 2015 03:24:09 +0800 Subject: [PATCH 0173/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e6761ef74..3b52250ed 100644 --- a/README.md +++ b/README.md @@ -609,7 +609,7 @@ Problem | Solution | Time | Space | Difficul [Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | [Restore IP Addresses] | [restore-ip-addresses.py] | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium | [Sudoku Solver] | [sudoku-solver.py] | _O((9!)^9)_ | _O(1)_ | Hard | -[Word Search] | [word-search.py] | _O(m * n * 3^p)_ | _O(m * n * p)_ | Medium | +[Word Search] | [word-search.py] | _O(m * n * l)_ | _O(l)_ | Medium | [Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ [binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py From 24c62087c183af74cb000e3f79dafb5fb4b6f458 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 May 2015 14:23:17 +0800 Subject: [PATCH 0174/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3b52250ed..dc1a0266e 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ LeetCode Up to date (2015-04-29), there are `189` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. Here is the classification of all `205` problems. +For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. --- From 8d93982fd93d6646be96555c5235f4446713ea07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 May 2015 07:58:46 +0800 Subject: [PATCH 0175/1939] Update wildcard-matching.py --- Python/wildcard-matching.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index d930727d7..4262a1458 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -98,8 +98,8 @@ def isMatch(self, s, p): class Solution4: # @return a boolean def isMatch(self, s, p): - if not p: - return not s + if not p or not s: + return not s and not p if p[0] != '*': if not s or (p[0] == s[0] or p[0] == '?'): From e8db313baa3fafbbf09b17a177be31f23c854136 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 May 2015 08:05:08 +0800 Subject: [PATCH 0176/1939] Update wildcard-matching.py --- Python/wildcard-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index 4262a1458..aeecdaf59 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -102,7 +102,7 @@ def isMatch(self, s, p): return not s and not p if p[0] != '*': - if not s or (p[0] == s[0] or p[0] == '?'): + if p[0] == s[0] or p[0] == '?': return self.isMatch(s[1:], p[1:]) else: return False From 124dc3777cbae0c00b0297ce0064964dfd6bdfb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 May 2015 08:05:34 +0800 Subject: [PATCH 0177/1939] Update wildcard-matching.py --- Python/wildcard-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index aeecdaf59..7965368aa 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -94,7 +94,7 @@ def isMatch(self, s, p): return result[len(s)][len(p)] -# recursive, slowest +# recursive, slowest, TLE class Solution4: # @return a boolean def isMatch(self, s, p): From 89d2e86913b5d2a2f4b0a441ac1527b7bfd5cfe5 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 2 May 2015 10:51:14 +0800 Subject: [PATCH 0178/1939] update --- Python/regular-expression-matching.py | 32 ++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 969a92981..67cf4b461 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -66,8 +66,38 @@ def isMatch(self, s, p): return result[len(s)][len(p)] -# recursive +# iteration class Solution3: + # @return a boolean + def isMatch(self, s, p): + p_ptr, s_ptr, last_s_ptr, last_p_ptr = 0, 0, -1, -1 + last_ptr = [] + while s_ptr < len(s): + if p_ptr < len(p) and (p_ptr == len(p) - 1 or p[p_ptr + 1] != '*') and \ + (s_ptr < len(s) and (p[p_ptr] == s[s_ptr] or p[p_ptr] == '?')): + s_ptr += 1 + p_ptr += 1 + elif p_ptr < len(p) - 1 and (p_ptr != len(p) - 1 and p[p_ptr + 1] == '*'): + p_ptr += 2 + last_ptr.append([s_ptr, p_ptr]) + elif last_ptr: + [last_s_ptr, last_p_ptr] = last_ptr.pop() + while last_ptr and p[last_p_ptr - 2] != s[last_s_ptr] and p[last_p_ptr - 2] != '.': + [last_s_ptr, last_p_ptr] = last_ptr.pop() + last_s_ptr += 1 + s_ptr = last_s_ptr + p_ptr = last_p_ptr + last_ptr.append([s_ptr, p_ptr]) + else: + return False + + while p_ptr < len(p) and p[p_ptr] == '.' and p[p_ptr + 1] == '*': + p_ptr += 2 + + return p_ptr == len(p) + +# recursive +class Solution4: # @return a boolean def isMatch(self, s, p): if not p: From ff9c349212fb1ebfa8b1f371567274787ef070e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 May 2015 11:09:01 +0800 Subject: [PATCH 0179/1939] Update regular-expression-matching.py --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 67cf4b461..ce481e622 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -74,7 +74,7 @@ def isMatch(self, s, p): last_ptr = [] while s_ptr < len(s): if p_ptr < len(p) and (p_ptr == len(p) - 1 or p[p_ptr + 1] != '*') and \ - (s_ptr < len(s) and (p[p_ptr] == s[s_ptr] or p[p_ptr] == '?')): + (s_ptr < len(s) and (p[p_ptr] == s[s_ptr] or p[p_ptr] == '.')): s_ptr += 1 p_ptr += 1 elif p_ptr < len(p) - 1 and (p_ptr != len(p) - 1 and p[p_ptr + 1] == '*'): From d84bd7beb776a9bee11aa579c6f59c181e617a74 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 2 May 2015 11:17:55 +0800 Subject: [PATCH 0180/1939] update --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index ce481e622..6c39e84e8 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -91,7 +91,7 @@ def isMatch(self, s, p): else: return False - while p_ptr < len(p) and p[p_ptr] == '.' and p[p_ptr + 1] == '*': + while p_ptr < len(p) - 1 and p[p_ptr] == '.' and p[p_ptr + 1] == '*': p_ptr += 2 return p_ptr == len(p) From 8f500756d0d81a065d8952a72f7894ba3155b2ea Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 2 May 2015 11:35:43 +0800 Subject: [PATCH 0181/1939] update --- Python/regular-expression-matching.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 6c39e84e8..194fd2f25 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -84,10 +84,14 @@ def isMatch(self, s, p): [last_s_ptr, last_p_ptr] = last_ptr.pop() while last_ptr and p[last_p_ptr - 2] != s[last_s_ptr] and p[last_p_ptr - 2] != '.': [last_s_ptr, last_p_ptr] = last_ptr.pop() - last_s_ptr += 1 - s_ptr = last_s_ptr - p_ptr = last_p_ptr - last_ptr.append([s_ptr, p_ptr]) + + if p[last_p_ptr - 2] == s[last_s_ptr] or p[last_p_ptr - 2] == '.': + last_s_ptr += 1 + s_ptr = last_s_ptr + p_ptr = last_p_ptr + last_ptr.append([s_ptr, p_ptr]) + else: + return False else: return False @@ -116,7 +120,7 @@ def isMatch(self, s, p): return self.isMatch(s, p[2:]) if __name__ == "__main__": - print Solution().isMatch("abcd","d*") + print Solution3().isMatch("abab", "a*b*") print Solution().isMatch("aaaaaaaaaaaaab", "a*a*a*a*a*a*a*a*a*a*c") print Solution().isMatch("aa","a") print Solution().isMatch("aa","aa") From 5d22cadee6fadb9b14fb495bc1feef3b99cbc3f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 May 2015 22:26:31 +0800 Subject: [PATCH 0182/1939] Update jump-game-ii.py --- Python/jump-game-ii.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Python/jump-game-ii.py b/Python/jump-game-ii.py index 6a660882e..bd771dabf 100644 --- a/Python/jump-game-ii.py +++ b/Python/jump-game-ii.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(n) # Space: O(1) # # Given an array of non-negative integers, you are initially positioned at the first index of the array. @@ -14,6 +14,24 @@ # class Solution: + # @param A, a list of integers + # @return an integer + def jump(self, A): + jump_count = 0 + reachable = 0 + curr_reachable = 0 + for i, length in enumerate(A): + if i > reachable: + return -1 + if i > curr_reachable: + curr_reachable = reachable + jump_count += 1 + reachable = max(reachable, i + length) + return jump_count + +# Time: O(n^2) +# Space: O(1) +class Solution2: # @param A, a list of integers # @return an integer def jump(self, A): From e3ab713c6a7729675d0f6c33aaeba51f24d88949 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 May 2015 22:28:34 +0800 Subject: [PATCH 0183/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dc1a0266e..5246e03da 100644 --- a/README.md +++ b/README.md @@ -734,7 +734,7 @@ Problem | Solution | Time | Space | Difficul [Container With Most Water]| [container-with-most-water.py] | _O(n)_ | _O(1)_ | Medium | [Gas Station]| [gas-station.py] | _O(n)_ | _O(1)_ | Medium | [Jump Game] | [jump-game.py] | _O(n)_ | _O(1)_ | Medium | -[Jump Game II] | [jump-game-ii.py] | _O(n^2)_ | _O(1)_ | Hard | +[Jump Game II] | [jump-game-ii.py] | _O(n)_ | _O(1)_ | Hard | [Largest Rectangle in Histogram] | [largest-rectangle-in-histogram.py] | _O(n)_ | _O(n)_ | Hard | Tricky [Trapping Rain Water] | [trapping-rain-water.py] | _O(n)_ | _O(1)_ | Hard | Tricky [Wildcard Matching] | [wildcard-matching.py] | _O(m + n)_ | _O(1)_ | Hard | Tricky From 26276ab2bae5c200a4a30a3078008911080fd448 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 May 2015 14:18:20 +0800 Subject: [PATCH 0184/1939] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 89caa92dc..e9708c058 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -23,10 +23,10 @@ def getKth(self, A, B, k): while left < right: mid = left + (right - left) / 2 j = k - 1 - mid - if j >= n or A[mid] < B[j]: - left = mid + 1 - else: + if 0 <= j and j < n and A[mid] >= B[j]: right = mid + else: + left = mid + 1 Ai_minus_1, Bj = float("-inf"), float("-inf") if left - 1 >= 0: From e54748e9a83844455661f5fe76980728e9d46690 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 May 2015 14:20:41 +0800 Subject: [PATCH 0185/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5246e03da..9f206eb5b 100644 --- a/README.md +++ b/README.md @@ -532,9 +532,9 @@ Problem | Solution | Time | Space | Difficul [Find Minimum in Rotated Sorted Array] | [find-minimum-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Medium | [Find Minimum in Rotated Sorted Array II] | [find-minimum-in-rotated-sorted-array-ii.py] | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard | [Find Peak Element] | [find-peak-element.py] | _O(logn)_ | _O(1)_ | Medium | -[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n)_ | _O(1)_ | Hard | +[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n))_ | _O(1)_ | Hard | [Pow(x, n)] | [powx-n.py] | _O(logn)_ | _O(logn)_ | Medium | -[Search a 2D Matrix] | [search-a-2d-matrix.py] | _O(log m + logn)_ | _O(1)_ | Medium | +[Search a 2D Matrix] | [search-a-2d-matrix.py] | _O(logm + logn)_ | _O(1)_ | Medium | [Search for a Range] | [search-for-a-range.py] | _O(logn)_ | _O(1)_ | Medium | [Search in Rotated Sorted Array] | [search-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Hard | [Search in Rotated Sorted Array II] | [search-in-rotated-sorted-array-ii.py] | _O(logn)_ | _O(1)_ | Medium | From 10dcf4e01e973185ee5bb59c04cd8bd6a167861f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 4 May 2015 14:54:45 +0800 Subject: [PATCH 0186/1939] update --- Python/4sum.py | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/Python/4sum.py b/Python/4sum.py index c049c577c..a1a77ef20 100644 --- a/Python/4sum.py +++ b/Python/4sum.py @@ -1,5 +1,5 @@ -# Time: O(n^2) ~ O(n^4) -# Space: O(n^2) +# Time: O(n^2 * p) +# Space: O(n^2 * p) # # Given an array S of n integers, # are there elements a, b, c, and d in S such that a + b + c + d = target? @@ -17,6 +17,36 @@ # class Solution: + # @return a list of lists of length 4, [[val1,val2,val3,val4]] + def fourSum(self, nums, target): + nums, result, lookup = sorted(nums), [], {} + for i in xrange(0, len(nums) - 1): + for j in xrange(i + 1, len(nums)): + if nums[i] + nums[j] not in lookup: + lookup[nums[i] + nums[j]] = [] + is_duplicated = False + for [x, y] in lookup[nums[i] + nums[j]]: + if nums[x] == nums[i]: + is_duplicated = True + break + if not is_duplicated: + lookup[nums[i] + nums[j]].append([i, j]) + ans = {} + for c in xrange(2, len(nums)): + for d in xrange(c+1, len(nums)): + if target - nums[c] - nums[d] in lookup: + for [a, b] in lookup[target - nums[c] - nums[d]]: + if b < c: + quad = [nums[a], nums[b], nums[c], nums[d]] + quad_hash = " ".join(str(quad)) + if quad_hash not in ans: + ans[quad_hash] = True + result.append(quad) + return result + +# Time: O(n^2 * p) ~ O(n^4) +# Space: O(n^2) +class Solution2: # @return a list of lists of length 4, [[val1,val2,val3,val4]] def fourSum(self, nums, target): nums, result, lookup = sorted(nums), [], {} From 96f209b11cf8c787b13a149845ee6cdb16e0db0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 May 2015 14:55:32 +0800 Subject: [PATCH 0187/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f206eb5b..e6375ba70 100644 --- a/README.md +++ b/README.md @@ -293,7 +293,7 @@ Problem | Solution | Time | Space | Difficul ##Hash Table Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[4 Sum] |[4sum.py] | _O(n^2)_ ~ _O(n^4)_ | _O(n^2)_ | Medium | +[4 Sum] |[4sum.py] | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium | [Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | [Count Primes] | [count-primes.py] | _O(n)_ | _O(n)_ | Easy | [Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | From e72894b16449e2dbf444c50722e87142381a37a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 May 2015 17:19:22 +0800 Subject: [PATCH 0188/1939] Update word-break.py --- Python/word-break.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/Python/word-break.py b/Python/word-break.py index bd39ed955..b1f9ad9ee 100644 --- a/Python/word-break.py +++ b/Python/word-break.py @@ -12,6 +12,34 @@ # class Solution: + # @param s: A string s + # @param dict: A dictionary of words dict + def wordSegmentation(self, s, dict): + if not s: + return True + + cnt = {} + for w in dict: + for c in w: + if c not in cnt: + cnt[c] = 0 + cnt[c] += 1 + for c in s: + if c not in cnt: + return False + + n = len(s) + possible = [False for _ in xrange(n)] + for i in xrange(n): + for j in reversed(xrange(i + 1)): + if (j == 0 or possible[j-1]) and s[j:i+1] in dict: + possible[i] = True + break + + return possible[n-1] + +# slower +class Solution2: # @param s, a string # @param dict, a set of string # @return a boolean @@ -29,4 +57,4 @@ def wordBreak(self, s, dict): return possible[n-1] if __name__ == "__main__": - print Solution().wordBreak("leetcode", ["leet", "code"]) \ No newline at end of file + print Solution().wordBreak("leetcode", ["leet", "code"]) From ec6bb573b3173bb80a7fc2fd7ef808096b7e4dcc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 13:59:49 +0800 Subject: [PATCH 0189/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e6375ba70..59a34d549 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-04-29), there are `189` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-05), there are `190` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `205` problems. +Here is the classification of all `206` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. From b72a81ee132abf84dc16197252559093676d28d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 20:47:28 +0800 Subject: [PATCH 0190/1939] Create reverse-linked-list.py --- Python/reverse-linked-list.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/reverse-linked-list.py diff --git a/Python/reverse-linked-list.py b/Python/reverse-linked-list.py new file mode 100644 index 000000000..40bce191a --- /dev/null +++ b/Python/reverse-linked-list.py @@ -0,0 +1,26 @@ +# Time: O(n) +# Space: O(1) +# +# Reverse a singly linked list. +# +# click to show more hints. +# +# Hint: +# A linked list can be reversed either iteratively or recursively. Could you implement both? +# + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param {ListNode} head + # @return {ListNode} + def reverseList(self, head): + dummy = ListNode(float("-inf")) + while head: + dummy.next, head.next, head = head, dummy.next, head.next + return dummy.next + From 7f0fb38158a24d9eec8071873d8d661b8ba9463f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 6 May 2015 21:10:20 +0800 Subject: [PATCH 0191/1939] add solution --- Python/reverse-linked-list.py | 43 +++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/Python/reverse-linked-list.py b/Python/reverse-linked-list.py index 40bce191a..8e8441ddc 100644 --- a/Python/reverse-linked-list.py +++ b/Python/reverse-linked-list.py @@ -10,11 +10,16 @@ # # Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + def __repr__(self): + if self: + return "{} -> {}".format(self.val, repr(self.next)) +# Iterative solution. class Solution: # @param {ListNode} head # @return {ListNode} @@ -23,4 +28,34 @@ def reverseList(self, head): while head: dummy.next, head.next, head = head, dummy.next, head.next return dummy.next + +# Time: O(n) +# Space: O(n) +# Recursive solution. +class Solution2: + # @param {ListNode} head + # @return {ListNode} + def reverseList(self, head): + [begin, end] = self.reverseListRecu(head) + return begin + + def reverseListRecu(self, head): + if not head: + return [None, None] + + [begin, end] = self.reverseListRecu(head.next) + + if end: + end.next = head + head.next = None + return [begin, head] + else: + return [head, head] +if __name__ == "__main__": + head = ListNode(1) + head.next = ListNode(2) + head.next.next = ListNode(3) + head.next.next.next = ListNode(4) + head.next.next.next.next = ListNode(5) + print Solution2().reverseList(head) \ No newline at end of file From cddf8ad6d6fddf1e9982dd6dec3c3d71259395c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 21:14:12 +0800 Subject: [PATCH 0192/1939] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 59a34d549..4961ce48e 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ Problem | Solution | Time | Space | Difficul [Remove Duplicates from Sorted List]| [remove-duplicates-from-sorted-list.py] | _O(n)_ | _O(1)_ | Easy | [Remove Duplicates from Sorted List II]| [remove-duplicates-from-sorted-list-ii.py] | _O(n)_ | _O(1)_ | Medium | [Remove Linked List Elements]| [remove-linked-list-elements.py] | _O(n)_ | _O(1)_ | Easy | +[Reverse Linked List]| [reverse-linked-list.py] | _O(n)_ | _O(1)_ | Easy | [Reverse Linked List II]| [reverse-linked-list-ii.py] | _O(n)_ | _O(1)_ | Medium | [Reverse Nodes in k-Group]| [reverse-nodes-in-k-group.py] | _O(n)_ | _O(1)_ | Hard | [Rotate List]| [rotate-list.py] | _O(n)_ | _O(1)_ | Medium | @@ -222,6 +223,8 @@ Problem | Solution | Time | Space | Difficul [remove-duplicates-from-sorted-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list-ii.py [Remove Linked List Elements]:https://oj.leetcode.com/problems/remove-linked-list-elements/ [remove-linked-list-elements.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-linked-list-elements.py +[Reverse Linked List]:https://oj.leetcode.com/problems/reverse-linked-list/ +[reverse-linked-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list.py [Reverse Linked List II]:https://oj.leetcode.com/problems/reverse-linked-list-ii/ [reverse-linked-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list-ii.py [Reverse Nodes in k-Group]:https://oj.leetcode.com/problems/reverse-nodes-in-k-group/ From f78170452f8b6d73a290a5eb69ebf52581c6ec00 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 21:44:46 +0800 Subject: [PATCH 0193/1939] Update permutation-sequence.py --- Python/permutation-sequence.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/permutation-sequence.py b/Python/permutation-sequence.py index 2252f26ad..a3b5e1158 100644 --- a/Python/permutation-sequence.py +++ b/Python/permutation-sequence.py @@ -1,5 +1,5 @@ -# Time: O(n) -# Space: O(1) +# Time: O(n^2) +# Space: O(n) # # The set [1,2,3,...,n] contains a total of n! unique permutations. # From b8d78ffc9ed011c9e294a2422434ddbf4dd9e524 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 May 2015 21:45:31 +0800 Subject: [PATCH 0194/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4961ce48e..8cf458261 100644 --- a/README.md +++ b/README.md @@ -361,7 +361,7 @@ Problem | Solution | Time | Space | Difficul [Gray Code] | [gray-code.py] | _O(2^n)_ | _O(1)_ | Medium | [Integer to Roman] | [integer-to-roman.py] | _O(n)_ | _O(1)_ | Medium | [Palindrome Number] | [palindrome-number.py] | _O(1)_ | _O(1)_ | Easy | -[Permutation Sequence] | [permutation-sequence.py] | _O(n)_ | _O(1)_ | Medium | `Cantor Ordering` +[Permutation Sequence] | [permutation-sequence.py] | _O(n^2)_ | _O(n)_ | Medium | `Cantor Ordering` [Reverse Integer] | [reverse-integer.py] | _O(logn)_ | _O(1)_ | Easy | [Roman to Integer] | [roman-to-integer.py] | _O(n)_ | _O(1)_ | Easy | [Valid Number] | [valid-number.py] | _O(n)_ | _O(1)_ | Hard | `Automata` From 0e8406574f71bd3ace0abcec83b1d9f107969db3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 May 2015 22:13:43 +0800 Subject: [PATCH 0195/1939] Create course-schedule.cpp --- C++/course-schedule.cpp | 50 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 C++/course-schedule.cpp diff --git a/C++/course-schedule.cpp b/C++/course-schedule.cpp new file mode 100644 index 000000000..2cf78f602 --- /dev/null +++ b/C++/course-schedule.cpp @@ -0,0 +1,50 @@ +// Time: O(|V| + |E|) +// Space: O(|E|) + +// Topological sort solution. +class Solution { +public: + bool canFinish(int numCourses, vector>& prerequisites) { + // Store courses with in-degree zero. + queue zeroInDegree; + + // in-degree, out-degree + unordered_map> inDegree; + unordered_map> outDegree; + for (int i = 0; i < prerequisites.size(); ++i) { + inDegree[prerequisites[i][0]].insert(prerequisites[i][1]); + outDegree[prerequisites[i][1]].insert(prerequisites[i][0]); + } + + // Put all the courses with in-degree zero into queue. + for(int i = 0; i < numCourses; ++i) { + if(inDegree.find(i) == inDegree.end()) { + zeroInDegree.push(i); + } + } + + // V+E + while(!zeroInDegree.empty()) { + // Take the course which prerequisites are all taken. + int prerequisite = zeroInDegree.front(); + zeroInDegree.pop(); + for (const auto & course: outDegree[prerequisite]) { + // Update info of all the courses with the taken prerequisite. + inDegree[course].erase(prerequisite); + // If all the prerequisites are taken, add the course to the queue. + if (inDegree[course].empty()) { + zeroInDegree.push(course); + } + } + // Mark the course as taken. + outDegree.erase(prerequisite); + } + + // All of the courses have been taken. + if (!outDegree.empty()) { + return false; + } + + return true; + } +}; From 9cd9ab9ed05ae5ed0344ea1e7a02850999822c20 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 7 May 2015 22:54:34 +0800 Subject: [PATCH 0196/1939] add solution --- Python/course-schedule.py | 69 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Python/course-schedule.py diff --git a/Python/course-schedule.py b/Python/course-schedule.py new file mode 100644 index 000000000..f152d597b --- /dev/null +++ b/Python/course-schedule.py @@ -0,0 +1,69 @@ +# Time: O(|V| + |E|) +# Space: O(|E|) +# +# There are a total of n courses you have to take, labeled from 0 to n - 1. +# +# Some courses may have prerequisites, for example to take course 0 +# you have to first take course 1, which is expressed as a pair: [0,1] +# +# Given the total number of courses and a list of prerequisite pairs, +# is it possible for you to finish all courses? +# +# For example: +# +# 2, [[1,0]] +# There are a total of 2 courses to take. To take course 1 +# you should have finished course 0. So it is possible. +# +# 2, [[1,0],[0,1]] +# There are a total of 2 courses to take. To take course 1 you should have +# finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. +# +# click to show more hints. +# +# Hints: +# This problem is equivalent to finding if a cycle exists in a directed graph. +# If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. +# There are several ways to represent a graph. For example, the input prerequisites is a graph represented by +# a list of edges. Is this graph representation appropriate? +# Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts +# of Topological Sort. +# Topological sort could also be done via BFS. +# +class Solution: + # @param {integer} numCourses + # @param {integer[][]} prerequisites + # @return {boolean} + def canFinish(self, numCourses, prerequisites): + zero_in_degree_queue, in_degree, out_degree = [], {}, {} + + for i, j in prerequisites: + if i not in in_degree: + in_degree[i] = {} + if j not in out_degree: + out_degree[j] = {} + in_degree[i][j] = True + out_degree[j][i] = True + + for i in xrange(numCourses): + if i not in in_degree: + zero_in_degree_queue.append(i) + + while zero_in_degree_queue: + prerequisite = zero_in_degree_queue.pop() + + if prerequisite in out_degree: + for course in out_degree[prerequisite]: + del (in_degree[course])[prerequisite] + if not in_degree[course]: + zero_in_degree_queue.append(course) + + del out_degree[prerequisite] + + if len(out_degree): + return False + + return True + +if __name__ == "__main__": + print Solution().canFinish(1, []) \ No newline at end of file From f90b64b7d839f3108c55921bc737e3c770e54dc9 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 7 May 2015 22:56:03 +0800 Subject: [PATCH 0197/1939] update --- Python/course-schedule.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/course-schedule.py b/Python/course-schedule.py index f152d597b..80542d46f 100644 --- a/Python/course-schedule.py +++ b/Python/course-schedule.py @@ -54,7 +54,7 @@ def canFinish(self, numCourses, prerequisites): if prerequisite in out_degree: for course in out_degree[prerequisite]: - del (in_degree[course])[prerequisite] + del in_degree[course][prerequisite] if not in_degree[course]: zero_in_degree_queue.append(course) From c3291704723c9dfed1e2e3abaf3cf57c37359255 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 May 2015 23:01:57 +0800 Subject: [PATCH 0198/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8cf458261..2c90df648 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-05), there are `190` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-07), there are `191` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `206` problems. +Here is the classification of all `207` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -576,6 +576,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | +[Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(|V| + |E|)_ | _O(|E|)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | [Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | [Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | From 3f4f3b6b92b0757cfdc6d468960036ebb509333b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 May 2015 23:02:41 +0800 Subject: [PATCH 0199/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2c90df648..9f5c1c573 100644 --- a/README.md +++ b/README.md @@ -576,7 +576,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | -[Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(|V| + |E|)_ | _O(|E|)_ | Medium | +[Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | [Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | [Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | From 4f49b3697f6401fe1dc107097de5d3451e77d07a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 May 2015 01:37:59 +0800 Subject: [PATCH 0200/1939] Update merge-k-sorted-lists.py --- Python/merge-k-sorted-lists.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/merge-k-sorted-lists.py b/Python/merge-k-sorted-lists.py index 0cd4e311b..8003ec215 100644 --- a/Python/merge-k-sorted-lists.py +++ b/Python/merge-k-sorted-lists.py @@ -1,5 +1,5 @@ # Time: O(nlogk) -# Space: O(1) +# Space: O(k) # # Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. import heapq @@ -41,4 +41,4 @@ def mergeKLists(self, lists): list2 = ListNode(2) list2.next = ListNode(4) - print Solution().mergeKLists([list1, list2]) \ No newline at end of file + print Solution().mergeKLists([list1, list2]) From 0324251bb994eea6292a1195e5550000d8064943 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 May 2015 01:38:30 +0800 Subject: [PATCH 0201/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f5c1c573..c525cf7b6 100644 --- a/README.md +++ b/README.md @@ -267,7 +267,7 @@ Problem | Solution | Time | Space | Difficul ##Heap Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Merge k Sorted Lists] | [merge-k-sorted-lists.py] | _O(nlogk)_| _O(1)_| Hard | +[Merge k Sorted Lists] | [merge-k-sorted-lists.py] | _O(nlogk)_| _O(k)_| Hard | [Merge k Sorted Lists]:https://oj.leetcode.com/problems/merge-k-sorted-lists/ [merge-k-sorted-lists.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-k-sorted-lists.py From 30f8f1552bcfb1dd79db6dcd9c86b81bf41f8a15 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 May 2015 12:49:04 +0800 Subject: [PATCH 0202/1939] Create implement-trie-prefix-tree.py --- Python/implement-trie-prefix-tree.py | 61 ++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/implement-trie-prefix-tree.py diff --git a/Python/implement-trie-prefix-tree.py b/Python/implement-trie-prefix-tree.py new file mode 100644 index 000000000..1fc9cb47a --- /dev/null +++ b/Python/implement-trie-prefix-tree.py @@ -0,0 +1,61 @@ +# Time: O(n), per operation +# Space: O(1) +# +# Implement a trie with insert, search, and startsWith methods. +# +# Note: +# You may assume that all inputs are consist of lowercase letters a-z. +# + +class TrieNode: + # Initialize your data structure here. + def __init__(self): + self.flag = False + self.children = {} + + +class Trie: + + def __init__(self): + self.root = TrieNode() + + # @param {string} word + # @return {void} + # Inserts a word into the trie. + def insert(self, word): + cur = self.root + for c in word: + if not c in cur.children: + cur.children[c] = TrieNode() + cur = cur.children[c] + cur.flag = True + + # @param {string} word + # @return {boolean} + # Returns if the word is in the trie. + def search(self, word): + res, node = self.childSearch(word) + if res: + return node.flag + return False + + # @param {string} prefix + # @return {boolean} + # Returns if there is any word in the trie + # that starts with the given prefix. + def startsWith(self, prefix): + return self.childSearch(prefix)[0] + + def childSearch(self, word): + cur = self.root + for c in word: + if c in cur.children: + cur = cur.children[c] + else: + return False, None + return True, cur + +# Your Trie object will be instantiated and called as such: +# trie = Trie() +# trie.insert("somestring") +# trie.search("key") From 59e955592f94f8855c0978186c5b9d70c238839a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 May 2015 12:53:45 +0800 Subject: [PATCH 0203/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c525cf7b6..21dcf2e8c 100644 --- a/README.md +++ b/README.md @@ -280,6 +280,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` +[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [implement-trie-prefix-tree](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` [Recover Binary Search Tree]| [recover-binary-search-tree.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` [Binary Tree Preorder Traversal]:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ From 1c8deb0efda6b9f45b91f06303e8b47b0e11028c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 May 2015 16:00:58 +0800 Subject: [PATCH 0204/1939] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 21dcf2e8c..638d67af5 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-07), there are `191` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-07), there are `192` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `207` problems. +Here is the classification of all `208` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -280,7 +280,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` -[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [implement-trie-prefix-tree](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` +[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [implement-trie-prefix-tree.py](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` [Recover Binary Search Tree]| [recover-binary-search-tree.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` [Binary Tree Preorder Traversal]:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ From 57d0f2a9b1ad1a26e7daaa0934c1a141c3d4c3cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 May 2015 12:06:03 +0800 Subject: [PATCH 0205/1939] Create minimum-size-subarray-sum.py --- Python/minimum-size-subarray-sum.py | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/minimum-size-subarray-sum.py diff --git a/Python/minimum-size-subarray-sum.py b/Python/minimum-size-subarray-sum.py new file mode 100644 index 000000000..860932c60 --- /dev/null +++ b/Python/minimum-size-subarray-sum.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(1) +# +# Given an array of n positive integers and a positive integer s, +# find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead. +# +# For example, given the array [2,3,1,2,4,3] and s = 7, +# the subarray [4,3] has the minimal length under the problem constraint. +# +# More practice: +# If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). +# + +class Solution: + # @param {integer} s + # @param {integer[]} nums + # @return {integer} + def minSubArrayLen(self, s, nums): + start = 0 + sum = 0 + min_len = float("inf") + for i in xrange(len(nums)): + sum += nums[i] + while sum >= s: + min_len = min(min_len, i - start + 1) + sum -= nums[start] + start += 1 + if min_len == float("inf"): + return 0 + return min_len From bc717fb19279d22f497c44d383d704669de2379b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 May 2015 12:08:37 +0800 Subject: [PATCH 0206/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 638d67af5..6050f641f 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ Problem | Solution | Time | Space | Difficul [First Missing Positive]| [first-missing-positive.py] | _O(n)_ | _O(1)_ | Hard | Tricky [Longest Consecutive Sequence]| [longest-consecutive-sequence.py] | _O(n)_ | _O(n)_ | Hard | Tricky [Majority Element] | [majority-element.py] | _O(n)_ | _O(1)_ | Easy | +[Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [minimum-size-subarray-sum.py] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | [Missing Ranges]| [missing-ranges.py] | _O(n)_ | _O(1)_ | Medium | [Next Permutation]| [next-permutation.py] | _O(n)_ | _O(1)_ | Medium | Tricky [Pascal's Triangle]| [pascals-triangle.py] | _O(n^2)_ | _O(n)_ | Easy | From 776a20cb34805761ba4e1482f00fdd9da7dc644b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 12:56:25 +0800 Subject: [PATCH 0207/1939] Create course-schedule-ii.py --- Python/course-schedule-ii.py | 72 ++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Python/course-schedule-ii.py diff --git a/Python/course-schedule-ii.py b/Python/course-schedule-ii.py new file mode 100644 index 000000000..3ae0bdc11 --- /dev/null +++ b/Python/course-schedule-ii.py @@ -0,0 +1,72 @@ +# Time: O(|V| + |E|) +# Space: O(|V|) + +# There are a total of n courses you have to take, labeled from 0 to n - 1. +# +# Some courses may have prerequisites, for example to take course 0 you have to first take course 1, +# which is expressed as a pair: [0,1] +# +# Given the total number of courses and a list of prerequisite pairs, return the ordering of courses +# you should take to finish all courses. +# +# There may be multiple correct orders, you just need to return one of them. If it is impossible +# to finish all courses, return an empty array. +# +# For example: +# +# 2, [[1,0]] +# There are a total of 2 courses to take. To take course 1 you should have finished course 0. +# So the correct course order is [0,1] +# +# 4, [[1,0],[2,0],[3,1],[3,2]] +# There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. +# Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. +# Another correct ordering is[0,2,1,3]. +# +# Note: +# The input prerequisites is a graph represented by a list of edges, not adjacency matrices. +# Read more about how a graph is represented. +# +# Hints: +# This problem is equivalent to finding the topological order in a directed graph. +# If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. +# Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining +# the basic concepts of Topological Sort. +# Topological sort could also be done via BFS. +# + +class Solution: + # @param {integer} numCourses + # @param {integer[][]} prerequisites + # @return {integer[]} + def findOrder(self, numCourses, prerequisites): + res, zero_in_degree_queue, in_degree, out_degree = [], [], {}, {} + + for i, j in prerequisites: + if i not in in_degree: + in_degree[i] = {} + if j not in out_degree: + out_degree[j] = {} + in_degree[i][j] = True + out_degree[j][i] = True + + for i in xrange(numCourses): + if i not in in_degree: + zero_in_degree_queue.append(i) + + while zero_in_degree_queue: + prerequisite = zero_in_degree_queue.pop() + res.append(prerequisite) + + if prerequisite in out_degree: + for course in out_degree[prerequisite]: + del in_degree[course][prerequisite] + if not in_degree[course]: + zero_in_degree_queue.append(course) + + del out_degree[prerequisite] + + if len(out_degree): + return [] + + return res From f66dd476e9ece8f0d111040ec1b7152837d9b83e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:00:36 +0800 Subject: [PATCH 0208/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6050f641f..979c1434a 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-07), there are `192` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-07), there are `194` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `208` problems. +Here is the classification of all `210` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -579,6 +579,7 @@ Problem | Solution | Time | Space | Difficul [Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | [Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | +[Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [course-schedule-ii.py](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | [Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | [Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | [Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | From 215812ace3bcf625d76a51f1cc1b03ad9905ebb9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:01:04 +0800 Subject: [PATCH 0209/1939] Update course-schedule-ii.py --- Python/course-schedule-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/course-schedule-ii.py b/Python/course-schedule-ii.py index 3ae0bdc11..d6701a084 100644 --- a/Python/course-schedule-ii.py +++ b/Python/course-schedule-ii.py @@ -1,5 +1,5 @@ # Time: O(|V| + |E|) -# Space: O(|V|) +# Space: O(|E|) # There are a total of n courses you have to take, labeled from 0 to n - 1. # From d4ca2724b0b1fa3ccf0d731e8ef390688bfc7a30 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:01:35 +0800 Subject: [PATCH 0210/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 979c1434a..c68a30285 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-05-07), there are `194` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-14), there are `194` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. Here is the classification of all `210` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. From 335864311edd87ddfea0f279d97423e6e47dcca1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:08:10 +0800 Subject: [PATCH 0211/1939] Create course-schedule-ii.cpp --- C++/course-schedule-ii.cpp | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 C++/course-schedule-ii.cpp diff --git a/C++/course-schedule-ii.cpp b/C++/course-schedule-ii.cpp new file mode 100644 index 000000000..56ea5087b --- /dev/null +++ b/C++/course-schedule-ii.cpp @@ -0,0 +1,52 @@ +// Time: O(|V| + |E||) +// Space: O(1) + +// Topological sort. +class Solution { +public: + vector findOrder(int numCourses, vector>& prerequisites) { + vector res; + // Store courses with in-degree zero. + queue zeroInDegree; + + // in-degree, out-degree + unordered_map> inDegree; + unordered_map> outDegree; + for (int i = 0; i < prerequisites.size(); ++i) { + inDegree[prerequisites[i].first].insert(prerequisites[i].second); + outDegree[prerequisites[i].second].insert(prerequisites[i].first); + } + + // Put all the courses with in-degree zero into queue. + for(int i = 0; i < numCourses; ++i) { + if(inDegree.find(i) == inDegree.end()) { + zeroInDegree.push(i); + } + } + + // V+E + while(!zeroInDegree.empty()) { + // Take the course which prerequisites are all taken. + int prerequisite = zeroInDegree.front(); + res.emplace_back(prerequisite); + zeroInDegree.pop(); + for (const auto & course: outDegree[prerequisite]) { + // Update info of all the courses with the taken prerequisite. + inDegree[course].erase(prerequisite); + // If all the prerequisites are taken, add the course to the queue. + if (inDegree[course].empty()) { + zeroInDegree.push(course); + } + } + // Mark the course as taken. + outDegree.erase(prerequisite); + } + + // All of the courses have been taken. + if (!outDegree.empty()) { + return {}; + } + + return res; + } +}; From 9d1f0b8b03c97a51235757b9423748f7659f1014 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:08:27 +0800 Subject: [PATCH 0212/1939] Update course-schedule-ii.cpp --- C++/course-schedule-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/course-schedule-ii.cpp b/C++/course-schedule-ii.cpp index 56ea5087b..ec390a510 100644 --- a/C++/course-schedule-ii.cpp +++ b/C++/course-schedule-ii.cpp @@ -1,5 +1,5 @@ // Time: O(|V| + |E||) -// Space: O(1) +// Space: O(|E|) // Topological sort. class Solution { From 8f671a10343cb5b675dfa06ffea2d29a0f64bc5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 May 2015 13:08:50 +0800 Subject: [PATCH 0213/1939] Update course-schedule-ii.cpp --- C++/course-schedule-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/course-schedule-ii.cpp b/C++/course-schedule-ii.cpp index ec390a510..198122315 100644 --- a/C++/course-schedule-ii.cpp +++ b/C++/course-schedule-ii.cpp @@ -1,7 +1,7 @@ // Time: O(|V| + |E||) // Space: O(|E|) -// Topological sort. +// Topological sort solution. class Solution { public: vector findOrder(int numCourses, vector>& prerequisites) { From 25bcde35cbc832fc2d94328b55d83a3f8430d864 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 10:27:53 +0800 Subject: [PATCH 0214/1939] Create add-and-search-word-data-structure-design.py --- ...d-and-search-word-data-structure-design.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Python/add-and-search-word-data-structure-design.py diff --git a/Python/add-and-search-word-data-structure-design.py b/Python/add-and-search-word-data-structure-design.py new file mode 100644 index 000000000..1c8b80d59 --- /dev/null +++ b/Python/add-and-search-word-data-structure-design.py @@ -0,0 +1,67 @@ +# Time: O(min(n, h)), per operation +# Space: O(min(n, h)) +# +# Design a data structure that supports the following two operations: +# +# void addWord(word) +# bool search(word) +# search(word) can search a literal word or a regular expression string containing only letters a-z or .. +# A . means it can represent any one letter. +# +# For example: +# +# addWord("bad") +# addWord("dad") +# addWord("mad") +# search("pad") -> false +# search("bad") -> true +# search(".ad") -> true +# search("b..") -> true +# Note: +# You may assume that all words are consist of lowercase letters a-z. +# + +class TrieNode: + # Initialize your data structure here. + def __init__(self): + self.flag = False + self.children = {} + +class WordDictionary: + def __init__(self): + self.root = TrieNode() + + # @param {string} word + # @return {void} + # Adds a word into the data structure. + def addWord(self, word): + curr = self.root + for c in word: + if not c in curr.children: + curr.children[c] = TrieNode() + curr = curr.children[c] + curr.flag = True + + # @param {string} word + # @return {boolean} + # Returns if the word is in the data structure. A word could + # contain the dot character '.' to represent any one letter. + def search(self, word): + return self.searchHelper(word, 0, self.root) + + def searchHelper(self, word, start, curr): + if start == len(word): + return curr.flag + if word[start] in curr.children: + return self.searchHelper(word, start+1, curr.children[word[start]]) + elif word[start] == '.': + for c in curr.children: + if self.searchHelper(word, start+1, curr.children[c]): + return True + + return False + +# Your WordDictionary object will be instantiated and called as such: +# wordDictionary = WordDictionary() +# wordDictionary.addWord("word") +# wordDictionary.search("pattern") From 122e264fa388b9ad6a9ccff40d8d74c9457395ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 10:31:06 +0800 Subject: [PATCH 0215/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c68a30285..bda35ef55 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-14), there are `194` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-16), there are `195` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `210` problems. +Here is the classification of all `211` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. @@ -278,6 +278,7 @@ Problem | Solution | Time | Space | Difficul ##Tree Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- +[Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` [Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` From 9ce37e650a8365a66deff24b71b7fc69461367ad Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 10:49:08 +0800 Subject: [PATCH 0216/1939] Create add-and-search-word-data-structure-design.cpp --- ...-and-search-word-data-structure-design.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 C++/add-and-search-word-data-structure-design.cpp diff --git a/C++/add-and-search-word-data-structure-design.cpp b/C++/add-and-search-word-data-structure-design.cpp new file mode 100644 index 000000000..053516acd --- /dev/null +++ b/C++/add-and-search-word-data-structure-design.cpp @@ -0,0 +1,57 @@ +// Time: O(min(n, h)), per operation +// Space: O(min(n, h)) + +class WordDictionary { +public: + struct TrieNode{ + public: + bool isString = false; + unordered_map leaves; + }; + + WordDictionary(){ + root_ = new TrieNode(); + root_->isString = true; + } + + // Adds a word into the data structure. + void addWord(string word) { + auto* p = root_; + for (const auto& c : word) { + if (p->leaves.find(c) == p->leaves.cend()) { + p->leaves[c] = new TrieNode; + } + p = p->leaves[c]; + } + p->isString = true; + } + + // Returns if the word is in the data structure. A word could + // contain the dot character '.' to represent any one letter. + bool search(string word) { + return searchWord(word, root_, 0); + } + + bool searchWord(string word, TrieNode* node, int s) { + if (s == word.length()) { + return node->isString; + } + if (node->leaves.find(word[s]) != node->leaves.end()){ // Match the char. + return searchWord(word, node->leaves[word[s]], s + 1); + } else if (word[s] == '.') { // Skip the char. + for (const auto& i : node->leaves) { + if (searchWord(word, i.second, s + 1)) { + return true; + } + } + } + return false; + } +private: + TrieNode *root_; +}; + +// Your WordDictionary object will be instantiated and called as such: +// WordDictionary wordDictionary; +// wordDictionary.addWord("word"); +// wordDictionary.search("pattern"); From dab2b3009ade0c169105a79f0244f7094138fb7e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 10:50:03 +0800 Subject: [PATCH 0217/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bda35ef55..84cc9b1d8 100644 --- a/README.md +++ b/README.md @@ -278,7 +278,7 @@ Problem | Solution | Time | Space | Difficul ##Tree Problem | Solution | Time | Space | Difficulty | Notes --------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` +[Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` [Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` [Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` From cbc893bad1e5a93766353325656d06f3e3b0daf2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:00:12 +0800 Subject: [PATCH 0218/1939] Update README.md --- README.md | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 84cc9b1d8..a2981d7de 100644 --- a/README.md +++ b/README.md @@ -276,23 +276,14 @@ Problem | Solution | Time | Space | Difficul --- ##Tree -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` -[Binary Tree Preorder Traversal] | [binary-tree-preorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` -[Binary Tree Inorder Traversal] | [binary-tree-inorder-traversal.py] | _O(n)_| _O(1)_| Medium | `Morris Traversal` -[Binary Tree Postorder Traversal]| [binary-tree-postorder-traversal.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` -[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [implement-trie-prefix-tree.py](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` -[Recover Binary Search Tree]| [recover-binary-search-tree.py] | _O(n)_| _O(1)_| Hard | `Morris Traversal` - -[Binary Tree Preorder Traversal]:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ -[binary-tree-preorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-preorder-traversal.py -[Binary Tree Inorder Traversal]:https://oj.leetcode.com/problems/binary-tree-inorder-traversal/ -[binary-tree-inorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-inorder-traversal.py -[Binary Tree Postorder Traversal]:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/ -[binary-tree-postorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-postorder-traversal.py -[Recover Binary Search Tree]:https://oj.leetcode.com/problems/recover-binary-search-tree/ -[recover-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/recover-binary-search-tree.py + # | Problem | Solution | Time | Space | Difficulty | Notes +-----|--------------- | --------------- | --------------- | --------------- | -------------- | ----- +94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium | `Morris Traversal` | +99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard | `Morris Traversal` +144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium | `Morris Traversal` +145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard | `Morris Traversal` +208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` +211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` --- From d5e2312f25cfebcdbc4865a8e765f9bbc05941e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:03:03 +0800 Subject: [PATCH 0219/1939] Update README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a2981d7de..75c4d3a77 100644 --- a/README.md +++ b/README.md @@ -276,14 +276,14 @@ Problem | Solution | Time | Space | Difficul --- ##Tree - # | Problem | Solution | Time | Space | Difficulty | Notes ------|--------------- | --------------- | --------------- | --------------- | -------------- | ----- -94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium | `Morris Traversal` | -99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard | `Morris Traversal` -144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium | `Morris Traversal` -145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard | `Morris Traversal` -208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium | `Trie` -211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium | `Trie` + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|--------------- | --------------- | --------------- | --------------- | -------------- |--------------| ----- +94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | +99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` +145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie +211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS --- From 3eb855840b835fe802cc3521db68c193d4050e2a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:04:12 +0800 Subject: [PATCH 0220/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75c4d3a77..694f8892c 100644 --- a/README.md +++ b/README.md @@ -283,7 +283,7 @@ Problem | Solution | Time | Space | Difficul 144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie -211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS +211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./Python/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS --- From 2686786ca5132b8f47d8e92967e5530c505cbfb5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:11:29 +0800 Subject: [PATCH 0221/1939] Update README.md --- README.md | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 694f8892c..f99910838 100644 --- a/README.md +++ b/README.md @@ -47,24 +47,13 @@ Shell --- ##Bit Manipulation -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Number of 1 Bits] | [number-of-1-bits.py] | _O(m)_ | _O(1)_ | Easy | -[Reverse Bits] | [reverse-bits.py] | _O(n)_ | _O(1)_ | Easy | -[Bitwise AND of Numbers Range] | [bitwise-and-of-numbers-range.py] | _O(1)_ | _O(1)_ | Medium | -[Single Number] | [single-number.py] | _O(n)_ | _O(1)_ | Medium | -[Single Number II] | [single-number-ii.py] | _O(n)_ | _O(1)_ | Medium | - -[Number of 1 Bits]: https://oj.leetcode.com/problems/number-of-1-bits/ -[number-of-1-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-1-bits.py -[Reverse Bits]: https://oj.leetcode.com/problems/reverse-bits/ -[reverse-bits.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py -[Bitwise AND of Numbers Range]: https://leetcode.com/problems/bitwise-and-of-numbers-range/ -[bitwise-and-of-numbers-range.py]: https://github.com/kamyu104/LeetCode/blob/master/Python/bitwise-and-of-numbers-range.py -[Single Number]: https://oj.leetcode.com/problems/single-number/ -[single-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number.py -[Single Number II]: https://oj.leetcode.com/problems/single-number-ii/ -[single-number-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/single-number-ii.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +136 | [Single Number](https://oj.leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || +137 | [Single Number II](https://oj.leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || +190 | [Reverse Bits](https://oj.leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || +191 |[Number of 1 Bits](https://oj.leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || +201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || --- @@ -277,7 +266,7 @@ Problem | Solution | Time | Space | Difficul ##Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Notes ------|--------------- | --------------- | --------------- | --------------- | -------------- |--------------| ----- +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | 99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` From 7c9316c83036467820b8bf4480a98f0625de28e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:38:56 +0800 Subject: [PATCH 0222/1939] Update README.md --- README.md | 93 ++++++++++++++----------------------------------------- 1 file changed, 24 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index f99910838..3a1dece69 100644 --- a/README.md +++ b/README.md @@ -59,75 +59,30 @@ Shell ##Array -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[3 Sum] | [3sum.py] | _O(n^2)_ | _O(1)_ | Medium | -[3 Sum Closest] | [3sum-closest.py]| _O(n^2)_ | _O(1)_ | Medium | -[Best Time to Buy and Sell Stock]| [best-time-to-buy-and-sell-stock.py] | _O(n)_ | _O(1)_ | Medium | -[First Missing Positive]| [first-missing-positive.py] | _O(n)_ | _O(1)_ | Hard | Tricky -[Longest Consecutive Sequence]| [longest-consecutive-sequence.py] | _O(n)_ | _O(n)_ | Hard | Tricky -[Majority Element] | [majority-element.py] | _O(n)_ | _O(1)_ | Easy | -[Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [minimum-size-subarray-sum.py] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | -[Missing Ranges]| [missing-ranges.py] | _O(n)_ | _O(1)_ | Medium | -[Next Permutation]| [next-permutation.py] | _O(n)_ | _O(1)_ | Medium | Tricky -[Pascal's Triangle]| [pascals-triangle.py] | _O(n^2)_ | _O(n)_ | Easy | -[Pascal's Triangle II]| [pascals-triangle-ii.py] | _O(n^2)_ | _O(n)_ | Easy | -[Plus One] | [plus-one.py] | _O(n)_ | _O(1)_ | Easy | -[Read N Characters Given Read4] | [read-n-characters-given-read4.py] | _O(n)_ | _O(1)_ | Easy | -[Read N Characters Given Read4 II - Call multiple times] | [read-n-characters-given-read4-ii-call-multiple-times.py] | _O(n)_ | _O(1)_ | Hard | -[Remove Duplicates from Sorted Array]| [remove-duplicates-from-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | -[Remove Duplicates from Sorted Array II]| [remove-duplicates-from-sorted-array-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Remove Element] | [remove-element.py] | _O(n)_ | _O(1)_ | Easy | -[Rotate Array] | [rotate-array.py] | _O(n)_ | _O(1)_ | Easy | -[Rotate Image] | [rotate-image.py] | _O(n^2)_ | _O(1)_ | Medium | -[Set Matrix Zeroes] | [set-matrix-zeroes.py] | _O(m * n)_ | _O(1)_ | Medium | -[Spiral Matrix] | [spiral-matrix.py] | _O(m * n)_ | _O(1)_ | Medium | -[Spiral Matrix II] | [spiral-matrix-ii.py] | _O(m * n)_ | _O(1)_ | Medium | - - -[3 Sum]: https://oj.leetcode.com/problems/3sum/ -[3sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/3sum.py -[3 Sum Closest]: https://oj.leetcode.com/problems/3sum-closest/ -[3sum-closest.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/3sum-closest.py -[Best Time to Buy and Sell Stock]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/ -[best-time-to-buy-and-sell-stock.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock.py -[First Missing Positive]:https://oj.leetcode.com/problems/first-missing-positive/ -[first-missing-positive.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/first-missing-positive.py -[Longest Consecutive Sequence]:https://oj.leetcode.com/problems/longest-consecutive-sequence/ -[longest-consecutive-sequence.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-consecutive-sequence.py -[Majority Element]: https://oj.leetcode.com/problems/majority-element/ -[majority-element.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/majority-element.py -[Missing Ranges]:https://oj.leetcode.com/problems/missing-ranges/ -[missing-ranges.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/missing-ranges.py -[Next Permutation]:https://oj.leetcode.com/problems/next-permutation/ -[next-permutation.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/next-permutation.py -[Pascal's Triangle]:https://oj.leetcode.com/problems/pascals-triangle/ -[pascals-triangle.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/pascals-triangle.py -[Pascal's Triangle II]:https://oj.leetcode.com/problems/pascals-triangle-ii/ -[pascals-triangle-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/pascals-triangle-ii.py -[Plus One]:https://oj.leetcode.com/problems/plus-one/ -[plus-one.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/plus-one.py -[Read N Characters Given Read4]:https://oj.leetcode.com/problems/read-n-characters-given-read4/ -[read-n-characters-given-read4.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/read-n-characters-given-read4.py -[Read N Characters Given Read4 II - Call multiple times]:https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/ -[read-n-characters-given-read4-ii-call-multiple-times.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/read-n-characters-given-read4-ii-call-multiple-times.py -[Remove Duplicates from Sorted Array]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/ -[remove-duplicates-from-sorted-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-array.py -[Remove Duplicates from Sorted Array II]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ -[remove-duplicates-from-sorted-array-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-array-ii.py -[Remove Element]:https://oj.leetcode.com/problems/remove-element/ -[remove-element.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-element.py -[Rotate Array]:https://oj.leetcode.com/problems/rotate-array/ -[rotate-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-array.py -[Rotate Image]:https://oj.leetcode.com/problems/rotate-image/ -[rotate-image.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-image.py -[Set Matrix Zeroes]:https://oj.leetcode.com/problems/set-matrix-zeroes/ -[set-matrix-zeroes.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/set-matrix-zeroes.py -[Spiral Matrix]:https://oj.leetcode.com/problems/spiral-matrix/ -[spiral-matrix.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/spiral-matrix.py -[Spiral Matrix II]:https://oj.leetcode.com/problems/spiral-matrix-ii/ -[spiral-matrix-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/spiral-matrix-ii.py - + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +15 | [3 Sum](https://oj.leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || +16 | [3 Sum Closest](https://oj.leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py)| _O(n^2)_ | _O(1)_ | Medium || +26 | [Remove Duplicates from Sorted Array](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +27 | [Remove Element](https://oj.leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || +31 | [Next Permutation](https://oj.leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky +41 | [First Missing Positive](https://oj.leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky +48 | [Rotate Image](https://oj.leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || +54 | [Spiral Matrix](https://oj.leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || +59 | [Spiral Matrix II](https://oj.leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(m * n)_ | _O(1)_ | Medium || +66 | [Plus One]([Plus One]:https://oj.leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || +73 | [Set Matrix Zeroes](https://oj.leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || +80 | [Remove Duplicates from Sorted Array II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || +118 | [Pascal's Triangle](https://oj.leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || +119 | [Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || +121 | [Best Time to Buy and Sell Stock](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || +128 | [Longest Consecutive Sequence](https://oj.leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky +157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](/Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy || +158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard || +163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium || +169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | +189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || +209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [minimum-size-subarray-sum.py] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || --- From 74573bea7ddebbc150d581917b2e2be48c1a5dc6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:40:22 +0800 Subject: [PATCH 0223/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3a1dece69..9f2688e14 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ Shell 163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium || 169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || -209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [minimum-size-subarray-sum.py] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || +209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || --- From a68759c333111650ded557b9c627e8e2a6c5b689 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:48:33 +0800 Subject: [PATCH 0224/1939] Update README.md --- README.md | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 9f2688e14..568ea8ea8 100644 --- a/README.md +++ b/README.md @@ -747,18 +747,9 @@ Problem | Solution | Time | Space | Difficul --- ##Shell Script -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Tenth Line] | [tenth-line.sh] | _O(n)_ | _O(1)_ | Easy | -[Transpose File] | [transpose-file.sh] | _O(n^2)_ | _O(n^2)_ | Medium | -[Valid Phone Numbers] | [valid-phone-numbers.sh] | _O(n)_ | _O(1)_ | Easy | -[Word Frequency] | [word-frequency.sh] | _O(n)_ | _O(k)_ | Medium | - -[Tenth Line]:https://oj.leetcode.com/problems/tenth-line/ -[tenth-line.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/tenth-line.sh -[Transpose File]:https://oj.leetcode.com/problems/transpose-file/ -[transpose-file.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/transpose-file.sh -[Valid Phone Numbers]:https://oj.leetcode.com/problems/valid-phone-numbers/ -[valid-phone-numbers.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/valid-phone-numbers.sh -[Word Frequency]:https://oj.leetcode.com/problems/word-frequency/ -[word-frequency.sh]:https://github.com/kamyu104/LeetCode/blob/master/Shell/word-frequency.sh + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +192 | [Word Frequency](https://oj.leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || +193 | [Valid Phone Numbers](https://oj.leetcode.com/problems/valid-phone-numbers/) | [Shell](./Shell/valid-phone-numbers.sh) | _O(n)_ | _O(1)_ | Easy || +194 | [Transpose File](https://oj.leetcode.com/problems/transpose-file/) | [Shell](./Shell/transpose-file.sh) | _O(n^2)_ | _O(n^2)_ | Medium || +195 | [Tenth Line](https://oj.leetcode.com/problems/tenth-line/) | [Shell](./Shell/tenth-line.sh) | _O(n)_ | _O(1)_ | Easy || From 091af2f9cdcaeac322be91efb8c640f9bbbbc52e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 11:51:43 +0800 Subject: [PATCH 0225/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 568ea8ea8..a85379e50 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ Shell 48 | [Rotate Image](https://oj.leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || 54 | [Spiral Matrix](https://oj.leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || 59 | [Spiral Matrix II](https://oj.leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(m * n)_ | _O(1)_ | Medium || -66 | [Plus One]([Plus One]:https://oj.leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || +66 | [Plus One](https://oj.leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || 73 | [Set Matrix Zeroes](https://oj.leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || 80 | [Remove Duplicates from Sorted Array II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || 118 | [Pascal's Triangle](https://oj.leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || From f9aeac95d9cffd13c3a9ee3922f465149cc9612d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 12:05:10 +0800 Subject: [PATCH 0226/1939] Update README.md --- README.md | 53 ++++++++++++++--------------------------------------- 1 file changed, 14 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index a85379e50..a0db4b983 100644 --- a/README.md +++ b/README.md @@ -704,45 +704,20 @@ Problem | Solution | Time | Space | Difficul --- ##SQL -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Combine Two Tables] | [combine-two-tables.sql] | _O(m + n)_ | _O(m + n)_ | Easy | -[Consecutive Numbers] | [consecutive-numbers.sql] | _O(n)_ | _O(n)_ | Medium | -[Customers Who Never Order] | [customers-who-never-order.sql] | _O(n^2)_ | _O(1)_ | Easy | -[Delete Duplicate Emails] | [delete-duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | -[Department Highest Salary] | [department-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | -[Department Top Three Salaries] | [department-top-three-salaries.sql] | _O(n^2)_ | _O(n)_ | Hard | -[Duplicate Emails] | [duplicate-emails.sql] | _O(n^2)_ | _O(n)_ | Easy | -[Employees Earning More Than Their Managers] | [employees-earning-more-than-their-managers.sql] | _O(n^2)_ | _O(1)_ | Easy | -[Nth Highest Salary] | [nth-highest-salary.sql] | _O(n^2)_ | _O(n)_ | Medium | -[Rank Scores] | [rank-scores.sql] | _O(n^2)_ | _O(n)_ | Medium | -[Rising Temperature] | [rising-temperature.sql] | _O(n^2)_ | _O(n)_ | Easy | -[Second Highest Salary] | [second-highest-salary.sql] | _O(n)_ | _O(1)_ | Easy | - -[Combine Two Tables]:https://oj.leetcode.com/problems/combine-two-tables/ -[combine-two-tables.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/combine-two-tables.sql -[Consecutive Numbers]:https://oj.leetcode.com/problems/consecutive-numbers/ -[consecutive-numbers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/consecutive-numbers.sql -[Customers Who Never Order]:https://oj.leetcode.com/problems/customers-who-never-order/ -[customers-who-never-order.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/customers-who-never-order.sql -[Delete Duplicate Emails]:https://oj.leetcode.com/problems/delete-duplicate-emails/ -[delete-duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/delete-duplicate-emails.sql -[Department Highest Salary]:https://oj.leetcode.com/problems/department-highest-salary/ -[department-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-highest-salary.sql -[Department Top Three Salaries]:https://oj.leetcode.com/problems/department-top-three-salaries/ -[department-top-three-salaries.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/department-top-three-salaries.sql -[Duplicate Emails]:https://oj.leetcode.com/problems/duplicate-emails/ -[duplicate-emails.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/duplicate-emails.sql -[Employees Earning More Than Their Managers]:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/ -[employees-earning-more-than-their-managers.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/employees-earning-more-than-their-managers.sql -[Nth Highest Salary]:https://oj.leetcode.com/problems/nth-highest-salary/ -[nth-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/nth-highest-salary.sql -[Rank Scores]:https://oj.leetcode.com/problems/rank-scores/ -[rank-scores.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/rank-scores.sql -[Rising Temperature]:https://oj.leetcode.com/problems/rising-temperature/ -[rising-temperature.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/rising-temperature.sql -[Second Highest Salary]:https://oj.leetcode.com/problems/second-highest-salary/ -[second-highest-salary.sql]:https://github.com/kamyu104/LeetCode/blob/master/MySQL/second-highest-salary.sql + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +175| [Combine Two Tables](https://oj.leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || +176| [Second Highest Salary](https://oj.leetcode.com/problems/second-highest-salary/) | [MySQL](./MySQL/second-highest-salary.sql) | _O(n)_ | _O(1)_ | Easy || +177| [Nth Highest Salary](https://oj.leetcode.com/problems/nth-highest-salary/) | [MySQL](./MySQL/nth-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || +178| [Rank Scores](https://oj.leetcode.com/problems/rank-scores/) | [MySQL](./MySQL/rank-scores.sql) | _O(n^2)_ | _O(n)_ | Medium || +180| [Consecutive Numbers](https://oj.leetcode.com/problems/consecutive-numbers/) | [MySQL](./MySQL/consecutive-numbers.sql) | _O(n)_ | _O(n)_ | Medium || +181| [Employees Earning More Than Their Managers](https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/) | [MySQL](./MySQL/employees-earning-more-than-their-managers.sql) | _O(n^2)_ | _O(1)_ | Easy || +182| [Duplicate Emails](https://oj.leetcode.com/problems/duplicate-emails/) | [MySQL](./MySQL/duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || +183| [Customers Who Never Order](https://oj.leetcode.com/problems/customers-who-never-order/) | [MySQL](./MySQL/customers-who-never-order.sql) | _O(n^2)_ | _O(1)_ | Easy || +184| [Department Highest Salary](https://oj.leetcode.com/problems/department-highest-salary/) | [MySQL](./MySQL/department-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || +185| [Department Top Three Salaries](https://oj.leetcode.com/problems/department-top-three-salaries/) | [MySQL](./MySQL/department-top-three-salaries.sql) | _O(n^2)_ | _O(n)_ | Hard || +196| [Delete Duplicate Emails](https://oj.leetcode.com/problems/delete-duplicate-emails/) | [MySQL](./MySQL/delete-duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || +197| [Rising Temperature](https://oj.leetcode.com/problems/rising-temperature/) | [MySQL](./MySQL/rising-temperature.sql) | _O(n^2)_ | _O(n)_ | Easy || --- From f25b46b97585377a058d8ca5acc13aa1fc202ea3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 12:28:23 +0800 Subject: [PATCH 0227/1939] Update README.md --- README.md | 69 +++++++++++++++---------------------------------------- 1 file changed, 18 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index a0db4b983..5832e7bc4 100644 --- a/README.md +++ b/README.md @@ -87,57 +87,24 @@ Shell --- ##String -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Add Binary] | [add-binary.py] | _O(n)_ | _O(1)_ | Easy | -[Compare Version Numbers] | [compare-version-numbers.py] | _O(n)_ | _O(1)_ | Easy | -[Count and Say] | [count-and-say.py]| _O(n * 2^n)_ | _O(2^n)_ | Easy | -[Implement strStr()] | [implement-strstr.py] | _O(n + m)_ | _O(m)_ | Easy | `KMP Algorithm` -[Isomorphic Strings] | [isomorphic-strings.py] | _O(n)_ | _O(1)_ | Easy | -[Length of Last Word] | [length-of-last-word.py] | _O(n)_ | _O(1)_ | Easy | -[Longest Common Prefix] | [longest-common-prefix.py] | _O(n1 + n2 + ...)_ | _O(1)_ | Easy | -[Longest Palindromic Substring] | [longest-palindromic-substring.py] | _O(n)_ | _O(n)_ | Medium | `Manacher's Algorithm` -[Multiply Strings] | [multiply-strings.py] | _O(m * n)_ | _O(m + n)_ | Medium | -[One Edit Distance] | [one-edit-distance.py] | _O(m + n)_ | _O(1)_ | Medium | -[Reverse Words in a String] | [reverse-words-in-a-string.py] | _O(n)_ | _O(n)_ | Medium | -[Reverse Words in a String II] | [reverse-words-in-a-string-ii.py] | _O(n)_ | _O(1)_ | Medium | -[String to Integer (atoi)] | [string-to-integer-atoi.py] | _O(n)_ | _O(1)_ | Easy | -[Text Justification] | [text-justification.py] | _O(n)_ | _O(1)_ | Hard | -[Valid Palindrome] | [valid-palindrome.py] | _O(n)_ | _O(1)_ | Easy | -[ZigZag Conversion] | [zigzag-conversion.py] | _O(n)_ | _O(1)_ | Easy | - -[Add Binary]:https://oj.leetcode.com/problems/add-binary/ -[add-binary.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/add-binary.py -[Count and Say]:https://oj.leetcode.com/problems/count-and-say/ -[count-and-say.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/count-and-say.py -[Compare Version Numbers]:https://oj.leetcode.com/problems/compare-version-numbers/ -[compare-version-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/compare-version-numbers.py -[Implement strStr()]:https://oj.leetcode.com/problems/implement-strstr/ -[implement-strstr.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/implement-strstr.py -[Isomorphic Strings]:https://oj.leetcode.com/problems/isomorphic-strings/ -[isomorphic-strings.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/isomorphic-strings.py -[Length of Last Word]:https://oj.leetcode.com/problems/length-of-last-word/ -[length-of-last-word.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/length-of-last-word.py -[Longest Common Prefix]:https://oj.leetcode.com/problems/longest-common-prefix/ -[longest-common-prefix.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-common-prefix.py -[Longest Palindromic Substring]:https://oj.leetcode.com/problems/longest-palindromic-substring/ -[longest-palindromic-substring.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-palindromic-substring.py -[Multiply Strings]:https://oj.leetcode.com/problems/multiply-strings/ -[multiply-strings.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/multiply-strings.py -[One Edit Distance]:https://oj.leetcode.com/problems/one-edit-distance/ -[one-edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/one-edit-distance.py -[Reverse Words in a String]:https://oj.leetcode.com/problems/reverse-words-in-a-string/ -[reverse-words-in-a-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-words-in-a-string.py -[Reverse Words in a String II]:https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/ -[reverse-words-in-a-string-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-words-in-a-string-ii.py -[String to Integer (atoi)]:https://oj.leetcode.com/problems/string-to-integer-atoi/ -[string-to-integer-atoi.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/string-to-integer-atoi.py -[Text Justification]:https://oj.leetcode.com/problems/text-justification/ -[text-justification.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/text-justification.py -[Valid Palindrome]:https://oj.leetcode.com/problems/valid-palindrome/ -[valid-palindrome.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/valid-palindrome.py -[ZigZag Conversion]:https://oj.leetcode.com/problems/zigzag-conversion/ -[zigzag-conversion.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/zigzag-conversion.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +5| [Longest Palindromic Substring](https://oj.leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` +6| [ZigZag Conversion](https://oj.leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || +8| [String to Integer (atoi)](https://oj.leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || +14| [Longest Common Prefix](https://oj.leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || +20| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || +28| [Implement strStr()](https://oj.leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` +38| [Count and Say](https://oj.leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || +43| [Multiply Strings](https://oj.leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || +58| [Length of Last Word](https://oj.leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || +67| [Add Binary](https://oj.leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || +68| [Text Justification](https://oj.leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || +151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || +161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium || +165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || +186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium || +205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || --- From eaaee1179be4273090f93d4a57d78d34029e7f2e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 12:43:32 +0800 Subject: [PATCH 0228/1939] Update README.md --- README.md | 49 +++++++++++++------------------------------------ 1 file changed, 13 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 5832e7bc4..fdbd30b3e 100644 --- a/README.md +++ b/README.md @@ -109,42 +109,19 @@ Shell --- ##Linked List -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Add Two Numbers] | [add-two-numbers.py] | _O(n)_ | _O(1)_ | Medium | -[Copy List with Random Pointer] | [copy-list-with-random-pointer.py] | _O(n)_ | _O(1)_ | Hard | -[Intersection of Two Linked Lists]| [intersection-of-two-linked-lists.py] | _O(m + n)_ | _O(1)_ | Easy | -[Remove Duplicates from Sorted List]| [remove-duplicates-from-sorted-list.py] | _O(n)_ | _O(1)_ | Easy | -[Remove Duplicates from Sorted List II]| [remove-duplicates-from-sorted-list-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Remove Linked List Elements]| [remove-linked-list-elements.py] | _O(n)_ | _O(1)_ | Easy | -[Reverse Linked List]| [reverse-linked-list.py] | _O(n)_ | _O(1)_ | Easy | -[Reverse Linked List II]| [reverse-linked-list-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Reverse Nodes in k-Group]| [reverse-nodes-in-k-group.py] | _O(n)_ | _O(1)_ | Hard | -[Rotate List]| [rotate-list.py] | _O(n)_ | _O(1)_ | Medium | -[Swap Nodes in Pairs]| [swap-nodes-in-pairs.py] | _O(n)_ | _O(1)_ | Medium | - -[Add Two Numbers]:https://oj.leetcode.com/problems/add-two-numbers/ -[add-two-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/add-two-numbers.py -[Copy List with Random Pointer]:https://oj.leetcode.com/problems/copy-list-with-random-pointer/ -[copy-list-with-random-pointer.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/copy-list-with-random-pointer.py -[Intersection of Two Linked Lists]:https://oj.leetcode.com/problems/intersection-of-two-linked-lists/ -[intersection-of-two-linked-lists.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/intersection-of-two-linked-lists.py -[Remove Duplicates from Sorted List]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/ -[remove-duplicates-from-sorted-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list.py -[Remove Duplicates from Sorted List II]:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ -[remove-duplicates-from-sorted-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-duplicates-from-sorted-list-ii.py -[Remove Linked List Elements]:https://oj.leetcode.com/problems/remove-linked-list-elements/ -[remove-linked-list-elements.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-linked-list-elements.py -[Reverse Linked List]:https://oj.leetcode.com/problems/reverse-linked-list/ -[reverse-linked-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list.py -[Reverse Linked List II]:https://oj.leetcode.com/problems/reverse-linked-list-ii/ -[reverse-linked-list-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-linked-list-ii.py -[Reverse Nodes in k-Group]:https://oj.leetcode.com/problems/reverse-nodes-in-k-group/ -[reverse-nodes-in-k-group.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-nodes-in-k-group.py -[Rotate List]:https://oj.leetcode.com/problems/rotate-list/ -[rotate-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/rotate-list.py -[Swap Nodes in Pairs]:https://oj.leetcode.com/problems/swap-nodes-in-pairs/ -[swap-nodes-in-pairs.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/swap-nodes-in-pairs.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +2| [Add Two Numbers](https://oj.leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || +24| [Swap Nodes in Pairs](https://oj.leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || +25| [Reverse Nodes in k-Group](https://oj.leetcode.com/problems/reverse-nodes-in-k-group/)| [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || +61| [Rotate List](https://oj.leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || +82| [Remove Duplicates from Sorted List II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +83| [Remove Duplicates from Sorted List](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || +92| [Reverse Linked List II](https://oj.leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +138| [Copy List with Random Pointer](https://oj.leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || +160| [Intersection of Two Linked Lists](https://oj.leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || +203| [Remove Linked List Elements](https://oj.leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || +206| [Reverse Linked List](https://oj.leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || --- From 7a6f95fde5c3d8797a640ec72c5fc548a607a225 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 12:57:23 +0800 Subject: [PATCH 0229/1939] Update README.md --- README.md | 42 ++++++++++++------------------------------ 1 file changed, 12 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index fdbd30b3e..456d5de5e 100644 --- a/README.md +++ b/README.md @@ -126,40 +126,22 @@ Shell --- ##Stack -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Binary Search Tree Iterator] | [binary-search-tree-iterator.py] | _O(1)_| _O(h)_| Medium -[Evaluate Reverse Polish Notation]| [evaluate-reverse-polish-notation.py]| _O(n)_| _O(n)_| Medium | -[Longest Valid Parentheses]| [longest-valid-parentheses.py] | _O(n)_ | _O(1)_ | Hard | -[Min Stack] | [min-stack.py] | _O(n)_ | _O(1)_ | Easy | -[Simplify Path]| [simplify-path.py] | _O(n)_ | _O(n)_ | Medium | -[Symmetric Tree]| [symmetric-tree.py] | _O(n)_ | _O(h)_ | Easy | -[Valid Parentheses]| [valid-parentheses.py] | _O(n)_ | _O(n)_ | Easy | - -[Binary Search Tree Iterator]:https://oj.leetcode.com/problems/binary-search-tree-iterator/ -[binary-search-tree-iterator.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-search-tree-iterator.py -[Evaluate Reverse Polish Notation]:https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ -[evaluate-reverse-polish-notation.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/evaluate-reverse-polish-notation.py -[Longest Valid Parentheses]:https://oj.leetcode.com/problems/longest-valid-parentheses/ -[longest-valid-parentheses.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-valid-parentheses.py -[Min Stack]:https://oj.leetcode.com/problems/min-stack/ -[min-stack.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/min-stack.py -[Simplify Path]:https://oj.leetcode.com/problems/simplify-path/ -[simplify-path.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/simplify-path.py -[Symmetric Tree]:https://oj.leetcode.com/problems/symmetric-tree/ -[symmetric-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/symmetric-tree.py -[Valid Parentheses]:https://oj.leetcode.com/problems/valid-parentheses/ -[valid-parentheses.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/valid-parentheses.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +20| [Valid Parentheses](https://oj.leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || +32| [Longest Valid Parentheses](https://oj.leetcode.com/problems/longest-valid-parentheses/)| [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || +71| [Simplify Path](https://oj.leetcode.com/problems/simplify-path/)| [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || +101| [Symmetric Tree](https://oj.leetcode.com/problems/symmetric-tree/)| [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || +150| [Evaluate Reverse Polish Notation](https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/)| [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || +155| [Min Stack](https://oj.leetcode.com/problems/min-stack/) | [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || +173| [Binary Search Tree Iterator](https://oj.leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || --- ##Heap -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Merge k Sorted Lists] | [merge-k-sorted-lists.py] | _O(nlogk)_| _O(k)_| Hard | - -[Merge k Sorted Lists]:https://oj.leetcode.com/problems/merge-k-sorted-lists/ -[merge-k-sorted-lists.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-k-sorted-lists.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +23| [Merge k Sorted Lists](https://oj.leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || --- From 68e93ed2be4d7aac56488277a4fe12e33d5332d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 13:22:52 +0800 Subject: [PATCH 0230/1939] Update README.md --- README.md | 57 +++++++++++++++---------------------------------------- 1 file changed, 15 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 456d5de5e..f68de3937 100644 --- a/README.md +++ b/README.md @@ -158,48 +158,21 @@ Shell --- ##Hash Table -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[4 Sum] |[4sum.py] | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium | -[Anagrams] | [anagrams.py] | _O(n)_ | _O(n)_ | Medium | -[Count Primes] | [count-primes.py] | _O(n)_ | _O(n)_ | Easy | -[Happy Number] | [happy-number.py] | _O(k)_ | _O(k)_ | Easy | -[Longest Substring with At Most Two Distinct Characters]| [longest-substring-with-at-most-two-distinct-characters.py] | _O(n^2)_ | _O(1)_ | Hard | -[Longest Substring Without Repeating Characters] | [longest-substring-without-repeating-characters.py] | _O(n)_ | _O(1)_ | Medium | -[Max Points on a Line] | [max-points-on-a-line.py] | _O(n^2)_ | _O(n)_ | Hard | -[Minimum Window Substring] | [minimum-window-substring.py] | _O(n)_ | _O(k)_ | Hard | -[Repeated DNA Sequences] | [repeated-dna-sequences.py] | _O(n)_ | _O(n)_ | Medium | -[Substring with Concatenation of All Words] | [substring-with-concatenation-of-all-words.py] | _O(m * n * k)_ | _O(n * k)_ | Hard | -[Two Sum] | [two-sum.py] | _O(n)_ | _O(n)_ | Medium | -[Two Sum III - Data structure design] | [two-sum-iii-data-structure-design.py] | _O(n)_ | _O(n)_ | Easy | -[Valid Sudoku] | [valid-sudoku.py] | _O(n^2)_ | _O(n)_ | Easy | - -[4 Sum]: https://oj.leetcode.com/problems/4sum/ -[4sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/4sum.py -[Anagrams]:https://oj.leetcode.com/problems/anagrams/ -[anagrams.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/anagrams.py -[Count Primes]:https://oj.leetcode.com/problems/count-primes/ -[count-primes.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/count-primes.py -[Happy Number]:https://oj.leetcode.com/problems/happy-number/ -[happy-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/happy-number.py -[Longest Substring with At Most Two Distinct Characters]:https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ -[longest-substring-with-at-most-two-distinct-characters.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-with-at-most-two-distinct-characters.py -[Longest Substring Without Repeating Characters]:https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ -[longest-substring-without-repeating-characters.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-without-repeating-characters.py -[Max Points on a Line]:https://oj.leetcode.com/problems/max-points-on-a-line/ -[max-points-on-a-line.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/max-points-on-a-line.py -[Minimum Window Substring]:https://oj.leetcode.com/problems/minimum-window-substring/ -[minimum-window-substring.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/minimum-window-substring.py -[Repeated DNA Sequences]:https://oj.leetcode.com/problems/repeated-dna-sequences/ -[repeated-dna-sequences.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/repeated-dna-sequences.py -[Substring with Concatenation of All Words]:https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/ -[substring-with-concatenation-of-all-words.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/substring-with-concatenation-of-all-words.py -[Two Sum]:https://oj.leetcode.com/problems/two-sum/ -[two-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/two-sum.py -[Two Sum III - Data structure design]:https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/ -[two-sum-iii-data-structure-design.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/two-sum-iii-data-structure-design.py -[Valid Sudoku]:https://oj.leetcode.com/problems/valid-sudoku/ -[valid-sudoku.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/valid-sudoku.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +1| [Two Sum](https://oj.leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || +3| [Longest Substring Without Repeating Characters](https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || +18| [4 Sum](https://oj.leetcode.com/problems/4sum/) |[Python](./Python/4sum.py) | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium || +30| [Substring with Concatenation of All Words](https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/) | [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || +36| [Valid Sudoku](https://oj.leetcode.com/problems/valid-sudoku/) | [Python](./Python/valid-sudoku.py) | _O(n^2)_ | _O(n)_ | Easy || +49| [Anagrams](https://oj.leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n)_ | _O(n)_ | Medium || +76| [Minimum Window Substring](https://oj.leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || +149| [Max Points on a Line](https://oj.leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || +159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard || +167| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy || +187| [Repeated DNA Sequences](https://oj.leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || +202| [Happy Number](https://oj.leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || +204| [Count Primes](https://oj.leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || --- From 5e98fb39f2f89b1ce457cfe9d4e3290d6ed44240 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 13:25:20 +0800 Subject: [PATCH 0231/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f68de3937..365fb263f 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ Shell 144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie -211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./Python/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS +211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS --- From af3e3eac49fe9186eeee966bfb025648aeb80d11 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 15:36:03 +0800 Subject: [PATCH 0232/1939] Update README.md --- README.md | 64 +++++++++++++++---------------------------------------- 1 file changed, 17 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 365fb263f..d8384d9cf 100644 --- a/README.md +++ b/README.md @@ -177,57 +177,27 @@ Shell --- ##Data Structure -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[LRU Cache] | [lru-cache.py] | _O(1)_ | _O(n)_ | Hard | - - -[LRU Cache]:https://oj.leetcode.com/problems/lru-cache/ -[lru-cache.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/lru-cache.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +146| [LRU Cache](https://oj.leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || --- ##Math -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Divide Two Integers] | [divide-two-integers.py] | _O(logn)_ | _O(1)_ | Medium | -[Excel Sheet Column Title] | [excel-sheet-column-title.py] | _O(logn)_ | _O(1)_ | Easy | -[Excel Sheet Column Number] | [excel-sheet-column-number.py] | _O(n)_ | _O(1)_ | Easy | -[Factorial Trailing Zeroes] | [factorial-trailing-zeroes.py] | _O(logn)_ | _O(1)_ | Easy | -[Fraction to Recurring Decimal] | [fraction-to-recurring-decimal.py] | _O(logn)_ | _O(1)_ | Medium | -[Gray Code] | [gray-code.py] | _O(2^n)_ | _O(1)_ | Medium | -[Integer to Roman] | [integer-to-roman.py] | _O(n)_ | _O(1)_ | Medium | -[Palindrome Number] | [palindrome-number.py] | _O(1)_ | _O(1)_ | Easy | -[Permutation Sequence] | [permutation-sequence.py] | _O(n^2)_ | _O(n)_ | Medium | `Cantor Ordering` -[Reverse Integer] | [reverse-integer.py] | _O(logn)_ | _O(1)_ | Easy | -[Roman to Integer] | [roman-to-integer.py] | _O(n)_ | _O(1)_ | Easy | -[Valid Number] | [valid-number.py] | _O(n)_ | _O(1)_ | Hard | `Automata` - -[Divide Two Integers]:https://oj.leetcode.com/problems/divide-two-integers/ -[divide-two-integers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/divide-two-integers.py -[Excel Sheet Column Title]:https://oj.leetcode.com/problems/excel-sheet-column-title/ -[excel-sheet-column-title.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/excel-sheet-column-title.py -[Excel Sheet Column Number]:https://oj.leetcode.com/problems/excel-sheet-column-number/ -[excel-sheet-column-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/excel-sheet-column-number.py -[Factorial Trailing Zeroes]:https://oj.leetcode.com/problems/factorial-trailing-zeroes/ -[factorial-trailing-zeroes.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/factorial-trailing-zeroes.py -[Fraction to Recurring Decimal]:https://oj.leetcode.com/problems/fraction-to-recurring-decimal/ -[fraction-to-recurring-decimal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/fraction-to-recurring-decimal.py -[Gray Code]:https://oj.leetcode.com/problems/gray-code/ -[gray-code.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/gray-code.py -[Integer to Roman]:https://oj.leetcode.com/problems/integer-to-roman/ -[integer-to-roman.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/integer-to-roman.py -[Palindrome Number]:https://oj.leetcode.com/problems/palindrome-number/ -[palindrome-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/palindrome-number.py -[Permutation Sequence]:https://oj.leetcode.com/problems/permutation-sequence/ -[permutation-sequence.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/permutation-sequence.py -[Reverse Integer]:https://oj.leetcode.com/problems/reverse-integer/ -[reverse-integer.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-integer.py -[Roman to Integer]:https://oj.leetcode.com/problems/roman-to-integer/ -[roman-to-integer.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/roman-to-integer.py -[Valid Number]:https://oj.leetcode.com/problems/valid-number/ -[valid-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/valid-number.py - + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +7| [Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy | +9| [Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy | +12| [Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium | +13| [Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy | +29| [Divide Two Integers](https://oj.leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium | +60| [Permutation Sequence](https://oj.leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium | `Cantor Ordering` +65| [Valid Number](https://oj.leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard | `Automata` +89| [Gray Code](https://oj.leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium | +166| [Fraction to Recurring Decimal](https://oj.leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium | +168| [Excel Sheet Column Title](https://oj.leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy | +171| [Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy | +172| [Factorial Trailing Zeroes](https://oj.leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy | --- From 8fb78741bdc0ac601f76cea116b5384707f2d2b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 15:37:30 +0800 Subject: [PATCH 0233/1939] Update README.md --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index d8384d9cf..4aa1f6ad8 100644 --- a/README.md +++ b/README.md @@ -186,18 +186,18 @@ Shell ##Math # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -7| [Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy | -9| [Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy | -12| [Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium | -13| [Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy | -29| [Divide Two Integers](https://oj.leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium | -60| [Permutation Sequence](https://oj.leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium | `Cantor Ordering` -65| [Valid Number](https://oj.leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard | `Automata` -89| [Gray Code](https://oj.leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium | -166| [Fraction to Recurring Decimal](https://oj.leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium | -168| [Excel Sheet Column Title](https://oj.leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy | -171| [Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy | -172| [Factorial Trailing Zeroes](https://oj.leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy | +7| [Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || +9| [Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || +12| [Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || +13| [Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || +29| [Divide Two Integers](https://oj.leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium || +60| [Permutation Sequence](https://oj.leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` +65| [Valid Number](https://oj.leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` +89| [Gray Code](https://oj.leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || +166| [Fraction to Recurring Decimal](https://oj.leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium || +168| [Excel Sheet Column Title](https://oj.leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || +171| [Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || +172| [Factorial Trailing Zeroes](https://oj.leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || --- From 5bd50bc4fd710f23e5e0a83f7adf199c9e861e07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 15:54:17 +0800 Subject: [PATCH 0234/1939] Update README.md --- README.md | 41 +++++++++++------------------------------ 1 file changed, 11 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 4aa1f6ad8..94dcf9796 100644 --- a/README.md +++ b/README.md @@ -202,36 +202,17 @@ Shell --- ##Sort -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Insert Interval]| [insert-interval.py] | _O(n)_ | _O(1)_ | Hard | -[Insertion Sort List]|[insertion-sort-list.py] | _O(n^2)_ | _O(1)_ | Medium | -[Largest Number] | [largest-number.py] | _O(nlogn)_ | _O(1)_ | Medium | -[Maximum Gap] | [maximum-gap.py]| _O(n)_ | _O(n)_ | Hard | Tricky -[Merge Intervals]| [merge-intervals.py] | _O(nlogn)_ | _O(1)_ | Hard | -[Merge Sorted Array]| [merge-sorted-array.py] | _O(n)_ | _O(1)_ | Easy | -[Merge Two Sorted Lists]| [merge-two-sorted-lists.py] | _O(n)_ | _O(1)_ | Easy | -[Sort Colors] | [sort-colors.py] | _O(n)_ | _O(1)_ | Medium | -[Sort List] | [sort-list.py] | _O(nlogn)_ | _O(logn)_ | Medium | - -[Insert Interval]:https://oj.leetcode.com/problems/insert-interval/ -[insert-interval.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/insert-interval.py -[Insertion Sort List]:https://oj.leetcode.com/problems/insertion-sort-list/ -[insertion-sort-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/insertion-sort-list.py -[Largest Number]:https://oj.leetcode.com/problems/largest-number/ -[largest-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/largest-number.py -[Maximum Gap]:https://oj.leetcode.com/problems/maximum-gap/ -[maximum-gap.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximum-gap.py -[Merge Intervals]:https://oj.leetcode.com/problems/merge-intervals/ -[merge-intervals.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-intervals.py -[Merge Sorted Array]:https://oj.leetcode.com/problems/merge-sorted-array/ -[merge-sorted-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-sorted-array.py -[Merge Two Sorted Lists]:https://oj.leetcode.com/problems/merge-two-sorted-lists/ -[merge-two-sorted-lists.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/merge-two-sorted-lists.py -[Sort Colors]:https://oj.leetcode.com/problems/sort-colors/ -[sort-colors.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sort-colors.py -[Sort List]:https://oj.leetcode.com/problems/sort-list/ -[sort-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sort-list.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +21| [Merge Two Sorted Lists](https://oj.leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || +56| [Merge Intervals](https://oj.leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || +57| [Insert Interval](https://oj.leetcode.com/problems/insert-interval/)| [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || +75| [Sort Colors](https://oj.leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || +88| [Merge Sorted Array](https://oj.leetcode.com/problems/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +147| [Insertion Sort List](https://oj.leetcode.com/problems/insertion-sort-list/)|[Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || +148| [Sort List](https://oj.leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || +164| [Maximum Gap](https://oj.leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky +179| [Largest Number](https://oj.leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || --- From ff4efe82715a82a93037c7b3f52aa33f6bc089e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:01:22 +0800 Subject: [PATCH 0235/1939] Update README.md --- README.md | 29 ++++++++--------------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 94dcf9796..18fbf8cfa 100644 --- a/README.md +++ b/README.md @@ -217,27 +217,14 @@ Shell --- ##Two Pointer -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Linked List Cycle]| [linked-list-cycle.py] | _O(n)_ | _O(1)_ | Medium | -[Linked List Cycle II]| [linked-list-cycle-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Partition List]| [partition-list.py] | _O(n)_ | _O(1)_ | Medium | -[Remove Nth Node From End of List]| [remove-nth-node-from-end-of-list.py] | _O(n)_ | _O(1)_ | Easy | -[Reorder List]| [reorder-list.py] | _O(n)_ | _O(1)_ | Medium | -[Two Sum II - Input array is sorted] | [two-sum-ii-input-array-is-sorted.py] | _O(n)_ | _O(1)_ | Medium | - -[Linked List Cycle]:https://oj.leetcode.com/problems/linked-list-cycle/ -[linked-list-cycle.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/linked-list-cycle.py -[Linked List Cycle II]:https://oj.leetcode.com/problems/linked-list-cycle-ii/ -[linked-list-cycle-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/linked-list-cycle-ii.py -[Partition List]:https://oj.leetcode.com/problems/partition-list/ -[partition-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/partition-list.py -[Remove Nth Node From End of List]:https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/ -[remove-nth-node-from-end-of-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/remove-nth-node-from-end-of-list.py -[Reorder List]:https://oj.leetcode.com/problems/reorder-list/ -[reorder-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/reorder-list.py -[Two Sum II - Input array is sorted]:https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/ -[two-sum-ii-input-array-is-sorted.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/two-sum-ii-input-array-is-sorted.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +19| [Remove Nth Node From End of List](https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || +86| [Partition List](https://oj.leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || +141| [Linked List Cycle](https://oj.leetcode.com/problems/linked-list-cycle/)| [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || +142| [Linked List Cycle II](https://oj.leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || +143| [Reorder List](https://oj.leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || +167| [Two Sum II - Input array is sorted](https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium || --- From f264f01d2bb42c6f7765de0c81578528b84e3948 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:12:30 +0800 Subject: [PATCH 0236/1939] Update README.md --- README.md | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 18fbf8cfa..da4212955 100644 --- a/README.md +++ b/README.md @@ -229,24 +229,13 @@ Shell --- ##Brute Force Search -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Letter Combinations of a Phone Number]| [letter-combinations-of-a-phone-number.py] | _O(n * 4^n)_ | _O(n)_ | Medium | -[Permutations]| [permutations.py] | _O(n!)_ | _O(n)_ | Medium | -[Permutations II]| [permutations-ii.py] | _O(n!)_ | _O(n)_ | Hard | -[Subsets] | [subsets.py] | _O(n * 2^n)_ | _O(1)_ | Medium | -[Subsets II] | [subsets-ii.py] | _O(n * 2^n)_ | _O(1)_ | Medium | - -[Letter Combinations of a Phone Number]:https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ -[letter-combinations-of-a-phone-number.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/letter-combinations-of-a-phone-number.py -[Permutations]:https://oj.leetcode.com/problems/permutations/ -[permutations.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/permutations.py -[Permutations II]:https://oj.leetcode.com/problems/permutations-ii/ -[permutations-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/permutations-ii.py -[Subsets]:https://oj.leetcode.com/problems/subsets/ -[subsets.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/subsets.py -[Subsets II]:https://oj.leetcode.com/problems/subsets-ii/ -[subsets-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/subsets-ii.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +17| [Letter Combinations of a Phone Number](https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || +46| [Permutations](https://oj.leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n!)_ | _O(n)_ | Medium || +47| [Permutations II](https://oj.leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n!)_ | _O(n)_ | Hard || +78| [Subsets](https://oj.leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +90| [Subsets II](https://oj.leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || --- From e04d2fca94ea0d7dfdf559c06b84e0273a1ab50d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:33:44 +0800 Subject: [PATCH 0237/1939] Update README.md --- README.md | 66 ++++++++++++++----------------------------------------- 1 file changed, 17 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index da4212955..f5d935d04 100644 --- a/README.md +++ b/README.md @@ -240,55 +240,23 @@ Shell --- ##Divide and Conquer -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Balanced Binary Tree] | [balanced-binary-tree.py] | _O(n)_| _O(h)_ | Easy | -[Binary Tree Maximum Path Sum]| [binary-tree-maximum-path-sum.py] | _O(n)_| _O(h)_| Hard | -[Binary Tree Upside Down] | [binary-tree-upside-down.py] | _O(n)_ | _O(1)_ | Medium | -[Construct Binary Tree from Inorder and Postorder Traversal] | [construct-binary-tree-from-inorder-and-postorder-traversal.py] | _O(n)_ | _O(n)_ | Medium | -[Construct Binary Tree from Preorder and Inorder Traversal] | [construct-binary-tree-from-preorder-and-inorder-traversal.py] | _O(n)_ | _O(n)_ | Medium -[Convert Sorted Array to Binary Search Tree] | [convert-sorted-array-to-binary-search-tree.py] | _O(n)_ | _O(logn)_ | Medium | -[Convert Sorted List to Binary Search Tree] | [convert-sorted-list-to-binary-search-tree.py] | _O(n)_ | _O(logn)_ | Medium | -[Flatten Binary Tree to Linked List]|[flatten-binary-tree-to-linked-list.py]| _O(n)_ | _O(h)_ | Medium | -[Maximum Depth of Binary Tree]|[maximum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | -[Minimum Depth of Binary Tree]|[minimum-depth-of-binary-tree.py]| _O(n)_ | _O(h)_ | Easy | -[Populating Next Right Pointers in Each Node]|[populating-next-right-pointers-in-each-node.py]| _O(n)_ | _O(1)_ | Medium | -[Same Tree] |[same-tree.py] | _O(n)_ | _O(h)_ | Easy | -[Sum Root to Leaf Numbers] | [sum-root-to-leaf-numbers.py] | _O(n)_ | _O(h)_ | Medium | -[Unique Binary Search Trees II] | [unique-binary-search-trees-ii.py] | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium | -[Validate Binary Search Tree]|[validate-binary-search-tree.py]| _O(n)_ | _O(1)_ | Medium | - -[Balanced Binary Tree]:https://oj.leetcode.com/problems/balanced-binary-tree/ -[balanced-binary-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/balanced-binary-tree.py -[Binary Tree Maximum Path Sum]:https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ -[binary-tree-maximum-path-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-maximum-path-sum.py -[Binary Tree Upside Down]:https://oj.leetcode.com/problems/binary-tree-upside-down/ -[binary-tree-upside-down.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-upside-down.py -[Construct Binary Tree from Inorder and Postorder Traversal]:https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ -[construct-binary-tree-from-inorder-and-postorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py -[Construct Binary Tree from Preorder and Inorder Traversal]:https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ -[construct-binary-tree-from-preorder-and-inorder-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py -[Convert Sorted Array to Binary Search Tree]:https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ -[convert-sorted-array-to-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/convert-sorted-array-to-binary-search-tree.py -[Convert Sorted List to Binary Search Tree]:https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ -[convert-sorted-list-to-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/convert-sorted-list-to-binary-search-tree.py -[Flatten Binary Tree to Linked List]:https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/ -[flatten-binary-tree-to-linked-list.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/flatten-binary-tree-to-linked-list.py -[Maximum Depth of Binary Tree]:https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/ -[maximum-depth-of-binary-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximum-depth-of-binary-tree.py -[Minimum Depth of Binary Tree]:https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/ -[minimum-depth-of-binary-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/minimum-depth-of-binary-tree.py -[Populating Next Right Pointers in Each Node]:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/ -[populating-next-right-pointers-in-each-node.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/populating-next-right-pointers-in-each-node.py -[Same Tree]:https://oj.leetcode.com/problems/same-tree/ -[same-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/same-tree.py -[Sum Root to Leaf Numbers]:https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/ -[sum-root-to-leaf-numbers.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sum-root-to-leaf-numbers.py -[Unique Binary Search Trees II]:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ -[unique-binary-search-trees-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-binary-search-trees-ii.py -[Validate Binary Search Tree]:https://oj.leetcode.com/problems/validate-binary-search-tree/ -[validate-binary-search-tree.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/validate-binary-search-tree.py - + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +95| [Unique Binary Search Trees II](https://oj.leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || +98| [Validate Binary Search Tree](https://oj.leetcode.com/problems/validate-binary-search-tree/)|[Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || +100| [Same Tree](https://oj.leetcode.com/problems/same-tree/) |[Python](./Python/same-tree.py) | _O(n)_ | _O(h)_ | Easy || +104| [Maximum Depth of Binary Tree](https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/)|[Python](./Python/maximum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || +105| [Construct Binary Tree from Preorder and Inorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [Python](./Python/construct-binary-tree-from-preorder-and-inorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || +106| [Construct Binary Tree from Inorder and Postorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [Python](./Python/construct-binary-tree-from-inorder-and-postorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || +108| [Convert Sorted Array to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [Python](./Python/convert-sorted-array-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || +109| [Convert Sorted List to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [Python](./Python/convert-sorted-list-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || +110| [Balanced Binary Tree](https://oj.leetcode.com/problems/balanced-binary-tree/) | [Python](./Python/balanced-binary-tree.py) | _O(n)_| _O(h)_ | Easy || +111| [Minimum Depth of Binary Tree](https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/)|[Python](./Python/minimum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || +114| [Flatten Binary Tree to Linked List](https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/)|[Python](./Python/flatten-binary-tree-to-linked-list.py)| _O(n)_ | _O(h)_ | Medium || +116| [Populating Next Right Pointers in Each Node](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/)|[Python](./Python/populating-next-right-pointers-in-each-node.py)| _O(n)_ | _O(1)_ | Medium || +124| [Binary Tree Maximum Path Sum](https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || +129| [Sum Root to Leaf Numbers](https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || +156| [Binary Tree Upside Down](https://oj.leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium || --- From 9abf8ad8f9e2df67afe308c3e5d0498e80cd7daf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:46:47 +0800 Subject: [PATCH 0238/1939] Update README.md --- README.md | 50 +++++++++++++------------------------------------- 1 file changed, 13 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index f5d935d04..111cb54c8 100644 --- a/README.md +++ b/README.md @@ -261,43 +261,19 @@ Shell --- ##Binary Search - -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Find Minimum in Rotated Sorted Array] | [find-minimum-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Medium | -[Find Minimum in Rotated Sorted Array II] | [find-minimum-in-rotated-sorted-array-ii.py] | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard | -[Find Peak Element] | [find-peak-element.py] | _O(logn)_ | _O(1)_ | Medium | -[Median of Two Sorted Arrays] | [median-of-two-sorted-arrays.py] | _O(log(m + n))_ | _O(1)_ | Hard | -[Pow(x, n)] | [powx-n.py] | _O(logn)_ | _O(logn)_ | Medium | -[Search a 2D Matrix] | [search-a-2d-matrix.py] | _O(logm + logn)_ | _O(1)_ | Medium | -[Search for a Range] | [search-for-a-range.py] | _O(logn)_ | _O(1)_ | Medium | -[Search in Rotated Sorted Array] | [search-in-rotated-sorted-array.py] | _O(logn)_ | _O(1)_ | Hard | -[Search in Rotated Sorted Array II] | [search-in-rotated-sorted-array-ii.py] | _O(logn)_ | _O(1)_ | Medium | -[Search Insert Position] | [search-insert-position.py] | _O(logn)_ | _O(1)_ | Medium | -[Sqrt(x)] | [sqrtx.py] | _O(logn)_ | _O(1)_ | Medium | - -[Find Minimum in Rotated Sorted Array]:https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/ -[find-minimum-in-rotated-sorted-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/find-minimum-in-rotated-sorted-array.py -[Find Minimum in Rotated Sorted Array II]:https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ -[find-minimum-in-rotated-sorted-array-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/find-minimum-in-rotated-sorted-array-ii.py -[Find Peak Element]:https://oj.leetcode.com/problems/find-peak-element/ -[find-peak-element.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/find-peak-element.py -[Median of Two Sorted Arrays]:https://oj.leetcode.com/problems/median-of-two-sorted-arrays/ -[median-of-two-sorted-arrays.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/median-of-two-sorted-arrays.py -[Pow(x, n)]:https://oj.leetcode.com/problems/powx-n/ -[powx-n.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/powx-n.py -[Search a 2D Matrix]:https://oj.leetcode.com/problems/search-a-2d-matrix/ -[search-a-2d-matrix.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-a-2d-matrix.py -[Search for a Range]:https://oj.leetcode.com/problems/search-for-a-range/ -[search-for-a-range.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-for-a-range.py -[Search in Rotated Sorted Array]:https://oj.leetcode.com/problems/search-in-rotated-sorted-array/ -[search-in-rotated-sorted-array.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-in-rotated-sorted-array.py -[Search in Rotated Sorted Array II]:https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/ -[search-in-rotated-sorted-array-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-in-rotated-sorted-array-ii.py -[Search Insert Position]:https://oj.leetcode.com/problems/search-insert-position/ -[search-insert-position.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/search-insert-position.py -[Sqrt(x)]:https://oj.leetcode.com/problems/sqrtx/ -[sqrtx.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sqrtx.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +4| [Median of Two Sorted Arrays](https://oj.leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || +33| [Search in Rotated Sorted Array](https://oj.leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || +34| [Search for a Range](https://oj.leetcode.com/problems/search-for-a-range/) | [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || +35| [Search Insert Position](https://oj.leetcode.com/problems/search-insert-position/) | [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || +50| [Pow(x, n)](https://oj.leetcode.com/problems/powx-n/) | [Python](./Python/powx-n.py) | _O(logn)_ | _O(logn)_ | Medium || +69| [Sqrt(x)](https://oj.leetcode.com/problems/sqrtx/) | [Python](./Python/sqrtx.py) | _O(logn)_ | _O(1)_ | Medium || +74| [Search a 2D Matrix](https://oj.leetcode.com/problems/search-a-2d-matrix/) | [Python](./Python/search-a-2d-matrix.py) | _O(logm + logn)_ | _O(1)_ | Medium || +81| [Search in Rotated Sorted Array II](https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/) | [Python](./Python/search-in-rotated-sorted-array-ii.py) | _O(logn)_ | _O(1)_ | Medium || +153| [Find Minimum in Rotated Sorted Array](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || +154| [Find Minimum in Rotated Sorted Array II](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || +162| [Find Peak Element](https://oj.leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || --- From 177eb77c61d0334f6f5e77550f916225c1c0628e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 16:57:01 +0800 Subject: [PATCH 0239/1939] Update README.md --- README.md | 37 +++++++++++-------------------------- 1 file changed, 11 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 111cb54c8..11110b3be 100644 --- a/README.md +++ b/README.md @@ -278,32 +278,17 @@ Shell --- ##Breadth-First Search -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Binary Tree Level Order Traversal]| [binary-tree-level-order-traversal.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Level Order Traversal II]| [binary-tree-level-order-traversal-ii.py] | _O(n)_| _O(n)_| Easy | -[Binary Tree Zigzag Level Order Traversal]| [binary-tree-zigzag-level-order-traversal.py] | _O(n)_| _O(n)_| Medium | -[Clone Graph]| [clone-graph.py] | _O(n)_ | _O(n)_ | Medium | -[Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | -[Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [course-schedule-ii.py](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | -[Populating Next Right Pointers in Each Node II]|[populating-next-right-pointers-in-each-node-ii.py]| _O(n)_ | _O(1)_ | Hard | -[Surrounded Regions]|[surrounded-regions.py]| _O(m * n)_ | _O(m + n)_ | Medium | -[Word Ladder] |[word-ladder.py] | _O(n * d)_ | _O(d)_ | Medium | - -[Binary Tree Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ -[binary-tree-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal.py -[Binary Tree Level Order Traversal II]:https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ -[binary-tree-level-order-traversal-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-level-order-traversal-ii.py -[Binary Tree Zigzag Level Order Traversal]:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ -[binary-tree-zigzag-level-order-traversal.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-zigzag-level-order-traversal.py -[Clone Graph]:https://oj.leetcode.com/problems/clone-graph/ -[clone-graph.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/clone-graph.py -[Populating Next Right Pointers in Each Node II]:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ -[populating-next-right-pointers-in-each-node-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/populating-next-right-pointers-in-each-node-ii.py -[Surrounded Regions]:https://oj.leetcode.com/problems/surrounded-regions/ -[surrounded-regions.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/surrounded-regions.py -[Word Ladder]:https://oj.leetcode.com/problems/word-ladder/ -[word-ladder.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-ladder.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +102| [Binary Tree Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || +107| [Binary Tree Level Order Traversal II](https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](./Python/binary-tree-level-order-traversal-ii.py) | _O(n)_| _O(n)_| Easy || +103| [Binary Tree Zigzag Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Python](./Python/binary-tree-zigzag-level-order-traversal.py) | _O(n)_| _O(n)_| Medium || +117| [Populating Next Right Pointers in Each Node II](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)|[Python](./Python/populating-next-right-pointers-in-each-node-ii.py)| _O(n)_ | _O(1)_ | Hard || +127| [Word Ladder](https://oj.leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || +130| [Surrounded Regions](https://oj.leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || +133| [Clone Graph](https://oj.leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || +207| [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +210| [Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [course-schedule-ii.py](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || --- From d5a1cc7001b9e97d295fd5c6454548b9d5ac39e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:12:42 +0800 Subject: [PATCH 0240/1939] Update README.md --- README.md | 61 +++++++++++++++---------------------------------------- 1 file changed, 16 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 11110b3be..47ecbe979 100644 --- a/README.md +++ b/README.md @@ -293,51 +293,22 @@ Shell --- ##Depth-First Search -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Binary Tree Right Side View] | [binary-tree-right-side-view.py] | _O(n)_ | _O(h)_ | Medium | -[Combination Sum]| [combination-sum.py] | _O(n^m)_ | _O(m)_ | Medium | -[Combination Sum II]| [combination-sum-ii.py]| _O(n! / m!(n-m)!)_| _O(m)_ | Medium | -[Combinations] | [combinations.py] | _O(n!)_ | _O(n)_ | Medium | -[Generate Parentheses]| [generate-parentheses.py]| _O(4^n / n^(3/2))_ | _O(n)_ | Medium | -[N-Queens] | [n-queens.py] | _O(n!)_ | _O(n)_ | Hard | -[N-Queens-II] | [n-queens-ii.py] | _O(n!)_ | _O(n)_ | Hard | -[Number of Islands] | [number-of-islands.py] | _O(m * n)_ | _O(m * n)_| Medium | -[Palindrome Partitioning] | [palindrome-partitioning.py] | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium | -[Path Sum] | [path-sum.py] | _O(n)_ | _O(h)_ | Easy | -[Path Sum II] | [path-sum-ii.py] | _O(n)_ | _O(h)_ | Medium | -[Restore IP Addresses] | [restore-ip-addresses.py] | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium | -[Sudoku Solver] | [sudoku-solver.py] | _O((9!)^9)_ | _O(1)_ | Hard | -[Word Search] | [word-search.py] | _O(m * n * l)_ | _O(l)_ | Medium | - -[Binary Tree Right Side View]:https://oj.leetcode.com/problems/binary-tree-right-side-view/ -[binary-tree-right-side-view.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-right-side-view.py -[Combination Sum]:https://oj.leetcode.com/problems/combination-sum/ -[combination-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/combination-sum.py -[Combination Sum II]:https://oj.leetcode.com/problems/combination-sum-ii/ -[combination-sum-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/combination-sum-ii.py -[Combinations]:https://oj.leetcode.com/problems/combinations/ -[combinations.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/combinations.py -[Generate Parentheses]:https://oj.leetcode.com/problems/generate-parentheses/ -[generate-parentheses.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/generate-parentheses.py -[N-Queens]:https://oj.leetcode.com/problems/n-queens/ -[n-queens.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/n-queens.py -[N-Queens-II]:https://oj.leetcode.com/problems/n-queens-ii/ -[n-queens-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/n-queens-ii.py -[Number of Islands]:https://leetcode.com/problems/number-of-islands/ -[number-of-islands.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-islands.py -[Palindrome Partitioning]:https://oj.leetcode.com/problems/palindrome-partitioning/ -[palindrome-partitioning.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/palindrome-partitioning.py -[Path Sum]:https://oj.leetcode.com/problems/path-sum/ -[path-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/path-sum.py -[Path Sum II]:https://oj.leetcode.com/problems/path-sum-ii/ -[path-sum-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/path-sum-ii.py -[Restore IP Addresses]:https://oj.leetcode.com/problems/restore-ip-addresses/ -[restore-ip-addresses.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/restore-ip-addresses.py -[Sudoku Solver]:https://oj.leetcode.com/problems/sudoku-solver/ -[sudoku-solver.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/sudoku-solver.py -[Word Search]:https://oj.leetcode.com/problems/word-search/ -[word-search.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-search.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +22| [Generate Parentheses](https://oj.leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || +37| [Sudoku Solver](https://oj.leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || +39| [Combination Sum](https://oj.leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(n^m)_ | _O(m)_ | Medium || +40| [Combination Sum II](https://oj.leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(n! / m!(n-m)!)_| _O(m)_ | Medium || +51| [N-Queens](https://oj.leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || +52| [N-Queens-II](https://oj.leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || +77| [Combinations](https://oj.leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || +79| [Word Search](https://oj.leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || +93| [Restore IP Addresses](https://oj.leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium || +112| [Path Sum](https://oj.leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || +113| [Path Sum II](https://oj.leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || +131| [Palindrome Partitioning](https://oj.leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || +199| [Binary Tree Right Side View](https://oj.leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || +200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || --- From 443ea06805c4dfcaf1b98ce5f8b1380b34b905a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:13:59 +0800 Subject: [PATCH 0241/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 47ecbe979..ec387f29b 100644 --- a/README.md +++ b/README.md @@ -287,8 +287,8 @@ Shell 127| [Word Ladder](https://oj.leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || 130| [Surrounded Regions](https://oj.leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || 133| [Clone Graph](https://oj.leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || -207| [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [course-schedule.py](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || -210| [Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [course-schedule-ii.py](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +207| [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +210| [Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || --- From ca8b46e1dfd3d400da0b98ae9f9ef2169a569958 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:36:02 +0800 Subject: [PATCH 0242/1939] Update README.md --- README.md | 93 ++++++++++++++----------------------------------------- 1 file changed, 24 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index ec387f29b..c3e6b73c5 100644 --- a/README.md +++ b/README.md @@ -313,75 +313,30 @@ Shell --- ##Dynamic Programming -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Best Time to Buy and Sell Stock III]| [best-time-to-buy-and-sell-stock-iii.py] | _O(n)_ | _O(1)_ | Hard | -[Best Time to Buy and Sell Stock IV]| [best-time-to-buy-and-sell-stock-iv.py] | _O(k * n)_ | _O(k)_ | Hard | -[Climbing Stairs]| [climbing-stairs.py] | _O(n)_ | _O(1)_ | Easy | -[Decode Ways] | [decode-ways.py]| _O(n)_ | _O(1)_ | Medium | -[Distinct Subsequences]|[distinct-subsequences.py]| _O(n^2)_ | _O(n)_ | Hard | -[Dungeon Game] | [dungeon-game.py]| _O(m * n)_ | _O(m + n)_ | Hard | -[Edit Distance]|[edit-distance.py]| _O(m * n)_ | _O(m + n)_ | Hard | -[House Robber]| [house-robber.py] | _O(n)_ | _O(1)_ | Easy | -[Interleaving String]|[interleaving-string.py]| _O(m * n)_ | _O(m + n)_ | Hard | -[Maximal Rectangle]|[maximal-rectangle.py]| _O(n^2)_ | _O(n)_ | Hard | -[Maximum Product Subarray]|[maximum-product-subarray.py]| _O(n)_ | _O(1)_ | Medium | -[Maximum Subarray]|[maximum-subarray.py]| _O(n)_ | _O(1)_ | Medium | -[Minimum Path Sum]|[minimum-path-sum.py]| _O(m * n)_ | _O(m + n)_ | Medium | -[Palindrome Partitioning II] | [palindrome-partitioning-ii.py] | _O(n^2)_ | _O(n^2)_ | Hard | -[Regular Expression Matching] | [regular-expression-matching.py] | _O(m * n)_ | _O(n)_ | Hard | -[Scramble String] | [scramble-string.py] | _O(n^4)_ | _O(n^3)_ | Hard | -[Triangle] | [triangle.py] | _O(m * n)_ | _O(n)_ | Medium | -[Unique Binary Search Trees] | [unique-binary-search-trees.py] | _O(n^2)_ | _O(n)_ | Medium | -[Unique Paths] | [unique-paths.py]| _O(m * n)_ | _O(m + n)_ | Medium | -[Unique Paths II] | [unique-paths-ii.py] | _O(m * n)_ | _O(m + n)_ | Medium | -[Word Break] | [word-break.py] | _O(n^2)_ | _O(n)_ | Medium | -[Word Break II] | [word-break-ii.py] | _O(n^2)_ | _O(n)_ | Hard | - -[Best Time to Buy and Sell Stock III]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ -[best-time-to-buy-and-sell-stock-iii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-iii.py -[Best Time to Buy and Sell Stock IV]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ -[best-time-to-buy-and-sell-stock-iv.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-iv.py -[Climbing Stairs]:https://oj.leetcode.com/problems/climbing-stairs/ -[climbing-stairs.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/climbing-stairs.py -[Decode Ways]:https://oj.leetcode.com/problems/decode-ways/ -[decode-ways.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/decode-ways.py -[Distinct Subsequences]:https://oj.leetcode.com/problems/distinct-subsequences/ -[distinct-subsequences.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/distinct-subsequences.py -[Dungeon Game]:https://oj.leetcode.com/problems/dungeon-game/ -[dungeon-game.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/dungeon-game.py -[Edit Distance]:https://oj.leetcode.com/problems/edit-distance/ -[edit-distance.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/edit-distance.py -[House Robber]:https://oj.leetcode.com/problems/house-robber/ -[house-robber.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/house-robber.py -[Interleaving String]:https://oj.leetcode.com/problems/interleaving-string/ -[interleaving-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/interleaving-string.py -[Maximal Rectangle]:https://oj.leetcode.com/problems/maximal-rectangle/ -[maximal-rectangle.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximal-rectangle.py -[Maximum Product Subarray]:https://oj.leetcode.com/problems/maximum-product-subarray/ -[maximum-product-subarray.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximum-product-subarray.py -[Maximum Subarray]:https://oj.leetcode.com/problems/maximum-subarray/ -[maximum-subarray.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/maximum-subarray.py -[Minimum Path Sum]:https://oj.leetcode.com/problems/minimum-path-sum/ -[minimum-path-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/minimum-path-sum.py -[Palindrome Partitioning II]:https://oj.leetcode.com/problems/palindrome-partitioning-ii/ -[palindrome-partitioning-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/palindrome-partitioning-ii.py -[Regular Expression Matching]:https://oj.leetcode.com/problems/regular-expression-matching/ -[regular-expression-matching.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/regular-expression-matching.py -[Scramble String]:https://oj.leetcode.com/problems/scramble-string/ -[scramble-string.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/scramble-string.py -[Triangle]:https://oj.leetcode.com/problems/triangle/ -[triangle.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/triangle.py -[Unique Binary Search Trees]:https://oj.leetcode.com/problems/unique-binary-search-trees/ -[unique-binary-search-trees.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-binary-search-trees.py -[Unique Paths]:https://oj.leetcode.com/problems/unique-paths/ -[unique-paths.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-paths.py -[Unique Paths II]:https://oj.leetcode.com/problems/unique-paths-ii/ -[unique-paths-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/unique-paths-ii.py -[Word Break]:https://oj.leetcode.com/problems/word-break/ -[word-break.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-break.py -[Word Break II]:https://oj.leetcode.com/problems/word-break-ii/ -[word-break-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-break-ii.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +10| [Regular Expression Matching](https://oj.leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || +53| [Maximum Subarray](https://oj.leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || +62| [Unique Paths](https://oj.leetcode.com/problems/unique-paths/) | [Python](./Python/unique-paths.py)| _O(m * n)_ | _O(m + n)_ | Medium || +63| [Unique Paths II](https://oj.leetcode.com/problems/unique-paths-ii/) | [Python](./Python/unique-paths-ii.py) | _O(m * n)_ | _O(m + n)_ | Medium || +64| [Minimum Path Sum](https://oj.leetcode.com/problems/minimum-path-sum/)|[Python](./Python/minimum-path-sum.py)| _O(m * n)_ | _O(m + n)_ | Medium || +70| [Climbing Stairs](https://oj.leetcode.com/problems/climbing-stairs/)| [Python](./Python/climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || +72| [Edit Distance](https://oj.leetcode.com/problems/edit-distance/)|[Python](./Python/edit-distance.py)| _O(m * n)_ | _O(m + n)_ | Hard || +85| [Maximal Rectangle](https://oj.leetcode.com/problems/maximal-rectangle/)|[Python](./Python/maximal-rectangle.py)| _O(n^2)_ | _O(n)_ | Hard || +87| [Scramble String](https://oj.leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || +91| [Decode Ways](https://oj.leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || +96| [Unique Binary Search Trees](https://oj.leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n^2)_ | _O(n)_ | Medium || +97| [Interleaving String](https://oj.leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || +115| [Distinct Subsequences](https://oj.leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || +120| [Triangle](https://oj.leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || +123| [Best Time to Buy and Sell Stock III](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || +132| [Palindrome Partitioning II](https://oj.leetcode.com/problems/palindrome-partitioning-ii/) | [Python](./Python/palindrome-partitioning-ii.py) | _O(n^2)_ | _O(n^2)_ | Hard || +139| [Word Break](https://oj.leetcode.com/problems/word-break/) | [Python](./Python/word-break.py) | _O(n^2)_ | _O(n)_ | Medium || +140| [Word Break II](https://oj.leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || +152| [Maximum Product Subarray](https://oj.leetcode.com/problems/maximum-product-subarray/)|[Python](./Python/maximum-product-subarray.py)| _O(n)_ | _O(1)_ | Medium || +174| [Dungeon Game](https://oj.leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || +188| [Best Time to Buy and Sell Stock IV](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || +198| [House Robber](https://oj.leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || --- From c3d40ccc182965fb311491419691ad1bda409d24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:37:00 +0800 Subject: [PATCH 0243/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c3e6b73c5..59c38d245 100644 --- a/README.md +++ b/README.md @@ -329,7 +329,7 @@ Shell 97| [Interleaving String](https://oj.leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || 115| [Distinct Subsequences](https://oj.leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || 120| [Triangle](https://oj.leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || -123| [Best Time to Buy and Sell Stock III](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || +123| [Best Time to Buy and Sell Stock III](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || 132| [Palindrome Partitioning II](https://oj.leetcode.com/problems/palindrome-partitioning-ii/) | [Python](./Python/palindrome-partitioning-ii.py) | _O(n^2)_ | _O(n^2)_ | Hard || 139| [Word Break](https://oj.leetcode.com/problems/word-break/) | [Python](./Python/word-break.py) | _O(n^2)_ | _O(n)_ | Medium || 140| [Word Break II](https://oj.leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || From dbe5eb1fe346bf1b99e843d3429238b486d10805 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:46:13 +0800 Subject: [PATCH 0244/1939] Update README.md --- README.md | 52 +++++++++++++++------------------------------------- 1 file changed, 15 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 59c38d245..3cc5eefc7 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Shell 119 | [Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || 128 | [Longest Consecutive Sequence](https://oj.leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky -157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](/Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy || +157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy || 158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard || 163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium || 169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | @@ -341,46 +341,24 @@ Shell --- ##Backtracking -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Word Ladder II] |[word-ladder-ii.py] | _O(n * d)_ | _O(d)_ | Hard | - -[Word Ladder II]:https://oj.leetcode.com/problems/word-ladder-ii/ -[word-ladder-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/word-ladder-ii.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +126| [Word Ladder II](https://oj.leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || --- ##Greedy -Problem | Solution | Time | Space | Difficulty | Notes ---------------- | --------------- | --------------- | --------------- | -------------- | ----- -[Best Time to Buy and Sell Stock II]| [best-time-to-buy-and-sell-stock-ii.py] | _O(n)_ | _O(1)_ | Medium | -[Candy]| [candy.py] | _O(n)_ | _O(n)_ | Hard | -[Container With Most Water]| [container-with-most-water.py] | _O(n)_ | _O(1)_ | Medium | -[Gas Station]| [gas-station.py] | _O(n)_ | _O(1)_ | Medium | -[Jump Game] | [jump-game.py] | _O(n)_ | _O(1)_ | Medium | -[Jump Game II] | [jump-game-ii.py] | _O(n)_ | _O(1)_ | Hard | -[Largest Rectangle in Histogram] | [largest-rectangle-in-histogram.py] | _O(n)_ | _O(n)_ | Hard | Tricky -[Trapping Rain Water] | [trapping-rain-water.py] | _O(n)_ | _O(1)_ | Hard | Tricky -[Wildcard Matching] | [wildcard-matching.py] | _O(m + n)_ | _O(1)_ | Hard | Tricky - -[Best Time to Buy and Sell Stock II]:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ -[best-time-to-buy-and-sell-stock-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-ii.py -[Candy]:https://oj.leetcode.com/problems/candy/ -[candy.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/candy.py -[Container With Most Water]:https://oj.leetcode.com/problems/container-with-most-water/ -[container-with-most-water.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/container-with-most-water.py -[Gas Station]:https://oj.leetcode.com/problems/gas-station/ -[gas-station.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/gas-station.py -[Jump Game]:https://oj.leetcode.com/problems/jump-game/ -[jump-game.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/jump-game.py -[Jump Game II]:https://oj.leetcode.com/problems/jump-game-ii/ -[jump-game-ii.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/jump-game-ii.py -[Largest Rectangle in Histogram]:https://oj.leetcode.com/problems/largest-rectangle-in-histogram/ -[largest-rectangle-in-histogram.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/largest-rectangle-in-histogram.py -[Trapping Rain Water]:https://oj.leetcode.com/problems/trapping-rain-water/ -[trapping-rain-water.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/trapping-rain-water.py -[Wildcard Matching]:https://oj.leetcode.com/problems/wildcard-matching/ -[wildcard-matching.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/wildcard-matching.py + # | Problem | Solution | Time | Space | Difficulty | Tag | Notes +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +11| [Container With Most Water](https://oj.leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || +42| [Trapping Rain Water](https://oj.leetcode.com/problems/trapping-rain-water/) | [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky +44| [Wildcard Matching](https://oj.leetcode.com/problems/wildcard-matching/) | [Python](./Python/wildcard-matching.py) | _O(m + n)_ | _O(1)_ | Hard || Tricky +45| [Jump Game II](https://oj.leetcode.com/problems/jump-game-ii/) | [Python](./Python/jump-game-ii.py) | _O(n)_ | _O(1)_ | Hard || +55| [Jump Game](https://oj.leetcode.com/problems/jump-game/) | [Python](./Python/jump-game.py) | _O(n)_ | _O(1)_ | Medium || +84| [Largest Rectangle in Histogram](https://oj.leetcode.com/problems/largest-rectangle-in-histogram/) | [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Tricky +122| [Best Time to Buy and Sell Stock II](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Python](./Python/best-time-to-buy-and-sell-stock-ii.py) | _O(n)_ | _O(1)_ | Medium || +134| [Gas Station](https://oj.leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || +135| [Candy](https://oj.leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || --- From 3563f768ab109b4af517198f6a1ea8a5c30ee1b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:48:09 +0800 Subject: [PATCH 0245/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3cc5eefc7..c1caad566 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,7 @@ Shell 76| [Minimum Window Substring](https://oj.leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || 149| [Max Points on a Line](https://oj.leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || 159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard || -167| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy || +170| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy || 187| [Repeated DNA Sequences](https://oj.leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || 202| [Happy Number](https://oj.leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://oj.leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || From cc79e6cfd0ab9c1fc9de1a33a220b8a72a66a371 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 17:49:50 +0800 Subject: [PATCH 0246/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c1caad566..6e0e2164f 100644 --- a/README.md +++ b/README.md @@ -93,13 +93,13 @@ Shell 6| [ZigZag Conversion](https://oj.leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || 8| [String to Integer (atoi)](https://oj.leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://oj.leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || -20| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://oj.leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://oj.leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://oj.leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://oj.leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://oj.leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://oj.leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || +125| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium || 165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || From 9614fc143ba0ef7af0e8d9bace8400fa5f79d6d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 18:14:55 +0800 Subject: [PATCH 0247/1939] Update README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6e0e2164f..736fd492e 100644 --- a/README.md +++ b/README.md @@ -77,9 +77,9 @@ Shell 119 | [Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || 128 | [Longest Consecutive Sequence](https://oj.leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky -157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy || -158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard || -163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium || +157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| +158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| +163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || @@ -101,7 +101,7 @@ Shell 68| [Text Justification](https://oj.leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || -161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium || +161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| 165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium || 205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || @@ -168,8 +168,8 @@ Shell 49| [Anagrams](https://oj.leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n)_ | _O(n)_ | Medium || 76| [Minimum Window Substring](https://oj.leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || 149| [Max Points on a Line](https://oj.leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || -159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard || -170| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy || +159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| +170| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 📖 | 187| [Repeated DNA Sequences](https://oj.leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || 202| [Happy Number](https://oj.leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://oj.leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || @@ -224,7 +224,7 @@ Shell 141| [Linked List Cycle](https://oj.leetcode.com/problems/linked-list-cycle/)| [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || 142| [Linked List Cycle II](https://oj.leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || 143| [Reorder List](https://oj.leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || -167| [Two Sum II - Input array is sorted](https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium || +167| [Two Sum II - Input array is sorted](https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | --- @@ -256,7 +256,7 @@ Shell 116| [Populating Next Right Pointers in Each Node](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/)|[Python](./Python/populating-next-right-pointers-in-each-node.py)| _O(n)_ | _O(1)_ | Medium || 124| [Binary Tree Maximum Path Sum](https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || 129| [Sum Root to Leaf Numbers](https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || -156| [Binary Tree Upside Down](https://oj.leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium || +156| [Binary Tree Upside Down](https://oj.leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| --- From 3951e5b103e1b32596e752c77d31d5af5b642c9b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 May 2015 18:18:59 +0800 Subject: [PATCH 0248/1939] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 736fd492e..478200dd7 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ The number of problems is increasing recently. Here is the classification of all `211` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. +(Notes: "📖" means you have to buy the book from LeetCode. ) --- Algorithms @@ -103,7 +104,7 @@ Shell 151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| 165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || -186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium || +186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || --- From 059ed13953da1b7c384acf937dcf8334045c2eeb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 May 2015 13:38:20 +0800 Subject: [PATCH 0249/1939] Update rotate-image.py --- Python/rotate-image.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/rotate-image.py b/Python/rotate-image.py index c434dffa5..dabc2734f 100644 --- a/Python/rotate-image.py +++ b/Python/rotate-image.py @@ -20,12 +20,12 @@ def rotate(self, matrix): # anti-diagonal mirror for i in xrange(n): for j in xrange(n - i): - matrix[i][j], matrix[n - 1 - j][n - 1 -i] = matrix[n - 1 - j][n - 1 -i], matrix[i][j] + matrix[i][j], matrix[n-1-j][n-1-i] = matrix[n-1-j][n-1-i], matrix[i][j] # horizontal mirror for i in xrange(n / 2): for j in xrange(n): - matrix[i][j], matrix[n - 1 - i][j] = matrix[n - 1 - i][j], matrix[i][j] + matrix[i][j], matrix[n-1-i][j] = matrix[n-1-i][j], matrix[i][j] return matrix From 3565d7fad5cbf96e964f9cb391803bd7e8e77711 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 13:30:41 +0800 Subject: [PATCH 0250/1939] Create word-search-ii.cpp --- C++/word-search-ii.cpp | 101 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 C++/word-search-ii.cpp diff --git a/C++/word-search-ii.cpp b/C++/word-search-ii.cpp new file mode 100644 index 000000000..768f0264d --- /dev/null +++ b/C++/word-search-ii.cpp @@ -0,0 +1,101 @@ +// Time: O(m * n * h), h is height of trie +// Space: O(26^h) + +class Solution { +private: + struct TrieNode { + bool isString = false; + unordered_map leaves; + + bool Insert(const string& s) { + auto* p = this; + for (const auto& c : s) { + if (p->leaves.find(c) == p->leaves.cend()) { + p->leaves[c] = new TrieNode; + } + p = p->leaves[c]; + } + + // s already existed in this trie. + if (p->isString) { + return false; + } else { + p->isString = true; + return true; + } + } + + ~TrieNode() { + for (auto& kv : leaves) { + if (kv.second) { + kv.second->~TrieNode(); + } + } + } + }; + +public: + /** + * @param board: A list of lists of character + * @param words: A list of string + * @return: A list of string + */ + vector findWords(vector>& board, vector& words) { + unordered_set ret; + vector> visited(board.size(), vector(board[0].size(), false)); + string curr; + TrieNode trie; + for (const auto& word : words) { + trie.Insert(word); + } + + for (int i = 0; i < board.size(); ++i) { + for (int j = 0; j < board[0].size(); ++j) { + findWordsDFS(board, visited, &trie, i, j, curr, ret); + } + } + + return vector(ret.begin(), ret.end()); + } + + void findWordsDFS(vector> &grid, + vector> &visited, + TrieNode *trie, + int i, + int j, + string curr, + unordered_set &ret) { + // Invalid state. + if (!trie || i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size()) { + return; + } + + // Not in trie or visited. + if (!trie->leaves[grid[i][j] ] || visited[i][j]) { + return; + } + + // Get next trie nodes. + TrieNode *nextNode = trie->leaves[grid[i][j]]; + + // Update current string. + curr.push_back(grid[i][j]); + + // Find the string, add to the answers. + if (nextNode->isString) { + ret.insert(curr); + } + + // Marked as visited. + visited[i][j] = true; + + // Try each direction. + vector> direction{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; + for (int k = 0; k < 4; ++k) { + findWordsDFS(grid, visited, nextNode, + i + direction[k].first, j + direction[k].second, curr, ret); + } + + visited[i][j] = false; + } +}; From b3bc5f56cb3fb59c3f618ad516e3a8fc66ddd74e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 13:31:57 +0800 Subject: [PATCH 0251/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 478200dd7..ced0ae0d8 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-16), there are `195` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-16), there are `196` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `211` problems. +Here is the classification of all `212` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -155,6 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./Python/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Medium || --- From 72e51f270d7547291e458ed04a9d1f78a951ab7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 13:33:37 +0800 Subject: [PATCH 0252/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ced0ae0d8..dc59542c0 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./Python/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Medium || +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./Python/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- From e32f5d65d9a02845b49a29c64dfc21b51ba5bb2d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 15:07:56 +0800 Subject: [PATCH 0253/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dc59542c0..ff4eb9ebb 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./Python/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- From b6e8693890b594f4c4f61d65d61aea1a9e525ebf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 16:01:19 +0800 Subject: [PATCH 0254/1939] Create word-search-ii.py --- Python/word-search-ii.py | 74 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Python/word-search-ii.py diff --git a/Python/word-search-ii.py b/Python/word-search-ii.py new file mode 100644 index 000000000..3b2ca2499 --- /dev/null +++ b/Python/word-search-ii.py @@ -0,0 +1,74 @@ +# Time: O(m * n * l) +# Space: O(l) +# +# Given a 2D board and a list of words from the dictionary, find all words in the board. +# +# Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells +# are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. +# +# For example, +# Given words = ["oath","pea","eat","rain"] and board = +# +# [ +# ['o','a','a','n'], +# ['e','t','a','e'], +# ['i','h','k','r'], +# ['i','f','l','v'] +# ] +# Return ["eat","oath"]. +# Note: +# You may assume that all inputs are consist of lowercase letters a-z. +# +class TrieNode: + # Initialize your data structure here. + def __init__(self): + self.flag = False + self.children = {} + + # Inserts a word into the trie. + def insert(self, word): + cur = self + for c in word: + if not c in cur.children: + cur.children[c] = TrieNode() + cur = cur.children[c] + cur.flag = True + +class Solution: + # @param {character[][]} board + # @param {string[]} words + # @return {string[]} + def findWords(self, board, words): + visited = [[False for j in xrange(len(board[0]))] for i in xrange(len(board))] + result = {} + trie = TrieNode() + for word in words: + trie.insert(word) + + for i in xrange(len(board)): + for j in xrange(len(board[0])): + if self.existRecu(board, trie, 0, i, j, visited, [], result): + return True + + return result.keys() + + def existRecu(self, board, trie, cur, i, j, visited, cur_word, result): + if not trie or i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j]: + return + + if board[i][j] not in trie.children: + return + + cur_word.append(board[i][j]) + next_node = trie.children[board[i][j]] + if next_node.flag: + result["".join(cur_word)] = True + + visited[i][j] = True + self.existRecu(board, next_node, cur + 1, i + 1, j, visited, cur_word, result) + self.existRecu(board, next_node, cur + 1, i - 1, j, visited, cur_word, result) + self.existRecu(board, next_node, cur + 1, i, j + 1, visited, cur_word, result) + self.existRecu(board, next_node, cur + 1, i, j - 1, visited, cur_word, result) + visited[i][j] = False + cur_word.pop() + From 77e2036be5bdad85e3511d0062288d4e88f68a0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 16:01:49 +0800 Subject: [PATCH 0255/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ff4eb9ebb..aab0242ef 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./C++/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- From c270af60c717fb1ae2eeb75cf5ccdfd02c9a5118 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 16:02:48 +0800 Subject: [PATCH 0256/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aab0242ef..6e91321b9 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Shell 145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./C++/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- From 89de62ff5fda0afc77e94ae8195479c5740159de Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 May 2015 16:04:11 +0800 Subject: [PATCH 0257/1939] Update word-search-ii.py --- Python/word-search-ii.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/word-search-ii.py b/Python/word-search-ii.py index 3b2ca2499..dd806f75f 100644 --- a/Python/word-search-ii.py +++ b/Python/word-search-ii.py @@ -47,12 +47,12 @@ def findWords(self, board, words): for i in xrange(len(board)): for j in xrange(len(board[0])): - if self.existRecu(board, trie, 0, i, j, visited, [], result): + if self.findWordsRecu(board, trie, 0, i, j, visited, [], result): return True return result.keys() - def existRecu(self, board, trie, cur, i, j, visited, cur_word, result): + def findWordsRecu(self, board, trie, cur, i, j, visited, cur_word, result): if not trie or i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j]: return @@ -65,10 +65,10 @@ def existRecu(self, board, trie, cur, i, j, visited, cur_word, result): result["".join(cur_word)] = True visited[i][j] = True - self.existRecu(board, next_node, cur + 1, i + 1, j, visited, cur_word, result) - self.existRecu(board, next_node, cur + 1, i - 1, j, visited, cur_word, result) - self.existRecu(board, next_node, cur + 1, i, j + 1, visited, cur_word, result) - self.existRecu(board, next_node, cur + 1, i, j - 1, visited, cur_word, result) + self.findWordsRecu(board, next_node, cur + 1, i + 1, j, visited, cur_word, result) + self.findWordsRecu(board, next_node, cur + 1, i - 1, j, visited, cur_word, result) + self.findWordsRecu(board, next_node, cur + 1, i, j + 1, visited, cur_word, result) + self.findWordsRecu(board, next_node, cur + 1, i, j - 1, visited, cur_word, result) visited[i][j] = False cur_word.pop() From 580a84353eb45297ffbfd5a105cd55c03ac8ca47 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 19 May 2015 20:52:03 +0800 Subject: [PATCH 0258/1939] update --- ...d-and-search-word-data-structure-design.py | 22 +++++++++---------- Python/implement-trie-prefix-tree.py | 18 +++++++-------- Python/word-search-ii.py | 18 +++++++-------- 3 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Python/add-and-search-word-data-structure-design.py b/Python/add-and-search-word-data-structure-design.py index 1c8b80d59..384b97d64 100644 --- a/Python/add-and-search-word-data-structure-design.py +++ b/Python/add-and-search-word-data-structure-design.py @@ -24,8 +24,8 @@ class TrieNode: # Initialize your data structure here. def __init__(self): - self.flag = False - self.children = {} + self.is_string = False + self.leaves = {} class WordDictionary: def __init__(self): @@ -37,10 +37,10 @@ def __init__(self): def addWord(self, word): curr = self.root for c in word: - if not c in curr.children: - curr.children[c] = TrieNode() - curr = curr.children[c] - curr.flag = True + if not c in curr.leaves: + curr.leaves[c] = TrieNode() + curr = curr.leaves[c] + curr.is_string = True # @param {string} word # @return {boolean} @@ -51,12 +51,12 @@ def search(self, word): def searchHelper(self, word, start, curr): if start == len(word): - return curr.flag - if word[start] in curr.children: - return self.searchHelper(word, start+1, curr.children[word[start]]) + return curr.is_string + if word[start] in curr.leaves: + return self.searchHelper(word, start+1, curr.leaves[word[start]]) elif word[start] == '.': - for c in curr.children: - if self.searchHelper(word, start+1, curr.children[c]): + for c in curr.leaves: + if self.searchHelper(word, start+1, curr.leaves[c]): return True return False diff --git a/Python/implement-trie-prefix-tree.py b/Python/implement-trie-prefix-tree.py index 1fc9cb47a..c52003ae3 100644 --- a/Python/implement-trie-prefix-tree.py +++ b/Python/implement-trie-prefix-tree.py @@ -10,8 +10,8 @@ class TrieNode: # Initialize your data structure here. def __init__(self): - self.flag = False - self.children = {} + self.is_string = False + self.leaves = {} class Trie: @@ -25,10 +25,10 @@ def __init__(self): def insert(self, word): cur = self.root for c in word: - if not c in cur.children: - cur.children[c] = TrieNode() - cur = cur.children[c] - cur.flag = True + if not c in cur.leaves: + cur.leaves[c] = TrieNode() + cur = cur.leaves[c] + cur.is_string = True # @param {string} word # @return {boolean} @@ -36,7 +36,7 @@ def insert(self, word): def search(self, word): res, node = self.childSearch(word) if res: - return node.flag + return node.is_string return False # @param {string} prefix @@ -49,8 +49,8 @@ def startsWith(self, prefix): def childSearch(self, word): cur = self.root for c in word: - if c in cur.children: - cur = cur.children[c] + if c in cur.leaves: + cur = cur.leaves[c] else: return False, None return True, cur diff --git a/Python/word-search-ii.py b/Python/word-search-ii.py index dd806f75f..36b7afe93 100644 --- a/Python/word-search-ii.py +++ b/Python/word-search-ii.py @@ -22,17 +22,17 @@ class TrieNode: # Initialize your data structure here. def __init__(self): - self.flag = False - self.children = {} + self.is_string = False + self.leaves = {} # Inserts a word into the trie. def insert(self, word): cur = self for c in word: - if not c in cur.children: - cur.children[c] = TrieNode() - cur = cur.children[c] - cur.flag = True + if not c in cur.leaves: + cur.leaves[c] = TrieNode() + cur = cur.leaves[c] + cur.is_string = True class Solution: # @param {character[][]} board @@ -56,12 +56,12 @@ def findWordsRecu(self, board, trie, cur, i, j, visited, cur_word, result): if not trie or i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j]: return - if board[i][j] not in trie.children: + if board[i][j] not in trie.leaves: return cur_word.append(board[i][j]) - next_node = trie.children[board[i][j]] - if next_node.flag: + next_node = trie.leaves[board[i][j]] + if next_node.is_string: result["".join(cur_word)] = True visited[i][j] = True From fc35e0e95c7020b0a2cf5a8c4a94751ae08f6b66 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:31:00 +0800 Subject: [PATCH 0259/1939] Create house-robber-ii.py --- Python/house-robber-ii.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/house-robber-ii.py diff --git a/Python/house-robber-ii.py b/Python/house-robber-ii.py new file mode 100644 index 000000000..554ed4828 --- /dev/null +++ b/Python/house-robber-ii.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(1) +# +# Note: This is an extension of House Robber. +# +# After robbing those houses on that street, the thief has found himself a new place +# for his thievery so that he will not get too much attention. This time, all houses +# at this place are arranged in a circle. That means the first house is the neighbor +# of the last one. Meanwhile, the security system for these houses remain the same as +# for those in the previous street. +# +# Given a list of non-negative integers representing the amount of money of each house, +# determine the maximum amount of money you can rob tonight without alerting the police. +# +class Solution: + # @param {integer[]} nums + # @return {integer} + def rob(self, nums): + if len(nums) == 0: + return 0 + + if len(nums) == 1: + return nums[0] + + return max(self.robRange(nums, 0, len(nums) - 1),\ + self.robRange(nums, 1, len(nums))) + + def robRange(self, nums, start, end): + num_i, num_i_1 = nums[start], 0 + for i in xrange(start + 1, end): + num_i_1, num_i_2 = num_i, num_i_1 + num_i = max(nums[i] + num_i_2, num_i_1); + + return num_i + +if __name__ == '__main__': + print Solution().rob([8,4,8,5,9,6,5,4,4,10]) From 63eb6e72c3243a8cb15706ed42502e49a41e6189 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:32:10 +0800 Subject: [PATCH 0260/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6e91321b9..8ae25980d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-16), there are `196` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-20), there are `197` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `212` problems. +Here is the classification of all `213` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -339,6 +339,7 @@ Shell 174| [Dungeon Game](https://oj.leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || 188| [Best Time to Buy and Sell Stock IV](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || 198| [House Robber](https://oj.leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || +213| [House Robber II](https://oj.leetcode.com/problems/house-robber-ii/)| [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || --- From 39355ee045cc9282b131ac55d3694b03afe6ff20 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:41:20 +0800 Subject: [PATCH 0261/1939] Create house-robber-ii.cpp --- C++/house-robber-ii.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/house-robber-ii.cpp diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp new file mode 100644 index 000000000..4648bfa2c --- /dev/null +++ b/C++/house-robber-ii.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int rob(vector& nums) { + if (nums.size() == 0) { + return 0; + } + if (nums.size() == 1) { + return nums[0]; + } + + return max(robRange(nums, 0, nums.size() - 1), robRange(nums, 1, nums.size())); + } + int robRange(vector& nums, int start, int end) { + int num_i = nums[start], num_i_1 = 0, num_i_2 = 0; + for (int i = start + 1; i < end; ++i) { + num_i_2 = num_i_1; + num_i_1 = num_i; + num_i = max(nums[i] + num_i_2, num_i_1); + } + return num_i; + } +}; From b3d6a96550612d3f7e8751d44e37ce90545c8681 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:41:53 +0800 Subject: [PATCH 0262/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ae25980d..9605b65ba 100644 --- a/README.md +++ b/README.md @@ -339,7 +339,7 @@ Shell 174| [Dungeon Game](https://oj.leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || 188| [Best Time to Buy and Sell Stock IV](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || 198| [House Robber](https://oj.leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || -213| [House Robber II](https://oj.leetcode.com/problems/house-robber-ii/)| [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || +213| [House Robber II](https://oj.leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || --- From d721ca8bf5a2b02f43e3d269e1de2af5a43cf830 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:43:25 +0800 Subject: [PATCH 0263/1939] Update house-robber-ii.cpp --- C++/house-robber-ii.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp index 4648bfa2c..7a11fb883 100644 --- a/C++/house-robber-ii.cpp +++ b/C++/house-robber-ii.cpp @@ -11,7 +11,8 @@ class Solution { return nums[0]; } - return max(robRange(nums, 0, nums.size() - 1), robRange(nums, 1, nums.size())); + return max(robRange(nums, 0, nums.size() - 1), // Include the first one of nums without the last one. + robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. } int robRange(vector& nums, int start, int end) { int num_i = nums[start], num_i_1 = 0, num_i_2 = 0; From e91e5107ffa1b837d78a21b379e7b78a2c83e2ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:43:38 +0800 Subject: [PATCH 0264/1939] Update house-robber-ii.cpp --- C++/house-robber-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp index 7a11fb883..10d119522 100644 --- a/C++/house-robber-ii.cpp +++ b/C++/house-robber-ii.cpp @@ -12,7 +12,7 @@ class Solution { } return max(robRange(nums, 0, nums.size() - 1), // Include the first one of nums without the last one. - robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. + robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. } int robRange(vector& nums, int start, int end) { int num_i = nums[start], num_i_1 = 0, num_i_2 = 0; From 41ac3c00c6a69b78c1c4b64abfbd49a487f024d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:43:50 +0800 Subject: [PATCH 0265/1939] Update house-robber-ii.cpp --- C++/house-robber-ii.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp index 10d119522..6aa8f6039 100644 --- a/C++/house-robber-ii.cpp +++ b/C++/house-robber-ii.cpp @@ -14,6 +14,7 @@ class Solution { return max(robRange(nums, 0, nums.size() - 1), // Include the first one of nums without the last one. robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. } + int robRange(vector& nums, int start, int end) { int num_i = nums[start], num_i_1 = 0, num_i_2 = 0; for (int i = start + 1; i < end; ++i) { From c9be7622681509b9e602a90d07feb663117299cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 May 2015 11:44:00 +0800 Subject: [PATCH 0266/1939] Update house-robber-ii.cpp --- C++/house-robber-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp index 6aa8f6039..5050a55f2 100644 --- a/C++/house-robber-ii.cpp +++ b/C++/house-robber-ii.cpp @@ -12,7 +12,7 @@ class Solution { } return max(robRange(nums, 0, nums.size() - 1), // Include the first one of nums without the last one. - robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. + robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. } int robRange(vector& nums, int start, int end) { From 79cbd4b6a81f59739aecb35b8d03dd9049f73e76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:27:22 +0800 Subject: [PATCH 0267/1939] Create shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 53 +++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 C++/shortest-palindrome.cpp diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp new file mode 100644 index 000000000..3a547b834 --- /dev/null +++ b/C++/shortest-palindrome.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + string shortestPalindrome(string s) { + string T = preProcess(s); + int n = T.length(); + vector P(n); + int C = 0, R = 0; + for (int i = 1; i < n - 1; ++i) { + int i_mirror = 2*C-i; // equals to i' = C - (i-C) + + P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; + + // Attempt to expand palindrome centered at i + while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) { + ++P[i]; + } + + // If palindrome centered at i expand past R, + // adjust center based on expanded palindrome. + if (i + P[i] > R) { + C = i; + R = i + P[i]; + } + } + + // Find the max len of palindrome which starts with the first char of s. + int max_len = 0; + for (int i = 1; i < n - 1; ++i) { + if (i - P[i] == 1) { + max_len = P[i]; + } + } + + // Assume s is (Palindrome)abc + string ans = s.substr(max_len); // abc. + reverse(ans.begin(), ans.end()); // cba. + ans.append(s); // cba(Palindrome)abc. + return ans; + } + private: + string preProcess(string s) { + int n = s.length(); + if (n == 0) { + return "^$"; + } + string ret = "^"; + for (int i = 0; i < n; i++) + ret += "#" + s.substr(i, 1); + + ret += "#$"; + return ret; + } +}; From e53d687dbd40f80b0f397a24207ab080d50ea993 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:30:38 +0800 Subject: [PATCH 0268/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9605b65ba..64e57766a 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-20), there are `197` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-23), there are `199` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `213` problems. +Here is the classification of all `215` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -106,6 +106,7 @@ Shell 165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || +214| [Shortest Palindromic Substring](https://oj.leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` --- From 17353621a5e474f886872b7b0134c9238ace6520 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:46:10 +0800 Subject: [PATCH 0269/1939] Create kth-largest-element-in-an-array.cpp --- C++/kth-largest-element-in-an-array.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 C++/kth-largest-element-in-an-array.cpp diff --git a/C++/kth-largest-element-in-an-array.cpp b/C++/kth-largest-element-in-an-array.cpp new file mode 100644 index 000000000..caabd1846 --- /dev/null +++ b/C++/kth-largest-element-in-an-array.cpp @@ -0,0 +1,10 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + nth_element(nums.begin(), next(nums.begin(), k - 1), nums.end(), greater()); + return *next(nums.begin(), k - 1); + } +}; From f99a27c0722e187c0cdeffb8ba10263461476e47 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:50:11 +0800 Subject: [PATCH 0270/1939] Update kth-largest-element-in-an-array.cpp --- C++/kth-largest-element-in-an-array.cpp | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/C++/kth-largest-element-in-an-array.cpp b/C++/kth-largest-element-in-an-array.cpp index caabd1846..095b917e6 100644 --- a/C++/kth-largest-element-in-an-array.cpp +++ b/C++/kth-largest-element-in-an-array.cpp @@ -2,6 +2,43 @@ // Space: O(1) class Solution { +public: + int findKthLargest(vector& nums, int k) { + int left = 0, right = nums.size() - 1; + default_random_engine gen((random_device())()); + while (left <= right) { + // Generates a random int in [left, right]. + uniform_int_distribution dis(left, right); + int pivot_idx = dis(gen); + int new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, &nums); + if (new_pivot_idx == k - 1) { + return nums[new_pivot_idx]; + } else if (new_pivot_idx > k - 1) { + right = new_pivot_idx - 1; + } else { // new_pivot_idx < k - 1. + left = new_pivot_idx + 1; + } + } + } + + int PartitionAroundPivot(int left, int right, int pivot_idx, vector* nums) { + auto& nums_ref = *nums; + int pivot_value = nums_ref[pivot_idx]; + int new_pivot_idx = left; + swap(nums_ref[pivot_idx], nums_ref[right]); + for (int i = left; i < right; ++i) { + if (nums_ref[i] > pivot_value) { + swap(nums_ref[i], nums_ref[new_pivot_idx++]); + } + } + swap(nums_ref[right], nums_ref[new_pivot_idx]); + return new_pivot_idx; + } +}; + +// Time: O(n) +// Space: O(1) +class Solution2 { public: int findKthLargest(vector& nums, int k) { nth_element(nums.begin(), next(nums.begin(), k - 1), nums.end(), greater()); From 52a4756cba832da4b84b14ae8522710afe8d2072 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:52:37 +0800 Subject: [PATCH 0271/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 64e57766a..fedbb3550 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,7 @@ Shell 169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || +215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) | _O(n)_ | _O(1)_ | Medium | EPI| --- From b9ec186dd8419f01877db17b9e5d045de3f44e6f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 20:56:28 +0800 Subject: [PATCH 0272/1939] Update README.md --- README.md | 420 +++++++++++++++++++++++++++--------------------------- 1 file changed, 210 insertions(+), 210 deletions(-) diff --git a/README.md b/README.md index fedbb3550..db7d1b8a9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-05-23), there are `199` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://oj.leetcode.com/). +Up to date (2015-05-23), there are `199` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. Here is the classification of all `215` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. @@ -50,10 +50,10 @@ Shell ##Bit Manipulation # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -136 | [Single Number](https://oj.leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || -137 | [Single Number II](https://oj.leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || -190 | [Reverse Bits](https://oj.leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || -191 |[Number of 1 Bits](https://oj.leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || +136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || +137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || +190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || +191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || --- @@ -62,27 +62,27 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -15 | [3 Sum](https://oj.leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || -16 | [3 Sum Closest](https://oj.leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py)| _O(n^2)_ | _O(1)_ | Medium || -26 | [Remove Duplicates from Sorted Array](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || -27 | [Remove Element](https://oj.leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || -31 | [Next Permutation](https://oj.leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky -41 | [First Missing Positive](https://oj.leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky -48 | [Rotate Image](https://oj.leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || -54 | [Spiral Matrix](https://oj.leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || -59 | [Spiral Matrix II](https://oj.leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(m * n)_ | _O(1)_ | Medium || -66 | [Plus One](https://oj.leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || -73 | [Set Matrix Zeroes](https://oj.leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || -80 | [Remove Duplicates from Sorted Array II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || -118 | [Pascal's Triangle](https://oj.leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || -119 | [Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || -121 | [Best Time to Buy and Sell Stock](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || -128 | [Longest Consecutive Sequence](https://oj.leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky -157 | [Read N Characters Given Read4](https://oj.leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| -158 | [Read N Characters Given Read4 II - Call multiple times](https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| -163 | [Missing Ranges](https://oj.leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | -169 | [Majority Element](https://oj.leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | -189 | [Rotate Array](https://oj.leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || +15 | [3 Sum](https://leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || +16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py)| _O(n^2)_ | _O(1)_ | Medium || +26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || +31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky +41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky +48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || +54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || +59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(m * n)_ | _O(1)_ | Medium || +66 | [Plus One](https://leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || +73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || +80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || +118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || +119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || +121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || +128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky +157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| +158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| +163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | +189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) | _O(n)_ | _O(1)_ | Medium | EPI| @@ -91,227 +91,227 @@ Shell ##String # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -5| [Longest Palindromic Substring](https://oj.leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` -6| [ZigZag Conversion](https://oj.leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || -8| [String to Integer (atoi)](https://oj.leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || -14| [Longest Common Prefix](https://oj.leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || -28| [Implement strStr()](https://oj.leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` -38| [Count and Say](https://oj.leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || -43| [Multiply Strings](https://oj.leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || -58| [Length of Last Word](https://oj.leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || -67| [Add Binary](https://oj.leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || -68| [Text Justification](https://oj.leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || -125| [Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || -151| [Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || -161| [One Edit Distance](https://oj.leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| -165| [Compare Version Numbers](https://oj.leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || -186| [Reverse Words in a String II](https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | -205| [Isomorphic Strings](https://oj.leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || -214| [Shortest Palindromic Substring](https://oj.leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` +5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` +6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || +8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || +14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || +28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` +38| [Count and Say](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || +43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || +58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || +67| [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || +68| [Text Justification](https://leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || +125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || +151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || +161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| +165| [Compare Version Numbers](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || +186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || +214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` --- ##Linked List # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -2| [Add Two Numbers](https://oj.leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || -24| [Swap Nodes in Pairs](https://oj.leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || -25| [Reverse Nodes in k-Group](https://oj.leetcode.com/problems/reverse-nodes-in-k-group/)| [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || -61| [Rotate List](https://oj.leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || -82| [Remove Duplicates from Sorted List II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || -83| [Remove Duplicates from Sorted List](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || -92| [Reverse Linked List II](https://oj.leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || -138| [Copy List with Random Pointer](https://oj.leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || -160| [Intersection of Two Linked Lists](https://oj.leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || -203| [Remove Linked List Elements](https://oj.leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || -206| [Reverse Linked List](https://oj.leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || +2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || +24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || +25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || +61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || +82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || +92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || +160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || +203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || +206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || --- ##Stack # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -20| [Valid Parentheses](https://oj.leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || -32| [Longest Valid Parentheses](https://oj.leetcode.com/problems/longest-valid-parentheses/)| [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || -71| [Simplify Path](https://oj.leetcode.com/problems/simplify-path/)| [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || -101| [Symmetric Tree](https://oj.leetcode.com/problems/symmetric-tree/)| [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || -150| [Evaluate Reverse Polish Notation](https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/)| [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || -155| [Min Stack](https://oj.leetcode.com/problems/min-stack/) | [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || -173| [Binary Search Tree Iterator](https://oj.leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || +20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || +32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || +71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || +101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || +150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || +155| [Min Stack](https://leetcode.com/problems/min-stack/) | [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || +173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || --- ##Heap # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -23| [Merge k Sorted Lists](https://oj.leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || +23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || --- ##Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -94 | [Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | -99 | [Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` -144 | [Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` -145 | [Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | +99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` +145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://oj.leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS --- ##Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -1| [Two Sum](https://oj.leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || -3| [Longest Substring Without Repeating Characters](https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || -18| [4 Sum](https://oj.leetcode.com/problems/4sum/) |[Python](./Python/4sum.py) | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium || -30| [Substring with Concatenation of All Words](https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/) | [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || -36| [Valid Sudoku](https://oj.leetcode.com/problems/valid-sudoku/) | [Python](./Python/valid-sudoku.py) | _O(n^2)_ | _O(n)_ | Easy || -49| [Anagrams](https://oj.leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n)_ | _O(n)_ | Medium || -76| [Minimum Window Substring](https://oj.leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || -149| [Max Points on a Line](https://oj.leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || -159| [Longest Substring with At Most Two Distinct Characters](https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| -170| [Two Sum III - Data structure design](https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 📖 | -187| [Repeated DNA Sequences](https://oj.leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || -202| [Happy Number](https://oj.leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || -204| [Count Primes](https://oj.leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || +1| [Two Sum](https://leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || +3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || +18| [4 Sum](https://leetcode.com/problems/4sum/) |[Python](./Python/4sum.py) | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium || +30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || +36| [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [Python](./Python/valid-sudoku.py) | _O(n^2)_ | _O(n)_ | Easy || +49| [Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n)_ | _O(n)_ | Medium || +76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || +149| [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || +159| [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| +170| [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 📖 | +187| [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || +202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || +204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || --- ##Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -146| [LRU Cache](https://oj.leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || +146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || --- ##Math # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -7| [Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || -9| [Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || -12| [Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || -13| [Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || -29| [Divide Two Integers](https://oj.leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium || -60| [Permutation Sequence](https://oj.leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` -65| [Valid Number](https://oj.leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` -89| [Gray Code](https://oj.leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || -166| [Fraction to Recurring Decimal](https://oj.leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium || -168| [Excel Sheet Column Title](https://oj.leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || -171| [Excel Sheet Column Number](https://oj.leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || -172| [Factorial Trailing Zeroes](https://oj.leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || +7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || +9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || +12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || +13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || +29| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [Python](./Python/divide-two-integers.py) | _O(logn)_ | _O(1)_ | Medium || +60| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` +65| [Valid Number](https://leetcode.com/problems/valid-number/) | [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` +89| [Gray Code](https://leetcode.com/problems/gray-code/) | [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || +166| [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium || +168| [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || +171| [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || +172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || --- ##Sort # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -21| [Merge Two Sorted Lists](https://oj.leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || -56| [Merge Intervals](https://oj.leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || -57| [Insert Interval](https://oj.leetcode.com/problems/insert-interval/)| [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || -75| [Sort Colors](https://oj.leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || -88| [Merge Sorted Array](https://oj.leetcode.com/problems/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || -147| [Insertion Sort List](https://oj.leetcode.com/problems/insertion-sort-list/)|[Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || -148| [Sort List](https://oj.leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || -164| [Maximum Gap](https://oj.leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky -179| [Largest Number](https://oj.leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || +21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || +56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || +57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || +75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || +88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || +148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || +164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky +179| [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || --- ##Two Pointer # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -19| [Remove Nth Node From End of List](https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || -86| [Partition List](https://oj.leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || -141| [Linked List Cycle](https://oj.leetcode.com/problems/linked-list-cycle/)| [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || -142| [Linked List Cycle II](https://oj.leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || -143| [Reorder List](https://oj.leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || -167| [Two Sum II - Input array is sorted](https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || +86| [Partition List](https://leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || +141| [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)| [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || +142| [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || +143| [Reorder List](https://leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || +167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | --- ##Brute Force Search # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -17| [Letter Combinations of a Phone Number](https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || -46| [Permutations](https://oj.leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n!)_ | _O(n)_ | Medium || -47| [Permutations II](https://oj.leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n!)_ | _O(n)_ | Hard || -78| [Subsets](https://oj.leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || -90| [Subsets II](https://oj.leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || +46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n!)_ | _O(n)_ | Medium || +47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n!)_ | _O(n)_ | Hard || +78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || --- ##Divide and Conquer # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -95| [Unique Binary Search Trees II](https://oj.leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || -98| [Validate Binary Search Tree](https://oj.leetcode.com/problems/validate-binary-search-tree/)|[Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || -100| [Same Tree](https://oj.leetcode.com/problems/same-tree/) |[Python](./Python/same-tree.py) | _O(n)_ | _O(h)_ | Easy || -104| [Maximum Depth of Binary Tree](https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/)|[Python](./Python/maximum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || -105| [Construct Binary Tree from Preorder and Inorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [Python](./Python/construct-binary-tree-from-preorder-and-inorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || -106| [Construct Binary Tree from Inorder and Postorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [Python](./Python/construct-binary-tree-from-inorder-and-postorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || -108| [Convert Sorted Array to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [Python](./Python/convert-sorted-array-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || -109| [Convert Sorted List to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [Python](./Python/convert-sorted-list-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || -110| [Balanced Binary Tree](https://oj.leetcode.com/problems/balanced-binary-tree/) | [Python](./Python/balanced-binary-tree.py) | _O(n)_| _O(h)_ | Easy || -111| [Minimum Depth of Binary Tree](https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/)|[Python](./Python/minimum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || -114| [Flatten Binary Tree to Linked List](https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/)|[Python](./Python/flatten-binary-tree-to-linked-list.py)| _O(n)_ | _O(h)_ | Medium || -116| [Populating Next Right Pointers in Each Node](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/)|[Python](./Python/populating-next-right-pointers-in-each-node.py)| _O(n)_ | _O(1)_ | Medium || -124| [Binary Tree Maximum Path Sum](https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || -129| [Sum Root to Leaf Numbers](https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || -156| [Binary Tree Upside Down](https://oj.leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| +95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || +98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || +100| [Same Tree](https://leetcode.com/problems/same-tree/) |[Python](./Python/same-tree.py) | _O(n)_ | _O(h)_ | Easy || +104| [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)|[Python](./Python/maximum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || +105| [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [Python](./Python/construct-binary-tree-from-preorder-and-inorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || +106| [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [Python](./Python/construct-binary-tree-from-inorder-and-postorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || +108| [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [Python](./Python/convert-sorted-array-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || +109| [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [Python](./Python/convert-sorted-list-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || +110| [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [Python](./Python/balanced-binary-tree.py) | _O(n)_| _O(h)_ | Easy || +111| [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/)|[Python](./Python/minimum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || +114| [Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)|[Python](./Python/flatten-binary-tree-to-linked-list.py)| _O(n)_ | _O(h)_ | Medium || +116| [Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)|[Python](./Python/populating-next-right-pointers-in-each-node.py)| _O(n)_ | _O(1)_ | Medium || +124| [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || +129| [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || +156| [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| --- ##Binary Search # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -4| [Median of Two Sorted Arrays](https://oj.leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || -33| [Search in Rotated Sorted Array](https://oj.leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || -34| [Search for a Range](https://oj.leetcode.com/problems/search-for-a-range/) | [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || -35| [Search Insert Position](https://oj.leetcode.com/problems/search-insert-position/) | [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || -50| [Pow(x, n)](https://oj.leetcode.com/problems/powx-n/) | [Python](./Python/powx-n.py) | _O(logn)_ | _O(logn)_ | Medium || -69| [Sqrt(x)](https://oj.leetcode.com/problems/sqrtx/) | [Python](./Python/sqrtx.py) | _O(logn)_ | _O(1)_ | Medium || -74| [Search a 2D Matrix](https://oj.leetcode.com/problems/search-a-2d-matrix/) | [Python](./Python/search-a-2d-matrix.py) | _O(logm + logn)_ | _O(1)_ | Medium || -81| [Search in Rotated Sorted Array II](https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/) | [Python](./Python/search-in-rotated-sorted-array-ii.py) | _O(logn)_ | _O(1)_ | Medium || -153| [Find Minimum in Rotated Sorted Array](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || -154| [Find Minimum in Rotated Sorted Array II](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || -162| [Find Peak Element](https://oj.leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || +4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || +33| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || +34| [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || +35| [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || +50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [Python](./Python/powx-n.py) | _O(logn)_ | _O(logn)_ | Medium || +69| [Sqrt(x)](https://leetcode.com/problems/sqrtx/) | [Python](./Python/sqrtx.py) | _O(logn)_ | _O(1)_ | Medium || +74| [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | [Python](./Python/search-a-2d-matrix.py) | _O(logm + logn)_ | _O(1)_ | Medium || +81| [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) | [Python](./Python/search-in-rotated-sorted-array-ii.py) | _O(logn)_ | _O(1)_ | Medium || +153| [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || +154| [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || +162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || --- ##Breadth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -102| [Binary Tree Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || -107| [Binary Tree Level Order Traversal II](https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](./Python/binary-tree-level-order-traversal-ii.py) | _O(n)_| _O(n)_| Easy || -103| [Binary Tree Zigzag Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Python](./Python/binary-tree-zigzag-level-order-traversal.py) | _O(n)_| _O(n)_| Medium || -117| [Populating Next Right Pointers in Each Node II](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)|[Python](./Python/populating-next-right-pointers-in-each-node-ii.py)| _O(n)_ | _O(1)_ | Hard || -127| [Word Ladder](https://oj.leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || -130| [Surrounded Regions](https://oj.leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || -133| [Clone Graph](https://oj.leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || -207| [Course Schedule](https://oj.leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || -210| [Course Schedule II](https://oj.leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +102| [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || +107| [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](./Python/binary-tree-level-order-traversal-ii.py) | _O(n)_| _O(n)_| Easy || +103| [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Python](./Python/binary-tree-zigzag-level-order-traversal.py) | _O(n)_| _O(n)_| Medium || +117| [Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)|[Python](./Python/populating-next-right-pointers-in-each-node-ii.py)| _O(n)_ | _O(1)_ | Hard || +127| [Word Ladder](https://leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || +130| [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || +133| [Clone Graph](https://leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || +207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || --- ##Depth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -22| [Generate Parentheses](https://oj.leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || -37| [Sudoku Solver](https://oj.leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || -39| [Combination Sum](https://oj.leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(n^m)_ | _O(m)_ | Medium || -40| [Combination Sum II](https://oj.leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(n! / m!(n-m)!)_| _O(m)_ | Medium || -51| [N-Queens](https://oj.leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || -52| [N-Queens-II](https://oj.leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || -77| [Combinations](https://oj.leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || -79| [Word Search](https://oj.leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || -93| [Restore IP Addresses](https://oj.leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium || -112| [Path Sum](https://oj.leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || -113| [Path Sum II](https://oj.leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || -131| [Palindrome Partitioning](https://oj.leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || -199| [Binary Tree Right Side View](https://oj.leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || +22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || +37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || +39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(n^m)_ | _O(m)_ | Medium || +40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(n! / m!(n-m)!)_| _O(m)_ | Medium || +51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || +52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || +77| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || +79| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || +93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium || +112| [Path Sum](https://leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || +113| [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || +131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || +199| [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || --- @@ -319,76 +319,76 @@ Shell ##Dynamic Programming # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -10| [Regular Expression Matching](https://oj.leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || -53| [Maximum Subarray](https://oj.leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || -62| [Unique Paths](https://oj.leetcode.com/problems/unique-paths/) | [Python](./Python/unique-paths.py)| _O(m * n)_ | _O(m + n)_ | Medium || -63| [Unique Paths II](https://oj.leetcode.com/problems/unique-paths-ii/) | [Python](./Python/unique-paths-ii.py) | _O(m * n)_ | _O(m + n)_ | Medium || -64| [Minimum Path Sum](https://oj.leetcode.com/problems/minimum-path-sum/)|[Python](./Python/minimum-path-sum.py)| _O(m * n)_ | _O(m + n)_ | Medium || -70| [Climbing Stairs](https://oj.leetcode.com/problems/climbing-stairs/)| [Python](./Python/climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || -72| [Edit Distance](https://oj.leetcode.com/problems/edit-distance/)|[Python](./Python/edit-distance.py)| _O(m * n)_ | _O(m + n)_ | Hard || -85| [Maximal Rectangle](https://oj.leetcode.com/problems/maximal-rectangle/)|[Python](./Python/maximal-rectangle.py)| _O(n^2)_ | _O(n)_ | Hard || -87| [Scramble String](https://oj.leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || -91| [Decode Ways](https://oj.leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || -96| [Unique Binary Search Trees](https://oj.leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n^2)_ | _O(n)_ | Medium || -97| [Interleaving String](https://oj.leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || -115| [Distinct Subsequences](https://oj.leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || -120| [Triangle](https://oj.leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || -123| [Best Time to Buy and Sell Stock III](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || -132| [Palindrome Partitioning II](https://oj.leetcode.com/problems/palindrome-partitioning-ii/) | [Python](./Python/palindrome-partitioning-ii.py) | _O(n^2)_ | _O(n^2)_ | Hard || -139| [Word Break](https://oj.leetcode.com/problems/word-break/) | [Python](./Python/word-break.py) | _O(n^2)_ | _O(n)_ | Medium || -140| [Word Break II](https://oj.leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || -152| [Maximum Product Subarray](https://oj.leetcode.com/problems/maximum-product-subarray/)|[Python](./Python/maximum-product-subarray.py)| _O(n)_ | _O(1)_ | Medium || -174| [Dungeon Game](https://oj.leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || -188| [Best Time to Buy and Sell Stock IV](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || -198| [House Robber](https://oj.leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || -213| [House Robber II](https://oj.leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || +10| [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || +53| [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || +62| [Unique Paths](https://leetcode.com/problems/unique-paths/) | [Python](./Python/unique-paths.py)| _O(m * n)_ | _O(m + n)_ | Medium || +63| [Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) | [Python](./Python/unique-paths-ii.py) | _O(m * n)_ | _O(m + n)_ | Medium || +64| [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/)|[Python](./Python/minimum-path-sum.py)| _O(m * n)_ | _O(m + n)_ | Medium || +70| [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)| [Python](./Python/climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || +72| [Edit Distance](https://leetcode.com/problems/edit-distance/)|[Python](./Python/edit-distance.py)| _O(m * n)_ | _O(m + n)_ | Hard || +85| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)|[Python](./Python/maximal-rectangle.py)| _O(n^2)_ | _O(n)_ | Hard || +87| [Scramble String](https://leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || +91| [Decode Ways](https://leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || +96| [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n^2)_ | _O(n)_ | Medium || +97| [Interleaving String](https://leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || +115| [Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || +120| [Triangle](https://leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || +123| [Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || +132| [Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii/) | [Python](./Python/palindrome-partitioning-ii.py) | _O(n^2)_ | _O(n^2)_ | Hard || +139| [Word Break](https://leetcode.com/problems/word-break/) | [Python](./Python/word-break.py) | _O(n^2)_ | _O(n)_ | Medium || +140| [Word Break II](https://leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || +152| [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)|[Python](./Python/maximum-product-subarray.py)| _O(n)_ | _O(1)_ | Medium || +174| [Dungeon Game](https://leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || +188| [Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || +198| [House Robber](https://leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || +213| [House Robber II](https://leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || --- ##Backtracking # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -126| [Word Ladder II](https://oj.leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || +126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || --- ##Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -11| [Container With Most Water](https://oj.leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || -42| [Trapping Rain Water](https://oj.leetcode.com/problems/trapping-rain-water/) | [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky -44| [Wildcard Matching](https://oj.leetcode.com/problems/wildcard-matching/) | [Python](./Python/wildcard-matching.py) | _O(m + n)_ | _O(1)_ | Hard || Tricky -45| [Jump Game II](https://oj.leetcode.com/problems/jump-game-ii/) | [Python](./Python/jump-game-ii.py) | _O(n)_ | _O(1)_ | Hard || -55| [Jump Game](https://oj.leetcode.com/problems/jump-game/) | [Python](./Python/jump-game.py) | _O(n)_ | _O(1)_ | Medium || -84| [Largest Rectangle in Histogram](https://oj.leetcode.com/problems/largest-rectangle-in-histogram/) | [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Tricky -122| [Best Time to Buy and Sell Stock II](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Python](./Python/best-time-to-buy-and-sell-stock-ii.py) | _O(n)_ | _O(1)_ | Medium || -134| [Gas Station](https://oj.leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || -135| [Candy](https://oj.leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || +11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || +42| [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky +44| [Wildcard Matching](https://leetcode.com/problems/wildcard-matching/) | [Python](./Python/wildcard-matching.py) | _O(m + n)_ | _O(1)_ | Hard || Tricky +45| [Jump Game II](https://leetcode.com/problems/jump-game-ii/) | [Python](./Python/jump-game-ii.py) | _O(n)_ | _O(1)_ | Hard || +55| [Jump Game](https://leetcode.com/problems/jump-game/) | [Python](./Python/jump-game.py) | _O(n)_ | _O(1)_ | Medium || +84| [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Tricky +122| [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Python](./Python/best-time-to-buy-and-sell-stock-ii.py) | _O(n)_ | _O(1)_ | Medium || +134| [Gas Station](https://leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || +135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || --- ##SQL # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -175| [Combine Two Tables](https://oj.leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || -176| [Second Highest Salary](https://oj.leetcode.com/problems/second-highest-salary/) | [MySQL](./MySQL/second-highest-salary.sql) | _O(n)_ | _O(1)_ | Easy || -177| [Nth Highest Salary](https://oj.leetcode.com/problems/nth-highest-salary/) | [MySQL](./MySQL/nth-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || -178| [Rank Scores](https://oj.leetcode.com/problems/rank-scores/) | [MySQL](./MySQL/rank-scores.sql) | _O(n^2)_ | _O(n)_ | Medium || -180| [Consecutive Numbers](https://oj.leetcode.com/problems/consecutive-numbers/) | [MySQL](./MySQL/consecutive-numbers.sql) | _O(n)_ | _O(n)_ | Medium || -181| [Employees Earning More Than Their Managers](https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/) | [MySQL](./MySQL/employees-earning-more-than-their-managers.sql) | _O(n^2)_ | _O(1)_ | Easy || -182| [Duplicate Emails](https://oj.leetcode.com/problems/duplicate-emails/) | [MySQL](./MySQL/duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || -183| [Customers Who Never Order](https://oj.leetcode.com/problems/customers-who-never-order/) | [MySQL](./MySQL/customers-who-never-order.sql) | _O(n^2)_ | _O(1)_ | Easy || -184| [Department Highest Salary](https://oj.leetcode.com/problems/department-highest-salary/) | [MySQL](./MySQL/department-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || -185| [Department Top Three Salaries](https://oj.leetcode.com/problems/department-top-three-salaries/) | [MySQL](./MySQL/department-top-three-salaries.sql) | _O(n^2)_ | _O(n)_ | Hard || -196| [Delete Duplicate Emails](https://oj.leetcode.com/problems/delete-duplicate-emails/) | [MySQL](./MySQL/delete-duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || -197| [Rising Temperature](https://oj.leetcode.com/problems/rising-temperature/) | [MySQL](./MySQL/rising-temperature.sql) | _O(n^2)_ | _O(n)_ | Easy || +175| [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || +176| [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/) | [MySQL](./MySQL/second-highest-salary.sql) | _O(n)_ | _O(1)_ | Easy || +177| [Nth Highest Salary](https://leetcode.com/problems/nth-highest-salary/) | [MySQL](./MySQL/nth-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || +178| [Rank Scores](https://leetcode.com/problems/rank-scores/) | [MySQL](./MySQL/rank-scores.sql) | _O(n^2)_ | _O(n)_ | Medium || +180| [Consecutive Numbers](https://leetcode.com/problems/consecutive-numbers/) | [MySQL](./MySQL/consecutive-numbers.sql) | _O(n)_ | _O(n)_ | Medium || +181| [Employees Earning More Than Their Managers](https://leetcode.com/problems/employees-earning-more-than-their-managers/) | [MySQL](./MySQL/employees-earning-more-than-their-managers.sql) | _O(n^2)_ | _O(1)_ | Easy || +182| [Duplicate Emails](https://leetcode.com/problems/duplicate-emails/) | [MySQL](./MySQL/duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || +183| [Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order/) | [MySQL](./MySQL/customers-who-never-order.sql) | _O(n^2)_ | _O(1)_ | Easy || +184| [Department Highest Salary](https://leetcode.com/problems/department-highest-salary/) | [MySQL](./MySQL/department-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || +185| [Department Top Three Salaries](https://leetcode.com/problems/department-top-three-salaries/) | [MySQL](./MySQL/department-top-three-salaries.sql) | _O(n^2)_ | _O(n)_ | Hard || +196| [Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/) | [MySQL](./MySQL/delete-duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || +197| [Rising Temperature](https://leetcode.com/problems/rising-temperature/) | [MySQL](./MySQL/rising-temperature.sql) | _O(n^2)_ | _O(n)_ | Easy || --- ##Shell Script # | Problem | Solution | Time | Space | Difficulty | Tag | Notes -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -192 | [Word Frequency](https://oj.leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || -193 | [Valid Phone Numbers](https://oj.leetcode.com/problems/valid-phone-numbers/) | [Shell](./Shell/valid-phone-numbers.sh) | _O(n)_ | _O(1)_ | Easy || -194 | [Transpose File](https://oj.leetcode.com/problems/transpose-file/) | [Shell](./Shell/transpose-file.sh) | _O(n^2)_ | _O(n^2)_ | Medium || -195 | [Tenth Line](https://oj.leetcode.com/problems/tenth-line/) | [Shell](./Shell/tenth-line.sh) | _O(n)_ | _O(1)_ | Easy || +192 | [Word Frequency](https://leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || +193 | [Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/) | [Shell](./Shell/valid-phone-numbers.sh) | _O(n)_ | _O(1)_ | Easy || +194 | [Transpose File](https://leetcode.com/problems/transpose-file/) | [Shell](./Shell/transpose-file.sh) | _O(n^2)_ | _O(n^2)_ | Medium || +195 | [Tenth Line](https://leetcode.com/problems/tenth-line/) | [Shell](./Shell/tenth-line.sh) | _O(n)_ | _O(1)_ | Easy || From e72a567686c0f8fc98c22d947838cdc146cf0605 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:06:06 +0800 Subject: [PATCH 0273/1939] Create shortest-palindrome.py --- Python/shortest-palindrome.py | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/shortest-palindrome.py diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py new file mode 100644 index 000000000..28491b939 --- /dev/null +++ b/Python/shortest-palindrome.py @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(n) + +# TLE +class Solution: + # @param {string} s + # @return {string} + def shortestPalindrome(self, s): + string = self.preProcess(s) + palindrome = [0] * len(string) + center, right = 0, 0 + for i in xrange(1, len(string) - 1): + i_mirror = 2 * center - i + if right > i: + palindrome[i] = min(right - i, palindrome[i_mirror]) + else: + palindrome[i] = 0 + + while string[i + 1 + palindrome[i]] == string[i - 1 - palindrome[i]]: + palindrome[i] += 1 + + if i + palindrome[i] > right: + center, right = i, i + palindrome[i] + + max_len, max_center = 0, 0 + for i in xrange(1, len(string) - 1): + if i - palindrome[i] == 1: + max_len = palindrome[i] + return s[len(s)-1:max_len-1:-1] + s + + def preProcess(self, s): + + if not s: + return "^$" + string = "^" + for i in s: + string += "#" + i + string += "#$" + return string + From 08b0157d40897f83b3d179a435e12e0dbc914198 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:06:41 +0800 Subject: [PATCH 0274/1939] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index 28491b939..75fb99fb1 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -22,7 +22,7 @@ def shortestPalindrome(self, s): if i + palindrome[i] > right: center, right = i, i + palindrome[i] - max_len, max_center = 0, 0 + max_len = 0 for i in xrange(1, len(string) - 1): if i - palindrome[i] == 1: max_len = palindrome[i] From d60898ee1e981d6dfd95ee87f021e40c501d9bd7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:07:24 +0800 Subject: [PATCH 0275/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db7d1b8a9..16c3331f2 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ Shell 165| [Compare Version Numbers](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || -214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` +214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` --- From 5aace18703e4b18d7b2cd013ee2191fe20ac7600 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:08:16 +0800 Subject: [PATCH 0276/1939] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index 3a547b834..00684fe84 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -1,3 +1,6 @@ +// Time: O(n) +// Space: O(n) + class Solution { public: string shortestPalindrome(string s) { From 58424d395251708a67536b2afd3cb72fc9da1796 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:22:41 +0800 Subject: [PATCH 0277/1939] Create kth-largest-element-in-an-array.py --- Python/kth-largest-element-in-an-array.py | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/kth-largest-element-in-an-array.py diff --git a/Python/kth-largest-element-in-an-array.py b/Python/kth-largest-element-in-an-array.py new file mode 100644 index 000000000..fe0dfa31b --- /dev/null +++ b/Python/kth-largest-element-in-an-array.py @@ -0,0 +1,34 @@ +# Time: O(n) +# Space: O(1) + +from random import randint + +class Solution: + # @param {integer[]} nums + # @param {integer} k + # @return {integer} + def findKthLargest(self, nums, k): + left, right = 0, len(nums) - 1 + while left <= right: + pivot_idx = randint(left, right) + new_pivot_idx = self.PartitionAroundPivot(left, right, pivot_idx, nums) + if new_pivot_idx == k - 1: + return nums[new_pivot_idx] + elif new_pivot_idx > k - 1: + right = new_pivot_idx - 1 + else: # new_pivot_idx < k - 1. + left = new_pivot_idx + 1 + + + def PartitionAroundPivot(self, left, right, pivot_idx, nums): + pivot_value = nums[pivot_idx] + new_pivot_idx = left + nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx] + for i in xrange(left, right): + if nums[i] > pivot_value: + nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] + new_pivot_idx += 1 + + nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right] + return new_pivot_idx + From 0c7ff94f7fa62d2d4ffa67db3ace90f57e9dadb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:23:32 +0800 Subject: [PATCH 0278/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 16c3331f2..6fea7f234 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ Shell 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || -215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) | _O(n)_ | _O(1)_ | Medium | EPI| +215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| --- From 6b4018d4ca5bd5e1aa47ecf2a7758cdf95238f16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 May 2015 21:25:02 +0800 Subject: [PATCH 0279/1939] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index 75fb99fb1..70c4c7d7f 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -29,7 +29,6 @@ def shortestPalindrome(self, s): return s[len(s)-1:max_len-1:-1] + s def preProcess(self, s): - if not s: return "^$" string = "^" From 10ccae1449474ee4e8b0ca6b57885543643f49ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:01:54 +0800 Subject: [PATCH 0280/1939] Update implement-strstr.py --- Python/implement-strstr.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index 9b7149b10..b57b11261 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -40,7 +40,7 @@ def KMP(self, text, pattern): def getPrefix(self, pattern): prefix = [-1] * len(pattern) - j = - 1 + j = -1 for i in xrange(1, len(pattern)): while j > -1 and pattern[j + 1] != pattern[i]: j = prefix[j] From 326e69c0af6612afba35df6b76757dcee8b7fb2e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:09:15 +0800 Subject: [PATCH 0281/1939] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index 70c4c7d7f..471222f69 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -1,8 +1,32 @@ # Time: O(n) # Space: O(n) -# TLE +# KMP algorithm class Solution: + # @param {string} s + # @return {string} + def shortestPalindrome(self, s): + if not s: + return s + + A = s + s[::-1] + prefix = self.getPrefix(A) + + return s[prefix[-1]+1:][::-1] + s + + def getPrefix(self, pattern): + prefix = [-1] * len(pattern) + j = -1 + for i in xrange(1, len(pattern)): + while j > -1 and pattern[j+1] != pattern[i]: + j = prefix[j] + if pattern[j+1] == pattern[i]: + j += 1 + prefix[i] = j + return prefix + +# Manacher's Algorithm +class Solution_TLE: # @param {string} s # @return {string} def shortestPalindrome(self, s): From 13d8656bbc02ce78c8bc4ab669e8ed98aa04d7ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:09:32 +0800 Subject: [PATCH 0282/1939] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index 471222f69..f43dada73 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(n) -# KMP algorithm +# KMP Algorithm class Solution: # @param {string} s # @return {string} From 74b0dbe0733abc493bed3617663f87e386971f4b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:10:14 +0800 Subject: [PATCH 0283/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6fea7f234..79c0dc06d 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ Shell 165| [Compare Version Numbers](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || -214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `Manacher's Algorithm` +214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` --- From 0304d526a42b205b8a7c5f62acf3713c4361c7b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 09:18:32 +0800 Subject: [PATCH 0284/1939] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 59 +++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index 00684fe84..083c21e11 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -1,7 +1,42 @@ // Time: O(n) // Space: O(n) +// KMP Algorithm class Solution { +public: + string shortestPalindrome(string s) { + if (s.empty()) { + return s; + } + string rev_s(s.crbegin(), s.crend()); + string A = s + rev_s; + vector pattern(move(getPrefix(A))); + string non_palindrome = s.substr(pattern.back() + 1); + reverse(non_palindrome.begin(), non_palindrome.end()); + return non_palindrome + s; + } + +private: + vector getPrefix(const string& pattern) { + vector prefix(pattern.length(), -1); + int j = -1; + for (int i = 1; i < pattern.length(); ++i) { + while (j > -1 && pattern[j + 1] != pattern[i]) { + j = prefix[j]; + } + if (pattern[j + 1] == pattern[i]) { + ++j; + } + prefix[i] = j; + } + return prefix; + } +}; + +// Time: O(n) +// Space: O(n) +// Manacher's Algorithm +class Solution2 { public: string shortestPalindrome(string s) { string T = preProcess(s); @@ -40,17 +75,17 @@ class Solution { ans.append(s); // cba(Palindrome)abc. return ans; } - private: - string preProcess(string s) { - int n = s.length(); - if (n == 0) { - return "^$"; - } - string ret = "^"; - for (int i = 0; i < n; i++) - ret += "#" + s.substr(i, 1); - - ret += "#$"; - return ret; +private: + string preProcess(string s) { + int n = s.length(); + if (n == 0) { + return "^$"; + } + string ret = "^"; + for (int i = 0; i < n; ++i) { + ret += "#" + s.substr(i, 1); } + ret += "#$"; + return ret; + } }; From deb96a8dc2d41f1525cac1eef5e9cb193c65240c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 May 2015 21:24:07 +0800 Subject: [PATCH 0285/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 79c0dc06d..82147d190 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-23), there are `199` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-05-24), there are `200` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `215` problems. +Here is the classification of all `216` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) From 0611e5be63cb4bf73e57140d331c0f913910b919 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 May 2015 18:04:26 +0800 Subject: [PATCH 0286/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 82147d190..3f017a68c 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-24), there are `200` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-05-25), there are `201` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `216` problems. +Here is the classification of all `217` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) From ae7e18a5f735f174d41dbaa707bfd0576b5e8a15 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:15:56 +0800 Subject: [PATCH 0287/1939] Create combination-sum-iii.cpp --- C++/combination-sum-iii.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/combination-sum-iii.cpp diff --git a/C++/combination-sum-iii.cpp b/C++/combination-sum-iii.cpp new file mode 100644 index 000000000..ff297a253 --- /dev/null +++ b/C++/combination-sum-iii.cpp @@ -0,0 +1,27 @@ +// Time: O(C(n, k)) +// Space: O(k) + +class Solution { +public: + vector > combinationSum3(int k, int n) { + vector> res; + vector combination; + combinationSum3(res, combination, 1, k, n); + return res; + } +private: + void combinationSum3(vector > &res, vector &combination, int start, int k, int n) { + if (!k && !n) { + res.push_back(combination); + return; + } else if (k < 0) { + return; + } + + for (int i = start; i < 10 && n >= k * i + k * (k - 1) / 2; ++i) { + combination.push_back(i); + combinationSum3(res, combination, i + 1, k - 1, n - i); + combination.pop_back(); + } + } +}; From 6d1a7a396ef00ade8485777e3ba9aa1f86e10376 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:24:54 +0800 Subject: [PATCH 0288/1939] Create combination-sum-iii.py --- Python/combination-sum-iii.py | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/combination-sum-iii.py diff --git a/Python/combination-sum-iii.py b/Python/combination-sum-iii.py new file mode 100644 index 000000000..eb2ce4407 --- /dev/null +++ b/Python/combination-sum-iii.py @@ -0,0 +1,45 @@ +# Time: O(C(n, k)) +# Space: O(k) +# +# Find all possible combinations of k numbers that add up to a number n, +# given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. +# +# Ensure that numbers within the set are sorted in ascending order. +# +# +# Example 1: +# +# Input: k = 3, n = 7 +# +# Output: +# +# [[1,2,4]] +# +# Example 2: +# +# Input: k = 3, n = 9 +# +# Output: +# +# [[1,2,6], [1,3,5], [2,3,4]] +# + +class Solution: + # @param {integer} k + # @param {integer} n + # @return {integer[][]} + def combinationSum3(self, k, n): + result = [] + self.combinationSumRecu(result, [], 1, k, n) + return result + + def combinationSumRecu(self, result, intermediate, start, k, target): + if k == 0 and target == 0: + result.append(list(intermediate)) + elif k < 0: + return + while start < 10 and start * k + k * (k - 1) / 2 <= target: + intermediate.append(start) + self.combinationSumRecu(result, intermediate, start + 1, k - 1, target - start) + intermediate.pop() + start += 1 From 48615995d7022a5bb83084fe44e85736551c9382 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:28:32 +0800 Subject: [PATCH 0289/1939] Create contains-duplicate.py --- Python/contains-duplicate.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Python/contains-duplicate.py diff --git a/Python/contains-duplicate.py b/Python/contains-duplicate.py new file mode 100644 index 000000000..16c26a3c3 --- /dev/null +++ b/Python/contains-duplicate.py @@ -0,0 +1,13 @@ +# Time: O(n) +# Space: O(n) +# +# Given an array of integers, find if the array contains any duplicates. +# Your function should return true if any value appears at least twice in the array, +# and it should return false if every element is distinct. +# + +class Solution: + # @param {integer[]} nums + # @return {boolean} + def containsDuplicate(self, nums): + return len(nums) > len(set(nums)) From 1c2bfe859e1505202de5bcece088154c5bd5c1a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:31:01 +0800 Subject: [PATCH 0290/1939] Create contains-duplicate.cpp --- C++/contains-duplicate.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 C++/contains-duplicate.cpp diff --git a/C++/contains-duplicate.cpp b/C++/contains-duplicate.cpp new file mode 100644 index 000000000..5d3abe2a7 --- /dev/null +++ b/C++/contains-duplicate.cpp @@ -0,0 +1,10 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set nums_set(nums.begin(), nums.end()); + return nums_set.size() != nums.size(); + } +}; From 618769d421f87bbeea4e121c917732d7655fd6ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:32:36 +0800 Subject: [PATCH 0291/1939] Update contains-duplicate.cpp --- C++/contains-duplicate.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/C++/contains-duplicate.cpp b/C++/contains-duplicate.cpp index 5d3abe2a7..524f4067c 100644 --- a/C++/contains-duplicate.cpp +++ b/C++/contains-duplicate.cpp @@ -8,3 +8,13 @@ class Solution { return nums_set.size() != nums.size(); } }; + +// Time: O(nlogn) +// Space: O(1) +class Solution2 { +public: + bool containsDuplicate(vector& nums) { + sort(nums.begin(), nums.end()); + return unique(nums.begin(), nums.end()) != nums.end(); + } +}; From 5ebacaa9152398d95af6c36486047336955904b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:36:30 +0800 Subject: [PATCH 0292/1939] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3f017a68c..9c027339d 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,7 @@ Shell 187| [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || 202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || +217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || --- @@ -313,6 +314,7 @@ Shell 131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || 199| [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || +216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(C(n, k))_ | _O(k)_ | Medium || --- From e779ec633c0a6fe8f05da7ee881024fd1d4289b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 02:42:48 +0800 Subject: [PATCH 0293/1939] Update kth-largest-element-in-an-array.py --- Python/kth-largest-element-in-an-array.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/kth-largest-element-in-an-array.py b/Python/kth-largest-element-in-an-array.py index fe0dfa31b..fe6b8d9c0 100644 --- a/Python/kth-largest-element-in-an-array.py +++ b/Python/kth-largest-element-in-an-array.py @@ -19,7 +19,6 @@ def findKthLargest(self, nums, k): else: # new_pivot_idx < k - 1. left = new_pivot_idx + 1 - def PartitionAroundPivot(self, left, right, pivot_idx, nums): pivot_value = nums[pivot_idx] new_pivot_idx = left From 5f1fe01496c32768edc681a077586dc7eea9de91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 14:22:55 +0800 Subject: [PATCH 0294/1939] Create the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 C++/the-skyline-problem.cpp diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp new file mode 100644 index 000000000..83c09ae44 --- /dev/null +++ b/C++/the-skyline-problem.cpp @@ -0,0 +1,47 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + vector > getSkyline(vector >& buildings) { + map > start_point_to_heights; + map > end_point_to_heights; + set points; + + for (int i = 0; i < buildings.size(); ++i) { + start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); + end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); + points.insert(buildings[i][0]); + points.insert(buildings[i][1]); + } + + vector > res; + map height_to_count; + int curr_max = 0; + // Enumerate each point in increasing order. + for (auto it = points.begin(); it != points.end(); ++it) { + vector start_point_heights = start_point_to_heights[*it]; + vector end_point_heights = end_point_to_heights[*it]; + + for (int i = 0; i < start_point_heights.size(); ++i) { + ++height_to_count[start_point_heights[i]]; + } + + for (int i = 0; i < end_point_heights.size(); ++i) { + --height_to_count[end_point_heights[i]]; + if (height_to_count[end_point_heights[i]] == 0) { + height_to_count.erase(end_point_heights[i]); + } + } + + if (height_to_count.size() == 0) { + curr_max = 0; + res.emplace_back(move(make_pair(*it, curr_max))); + } else if (curr_max != height_to_count.rbegin()->first) { + curr_max = height_to_count.rbegin()->first; + res.emplace_back(move(make_pair(*it, curr_max))); + } + } + return res; + } +}; From 54c34fbaf800e3888cfc3d746519537df421a5e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 14:33:25 +0800 Subject: [PATCH 0295/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9c027339d..bb7198065 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-25), there are `201` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-05-26), there are `202` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `217` problems. +Here is the classification of all `218` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -218,6 +218,7 @@ Shell 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky 179| [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || +218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) | _O(nlogn)_ | _O(n)_ | Hard || --- From 5966727834be79570e9ac1ad505a7fe12f942369 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 14:36:32 +0800 Subject: [PATCH 0296/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 83c09ae44..33a651712 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -4,8 +4,8 @@ class Solution { public: vector > getSkyline(vector >& buildings) { - map > start_point_to_heights; - map > end_point_to_heights; + map> start_point_to_heights; + map> end_point_to_heights; set points; for (int i = 0; i < buildings.size(); ++i) { @@ -15,7 +15,7 @@ class Solution { points.insert(buildings[i][1]); } - vector > res; + vector> res; map height_to_count; int curr_max = 0; // Enumerate each point in increasing order. From 9db921aeaa82ab057b813a50731cbd117eae8949 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 14:36:46 +0800 Subject: [PATCH 0297/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 33a651712..d84014f76 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -34,7 +34,7 @@ class Solution { } } - if (height_to_count.size() == 0) { + if (height_to_count.empty()) { curr_max = 0; res.emplace_back(move(make_pair(*it, curr_max))); } else if (curr_max != height_to_count.rbegin()->first) { From 65456320e4feb8e6b5b6ae3e252ae8ff88f19bc3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 17:38:10 +0800 Subject: [PATCH 0298/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index d84014f76..d82b7e74f 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -4,15 +4,15 @@ class Solution { public: vector > getSkyline(vector >& buildings) { - map> start_point_to_heights; - map> end_point_to_heights; + unordered_map> start_point_to_heights; + unordered_map> end_point_to_heights; set points; for (int i = 0; i < buildings.size(); ++i) { start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); - points.insert(buildings[i][0]); - points.insert(buildings[i][1]); + points.emplace(buildings[i][0]); + points.emplace(buildings[i][1]); } vector> res; From 71f11de1f3b026c1c116194be03c0882321dedb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 18:28:02 +0800 Subject: [PATCH 0299/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index d82b7e74f..247f48380 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -36,10 +36,10 @@ class Solution { if (height_to_count.empty()) { curr_max = 0; - res.emplace_back(move(make_pair(*it, curr_max))); + res.emplace_back(*it, curr_max); } else if (curr_max != height_to_count.rbegin()->first) { curr_max = height_to_count.rbegin()->first; - res.emplace_back(move(make_pair(*it, curr_max))); + res.emplace_back(*it, curr_max); } } return res; From afaa3e8733c4fd88060d2e3b26cb46060fd369d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 19:54:27 +0800 Subject: [PATCH 0300/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 247f48380..8fccc03dc 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -34,11 +34,8 @@ class Solution { } } - if (height_to_count.empty()) { - curr_max = 0; - res.emplace_back(*it, curr_max); - } else if (curr_max != height_to_count.rbegin()->first) { - curr_max = height_to_count.rbegin()->first; + if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { + curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; res.emplace_back(*it, curr_max); } } From b591a8b995b60fb56f9374c4b73e5f38c16d8f7b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:39:25 +0800 Subject: [PATCH 0301/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 99 +++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 8fccc03dc..21b9bdbc8 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -1,7 +1,106 @@ // Time: O(nlogn) // Space: O(n) +// Divide and Conquer. class Solution { +public: + enum {start, end, height}; + + vector> getSkyline(vector>& buildings) { + const auto intervals = move(ComputeSkylineInInterval(buildings, 0, buildings.size())); + + vector> res; + int last_end = -1; + for (const auto& interval : intervals) { + if (last_end != -1 && last_end < interval[start]) { + res.emplace_back(last_end, 0); + } + res.emplace_back(interval[start], interval[height]); + last_end = interval[end]; + } + if (last_end != -1) { + res.emplace_back(last_end, 0); + } + return res; + } + + // Divide and Conquer. + vector> ComputeSkylineInInterval(const vector>& buildings, + int left_endpoint, int right_endpoint) { + if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it. + return {buildings.cbegin() + left_endpoint, + buildings.cbegin() + right_endpoint}; + } + int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2); + auto left_skyline = move(ComputeSkylineInInterval(buildings, left_endpoint, mid)); + auto right_skyline = move(ComputeSkylineInInterval(buildings, mid, right_endpoint)); + return MergeSkylines(left_skyline, right_skyline); + } + + // Merge Sort + vector> MergeSkylines(vector>& left_skyline, vector>& right_skyline) { + int i = 0, j = 0; + vector> merged; + + while (i < left_skyline.size() && j < right_skyline.size()) { + if (left_skyline[i][end] < right_skyline[j][start]) { + merged.emplace_back(move(left_skyline[i++])); + } else if (right_skyline[j][end] < left_skyline[i][start]) { + merged.emplace_back(move(right_skyline[j++])); + } else if (left_skyline[i][start] <= right_skyline[j][start]) { + MergeIntersectSkylines(merged, left_skyline[i], i, + right_skyline[j], j); + } else { // left_skyline[i][start] > right_skyline[j][start]. + MergeIntersectSkylines(merged, right_skyline[j], j, + left_skyline[i], i); + } + } + + // Insert the remaining skylines. + merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end()); + merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end()); + return merged; + } + + // a[start] <= b[start] + void MergeIntersectSkylines(vector>& merged, vector& a, int& a_idx, + vector& b, int& b_idx) { + if (a[end] <= b[end]) { + if (a[height] > b[height]) { // |aaa| + if (b[end] != a[end]) { // |abb|b + b[start] = a[end]; + merged.emplace_back(move(a)), ++a_idx; + } else { // aaa + ++b_idx; // abb + } + } else if (a[height] == b[height]) { // abb + b[start] = a[start], ++a_idx; // abb + } else { // a[height] < b[height]. + if (a[start] != b[start]) { // bb + merged.emplace_back(move(vector{a[start], b[start], a[height]})); // |a|bb + } + ++a_idx; + } + } else { // a[end] > b[end]. + if (a[height] >= b[height]) { // aaaa + ++b_idx; // abba + } else { + // |bb| + // |a||bb|a + if (a[start] != b[start]) { + merged.emplace_back(move(vector{a[start], b[start], a[height]})); + } + a[start] = b[end]; + merged.emplace_back(move(b)), ++b_idx; + } + } + } +}; + +// Time: O(nlogn) +// Space: O(n) +// BST Solution. +class Solution2 { public: vector > getSkyline(vector >& buildings) { unordered_map> start_point_to_heights; From c8e1270eba611f8fb94888814584dd288235c70f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:40:58 +0800 Subject: [PATCH 0302/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 92 ++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 21b9bdbc8..b831a4f0f 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -1,7 +1,52 @@ // Time: O(nlogn) // Space: O(n) -// Divide and Conquer. +// BST solution. +class Solution { +public: + vector > getSkyline(vector >& buildings) { + unordered_map> start_point_to_heights; + unordered_map> end_point_to_heights; + set points; + + for (int i = 0; i < buildings.size(); ++i) { + start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); + end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); + points.emplace(buildings[i][0]); + points.emplace(buildings[i][1]); + } + + vector> res; + map height_to_count; + int curr_max = 0; + // Enumerate each point in increasing order. + for (auto it = points.begin(); it != points.end(); ++it) { + vector start_point_heights = start_point_to_heights[*it]; + vector end_point_heights = end_point_to_heights[*it]; + + for (int i = 0; i < start_point_heights.size(); ++i) { + ++height_to_count[start_point_heights[i]]; + } + + for (int i = 0; i < end_point_heights.size(); ++i) { + --height_to_count[end_point_heights[i]]; + if (height_to_count[end_point_heights[i]] == 0) { + height_to_count.erase(end_point_heights[i]); + } + } + + if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { + curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; + res.emplace_back(*it, curr_max); + } + } + return res; + } +}; + +// Time: O(nlogn) +// Space: O(n) +// Divide and conquer solution. class Solution { public: enum {start, end, height}; @@ -96,48 +141,3 @@ class Solution { } } }; - -// Time: O(nlogn) -// Space: O(n) -// BST Solution. -class Solution2 { -public: - vector > getSkyline(vector >& buildings) { - unordered_map> start_point_to_heights; - unordered_map> end_point_to_heights; - set points; - - for (int i = 0; i < buildings.size(); ++i) { - start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); - end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); - points.emplace(buildings[i][0]); - points.emplace(buildings[i][1]); - } - - vector> res; - map height_to_count; - int curr_max = 0; - // Enumerate each point in increasing order. - for (auto it = points.begin(); it != points.end(); ++it) { - vector start_point_heights = start_point_to_heights[*it]; - vector end_point_heights = end_point_to_heights[*it]; - - for (int i = 0; i < start_point_heights.size(); ++i) { - ++height_to_count[start_point_heights[i]]; - } - - for (int i = 0; i < end_point_heights.size(); ++i) { - --height_to_count[end_point_heights[i]]; - if (height_to_count[end_point_heights[i]] == 0) { - height_to_count.erase(end_point_heights[i]); - } - } - - if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { - curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; - res.emplace_back(*it, curr_max); - } - } - return res; - } -}; From f7b940942c9536aff3f4bf9d48b44460496244c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:41:17 +0800 Subject: [PATCH 0303/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index b831a4f0f..1b02c5b6a 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -47,7 +47,7 @@ class Solution { // Time: O(nlogn) // Space: O(n) // Divide and conquer solution. -class Solution { +class Solution2 { public: enum {start, end, height}; From 75853d17c5ca6c6eb0c8be2075b0cd812a2f9eab Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:44:17 +0800 Subject: [PATCH 0304/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 1b02c5b6a..d5ca6952b 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -10,8 +10,8 @@ class Solution { set points; for (int i = 0; i < buildings.size(); ++i) { - start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); - end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); + start_point_to_heights[buildings[i][0]].emplace_back(buildings[i][2]); + end_point_to_heights[buildings[i][1]].emplace_back(buildings[i][2]); points.emplace(buildings[i][0]); points.emplace(buildings[i][1]); } From b9699108393c4d7ed734f719ca425a2789831758 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 20:44:54 +0800 Subject: [PATCH 0305/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index d5ca6952b..bf59a6e2d 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -121,7 +121,7 @@ class Solution2 { } else if (a[height] == b[height]) { // abb b[start] = a[start], ++a_idx; // abb } else { // a[height] < b[height]. - if (a[start] != b[start]) { // bb + if (a[start] != b[start]) { // bb merged.emplace_back(move(vector{a[start], b[start], a[height]})); // |a|bb } ++a_idx; From 9cc2e468bf5a81f436df417edb20a945759d21d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:19:24 +0800 Subject: [PATCH 0306/1939] Create the-skyline-problem.py --- Python/the-skyline-problem.py | 114 ++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 Python/the-skyline-problem.py diff --git a/Python/the-skyline-problem.py b/Python/the-skyline-problem.py new file mode 100644 index 000000000..118fa8478 --- /dev/null +++ b/Python/the-skyline-problem.py @@ -0,0 +1,114 @@ +# Time: O(nlogn) +# Space: O(n) +# A city's skyline is the outer contour of the silhouette formed +# by all the buildings in that city when viewed from a distance. +# Now suppose you are given the locations and height of all the +# buildings as shown on a cityscape photo (Figure A), write a +# program to output the skyline formed by these buildings +# collectively (Figure B). +# +# The geometric information of each building is represented by a +# triplet of integers [Li, Ri, Hi], where Li and Ri are the x +# coordinates of the left and right edge of the ith building, +# respectively, and Hi is its height. It is guaranteed that 0 <= Li, +# Ri <= INT_MAX, 0 < Hi <= INT_MAX, and Ri - Li > 0. You may assume +# all buildings are perfect rectangles grounded on an absolutely +# flat surface at height 0. +# +# Notes: +# +# The number of buildings in any input list is guaranteed to be +# in the range [0, 10000]. +# The input list is already sorted in ascending order by the +# left x position Li. +# The output list must be sorted by the x position. +# There must be no consecutive horizontal lines of equal height +# in the output skyline. +# For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is +# not acceptable; +# the three lines of height 5 should be merged into one +# in the final output as such: [...[2 3], [4 5], [12 7], ...] +# + +# Divide and conquer solution. +start, end, height = 0, 1, 2 +class Solution: + # @param {integer[][]} buildings + # @return {integer[][]} + def getSkyline(self, buildings): + intervals = self.ComputeSkylineInInterval(buildings, 0, len(buildings)) + + res = [] + last_end = -1 + for interval in intervals: + if last_end != -1 and last_end < interval[start]: + res.append([last_end, 0]) + res.append([interval[start], interval[height]]) + last_end = interval[end] + if last_end != -1: + res.append([last_end, 0]) + + return res + + # Divide and Conquer. + def ComputeSkylineInInterval(self, buildings, left_endpoint, right_endpoint): + if right_endpoint - left_endpoint <= 1: + return buildings[left_endpoint:right_endpoint] + mid = left_endpoint + ((right_endpoint - left_endpoint) / 2) + left_skyline = self.ComputeSkylineInInterval(buildings, left_endpoint, mid) + right_skyline = self.ComputeSkylineInInterval(buildings, mid, right_endpoint) + return self.MergeSkylines(left_skyline, right_skyline) + + # Merge Sort. + def MergeSkylines(self, left_skyline, right_skyline): + i, j = 0, 0 + merged = [] + + while i < len(left_skyline) and j < len(right_skyline): + if left_skyline[i][end] < right_skyline[j][start]: + merged.append(left_skyline[i]) + i += 1 + elif right_skyline[j][end] < left_skyline[i][start]: + merged.append(right_skyline[j]) + j += 1 + elif left_skyline[i][start] <= right_skyline[j][start]: + i, j = self.MergeIntersectSkylines(merged, left_skyline[i], i,\ + right_skyline[j], j) + else: # left_skyline[i][start] > right_skyline[j][start]. + j, i = self.MergeIntersectSkylines(merged, right_skyline[j], j, \ + left_skyline[i], i) + + # Insert the remaining skylines. + merged += left_skyline[i:] + merged += right_skyline[j:] + return merged + + # a[start] <= b[start] + def MergeIntersectSkylines(self, merged, a, a_idx, b, b_idx): + if a[end] <= b[end]: + if a[height] > b[height]: # |aaa| + if b[end] != a[end]: # |abb|b + b[start] = a[end] + merged.append(a) + a_idx += 1 + else: # aaa + b_idx += 1 # abb + elif a[height] == b[height]: # abb + b[start] = a[start] # abb + a_idx += 1 + else: # a[height] < b[height]. + if a[start] != b[start]: # bb + merged.append([a[start], b[start], a[height]]) # |a|bb + a_idx += 1 + else: # a[end] > b[end]. + if a[height] >= b[height]: # aaaa + b_idx += 1 # abba + else: + # |bb| + # |a||bb|a + if a[start] != b[start]: + merged.append([a[start], b[start], a[height]]) + a[start] = b[end] + merged.append(b) + b_idx += 1 + return a_idx, b_idx From e6db0ba6add550423f236ab90f6ac10803158b7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:19:52 +0800 Subject: [PATCH 0307/1939] Update the-skyline-problem.py --- Python/the-skyline-problem.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/the-skyline-problem.py b/Python/the-skyline-problem.py index 118fa8478..e7c0d00cf 100644 --- a/Python/the-skyline-problem.py +++ b/Python/the-skyline-problem.py @@ -1,5 +1,6 @@ # Time: O(nlogn) # Space: O(n) +# # A city's skyline is the outer contour of the silhouette formed # by all the buildings in that city when viewed from a distance. # Now suppose you are given the locations and height of all the From 3b85415fc6f71b43b52028dea0922df11bb993d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:21:09 +0800 Subject: [PATCH 0308/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bb7198065..b60b09a10 100644 --- a/README.md +++ b/README.md @@ -218,7 +218,7 @@ Shell 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky 179| [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || -218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) | _O(nlogn)_ | _O(n)_ | Hard || +218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard || --- From 0655c5fe6af6a4938d55884af5b03a9cb7259c76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:22:20 +0800 Subject: [PATCH 0309/1939] Update the-skyline-problem.py --- Python/the-skyline-problem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/the-skyline-problem.py b/Python/the-skyline-problem.py index e7c0d00cf..d7e17a89c 100644 --- a/Python/the-skyline-problem.py +++ b/Python/the-skyline-problem.py @@ -74,10 +74,10 @@ def MergeSkylines(self, left_skyline, right_skyline): j += 1 elif left_skyline[i][start] <= right_skyline[j][start]: i, j = self.MergeIntersectSkylines(merged, left_skyline[i], i,\ - right_skyline[j], j) + right_skyline[j], j) else: # left_skyline[i][start] > right_skyline[j][start]. j, i = self.MergeIntersectSkylines(merged, right_skyline[j], j, \ - left_skyline[i], i) + left_skyline[i], i) # Insert the remaining skylines. merged += left_skyline[i:] From 1c9e2a76ced71510faae87a066bde5ea1639080b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:23:14 +0800 Subject: [PATCH 0310/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b60b09a10..36edc841f 100644 --- a/README.md +++ b/README.md @@ -218,7 +218,7 @@ Shell 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky 179| [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || -218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard || +218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard | Sort, BST| --- From 093d513c56ccfd8ba5b4ab0a14f4f76e97a5b9e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:26:56 +0800 Subject: [PATCH 0311/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index bf59a6e2d..7e79f2ffb 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -9,20 +9,20 @@ class Solution { unordered_map> end_point_to_heights; set points; - for (int i = 0; i < buildings.size(); ++i) { - start_point_to_heights[buildings[i][0]].emplace_back(buildings[i][2]); - end_point_to_heights[buildings[i][1]].emplace_back(buildings[i][2]); - points.emplace(buildings[i][0]); - points.emplace(buildings[i][1]); + for (const auto& building : buildings) { + start_point_to_heights[building[0]].emplace_back(building[2]); + end_point_to_heights[building[1]].emplace_back(building[2]); + points.emplace(building[0]); + points.emplace(building[1]); } vector> res; map height_to_count; int curr_max = 0; // Enumerate each point in increasing order. - for (auto it = points.begin(); it != points.end(); ++it) { - vector start_point_heights = start_point_to_heights[*it]; - vector end_point_heights = end_point_to_heights[*it]; + for (const auto& point : points) { + vector start_point_heights = start_point_to_heights[point]; + vector end_point_heights = end_point_to_heights[point]; for (int i = 0; i < start_point_heights.size(); ++i) { ++height_to_count[start_point_heights[i]]; @@ -37,7 +37,7 @@ class Solution { if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; - res.emplace_back(*it, curr_max); + res.emplace_back(point, curr_max); } } return res; From b16d243ee87ad779270122403c26130ed9b6e7cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:33:04 +0800 Subject: [PATCH 0312/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 7e79f2ffb..1e60ce4a5 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -24,14 +24,14 @@ class Solution { vector start_point_heights = start_point_to_heights[point]; vector end_point_heights = end_point_to_heights[point]; - for (int i = 0; i < start_point_heights.size(); ++i) { - ++height_to_count[start_point_heights[i]]; + for (const auto& height : start_point_heights) { + ++height_to_count[height]; } - for (int i = 0; i < end_point_heights.size(); ++i) { - --height_to_count[end_point_heights[i]]; - if (height_to_count[end_point_heights[i]] == 0) { - height_to_count.erase(end_point_heights[i]); + for (const auto& height : end_point_heights) { + --height_to_count[height]; + if (height_to_count[height] == 0) { + height_to_count.erase(height); } } From 1c89d4f7fda7ce414f4d703e5a0021fb399c9c24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:34:53 +0800 Subject: [PATCH 0313/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 1e60ce4a5..2b459b17e 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -35,8 +35,8 @@ class Solution { } } - if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { - curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; + if (height_to_count.empty() || curr_max != height_to_count.crbegin()->first) { + curr_max = height_to_count.empty() ? 0 : height_to_count.crbegin()->first; res.emplace_back(point, curr_max); } } From 020d2af83e1b42fe8212a57696638818f5b5b8ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:38:01 +0800 Subject: [PATCH 0314/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 2b459b17e..0c25ba545 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -7,7 +7,7 @@ class Solution { vector > getSkyline(vector >& buildings) { unordered_map> start_point_to_heights; unordered_map> end_point_to_heights; - set points; + set points; // Ordered, no duplicated. for (const auto& building : buildings) { start_point_to_heights[building[0]].emplace_back(building[2]); @@ -17,7 +17,7 @@ class Solution { } vector> res; - map height_to_count; + map height_to_count; // bst. int curr_max = 0; // Enumerate each point in increasing order. for (const auto& point : points) { From e5922d120b039f0dae494e74f4f418ddae23e6d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 22:38:53 +0800 Subject: [PATCH 0315/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 0c25ba545..14efa0746 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -7,7 +7,7 @@ class Solution { vector > getSkyline(vector >& buildings) { unordered_map> start_point_to_heights; unordered_map> end_point_to_heights; - set points; // Ordered, no duplicated. + set points; // Ordered, no duplicates. for (const auto& building : buildings) { start_point_to_heights[building[0]].emplace_back(building[2]); @@ -17,7 +17,7 @@ class Solution { } vector> res; - map height_to_count; // bst. + map height_to_count; // BST. int curr_max = 0; // Enumerate each point in increasing order. for (const auto& point : points) { From a9a3595ebab99cafa9c9ee22a05f05ece9213fbf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 May 2015 23:43:28 +0800 Subject: [PATCH 0316/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 42 +++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 14efa0746..51530222d 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -4,37 +4,39 @@ // BST solution. class Solution { public: + enum {start, end, height} ; + + struct Endpoint { + int height; + bool isStart; + }; + vector > getSkyline(vector >& buildings) { - unordered_map> start_point_to_heights; - unordered_map> end_point_to_heights; - set points; // Ordered, no duplicates. - + map> point_to_height; // Ordered, no duplicates. for (const auto& building : buildings) { - start_point_to_heights[building[0]].emplace_back(building[2]); - end_point_to_heights[building[1]].emplace_back(building[2]); - points.emplace(building[0]); - points.emplace(building[1]); + point_to_height[building[start]].emplace_back(Endpoint{building[height], true}); + point_to_height[building[end]].emplace_back(Endpoint{building[height], false}); } vector> res; map height_to_count; // BST. int curr_max = 0; // Enumerate each point in increasing order. - for (const auto& point : points) { - vector start_point_heights = start_point_to_heights[point]; - vector end_point_heights = end_point_to_heights[point]; + for (auto& kvp : point_to_height) { + auto& point = kvp.first; + auto& heights = kvp.second; - for (const auto& height : start_point_heights) { - ++height_to_count[height]; - } - - for (const auto& height : end_point_heights) { - --height_to_count[height]; - if (height_to_count[height] == 0) { - height_to_count.erase(height); + for (const auto& h : heights) { + if (h.isStart) { + ++height_to_count[h.height]; + } else { + --height_to_count[h.height]; + if (height_to_count[h.height] == 0) { + height_to_count.erase(h.height); + } } } - + if (height_to_count.empty() || curr_max != height_to_count.crbegin()->first) { curr_max = height_to_count.empty() ? 0 : height_to_count.crbegin()->first; res.emplace_back(point, curr_max); From 1eed7bd98f8f04563bd09d169b5d9e95ccd98a2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 00:17:35 +0800 Subject: [PATCH 0317/1939] Update README.md --- README.md | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 36edc841f..52c4c2485 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Shell --- ##Bit Manipulation - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || @@ -60,7 +60,7 @@ Shell ##Array - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || 16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py)| _O(n^2)_ | _O(1)_ | Medium || @@ -89,7 +89,7 @@ Shell --- ##String - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || @@ -112,7 +112,7 @@ Shell --- ##Linked List - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || 24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || @@ -129,7 +129,7 @@ Shell --- ##Stack - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || @@ -142,14 +142,14 @@ Shell --- ##Heap - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || --- ##Tree - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` @@ -162,7 +162,7 @@ Shell --- ##Hash Table - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || @@ -182,14 +182,14 @@ Shell --- ##Data Structure - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || --- ##Math - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || @@ -207,7 +207,7 @@ Shell --- ##Sort - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || @@ -223,7 +223,7 @@ Shell --- ##Two Pointer - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || 86| [Partition List](https://leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || @@ -235,7 +235,7 @@ Shell --- ##Brute Force Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || 46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n!)_ | _O(n)_ | Medium || @@ -246,7 +246,7 @@ Shell --- ##Divide and Conquer - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || 98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || @@ -267,7 +267,7 @@ Shell --- ##Binary Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || 33| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || @@ -284,7 +284,7 @@ Shell --- ##Breadth-First Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 102| [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || 107| [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](./Python/binary-tree-level-order-traversal-ii.py) | _O(n)_| _O(n)_| Easy || @@ -299,7 +299,7 @@ Shell --- ##Depth-First Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || 37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || @@ -320,7 +320,7 @@ Shell --- ##Dynamic Programming - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 10| [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || 53| [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || @@ -349,14 +349,14 @@ Shell --- ##Backtracking - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || --- ##Greedy - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || 42| [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky @@ -371,7 +371,7 @@ Shell --- ##SQL - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 175| [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || 176| [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/) | [MySQL](./MySQL/second-highest-salary.sql) | _O(n)_ | _O(1)_ | Easy || @@ -389,7 +389,7 @@ Shell --- ##Shell Script - # | Problem | Solution | Time | Space | Difficulty | Tag | Notes + # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 192 | [Word Frequency](https://leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || 193 | [Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/) | [Shell](./Shell/valid-phone-numbers.sh) | _O(n)_ | _O(1)_ | Easy || From 268468f9943e52a7e3a11241615c957225b0bbfc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 13:27:59 +0800 Subject: [PATCH 0318/1939] Update minimum-size-subarray-sum.py --- Python/minimum-size-subarray-sum.py | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Python/minimum-size-subarray-sum.py b/Python/minimum-size-subarray-sum.py index 860932c60..ab850fdec 100644 --- a/Python/minimum-size-subarray-sum.py +++ b/Python/minimum-size-subarray-sum.py @@ -11,6 +11,7 @@ # If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). # +# Sliding window solution. class Solution: # @param {integer} s # @param {integer[]} nums @@ -28,3 +29,34 @@ def minSubArrayLen(self, s, nums): if min_len == float("inf"): return 0 return min_len + +# Time: O(nlogn) +# Space: O(n) +# Binary search solution. +class Solution2: + # @param {integer} s + # @param {integer[]} nums + # @return {integer} + def minSubArrayLen(self, s, nums): + min_size = float("inf") + sum_from_start = [n for n in nums] + for i in xrange(len(sum_from_start) - 1): + sum_from_start[i + 1] += sum_from_start[i] + for i in xrange(len(sum_from_start)): + end = self.binarySearch(lambda x, y: x <= y, sum_from_start, \ + i, len(sum_from_start), \ + sum_from_start[i] - nums[i] + s) + if end < len(sum_from_start): + min_size = min(min_size, end - i + 1) + if min_size == float("inf"): + return 0 + return min_size + + def binarySearch(self, compare, A, start, end, target): + while start < end: + mid = start + (end - start) / 2 + if compare(target, A[mid]): + end = mid + else: + start = mid + 1 + return start From 4679f736eb650997264022b2e77c6fede4a740bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 13:28:42 +0800 Subject: [PATCH 0319/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 52c4c2485..88676b0f5 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ Shell 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || -209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium || +209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| --- From 382a56e5571bdb353e4b7b9a6b132ec02554bb82 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 13:50:23 +0800 Subject: [PATCH 0320/1939] Update minimum-size-subarray-sum.py --- Python/minimum-size-subarray-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/minimum-size-subarray-sum.py b/Python/minimum-size-subarray-sum.py index ab850fdec..229e07aa3 100644 --- a/Python/minimum-size-subarray-sum.py +++ b/Python/minimum-size-subarray-sum.py @@ -47,7 +47,7 @@ def minSubArrayLen(self, s, nums): i, len(sum_from_start), \ sum_from_start[i] - nums[i] + s) if end < len(sum_from_start): - min_size = min(min_size, end - i + 1) + min_size = min(min_size, end - i + 1) if min_size == float("inf"): return 0 return min_size From eb39cad5c55234040b07aa7bd9d84da39d2453a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 20:56:08 +0800 Subject: [PATCH 0321/1939] Update valid-number.py --- Python/valid-number.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/valid-number.py b/Python/valid-number.py index c45fbaab7..e1fb1f9e8 100644 --- a/Python/valid-number.py +++ b/Python/valid-number.py @@ -21,7 +21,7 @@ class InputType: DOT = 4 EXPONENT = 5 -# regular expression: "^\s*[\+\-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$" +# regular expression: "^\s*[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$" # automata: http://images.cnitblog.com/i/627993/201405/012016243309923.png class Solution: # @param s, a string @@ -63,11 +63,11 @@ class Solution2: # @return a boolean def isNumber(self, s): import re - return bool(re.match("^\s*[\+\-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$", s)) + return bool(re.match("^\s*[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$", s)) if __name__ == "__main__": print Solution().isNumber(" 0.1 ") print Solution().isNumber("abc") print Solution().isNumber("1 a") print Solution().isNumber("2e10") - \ No newline at end of file + From fb3389711207ae7ede6f6eb67c775f455d94a827 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 21:24:13 +0800 Subject: [PATCH 0322/1939] Update valid-number.py --- Python/valid-number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/valid-number.py b/Python/valid-number.py index e1fb1f9e8..8a5c744e7 100644 --- a/Python/valid-number.py +++ b/Python/valid-number.py @@ -21,7 +21,7 @@ class InputType: DOT = 4 EXPONENT = 5 -# regular expression: "^\s*[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$" +# regular expression: "^\s*[\+-]?((\d+(\.\d*)?)|\.\d+)([eE][\+-]?\d+)?\s*$" # automata: http://images.cnitblog.com/i/627993/201405/012016243309923.png class Solution: # @param s, a string @@ -63,7 +63,7 @@ class Solution2: # @return a boolean def isNumber(self, s): import re - return bool(re.match("^\s*[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$", s)) + return bool(re.match("^\s*[\+-]?((\d+(\.\d*)?)|\.\d+)([eE][\+-]?\d+)?\s*$", s)) if __name__ == "__main__": print Solution().isNumber(" 0.1 ") From 63ba9373368d2c502d25d2db2ebdc2fd57797ea5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 May 2015 21:41:30 +0800 Subject: [PATCH 0323/1939] Update valid-palindrome.py --- Python/valid-palindrome.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/valid-palindrome.py b/Python/valid-palindrome.py index b9abbfc9b..c0c562059 100644 --- a/Python/valid-palindrome.py +++ b/Python/valid-palindrome.py @@ -19,9 +19,9 @@ class Solution: def isPalindrome(self, s): i, j = 0, len(s) - 1 while i < j: - while i < j and not (s[i].isalpha() or s[i].isdigit()): + while i < j and not s[i].isalnum(): i += 1 - while i < j and not (s[j].isalpha() or s[j].isdigit()): + while i < j and not s[j].isalnum(): j -= 1 if s[i].lower() != s[j].lower(): return False @@ -29,4 +29,4 @@ def isPalindrome(self, s): return True if __name__ == "__main__": - print Solution().isPalindrome("A man, a plan, a canal: Panama") \ No newline at end of file + print Solution().isPalindrome("A man, a plan, a canal: Panama") From 4a9ef6b40f66592a7171cfc8b1688ce7a1a2455b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 May 2015 04:06:00 +0800 Subject: [PATCH 0324/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 88676b0f5..383fd46f1 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ Shell 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` -38| [Count and Say](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || +38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || @@ -104,7 +104,7 @@ Shell 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| -165| [Compare Version Numbers](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py) | _O(n)_ | _O(1)_ | Easy || +165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` From 4e271b221e3d85cdb3d01d3670d6db810d1b1c36 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:32:43 +0800 Subject: [PATCH 0325/1939] Create contains-duplicate-ii.cpp --- C++/contains-duplicate-ii.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/contains-duplicate-ii.cpp diff --git a/C++/contains-duplicate-ii.cpp b/C++/contains-duplicate-ii.cpp new file mode 100644 index 000000000..b49e925ac --- /dev/null +++ b/C++/contains-duplicate-ii.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + unordered_map hash; + for (int i = 0; i < nums.size(); ++i) { + if (hash.find(nums[i]) == hash.end()) { + hash[nums[i]] = i; + } else { + // It the value occurs before, check the difference. + if (i - hash[nums[i]] <= k) { + return true; + } + // Update the index of the value. + hash[nums[i]] = i; + } + } + return false; + } +}; From 8d2b0a00ca6ec4b171cbe7668c3e886ecb70a0f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:34:19 +0800 Subject: [PATCH 0326/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 383fd46f1..f4e04a26f 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-26), there are `202` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-05-29), there are `203` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `218` problems. +Here is the classification of all `219` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -178,6 +178,7 @@ Shell 202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || +219| [Contains DuplicateII](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || --- From e216a99682807d2b92cf6c04ebe1978cded19a7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:34:49 +0800 Subject: [PATCH 0327/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f4e04a26f..b667af53b 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ Shell 202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || -219| [Contains DuplicateII](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || +219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || --- From 34fa53f6bb024c23c3391db4634d3c2703b5ddf0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:39:15 +0800 Subject: [PATCH 0328/1939] Update contains-duplicate-ii.cpp --- C++/contains-duplicate-ii.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/contains-duplicate-ii.cpp b/C++/contains-duplicate-ii.cpp index b49e925ac..b70ad1928 100644 --- a/C++/contains-duplicate-ii.cpp +++ b/C++/contains-duplicate-ii.cpp @@ -4,17 +4,17 @@ class Solution { public: bool containsNearbyDuplicate(vector& nums, int k) { - unordered_map hash; + unordered_map lookup; for (int i = 0; i < nums.size(); ++i) { - if (hash.find(nums[i]) == hash.end()) { - hash[nums[i]] = i; + if (lookup.find(nums[i]) == lookup.end()) { + lookup[nums[i]] = i; } else { // It the value occurs before, check the difference. - if (i - hash[nums[i]] <= k) { + if (i - lookup[nums[i]] <= k) { return true; } // Update the index of the value. - hash[nums[i]] = i; + lookup[nums[i]] = i; } } return false; From b543322be3dac2c7931883c7c192e938daa9e0c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 May 2015 10:40:12 +0800 Subject: [PATCH 0329/1939] Create contains-duplicate-ii.py --- Python/contains-duplicate-ii.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/contains-duplicate-ii.py diff --git a/Python/contains-duplicate-ii.py b/Python/contains-duplicate-ii.py new file mode 100644 index 000000000..451a6bdde --- /dev/null +++ b/Python/contains-duplicate-ii.py @@ -0,0 +1,24 @@ +# Time: O(n) +# Space: O(n) +# +# Given an array of integers and an integer k, return true if +# and only if there are two distinct indices i and j in the array +# such that nums[i] = nums[j] and the difference between i and j is at most k. +# + +class Solution: + # @param {integer[]} nums + # @param {integer} k + # @return {boolean} + def containsNearbyDuplicate(self, nums, k): + lookup = {} + for i, num in enumerate(nums): + if num not in lookup: + lookup[num] = i + else: + # It the value occurs before, check the difference. + if i - lookup[num] <= k: + return True + # Update the index of the value. + lookup[num] = i + return False From ee86392cd4998936e2393f75cf577b36d0e271fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 May 2015 02:52:00 +0800 Subject: [PATCH 0330/1939] Update maximum-gap.py --- Python/maximum-gap.py | 58 +++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/Python/maximum-gap.py b/Python/maximum-gap.py index 6bc30d14f..4f3379731 100644 --- a/Python/maximum-gap.py +++ b/Python/maximum-gap.py @@ -16,46 +16,44 @@ # bucket sort class Solution: - # @param num, a list of integer - # @return an integer - def maximumGap(self, num): - if len(num) < 2: + # @param numss: a list of integers + # @return: the maximum difference + def maximumGap(self, nums): + # Linear time to get unique_nums. + unique_nums = list(set(nums)) + if len(unique_nums) < 2: return 0 - unique_num = self.removeDuplicate(num) - - max_val, min_val = max(unique_num), min(unique_num) - gap = (max_val - min_val) / (len(unique_num) - 1) + # Init bucket. + max_val, min_val = max(unique_nums), min(unique_nums) + gap = (max_val - min_val) / (len(unique_nums) - 1) bucket_size = (max_val - min_val) / gap + 1 - max_bucket = [float("-inf") for _ in xrange(bucket_size)] - min_bucket = [float("inf") for _ in xrange(bucket_size)] + bucket = [{'min':float("inf"), 'max':float("-inf")} \ + for _ in xrange(bucket_size)] - for i in unique_num: - if i in (max_val, min_val): + # Find the bucket where the n should be put. + for n in unique_nums: + # min_val / max_val is in the first / last bucket. + if n in (max_val, min_val): continue - idx = (i - min_val) / gap - max_bucket[idx] = max(max_bucket[idx], i) - min_bucket[idx] = min(min_bucket[idx], i) + i = (n - min_val) / gap + bucket[i]['min'] = min(bucket[i]['min'], n) + bucket[i]['max'] = max(bucket[i]['max'], n) - max_gap = 0 - pre = min_val + # Count each bucket gap between the first and the last bucket. + max_gap, pre_bucket_max = 0, min_val for i in xrange(bucket_size): - if max_bucket[i] == float("-inf") and min_bucket[i] == float("inf"): + # Skip the bucket it empty. + if bucket[i]['min'] == float("inf") and \ + bucket[i]['max'] == float("-inf"): continue - max_gap = max(max_gap, min_bucket[i] - pre) - pre = max_bucket[i] - max_gap = max(max_gap, max_val - pre) + max_gap = max(max_gap, bucket[i]['min'] - pre_bucket_max) + pre_bucket_max = bucket[i]['max'] + # Count the last bucket. + max_gap = max(max_gap, max_val - pre_bucket_max) return max_gap - - def removeDuplicate(self, num): - dict = {} - unique_num = [] - for i in num: - if i not in dict: - unique_num.append(i) - dict[i] = True - return unique_num + # Time: O(nlogn) # Space: O(n) From 2c6a7e3f8fae3135ce09fbf1eb878d9147027ae6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 May 2015 02:58:00 +0800 Subject: [PATCH 0331/1939] Update maximum-gap.py --- Python/maximum-gap.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Python/maximum-gap.py b/Python/maximum-gap.py index 4f3379731..fd574a9ac 100644 --- a/Python/maximum-gap.py +++ b/Python/maximum-gap.py @@ -15,24 +15,25 @@ # # bucket sort +# Time: O(n) +# Space: O(n) + class Solution: # @param numss: a list of integers # @return: the maximum difference def maximumGap(self, nums): - # Linear time to get unique_nums. - unique_nums = list(set(nums)) - if len(unique_nums) < 2: + if len(nums) < 2: return 0 # Init bucket. - max_val, min_val = max(unique_nums), min(unique_nums) - gap = (max_val - min_val) / (len(unique_nums) - 1) + max_val, min_val = max(nums), min(nums) + gap = max(1, (max_val - min_val) / (len(nums) - 1)) bucket_size = (max_val - min_val) / gap + 1 bucket = [{'min':float("inf"), 'max':float("-inf")} \ for _ in xrange(bucket_size)] # Find the bucket where the n should be put. - for n in unique_nums: + for n in nums: # min_val / max_val is in the first / last bucket. if n in (max_val, min_val): continue @@ -55,6 +56,7 @@ def maximumGap(self, nums): return max_gap + # Time: O(nlogn) # Space: O(n) class Solution2: From 8bb92083942bc796f6959820174120de4a6ed96b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 13:47:54 +0800 Subject: [PATCH 0332/1939] Create contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/contains-duplicate-iii.cpp diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp new file mode 100644 index 000000000..cc4cc48be --- /dev/null +++ b/C++/contains-duplicate-iii.cpp @@ -0,0 +1,28 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { + deque window_deq; + multiset window; + for (int i = 0; i < nums.size(); ++i) { + // Only keep at most k elements. + if (window.size() > k) { + int num = window_deq.front(); + window_deq.pop_front(); + window.erase(window.find(num)); + } + // Every search costs time: O(logn). + const auto it = window.lower_bound(nums[i] - t); + if (it == window.cend() || (*it - nums[i]) > t) { + // Not found. + window_deq.emplace_back(nums[i]); + window.emplace(nums[i]); + } else { + return true; + } + } + return false; + } +}; From 71d7ba6ada5a519b9a316289b5e326dedcf885d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 13:50:35 +0800 Subject: [PATCH 0333/1939] Update contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp index cc4cc48be..589b3f2f0 100644 --- a/C++/contains-duplicate-iii.cpp +++ b/C++/contains-duplicate-iii.cpp @@ -4,21 +4,21 @@ class Solution { public: bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { - deque window_deq; - multiset window; + deque window; + multiset bst; for (int i = 0; i < nums.size(); ++i) { // Only keep at most k elements. - if (window.size() > k) { - int num = window_deq.front(); - window_deq.pop_front(); - window.erase(window.find(num)); + if (bst.size() > k) { + int num = window.front(); + window.pop_front(); + bst.erase(bst.find(num)); } // Every search costs time: O(logn). - const auto it = window.lower_bound(nums[i] - t); - if (it == window.cend() || (*it - nums[i]) > t) { + const auto it = bst.lower_bound(nums[i] - t); + if (it == bst.cend() || (*it - nums[i]) > t) { // Not found. - window_deq.emplace_back(nums[i]); - window.emplace(nums[i]); + window.emplace_back(nums[i]); + bst.emplace(nums[i]); } else { return true; } From c13913dded51e4db320e93003b1a8e4b457c3a0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 13:54:01 +0800 Subject: [PATCH 0334/1939] Update README.md --- README.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b667af53b..6b54425f9 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-05-29), there are `203` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-01), there are `204` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `219` problems. +Here is the classification of all `220` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -26,7 +26,8 @@ Algorithms * [Sort](https://github.com/kamyu104/LeetCode#sort) * [Brute Force Search](https://github.com/kamyu104/LeetCode#brute-force-search) * [Divide and Conquer](https://github.com/kamyu104/LeetCode#divide-and-conquer) -* [Binary Search](https://github.com/kamyu104/LeetCode#binary-search) +* [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search) +* * [Binary Search](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search](https://github.com/kamyu104/LeetCode#depth-first-search) * [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) @@ -50,6 +51,7 @@ Shell ##Bit Manipulation # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || @@ -282,6 +284,12 @@ Shell 154| [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || 162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || +-- +##Binary Search Tree + # | Problem | Solution | Time | Space | Difficulty | Tag | Note +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) | _O(nlogn)_ | _O(n)_ | medium || + --- ##Breadth-First Search From dda2c02ff609fe89fe486a7417ba8f1c6e85e079 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 14:16:43 +0800 Subject: [PATCH 0335/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6b54425f9..985c9d826 100644 --- a/README.md +++ b/README.md @@ -26,8 +26,8 @@ Algorithms * [Sort](https://github.com/kamyu104/LeetCode#sort) * [Brute Force Search](https://github.com/kamyu104/LeetCode#brute-force-search) * [Divide and Conquer](https://github.com/kamyu104/LeetCode#divide-and-conquer) -* [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search) -* * [Binary Search](https://github.com/kamyu104/LeetCode#binary-search-tree) +* [Binary Search](https://github.com/kamyu104/LeetCode#binary-search) +* [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search](https://github.com/kamyu104/LeetCode#depth-first-search) * [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) From 78054d40fb0af17970ea900d1739b3139d5b24e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 14:20:02 +0800 Subject: [PATCH 0336/1939] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 985c9d826..c810ab6e4 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,6 @@ Shell ##Bit Manipulation # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || From 4d0d045bae664662941efd3f2b3f1166b8399a17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 14:33:20 +0800 Subject: [PATCH 0337/1939] Update contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp index 589b3f2f0..3485796c6 100644 --- a/C++/contains-duplicate-iii.cpp +++ b/C++/contains-duplicate-iii.cpp @@ -4,20 +4,20 @@ class Solution { public: bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { - deque window; + queue window; multiset bst; for (int i = 0; i < nums.size(); ++i) { // Only keep at most k elements. if (bst.size() > k) { int num = window.front(); - window.pop_front(); + window.pop(); bst.erase(bst.find(num)); } // Every search costs time: O(logn). const auto it = bst.lower_bound(nums[i] - t); if (it == bst.cend() || (*it - nums[i]) > t) { // Not found. - window.emplace_back(nums[i]); + window.emplace(nums[i]); bst.emplace(nums[i]); } else { return true; From fe90c48cae4f8ba2f4edaaafecc0c6da34d6f8fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 15:00:39 +0800 Subject: [PATCH 0338/1939] Update contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp index 3485796c6..a5fe92baa 100644 --- a/C++/contains-duplicate-iii.cpp +++ b/C++/contains-duplicate-iii.cpp @@ -1,5 +1,5 @@ -// Time: O(nlogn) -// Space: O(n) +// Time: O(nlogk) +// Space: O(k) class Solution { public: From 90355d55d35486467dbc2ebd67d11e42d7092f37 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 15:01:29 +0800 Subject: [PATCH 0339/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c810ab6e4..427c380e2 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,7 @@ Shell ##Binary Search Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) | _O(nlogn)_ | _O(n)_ | medium || +220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) | _O(nlogk)_ | _O(k)_ | medium || --- From 066dbd5b716289799c5f55debda2c850e3289564 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 15:25:47 +0800 Subject: [PATCH 0340/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 427c380e2..db078e68d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ LeetCode Up to date (2015-06-01), there are `204` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. Here is the classification of all `220` problems. -For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repo. +For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) From d3740bce433f46431bcc96f9cb997ad563ad36c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 17:59:33 +0800 Subject: [PATCH 0341/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 51530222d..55cb51376 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -4,7 +4,7 @@ // BST solution. class Solution { public: - enum {start, end, height} ; + enum {start, end, height}; struct Endpoint { int height; From dd545a5461e3fa65e1b2a0ec1e4fad94af42d7aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jun 2015 23:40:30 +0800 Subject: [PATCH 0342/1939] Update letter-combinations-of-a-phone-number.py --- Python/letter-combinations-of-a-phone-number.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Python/letter-combinations-of-a-phone-number.py b/Python/letter-combinations-of-a-phone-number.py index c3d5e7779..f25d8bcc8 100644 --- a/Python/letter-combinations-of-a-phone-number.py +++ b/Python/letter-combinations-of-a-phone-number.py @@ -17,25 +17,33 @@ class Solution: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): - lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"], [""] + if not digits: + return [] + + lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", \ + "pqrs", "tuv", "wxyz"], [""] - for digit in digits: + for digit in reversed(digits): choices = lookup[int(digit)] m, n = len(choices), len(result) result.extend([result[i % n] for i in xrange(n, m * n)]) for i in xrange(m * n): - result[i] += choices[i / n] + result[i] = choices[i / n] + result[i] return result + # Time: O(n * 4^n) # Space: O(n) # Recursive Solution class Solution2: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): - lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"], [] + if not digits: + return [] + lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", \ + "pqrs", "tuv", "wxyz"], [] self.letterCombinationsRecu(result, digits, lookup, "", 0) return result From 8b4759021206bdbe149127a55b8f5518b8f5d675 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Jun 2015 11:58:38 +0800 Subject: [PATCH 0343/1939] Create contains-duplicate-iii.py --- Python/contains-duplicate-iii.py | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/contains-duplicate-iii.py diff --git a/Python/contains-duplicate-iii.py b/Python/contains-duplicate-iii.py new file mode 100644 index 000000000..42841b948 --- /dev/null +++ b/Python/contains-duplicate-iii.py @@ -0,0 +1,34 @@ +# Time: O(n * t) +# Space: O(max(k, t)) +# +# Given an array of integers, find out whether there +# are two distinct inwindowes i and j in the array such +# that the difference between nums[i] and nums[j] is +# at most t and the difference between i and j is at +# most k. +# + +# This is not the best solution +# since there is no built-in bst structure in Python. +# The better solution could be found in C++ solution. +class Solution: + # @param {integer[]} nums + # @param {integer} k + # @param {integer} t + # @return {boolean} + def containsNearbyAlmostDuplicate(self, nums, k, t): + if k < 0 or t < 0: + return False + window = collections.OrderedDict() + for n in nums: + # Make sure window size + if len(window) > k: + window.popitem(False) + + bucket = n if not t else n // t + # At most 2t items. + for m in (window.get(bucket - 1), window.get(bucket), window.get(bucket + 1)): + if m is not None and abs(n - m) <= t: + return True + window[bucket] = n + return False From 4d15a0139ad10fdf2ef7486de22e7d8883e6f90c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Jun 2015 12:00:39 +0800 Subject: [PATCH 0344/1939] Update contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp index a5fe92baa..0231eb157 100644 --- a/C++/contains-duplicate-iii.cpp +++ b/C++/contains-duplicate-iii.cpp @@ -4,6 +4,10 @@ class Solution { public: bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { + if (k < 0 || t < 0) { + return false; + } + queue window; multiset bst; for (int i = 0; i < nums.size(); ++i) { From d8ff29563a1031242c591f794189d33d881a0ff7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Jun 2015 12:01:30 +0800 Subject: [PATCH 0345/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db078e68d..fc6b4178c 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,7 @@ Shell ##Binary Search Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) | _O(nlogk)_ | _O(k)_ | medium || +220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) [Python](./Python/contains-duplicate-iii.py) | _O(nlogk)_ | _O(k)_ | medium || --- From dc809bf4fa0f307f63e0caf72ebd1edce9ee9977 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jun 2015 18:26:35 +0800 Subject: [PATCH 0346/1939] Update scramble-string.py --- Python/scramble-string.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/scramble-string.py b/Python/scramble-string.py index 5d7d4feeb..fd8adefae 100644 --- a/Python/scramble-string.py +++ b/Python/scramble-string.py @@ -47,7 +47,7 @@ class Solution: def isScramble(self, s1, s2): if not s1 or not s2 or len(s1) != len(s2): return False - if not s1: + if s1 == "": return True result = [[[False for j in xrange(len(s2))] for i in xrange(len(s1))] for n in xrange(len(s1) + 1)] for i in xrange(len(s1)): From 729f6b0727ea1df88f281125bb775817bfb3be7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jun 2015 20:25:40 +0800 Subject: [PATCH 0347/1939] Update scramble-string.py --- Python/scramble-string.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/scramble-string.py b/Python/scramble-string.py index fd8adefae..7969954b0 100644 --- a/Python/scramble-string.py +++ b/Python/scramble-string.py @@ -47,7 +47,7 @@ class Solution: def isScramble(self, s1, s2): if not s1 or not s2 or len(s1) != len(s2): return False - if s1 == "": + if s1 == s2: return True result = [[[False for j in xrange(len(s2))] for i in xrange(len(s1))] for n in xrange(len(s1) + 1)] for i in xrange(len(s1)): From a8f79bbbdf6650df7c0d9b7b341139e2f964bfde Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jun 2015 22:06:19 +0800 Subject: [PATCH 0348/1939] Create maximal-square.cpp --- C++/maximal-square.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/maximal-square.cpp diff --git a/C++/maximal-square.cpp b/C++/maximal-square.cpp new file mode 100644 index 000000000..0a47a73b2 --- /dev/null +++ b/C++/maximal-square.cpp @@ -0,0 +1,46 @@ +// Time: O(n^2) +// Space: O(n^2) + +struct MaxHW { + int h, w; +}; + +class Solution { +public: + int maximalSquare(vector>& A) { + if (A.empty()) { + return 0; + } + + // DP table stores (h, w) for each (i, j). + vector> table(A.size(), vector(A.front().size())); + for (int i = A.size() - 1; i >= 0; --i) { + for (int j = A[i].size() - 1; j >= 0; --j) { + // Find the largest h such that (i, j) to (i + h - 1, j) are feasible. + // Find the largest w such that (i, j) to (i, j + w - 1) are feasible. + table[i][j] = A[i][j] == '1' + ? MaxHW{i + 1 < A.size() ? table[i + 1][j].h + 1 : 1, + j + 1 < A[i].size() ? table[i][j + 1].w + 1 : 1} + : MaxHW{0, 0}; + } + } + + // A table stores the length of largest square for each (i, j). + vector> s(A.size(), vector(A.front().size(), 0)); + int max_square_area = 0; + for (int i = A.size() - 1; i >= 0; --i) { + for (int j = A[i].size() - 1; j >= 0; --j) { + int side = min(table[i][j].h, table[i][j].w); + if (A[i][j]) { + // Get the length of largest square with bottom-left corner (i, j). + if (i + 1 < A.size() && j + 1 < A[i + 1].size()) { + side = min(s[i + 1][j + 1] + 1, side); + } + s[i][j] = side; + max_square_area = max(max_square_area, side * side); + } + } + } + return max_square_area; + } +}; From 7584d8d428bb5ae790b68d4f07ca2d810b184ad9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jun 2015 22:08:44 +0800 Subject: [PATCH 0349/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fc6b4178c..73a241886 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-01), there are `204` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-03), there are `205` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `220` problems. +Here is the classification of all `221` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -353,6 +353,7 @@ Shell 188| [Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || 198| [House Robber](https://leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || 213| [House Robber II](https://leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || +221| [Maximal Square](https://leetcode.com/problems/maximal-square/)| [C++](./C++/maximal-square.cpp) [Python](./Python/maximal-square.py) | _O(n^2)_ | _O(n^2)_ | Medium || --- From c5e59ca981c3316a038897627f528270d2347ecd Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jun 2015 22:09:18 +0800 Subject: [PATCH 0350/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 73a241886..4b59e22ea 100644 --- a/README.md +++ b/README.md @@ -353,7 +353,7 @@ Shell 188| [Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || 198| [House Robber](https://leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || 213| [House Robber II](https://leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || -221| [Maximal Square](https://leetcode.com/problems/maximal-square/)| [C++](./C++/maximal-square.cpp) [Python](./Python/maximal-square.py) | _O(n^2)_ | _O(n^2)_ | Medium || +221| [Maximal Square](https://leetcode.com/problems/maximal-square/)| [C++](./C++/maximal-square.cpp) [Python](./Python/maximal-square.py) | _O(n^2)_ | _O(n^2)_ | Medium | EPI | --- From da91a78db74b29cf084ca4dec9f7dec781d2e374 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jun 2015 22:31:23 +0800 Subject: [PATCH 0351/1939] Create maximal-square.py --- Python/maximal-square.py | 55 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/maximal-square.py diff --git a/Python/maximal-square.py b/Python/maximal-square.py new file mode 100644 index 000000000..75a983140 --- /dev/null +++ b/Python/maximal-square.py @@ -0,0 +1,55 @@ +# Time: O(n^2) +# Space: O(n) +# +# Given a 2D binary matrix filled with 0's and 1's, +# find the largest square containing all 1's and return its area. +# +# For example, given the following matrix: +# +# 1 0 1 0 0 +# 1 0 1 1 1 +# 1 1 1 1 1 +# 1 0 0 1 0 +# Return 4. +# + +class Solution: + # @param {character[][]} matrix + # @return {integer} + def maximalSquare(self, matrix): + if not matrix: + return 0 + + H, W = 0, 1 + # DP table stores (h, w) for each (i, j). + table = [[[0, 0] for j in xrange(len(matrix[0]))] \ + for i in xrange(len(matrix))] + + for i in reversed(xrange(len(matrix))): + for j in reversed(xrange(len(matrix[i]))): + # Find the largest h such that (i, j) to (i + h - 1, j) are feasible. + # Find the largest w such that (i, j) to (i, j + w - 1) are feasible. + if matrix[i][j] == '1': + h, w = 1, 1 + if i + 1 < len(matrix): + h = table[i + 1][j][H] + 1 + if j + 1 < len(matrix[i]): + w = table[i][j + 1][W] + 1 + table[i][j] = [h, w] + + # A table stores the length of largest square for each (i, j). + s = [[0 for j in xrange(len(matrix[0]))] \ + for i in xrange(len(matrix))] + max_square_area = 0 + for i in reversed(xrange(len(matrix))): + for j in reversed(xrange(len(matrix[i]))): + side = min(table[i][j][H], table[i][j][W]) + if matrix[i][j] == '1': + # Get the length of largest square with bottom-left corner (i, j). + if i + 1 < len(matrix) and j + 1 < len(matrix[i + 1]): + side = min(s[i + 1][j + 1] + 1, side) + s[i][j] = side + max_square_area = max(max_square_area, side * side) + + return max_square_area; + From 030e5eaa3af8d4af794d38786daf2ec6f26fc799 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jun 2015 22:32:05 +0800 Subject: [PATCH 0352/1939] Update maximal-square.py --- Python/maximal-square.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximal-square.py b/Python/maximal-square.py index 75a983140..38697de89 100644 --- a/Python/maximal-square.py +++ b/Python/maximal-square.py @@ -1,5 +1,5 @@ # Time: O(n^2) -# Space: O(n) +# Space: O(n^2) # # Given a 2D binary matrix filled with 0's and 1's, # find the largest square containing all 1's and return its area. From a4a9d95a02916e2d784562d2b5aa48064233cc68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jun 2015 22:32:51 +0800 Subject: [PATCH 0353/1939] Update maximal-square.py --- Python/maximal-square.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/maximal-square.py b/Python/maximal-square.py index 38697de89..a9065ef90 100644 --- a/Python/maximal-square.py +++ b/Python/maximal-square.py @@ -24,7 +24,6 @@ def maximalSquare(self, matrix): # DP table stores (h, w) for each (i, j). table = [[[0, 0] for j in xrange(len(matrix[0]))] \ for i in xrange(len(matrix))] - for i in reversed(xrange(len(matrix))): for j in reversed(xrange(len(matrix[i]))): # Find the largest h such that (i, j) to (i + h - 1, j) are feasible. From 02fcac2937a63b4b84f9c8508d1c14cce93278b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jun 2015 23:54:33 +0800 Subject: [PATCH 0354/1939] Update maximal-square.cpp --- C++/maximal-square.cpp | 77 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 73 insertions(+), 4 deletions(-) diff --git a/C++/maximal-square.cpp b/C++/maximal-square.cpp index 0a47a73b2..e75821269 100644 --- a/C++/maximal-square.cpp +++ b/C++/maximal-square.cpp @@ -1,12 +1,81 @@ // Time: O(n^2) -// Space: O(n^2) +// Space: O(n) -struct MaxHW { - int h, w; +// DP with rolling window. +class Solution { +public: + int maximalSquare(vector>& A) { + if (A.empty()) { + return 0; + } + const int m = A.size(), n = A[0].size(); + vector> size(2, vector(n, 0)); + int max_size = 0; + + for (int j = 0; j < n; ++j) { + size[0][j] = A[0][j] - '0'; + max_size = max(max_size, size[0][j]); + } + for (int i = 1; i < m; ++i) { + size[i % 2][0] = A[i][0] - '0'; + for (int j = 1; j < n; ++j) { + if (A[i][j] == '1') { + size[i % 2][j] = min(size[i % 2][j - 1], + min(size[(i - 1) % 2][j], + size[(i - 1) % 2][j - 1])) + 1; + max_size = max(max_size, size[i % 2][j]); + } else { + size[i % 2][j] = 0; + } + } + } + return max_size * max_size; + } }; -class Solution { +// Time: O(n^2) +// Space: O(n^2) +// DP. +class Solution2 { +public: + int maximalSquare(vector>& A) { + if (A.empty()) { + return 0; + } + const int m = A.size(), n = A[0].size(); + vector> size(m, vector(n, 0)); + int max_size = 0; + + for (int j = 0; j < n; ++j) { + size[0][j] = A[0][j] - '0'; + max_size = max(max_size, size[0][j]); + } + for (int i = 1; i < m; ++i) { + size[i][0] = A[i][0] - '0'; + for (int j = 1; j < n; ++j) { + if (A[i][j] == '1') { + size[i][j] = min(size[i][j - 1], + min(size[i - 1][j], + size[i - 1][j - 1])) + 1; + max_size = max(max_size, size[i][j]); + } else { + size[i][j] = 0; + } + } + } + return max_size * max_size; + } +}; + +// Time: O(n^2) +// Space: O(n^2) +// DP. +class Solution3 { public: + struct MaxHW { + int h, w; + }; + int maximalSquare(vector>& A) { if (A.empty()) { return 0; From d05ce66b8317c8a95a01e4d05a8f17d05d0d551b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Jun 2015 00:06:52 +0800 Subject: [PATCH 0355/1939] Update maximal-square.py --- Python/maximal-square.py | 75 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/Python/maximal-square.py b/Python/maximal-square.py index a9065ef90..2f95f9b99 100644 --- a/Python/maximal-square.py +++ b/Python/maximal-square.py @@ -1,5 +1,5 @@ # Time: O(n^2) -# Space: O(n^2) +# Space: O(n) # # Given a 2D binary matrix filled with 0's and 1's, # find the largest square containing all 1's and return its area. @@ -13,7 +13,80 @@ # Return 4. # +# DP with sliding window. class Solution: + # @param {character[][]} matrix + # @return {integer} + def maximalSquare(self, matrix): + if not matrix: + return 0 + + m, n = len(matrix), len(matrix[0]) + size = [[0 for j in xrange(n)] for i in xrange(2)] + max_size = 0 + + for j in xrange(n): + if matrix[0][j] == '1': + size[0][j] = 1 + max_size = max(max_size, size[0][j]) + + for i in xrange(1, m): + if matrix[i][0] == '1': + size[i % 2][0] = 1 + else: + size[i % 2][0] = 0 + for j in xrange(1, n): + if matrix[i][j] == '1': + size[i % 2][j] = min(size[i % 2][j - 1], \ + size[(i - 1) % 2][j], \ + size[(i - 1) % 2][j - 1]) + 1 + max_size = max(max_size, size[i % 2][j]) + else: + size[i % 2][j] = 0 + + return max_size * max_size + + +# Time: O(n^2) +# Space: O(n^2) +# DP. +class Solution2: + # @param {character[][]} matrix + # @return {integer} + def maximalSquare(self, matrix): + if not matrix: + return 0 + + m, n = len(matrix), len(matrix[0]) + size = [[0 for j in xrange(n)] for i in xrange(m)] + max_size = 0 + + for j in xrange(n): + if matrix[0][j] == '1': + size[0][j] = 1 + max_size = max(max_size, size[0][j]) + + for i in xrange(1, m): + if matrix[i][0] == '1': + size[i][0] = 1 + else: + size[i][0] = 0 + for j in xrange(1, n): + if matrix[i][j] == '1': + size[i][j] = min(size[i][j - 1], \ + size[i - 1][j], \ + size[i - 1][j - 1]) + 1 + max_size = max(max_size, size[i][j]) + else: + size[i][j] = 0 + + return max_size * max_size + + +# Time: O(n^2) +# Space: O(n^2) +# DP. +class Solution3: # @param {character[][]} matrix # @return {integer} def maximalSquare(self, matrix): From 75d4a67a811c25a71e20b7e8b4cbf9272ea92458 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Jun 2015 00:07:35 +0800 Subject: [PATCH 0356/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4b59e22ea..623baab79 100644 --- a/README.md +++ b/README.md @@ -353,7 +353,7 @@ Shell 188| [Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || 198| [House Robber](https://leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || 213| [House Robber II](https://leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || -221| [Maximal Square](https://leetcode.com/problems/maximal-square/)| [C++](./C++/maximal-square.cpp) [Python](./Python/maximal-square.py) | _O(n^2)_ | _O(n^2)_ | Medium | EPI | +221| [Maximal Square](https://leetcode.com/problems/maximal-square/)| [C++](./C++/maximal-square.cpp) [Python](./Python/maximal-square.py) | _O(n^2)_ | _O(n)_ | Medium | EPI | --- From fde87b16ea2945ea267703e9694f80071563770d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 5 Jun 2015 13:08:15 +0800 Subject: [PATCH 0357/1939] Update word-ladder-ii.py --- Python/word-ladder-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-ladder-ii.py b/Python/word-ladder-ii.py index 8d47c5806..b7ffb1180 100644 --- a/Python/word-ladder-ii.py +++ b/Python/word-ladder-ii.py @@ -37,7 +37,7 @@ def findLadders(self, start, end, dict): for word in cur: visited.add(word) - next = set([]) + next = set() for word in cur: for i in xrange(len(word)): for j in 'abcdefghijklmnopqrstuvwxyz': From caf14333850c0a2ac8c873e5833ff9c8171865cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 Jun 2015 16:40:36 +0800 Subject: [PATCH 0358/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 623baab79..9bd27ce74 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-03), there are `205` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-06), there are `206` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `221` problems. +Here is the classification of all `222` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) From 4821425d88997cea7c3eae9c602a13a3660fa443 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jun 2015 09:25:16 +0800 Subject: [PATCH 0359/1939] Create count-complete-tree-nodes.cpp --- C++/count-complete-tree-nodes.cpp | 59 +++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/count-complete-tree-nodes.cpp diff --git a/C++/count-complete-tree-nodes.cpp b/C++/count-complete-tree-nodes.cpp new file mode 100644 index 000000000..d1a4e1bd3 --- /dev/null +++ b/C++/count-complete-tree-nodes.cpp @@ -0,0 +1,59 @@ +// Time: O(h * logn) = O((logn)^2) +// Space: O(1) + +/** + * 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: + int countNodes(TreeNode* root) { + if (root == nullptr) { + return 0; + } + + TreeNode *p = root; + int level = 0; + while (p->left != nullptr) { + p = p->left; + ++level; + } + + // Binary search. + int left = pow(2, level), right = pow(2, level + 1); + while (left < right) { + int mid = left + (right - left) / 2; + if (!exist(root, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left - 1; + } + + // Check if the nth node exist. + bool exist(TreeNode *root, int n ){ + int k = 1; + while (k <= n) { + k <<= 1; + } + k >>= 2; + + TreeNode *p = root; + while (k > 0) { + if ((n & k) == 0) { + p = p->left; + } else { + p = p->right; + } + k >>= 1; + } + return p != nullptr; + } +}; From 8a17dab805d8bc81db2649e6506019a7c18fbb4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jun 2015 09:26:23 +0800 Subject: [PATCH 0360/1939] Update count-complete-tree-nodes.cpp --- C++/count-complete-tree-nodes.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/count-complete-tree-nodes.cpp b/C++/count-complete-tree-nodes.cpp index d1a4e1bd3..b0027289b 100644 --- a/C++/count-complete-tree-nodes.cpp +++ b/C++/count-complete-tree-nodes.cpp @@ -45,15 +45,15 @@ class Solution { } k >>= 2; - TreeNode *p = root; + TreeNode *node = root; while (k > 0) { if ((n & k) == 0) { - p = p->left; + node = node->left; } else { - p = p->right; + node = node->right; } k >>= 1; } - return p != nullptr; + return node != nullptr; } }; From f8a0138e0befe614c7391fe83ed92800bf412307 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jun 2015 09:26:48 +0800 Subject: [PATCH 0361/1939] Update count-complete-tree-nodes.cpp --- C++/count-complete-tree-nodes.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/count-complete-tree-nodes.cpp b/C++/count-complete-tree-nodes.cpp index b0027289b..d2b8ed029 100644 --- a/C++/count-complete-tree-nodes.cpp +++ b/C++/count-complete-tree-nodes.cpp @@ -16,14 +16,14 @@ class Solution { if (root == nullptr) { return 0; } - + TreeNode *p = root; int level = 0; while (p->left != nullptr) { p = p->left; ++level; } - + // Binary search. int left = pow(2, level), right = pow(2, level + 1); while (left < right) { @@ -36,7 +36,7 @@ class Solution { } return left - 1; } - + // Check if the nth node exist. bool exist(TreeNode *root, int n ){ int k = 1; @@ -44,7 +44,7 @@ class Solution { k <<= 1; } k >>= 2; - + TreeNode *node = root; while (k > 0) { if ((n & k) == 0) { From 762b2a980ada1ab38fa98466b058c71eab0d532c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jun 2015 09:28:54 +0800 Subject: [PATCH 0362/1939] Update count-complete-tree-nodes.cpp --- C++/count-complete-tree-nodes.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/count-complete-tree-nodes.cpp b/C++/count-complete-tree-nodes.cpp index d2b8ed029..2d82e65ac 100644 --- a/C++/count-complete-tree-nodes.cpp +++ b/C++/count-complete-tree-nodes.cpp @@ -17,10 +17,10 @@ class Solution { return 0; } - TreeNode *p = root; + TreeNode *node = root; int level = 0; - while (p->left != nullptr) { - p = p->left; + while (node->left != nullptr) { + node = node->left; ++level; } From 5ee74183ebde4656e31ff86bb8bf516130fc0c26 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jun 2015 09:31:35 +0800 Subject: [PATCH 0363/1939] Update count-complete-tree-nodes.cpp --- C++/count-complete-tree-nodes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-complete-tree-nodes.cpp b/C++/count-complete-tree-nodes.cpp index 2d82e65ac..eae170443 100644 --- a/C++/count-complete-tree-nodes.cpp +++ b/C++/count-complete-tree-nodes.cpp @@ -38,7 +38,7 @@ class Solution { } // Check if the nth node exist. - bool exist(TreeNode *root, int n ){ + bool exist(TreeNode *root, int n ) { int k = 1; while (k <= n) { k <<= 1; From 383c4c15b33e080eb0c643b5fdc9ff07fec6f74e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jun 2015 09:31:58 +0800 Subject: [PATCH 0364/1939] Update count-complete-tree-nodes.cpp --- C++/count-complete-tree-nodes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-complete-tree-nodes.cpp b/C++/count-complete-tree-nodes.cpp index eae170443..ec755d366 100644 --- a/C++/count-complete-tree-nodes.cpp +++ b/C++/count-complete-tree-nodes.cpp @@ -38,7 +38,7 @@ class Solution { } // Check if the nth node exist. - bool exist(TreeNode *root, int n ) { + bool exist(TreeNode *root, int n) { int k = 1; while (k <= n) { k <<= 1; From 34d030d89456dba1b67ba03ec058cbf97bd719a9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jun 2015 09:38:04 +0800 Subject: [PATCH 0365/1939] Create count-complete-tree-nodes.py --- Python/count-complete-tree-nodes.py | 56 +++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/count-complete-tree-nodes.py diff --git a/Python/count-complete-tree-nodes.py b/Python/count-complete-tree-nodes.py new file mode 100644 index 000000000..24695387b --- /dev/null +++ b/Python/count-complete-tree-nodes.py @@ -0,0 +1,56 @@ +# Time: O(h * logn) = O((logn)^2) +# Space: O(1) + +# Given a complete binary tree, count the number of nodes. +# +# In a complete binary tree every level, except possibly the last, +# is completely filled, and all nodes in the last level are as far +# left as possible. It can have between 1 and 2h nodes inclusive at +# the last level h. +# + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param {TreeNode} root + # @return {integer} + def countNodes(self, root): + if root is None: + return 0 + + node, level = root, 0 + while node.left is not None: + node = node.left + level += 1 + + # Binary search. + left, right = 2 ** level, 2 ** (level + 1) + while left < right: + mid = left + (right - left) / 2 + if not self.exist(root, mid): + right = mid + else: + left = mid + 1 + + return left - 1 + + # Check if the nth node exist. + def exist(self, root, n): + k = 1 + while k <= n: + k <<= 1 + k >>= 2 + + node = root + while k > 0: + if (n & k) == 0: + node = node.left + else: + node = node.right + k >>= 1 + return node is not None From 7e2c093dcc359b768866f4cb9ec50026c5a11e66 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jun 2015 09:39:30 +0800 Subject: [PATCH 0366/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9bd27ce74..71a89bad3 100644 --- a/README.md +++ b/README.md @@ -282,6 +282,7 @@ Shell 153| [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || 154| [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || 162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || +222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || -- ##Binary Search Tree From 76d3abcba59719d0edd236895aa7bd6ff735f5bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jun 2015 09:40:32 +0800 Subject: [PATCH 0367/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 71a89bad3..8525d10e0 100644 --- a/README.md +++ b/README.md @@ -282,7 +282,7 @@ Shell 153| [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || 154| [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || 162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || -222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || +222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./Python/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || -- ##Binary Search Tree From 4213ad9ba91832b1bac37c1520fa59a84986442c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Jun 2015 01:50:39 +0800 Subject: [PATCH 0368/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8525d10e0..ff59502c7 100644 --- a/README.md +++ b/README.md @@ -282,7 +282,7 @@ Shell 153| [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || 154| [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || 162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || -222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./Python/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || +222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./C++/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || -- ##Binary Search Tree From 9c0bc0cb7250e0e789382fb10edc182d39b70ab4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Jun 2015 14:05:43 +0800 Subject: [PATCH 0369/1939] Create rectangle-area.py --- Python/rectangle-area.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Python/rectangle-area.py diff --git a/Python/rectangle-area.py b/Python/rectangle-area.py new file mode 100644 index 000000000..52b879654 --- /dev/null +++ b/Python/rectangle-area.py @@ -0,0 +1,28 @@ +# Time: O(1) +# Space: O(1) +# +# Find the total area covered by two rectilinear rectangles in a 2D plane. +# +# Each rectangle is defined by its bottom left corner +# and top right corner as shown in the figure. +# +# Rectangle Area +# Assume that the total area is never beyond the maximum +# possible value of int. +# + +class Solution: + # @param {integer} A + # @param {integer} B + # @param {integer} C + # @param {integer} D + # @param {integer} E + # @param {integer} F + # @param {integer} G + # @param {integer} H + # @return {integer} + def computeArea(self, A, B, C, D, E, F, G, H): + return (D - B) * (C - A) + \ + (G - E) * (H - F) - \ + max(0, (min(C, G) - max(A, E))) * \ + max(0, (min(D, H) - max(B, F))) From f5de229d47bf561f4a8668215e8cd44d4f6dc0ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Jun 2015 14:07:15 +0800 Subject: [PATCH 0370/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ff59502c7..6b4ef7d66 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-06), there are `206` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-08), there are `207` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `222` problems. +Here is the classification of all `223` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -205,6 +205,7 @@ Shell 168| [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || 171| [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || 172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || +223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || --- From c8c389e4ebec0031a791038666e19e17bdab118c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Jun 2015 15:01:05 +0800 Subject: [PATCH 0371/1939] Create rectangle-area.cpp --- C++/rectangle-area.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 C++/rectangle-area.cpp diff --git a/C++/rectangle-area.cpp b/C++/rectangle-area.cpp new file mode 100644 index 000000000..5f30c95ea --- /dev/null +++ b/C++/rectangle-area.cpp @@ -0,0 +1,12 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { + return (D - B) * (C - A) + + (G - E) * (H - F) - + max(0, (min(C, G) - max(A, E))) * + max(0, (min(D, H) - max(B, F))); + } +}; From 00206d420e675e02bab417d799bc44acf328164b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Jun 2015 15:03:22 +0800 Subject: [PATCH 0372/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6b4ef7d66..deb743716 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,7 @@ Shell 168| [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || 171| [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || 172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || -223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || +223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C++](./C++/rectangle-area.cpp) [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || --- From f20f4434a0bce76eaca105e7047d08f92bbbc4d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jun 2015 11:30:24 +0800 Subject: [PATCH 0373/1939] Update house-robber-ii.cpp --- C++/house-robber-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/house-robber-ii.cpp b/C++/house-robber-ii.cpp index 5050a55f2..5bb26728c 100644 --- a/C++/house-robber-ii.cpp +++ b/C++/house-robber-ii.cpp @@ -10,11 +10,11 @@ class Solution { if (nums.size() == 1) { return nums[0]; } - + return max(robRange(nums, 0, nums.size() - 1), // Include the first one of nums without the last one. robRange(nums, 1, nums.size())); // Include the last one of nums without the first one. } - + int robRange(vector& nums, int start, int end) { int num_i = nums[start], num_i_1 = 0, num_i_2 = 0; for (int i = start + 1; i < end; ++i) { From 171fd7dfc2fb74204d09feb08a59a770607db325 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jun 2015 11:31:31 +0800 Subject: [PATCH 0374/1939] Update maximal-square.cpp --- C++/maximal-square.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/maximal-square.cpp b/C++/maximal-square.cpp index e75821269..8fdafb1a0 100644 --- a/C++/maximal-square.cpp +++ b/C++/maximal-square.cpp @@ -11,7 +11,7 @@ class Solution { const int m = A.size(), n = A[0].size(); vector> size(2, vector(n, 0)); int max_size = 0; - + for (int j = 0; j < n; ++j) { size[0][j] = A[0][j] - '0'; max_size = max(max_size, size[0][j]); @@ -45,7 +45,7 @@ class Solution2 { const int m = A.size(), n = A[0].size(); vector> size(m, vector(n, 0)); int max_size = 0; - + for (int j = 0; j < n; ++j) { size[0][j] = A[0][j] - '0'; max_size = max(max_size, size[0][j]); @@ -75,12 +75,12 @@ class Solution3 { struct MaxHW { int h, w; }; - + int maximalSquare(vector>& A) { if (A.empty()) { return 0; } - + // DP table stores (h, w) for each (i, j). vector> table(A.size(), vector(A.front().size())); for (int i = A.size() - 1; i >= 0; --i) { @@ -93,7 +93,7 @@ class Solution3 { : MaxHW{0, 0}; } } - + // A table stores the length of largest square for each (i, j). vector> s(A.size(), vector(A.front().size(), 0)); int max_square_area = 0; From ec1391d7e48e1af79b7eec7636430bba2758b7f4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jun 2015 14:26:19 +0800 Subject: [PATCH 0375/1939] Update next-permutation.py --- Python/next-permutation.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Python/next-permutation.py b/Python/next-permutation.py index 6af93140a..9da66f2e8 100644 --- a/Python/next-permutation.py +++ b/Python/next-permutation.py @@ -14,23 +14,29 @@ # class Solution: + # @param {integer[]} nums + # @return {void} Do not return anything, modify nums in-place instead. + def nextPermutation(self, num): + num = self.nextPermutation2(num) + # @param num, a list of integer # @return a list of integer - def nextPermutation(self, num): + def nextPermutation2(self, num): k, l = -1, 0 for i in xrange(len(num) - 1): if num[i] < num[i + 1]: k = i if k == -1: - return num[::-1] + num.reverse() + return for i in xrange(len(num)): if num[i] > num[k]: l = i num[k], num[l] = num[l], num[k] - return num[:k + 1] + num[:k:-1] + num[k + 1:] = num[:k:-1] if __name__ == "__main__": num = [1, 4, 3, 2] @@ -39,4 +45,4 @@ def nextPermutation(self, num): num = Solution().nextPermutation(num) print num num = Solution().nextPermutation(num) - print num \ No newline at end of file + print num From 9097479db1824b03ad9542669272a163be2f19fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jun 2015 14:27:11 +0800 Subject: [PATCH 0376/1939] Update next-permutation.py --- Python/next-permutation.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Python/next-permutation.py b/Python/next-permutation.py index 9da66f2e8..5dbe28944 100644 --- a/Python/next-permutation.py +++ b/Python/next-permutation.py @@ -17,11 +17,6 @@ class Solution: # @param {integer[]} nums # @return {void} Do not return anything, modify nums in-place instead. def nextPermutation(self, num): - num = self.nextPermutation2(num) - - # @param num, a list of integer - # @return a list of integer - def nextPermutation2(self, num): k, l = -1, 0 for i in xrange(len(num) - 1): if num[i] < num[i + 1]: From ccc58838f28705817ad5a5fe701a9eade013838d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jun 2015 22:57:43 +0800 Subject: [PATCH 0377/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index deb743716..96350a10d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-08), there are `207` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-09), there are `208` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `223` problems. +Here is the classification of all `224` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -139,6 +139,7 @@ Shell 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || 155| [Min Stack](https://leetcode.com/problems/min-stack/) | [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || 173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || +224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./Python/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Medium || --- From 991c1266c01c1951533b9b844f1b4f16a159cfe1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jun 2015 22:58:47 +0800 Subject: [PATCH 0378/1939] Create basic-calculator.cpp --- C++/basic-calculator.cpp | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/basic-calculator.cpp diff --git a/C++/basic-calculator.cpp b/C++/basic-calculator.cpp new file mode 100644 index 000000000..3840bb4e7 --- /dev/null +++ b/C++/basic-calculator.cpp @@ -0,0 +1,46 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int calculate(string s) { + stack operands; + stack operators; + string operand; + for (int i = s.length() - 1; i >= 0; --i) { + if (isdigit(s[i])) { + operand.push_back(s[i]); + if (i == 0 || !isdigit(s[i - 1])) { + reverse(operand.begin(), operand.end()); + operands.emplace(stoi(operand)); + operand.clear(); + } + } else if (s[i] == ')' || s[i] == '+' || s[i] == '-') { + operators.emplace(s[i]); + } else if (s[i] == '(') { + while (operators.top() != ')') { + compute(operands, operators); + } + operators.pop(); + } + } + while (!operators.empty()) { + compute(operands, operators); + } + return operands.top(); + } + + void compute(stack& operands, stack& operators) { + const int left = operands.top(); + operands.pop(); + const int right = operands.top(); + operands.pop(); + const char op = operators.top(); + operators.pop(); + if (op == '+') { + operands.push(left + right); + } else if (op == '-') { + operands.push(left - right); + } + } +}; From cd001e7f04047104b5e5ba2097a915c9adca300d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jun 2015 23:11:20 +0800 Subject: [PATCH 0379/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 96350a10d..24290e6c5 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ Shell 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || 155| [Min Stack](https://leetcode.com/problems/min-stack/) | [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || 173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || -224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./Python/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Medium || +224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./C++/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Medium || --- From 11149d92cd83f1ffe961e3bb2ce27e0a7e9dd4ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jun 2015 23:59:19 +0800 Subject: [PATCH 0380/1939] Create basic-calculator.py --- Python/basic-calculator.py | 47 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/basic-calculator.py diff --git a/Python/basic-calculator.py b/Python/basic-calculator.py new file mode 100644 index 000000000..ea4ca3245 --- /dev/null +++ b/Python/basic-calculator.py @@ -0,0 +1,47 @@ +# Time: O(n) +# Space: O(n) +# +# Implement a basic calculator to evaluate a simple expression string. +# +# The expression string may contain open ( and closing parentheses ), +# the plus + or minus sign -, non-negative integers and empty spaces . +# +# You may assume that the given expression is always valid. +# +# Some examples: +# "1 + 1" = 2 +# " 2-1 + 2 " = 3 +# "(1+(4+5+2)-3)+(6+8)" = 23 +# + +class Solution: + # @param {string} s + # @return {integer} + def calculate(self, s): + operands, operators = [], [] + operand = "" + for i in reversed(xrange(len(s))): + if s[i].isdigit(): + operand += s[i] + if i == 0 or not s[i-1].isdigit(): + operands.append(int(operand[::-1])) + operand = "" + elif s[i] == ')' or s[i] == '+' or s[i] == '-': + operators.append(s[i]) + elif s[i] == '(': + while operators[-1] != ')': + self.compute(operands, operators) + operators.pop() + + while operators: + self.compute(operands, operators) + + return operands[-1] + + def compute(self, operands, operators): + left, right = operands.pop(), operands.pop() + op = operators.pop() + if op == '+': + operands.append(left + right) + elif op == '-': + operands.append(left - right) From b89cd968e279c74873981c39f3f5e1cb0ed829b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Jun 2015 00:19:55 +0800 Subject: [PATCH 0381/1939] Update next-permutation.py --- Python/next-permutation.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/next-permutation.py b/Python/next-permutation.py index 5dbe28944..f3aa730ba 100644 --- a/Python/next-permutation.py +++ b/Python/next-permutation.py @@ -35,9 +35,9 @@ def nextPermutation(self, num): if __name__ == "__main__": num = [1, 4, 3, 2] - num = Solution().nextPermutation(num) + Solution().nextPermutation(num) print num - num = Solution().nextPermutation(num) + Solution().nextPermutation(num) print num - num = Solution().nextPermutation(num) + Solution().nextPermutation(num) print num From 3d69d37e115526ff58eac571b84a6165425f3d32 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Jun 2015 01:49:09 +0800 Subject: [PATCH 0382/1939] Update basic-calculator.cpp --- C++/basic-calculator.cpp | 59 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/C++/basic-calculator.cpp b/C++/basic-calculator.cpp index 3840bb4e7..45a95ef56 100644 --- a/C++/basic-calculator.cpp +++ b/C++/basic-calculator.cpp @@ -2,6 +2,65 @@ // Space: O(n) class Solution { +public: + int calculate(string s) { + stack operands; + stack operators; + string operand; + for (int i = s.length() - 1; i >= 0; --i) { + if (isdigit(s[i])) { + operand.push_back(s[i]); + if (i == 0 || !isdigit(s[i - 1])) { + reverse(operand.begin(), operand.end()); + operands.emplace(stoi(operand)); + operand.clear(); + } + } else if (s[i] == ')' || s[i] == '*' || + s[i] == '/') { + operators.emplace(s[i]); + } else if (s[i] == '+' || s[i] == '-') { + while (!operators.empty() && (operators.top() == '*' || + operators.top() == '/')) { + compute(operands, operators); + } + operators.emplace(s[i]); + } else if (s[i] == '(') { + // operators at least one element, i.e. ')'. + while (operators.top() != ')') { + compute(operands, operators); + } + operators.pop(); + } + } + while (!operators.empty()) { + compute(operands, operators); + } + return operands.top(); + } + + void compute(stack& operands, stack& operators) { + const int left = operands.top(); + operands.pop(); + const int right = operands.top(); + operands.pop(); + const char op = operators.top(); + operators.pop(); + + if (op == '+') { + operands.push(left + right); + } else if (op == '-') { + operands.push(left - right); + } else if (op == '*') { + operands.push(left * right); + } else if (op == '/') { + operands.push(left / right); + } + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { public: int calculate(string s) { stack operands; From 0cefbfc39125f3e55b8b9fa4e08bcdf2f1d71ee9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Jun 2015 01:50:36 +0800 Subject: [PATCH 0383/1939] Update basic-calculator.cpp --- C++/basic-calculator.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/basic-calculator.cpp b/C++/basic-calculator.cpp index 45a95ef56..9c535a94c 100644 --- a/C++/basic-calculator.cpp +++ b/C++/basic-calculator.cpp @@ -45,7 +45,6 @@ class Solution { operands.pop(); const char op = operators.top(); operators.pop(); - if (op == '+') { operands.push(left + right); } else if (op == '-') { From 0a994502d569226495240ef1d079db3434480daf Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Jun 2015 02:29:18 +0800 Subject: [PATCH 0384/1939] Update basic-calculator.cpp --- C++/basic-calculator.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/C++/basic-calculator.cpp b/C++/basic-calculator.cpp index 9c535a94c..01a04722b 100644 --- a/C++/basic-calculator.cpp +++ b/C++/basic-calculator.cpp @@ -1,6 +1,7 @@ // Time: O(n) // Space: O(n) +// Support +, -, *, /. class Solution { public: int calculate(string s) { @@ -59,6 +60,7 @@ class Solution { // Time: O(n) // Space: O(n) +// Only support +, -. class Solution2 { public: int calculate(string s) { From 7c167494c84cb4c79e8c8eb43e014e5036501932 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 21:03:56 +0800 Subject: [PATCH 0385/1939] Create implement-stack-using-queues.cpp --- C++/implement-stack-using-queues.cpp | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/implement-stack-using-queues.cpp diff --git a/C++/implement-stack-using-queues.cpp b/C++/implement-stack-using-queues.cpp new file mode 100644 index 000000000..5b6d4af2e --- /dev/null +++ b/C++/implement-stack-using-queues.cpp @@ -0,0 +1,32 @@ +// Time: push: O(n), pop: O(1), top: O(1) +// Space: O(n) + +class Stack { +public: + queue q; + + // Push element x onto stack. + void push(int x) { + int n = q.size(); + q.emplace(x); + for (; n > 0; --n) { + q.emplace(q.front()); + q.pop(); + } + } + + // Removes the element on top of the stack. + void pop() { + q.pop(); + } + + // Get the top element. + int top() { + return q.front(); + } + + // Return whether the stack is empty. + bool empty() { + return q.empty(); + } +}; From 2fc8172e13907b7dcbdd68320f402a4a10bc63bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 21:17:39 +0800 Subject: [PATCH 0386/1939] Update implement-stack-using-queues.cpp --- C++/implement-stack-using-queues.cpp | 46 +++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/C++/implement-stack-using-queues.cpp b/C++/implement-stack-using-queues.cpp index 5b6d4af2e..6fbb763d5 100644 --- a/C++/implement-stack-using-queues.cpp +++ b/C++/implement-stack-using-queues.cpp @@ -6,7 +6,7 @@ class Stack { queue q; // Push element x onto stack. - void push(int x) { + void push(int x) { // O(n) int n = q.size(); q.emplace(x); for (; n > 0; --n) { @@ -16,17 +16,55 @@ class Stack { } // Removes the element on top of the stack. - void pop() { + void pop() { // O(1) q.pop(); } // Get the top element. - int top() { + int top() { // O(1) return q.front(); } // Return whether the stack is empty. - bool empty() { + bool empty() { // O(1) + return q.empty(); + } +}; + +// Time: push: O(1), pop: O(n), top: O(n) +// Space: O(n) +class Stack2 { +public: + queue q, q2; + + // Push element x onto stack. + void push(int x) { // O(1) + q.emplace(x); + } + + // Removes the element on top of the stack. + void pop() { // O(n) + for (int i = 0; i < q.size() - 1; ++i) { + q.emplace(q.front()); + q.pop(); + } + q.pop(); + } + + // Get the top element. + int top() { // O(n) + for (int i = 0; i < q.size() - 1; ++i) { + q.emplace(q.front()); + q.pop(); + } + int top = q.front(); + q.emplace(q.front()); + q.pop(); + return top; + } + + // Return whether the stack is empty. + bool empty() { // O(1) return q.empty(); } }; From 39cd134d330bd61cbe15e879262836acb1418970 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 21:19:16 +0800 Subject: [PATCH 0387/1939] Update implement-stack-using-queues.cpp --- C++/implement-stack-using-queues.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/implement-stack-using-queues.cpp b/C++/implement-stack-using-queues.cpp index 6fbb763d5..35daf8316 100644 --- a/C++/implement-stack-using-queues.cpp +++ b/C++/implement-stack-using-queues.cpp @@ -7,9 +7,8 @@ class Stack { // Push element x onto stack. void push(int x) { // O(n) - int n = q.size(); q.emplace(x); - for (; n > 0; --n) { + for (int i = 0; i < q.size() - 1; ++i) { q.emplace(q.front()); q.pop(); } From 34cff13a1188a0330e04e1e82fa7a93c4c6dea75 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 21:27:28 +0800 Subject: [PATCH 0388/1939] Update implement-stack-using-queues.cpp --- C++/implement-stack-using-queues.cpp | 47 +++++++++++++--------------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/C++/implement-stack-using-queues.cpp b/C++/implement-stack-using-queues.cpp index 35daf8316..a344f90e6 100644 --- a/C++/implement-stack-using-queues.cpp +++ b/C++/implement-stack-using-queues.cpp @@ -3,67 +3,64 @@ class Stack { public: - queue q; + queue q_; // Push element x onto stack. void push(int x) { // O(n) - q.emplace(x); - for (int i = 0; i < q.size() - 1; ++i) { - q.emplace(q.front()); - q.pop(); + q_.emplace(x); + for (int i = 0; i < q_.size() - 1; ++i) { + q_.emplace(q_.front()); + q_.pop(); } } // Removes the element on top of the stack. void pop() { // O(1) - q.pop(); + q_.pop(); } // Get the top element. int top() { // O(1) - return q.front(); + return q_.front(); } // Return whether the stack is empty. bool empty() { // O(1) - return q.empty(); + return q_.empty(); } }; -// Time: push: O(1), pop: O(n), top: O(n) +// Time: push: O(1), pop: O(n), top: O(1) // Space: O(n) class Stack2 { public: - queue q, q2; + queue q_; + int top_; // Push element x onto stack. void push(int x) { // O(1) - q.emplace(x); + q_.emplace(x); + top_ = x; } // Removes the element on top of the stack. void pop() { // O(n) - for (int i = 0; i < q.size() - 1; ++i) { - q.emplace(q.front()); - q.pop(); + for (int i = 0; i < q_.size() - 1; ++i) { + top_ = q_.front(); + q_.emplace(top_); + q_.pop(); } - q.pop(); + q_.pop(); } // Get the top element. - int top() { // O(n) - for (int i = 0; i < q.size() - 1; ++i) { - q.emplace(q.front()); - q.pop(); - } - int top = q.front(); - q.emplace(q.front()); - q.pop(); - return top; + int top() { // O(1) + return top_; } // Return whether the stack is empty. bool empty() { // O(1) - return q.empty(); + return q_.empty(); } }; + From 7338b2e05232c86146b3ab078dd90718da0f0ce5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 22:03:07 +0800 Subject: [PATCH 0389/1939] Create implement-stack-using-queues.py --- Python/implement-stack-using-queues.py | 64 ++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Python/implement-stack-using-queues.py diff --git a/Python/implement-stack-using-queues.py b/Python/implement-stack-using-queues.py new file mode 100644 index 000000000..6ad144f38 --- /dev/null +++ b/Python/implement-stack-using-queues.py @@ -0,0 +1,64 @@ +# Time: push: O(n), pop: O(1), top: O(1) +# Space: O(1) +# +# Implement the following operations of a stack using queues. +# +# push(x) -- Push element x onto stack. +# pop() -- Removes the element on top of the stack. +# top() -- Get the top element. +# empty() -- Return whether the stack is empty. +# Notes: +# You must use only standard operations of a queue -- which +# means only push to back, peek/pop from front, size, and is +# empty operations are valid. +# Depending on your language, queue may not be supported natively. +# You may simulate a queue by using a list or deque (double-ended +# queue), as long as you use only standard operations of a queue. +# You may assume that all operations are valid (for example, no pop +# or top operations will be called on an empty stack). +# + +class Queue: + def __init__(self): + self.data = collections.deque() + + def push(self, x): + self.data.append(x) + + def peek(self): + return self.data[0] + + def pop(self): + return self.data.popleft() + + def size(self): + return len(self.data) + + def empty(self): + return len(self.data) == 0 + + +class Stack: + # initialize your data structure here. + def __init__(self): + self.q = Queue() + + # @param x, an integer + # @return nothing + def push(self, x): + q = self.q + q.push(x) + for _ in xrange(q.size() - 1): + q.push(q.pop()) + + # @return nothing + def pop(self): + self.q.pop() + + # @return an integer + def top(self): + return self.q.peek() + + # @return an boolean + def empty(self): + return self.q.empty() From 2dfdd5e7c7ed8bcbb209115b03f32216410f27b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 22:12:00 +0800 Subject: [PATCH 0390/1939] Update implement-stack-using-queues.py --- Python/implement-stack-using-queues.py | 46 +++++++++++++++++++++----- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/Python/implement-stack-using-queues.py b/Python/implement-stack-using-queues.py index 6ad144f38..0fb65ebc2 100644 --- a/Python/implement-stack-using-queues.py +++ b/Python/implement-stack-using-queues.py @@ -1,5 +1,5 @@ # Time: push: O(n), pop: O(1), top: O(1) -# Space: O(1) +# Space: O(n) # # Implement the following operations of a stack using queues. # @@ -41,24 +41,52 @@ def empty(self): class Stack: # initialize your data structure here. def __init__(self): - self.q = Queue() + self.q_ = Queue() # @param x, an integer # @return nothing def push(self, x): - q = self.q - q.push(x) - for _ in xrange(q.size() - 1): - q.push(q.pop()) + self.q_.push(x) + for _ in xrange(self.q_.size() - 1): + self.q_.push(self.q_.pop()) # @return nothing def pop(self): - self.q.pop() + self.q_.pop() # @return an integer def top(self): - return self.q.peek() + return self.q_.peek() # @return an boolean def empty(self): - return self.q.empty() + return self.q_.empty() + +# Time: push: O(1), pop: O(n), top: O(1) +# Space: O(n) +class Stack2: + # initialize your data structure here. + def __init__(self): + self.q_ = Queue() + self.top_ = None + + # @param x, an integer + # @return nothing + def push(self, x): + self.q_.push(x) + self.top_ = x + + # @return nothing + def pop(self): + for _ in xrange(self.q_.size() - 1): + self.top_ = self.q_.pop() + self.q_.push(self.top_) + self.q_.pop() + + # @return an integer + def top(self): + return self.top_ + + # @return an boolean + def empty(self): + return self.q_.empty() From 40cbc19c8af7af59a5bf437b2332e6471648366b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 22:15:04 +0800 Subject: [PATCH 0391/1939] Update implement-stack-using-queues.py --- Python/implement-stack-using-queues.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/implement-stack-using-queues.py b/Python/implement-stack-using-queues.py index 0fb65ebc2..05ec228d6 100644 --- a/Python/implement-stack-using-queues.py +++ b/Python/implement-stack-using-queues.py @@ -62,6 +62,7 @@ def top(self): def empty(self): return self.q_.empty() + # Time: push: O(1), pop: O(n), top: O(1) # Space: O(n) class Stack2: From 634d69fb05f34abd6dc03fcc4547a0ce00615ef1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 22:20:01 +0800 Subject: [PATCH 0392/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 24290e6c5..ed205541b 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-09), there are `208` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-11), there are `209` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `224` problems. +Here is the classification of all `225` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -188,6 +188,7 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || +225| [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | [Python](./Python/implement-stack-using-queues.py) | Push: _O(n)_, Pop: _O(1)_, Top: _O(1)_ | _O(n)_ | Medium || --- From 3bbe47107f2ac97ef470148f694e1a3680480d05 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 22:21:18 +0800 Subject: [PATCH 0393/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ed205541b..a384be072 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || -225| [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | [Python](./Python/implement-stack-using-queues.py) | Push: _O(n)_, Pop: _O(1)_, Top: _O(1)_ | _O(n)_ | Medium || +225| [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | [C++](./C++/implement-stack-using-queues.cpp) [Python](./Python/implement-stack-using-queues.py) | Push: _O(n)_, Pop: _O(1)_, Top: _O(1)_ | _O(n)_ | Medium || --- From c69a774b22c865583d184d6415316e1d46fdefd3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 23:32:22 +0800 Subject: [PATCH 0394/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 55cb51376..ba4950638 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -22,9 +22,9 @@ class Solution { map height_to_count; // BST. int curr_max = 0; // Enumerate each point in increasing order. - for (auto& kvp : point_to_height) { - auto& point = kvp.first; - auto& heights = kvp.second; + for (const auto& kvp : point_to_height) { + const auto& point = kvp.first; + const auto& heights = kvp.second; for (const auto& h : heights) { if (h.isStart) { From 6bae284fd358815af4d38d521394036ebb734359 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jun 2015 23:36:49 +0800 Subject: [PATCH 0395/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index ba4950638..3a1ff1142 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -37,8 +37,10 @@ class Solution { } } - if (height_to_count.empty() || curr_max != height_to_count.crbegin()->first) { - curr_max = height_to_count.empty() ? 0 : height_to_count.crbegin()->first; + if (height_to_count.empty() || + curr_max != height_to_count.crbegin()->first) { + curr_max = height_to_count.empty() ? + 0 : height_to_count.crbegin()->first; res.emplace_back(point, curr_max); } } From d7edc9dfddc371112a7249fae20c2007b19a0f0b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Jun 2015 10:29:48 +0800 Subject: [PATCH 0396/1939] Update max-points-on-a-line.py --- Python/max-points-on-a-line.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/max-points-on-a-line.py b/Python/max-points-on-a-line.py index cf47fa2ac..21573af9e 100644 --- a/Python/max-points-on-a-line.py +++ b/Python/max-points-on-a-line.py @@ -17,7 +17,7 @@ def maxPoints(self, points): max_points = 0 for i, start in enumerate(points): slope_count, same, current_max = {}, 1, 0 - for j in range(i + 1, len(points)): + for j in xrange(i + 1, len(points)): end = points[j] if start.x == end.x and start.y == end.y: same += 1 From abb51e8fbf8aefecd03bc5ae281b5840e9e2bfd2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Jun 2015 21:44:32 +0800 Subject: [PATCH 0397/1939] Create invert-binary-tree.cpp --- C++/invert-binary-tree.cpp | 78 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 C++/invert-binary-tree.cpp diff --git a/C++/invert-binary-tree.cpp b/C++/invert-binary-tree.cpp new file mode 100644 index 000000000..8c11f1449 --- /dev/null +++ b/C++/invert-binary-tree.cpp @@ -0,0 +1,78 @@ +// Time: O(n) +// Space: O(h) + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +// Time: O(n) +// Space: O(w), w is the max number of nodes of the levels. +// BFS solution +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if (root != nullptr) { + queue nodes; + nodes.emplace(root); + while (!nodes.empty()) { + auto node = nodes.front(); + nodes.pop(); + swap(node->left, node->right); + if (node->left != nullptr) { + nodes.emplace(node->left); + } + if (node->right != nullptr) { + nodes.emplace(node->right); + } + } + } + return root; + } +}; + +// Time: O(n) +// Space: O(h) +// Stack solution. +class Solution2 { +public: + TreeNode* invertTree(TreeNode* root) { + if (root != nullptr) { + stack nodes; + nodes.emplace(root); + while (!nodes.empty()) { + auto node = nodes.top(); + nodes.pop(); + swap(node->left, node->right); + if (node->left != nullptr) { + nodes.emplace(node->left); + } + if (node->right != nullptr) { + nodes.emplace(node->right); + } + } + } + return root; + } +}; + +// Time: O(n) +// Space: O(h) +// DFS, Recursive solution. +class Solution3 { +public: + TreeNode* invertTree(TreeNode* root) { + if (root != nullptr) { + TreeNode *left = root->left; + TreeNode *right = root->right; + root->left = invertTree(right); + root->right = invertTree(left); + } + return root; + } +}; From 5fa355cda5d9d3f6edbb88d627a96075d0f970c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Jun 2015 21:50:26 +0800 Subject: [PATCH 0398/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a384be072..88d82ed53 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-11), there are `209` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-12), there are `210` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `225` problems. +Here is the classification of all `226` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -160,6 +160,7 @@ Shell 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || --- From 0395b80e3eaf9cf793325d4bb5bec81c79b64f54 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Jun 2015 22:01:59 +0800 Subject: [PATCH 0399/1939] Create invert-binary-tree.py --- Python/invert-binary-tree.py | 97 ++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 Python/invert-binary-tree.py diff --git a/Python/invert-binary-tree.py b/Python/invert-binary-tree.py new file mode 100644 index 000000000..f92a761a3 --- /dev/null +++ b/Python/invert-binary-tree.py @@ -0,0 +1,97 @@ +# Time: O(n) +# Space: O(h) +# +# Invert a binary tree. +# +# 4 +# / \ +# 2 7 +# / \ / \ +# 1 3 6 9 +# to +# 4 +# / \ +# 7 2 +# / \ / \ +# 9 6 3 1 +# + +# Time: O(n) +# Space: O(w), w is the max number of the nodes of the levels. +# BFS solution. +class Queue: + def __init__(self): + self.data = collections.deque() + + def push(self, x): + self.data.append(x) + + def peek(self): + return self.data[0] + + def pop(self): + return self.data.popleft() + + def size(self): + return len(self.data) + + def empty(self): + return len(self.data) == 0 + + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param {TreeNode} root + # @return {TreeNode} + def invertTree(self, root): + if root is not None: + nodes = Queue() + nodes.push(root) + while not nodes.empty(): + node = nodes.pop() + node.left, node.right = node.right, node.left + if node.left is not None: + nodes.push(node.left) + if node.right is not None: + nodes.push(node.right) + + return root + +# Time: O(n) +# Space: O(h) +# Stack solution. +class Solution2: + # @param {TreeNode} root + # @return {TreeNode} + def invertTree(self, root): + if root is not None: + nodes = [] + nodes.append(root) + while nodes: + node = nodes.pop() + node.left, node.right = node.right, node.left + if node.left is not None: + nodes.append(node.left) + if node.right is not None: + nodes.append(node.right) + + return root + +# Time: O(n) +# Space: O(h) +# DFS, Recursive solution. +class Solution3: + # @param {TreeNode} root + # @return {TreeNode} + def invertTree(self, root): + if root is not None: + root.left, root.right = self.invertTree(root.right), \ + self.invertTree(root.left) + + return root From 38b5d62e56fa8a56137c9498ed8b7e8506902994 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Jun 2015 22:02:39 +0800 Subject: [PATCH 0400/1939] Update invert-binary-tree.py --- Python/invert-binary-tree.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/invert-binary-tree.py b/Python/invert-binary-tree.py index f92a761a3..d7d69b2eb 100644 --- a/Python/invert-binary-tree.py +++ b/Python/invert-binary-tree.py @@ -62,6 +62,7 @@ def invertTree(self, root): nodes.push(node.right) return root + # Time: O(n) # Space: O(h) @@ -82,6 +83,7 @@ def invertTree(self, root): nodes.append(node.right) return root + # Time: O(n) # Space: O(h) From a28ea1616b9385df822a5a092552c9b23005f16d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Jun 2015 22:11:36 +0800 Subject: [PATCH 0401/1939] Update invert-binary-tree.cpp --- C++/invert-binary-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/invert-binary-tree.cpp b/C++/invert-binary-tree.cpp index 8c11f1449..60ad7281a 100644 --- a/C++/invert-binary-tree.cpp +++ b/C++/invert-binary-tree.cpp @@ -13,7 +13,7 @@ // Time: O(n) // Space: O(w), w is the max number of nodes of the levels. -// BFS solution +// BFS solution. class Solution { public: TreeNode* invertTree(TreeNode* root) { From 2fa7f8e589fab8a622cbfd3589b54c7a263faed2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Jun 2015 22:47:17 +0800 Subject: [PATCH 0402/1939] Update max-points-on-a-line.py --- Python/max-points-on-a-line.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/max-points-on-a-line.py b/Python/max-points-on-a-line.py index 21573af9e..58bfcf73c 100644 --- a/Python/max-points-on-a-line.py +++ b/Python/max-points-on-a-line.py @@ -16,7 +16,7 @@ class Solution: def maxPoints(self, points): max_points = 0 for i, start in enumerate(points): - slope_count, same, current_max = {}, 1, 0 + slope_count, same = {}, 1 for j in xrange(i + 1, len(points)): end = points[j] if start.x == end.x and start.y == end.y: @@ -29,11 +29,12 @@ def maxPoints(self, points): slope_count[slope] = 1 else: slope_count[slope] += 1 - + + current_max = same for slope in slope_count: current_max = max(current_max, slope_count[slope] + same) - max_points = max(max_points, current_max, same) + max_points = max(max_points, current_max) return max_points From 1415295e00e9987df0870cc0212384cc34d7cdc6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Jun 2015 23:52:30 +0800 Subject: [PATCH 0403/1939] Update invert-binary-tree.cpp --- C++/invert-binary-tree.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/C++/invert-binary-tree.cpp b/C++/invert-binary-tree.cpp index 60ad7281a..f08fa7b42 100644 --- a/C++/invert-binary-tree.cpp +++ b/C++/invert-binary-tree.cpp @@ -68,10 +68,9 @@ class Solution3 { public: TreeNode* invertTree(TreeNode* root) { if (root != nullptr) { - TreeNode *left = root->left; - TreeNode *right = root->right; - root->left = invertTree(right); - root->right = invertTree(left); + swap(root->left, root->right); + invertTree(root->left); + invertTree(root->right); } return root; } From e6f631a9b2b7620d58ece28dff0bd0a38ceaa4ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Jun 2015 11:41:48 +0800 Subject: [PATCH 0404/1939] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index f43dada73..ba5f67df8 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -1,5 +1,16 @@ # Time: O(n) # Space: O(n) +# +# Given a string S, you are allowed to convert it to a palindrome +# by adding characters in front of it. Find and return the shortest +# palindrome you can find by performing this transformation. +# +# For example: +# +# Given "aacecaaa", return "aaacecaaa". +# +# Given "abcd", return "dcbabcd". +# # KMP Algorithm class Solution: @@ -25,6 +36,7 @@ def getPrefix(self, pattern): prefix[i] = j return prefix + # Manacher's Algorithm class Solution_TLE: # @param {string} s From a14c4ba695caf4bfd778a95316d957ec00b7931a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Jun 2015 11:49:14 +0800 Subject: [PATCH 0405/1939] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index 083c21e11..9747fbe42 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -9,11 +9,20 @@ class Solution { return s; } string rev_s(s.crbegin(), s.crend()); + // Assume s is (Palindrome)abc, + // A would be (Palindrome)abccba(Palindrome). string A = s + rev_s; vector pattern(move(getPrefix(A))); + // pattern.back() would be: + // (Palindrome)abc + // ^ + // pattern.back() + 1 would be: + // (Palindrome)abc + // ^ + // Get non palindrome part of s. string non_palindrome = s.substr(pattern.back() + 1); reverse(non_palindrome.begin(), non_palindrome.end()); - return non_palindrome + s; + return non_palindrome + s; // cba(Palindrome)abc. } private: @@ -69,7 +78,7 @@ class Solution2 { } } - // Assume s is (Palindrome)abc + // Assume s is (Palindrome)abc. string ans = s.substr(max_len); // abc. reverse(ans.begin(), ans.end()); // cba. ans.append(s); // cba(Palindrome)abc. From 186761fcf086ff230bc0eb395c4ba533d573d4dd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Jun 2015 11:53:51 +0800 Subject: [PATCH 0406/1939] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index 9747fbe42..e880be76a 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -12,15 +12,15 @@ class Solution { // Assume s is (Palindrome)abc, // A would be (Palindrome)abccba(Palindrome). string A = s + rev_s; - vector pattern(move(getPrefix(A))); - // pattern.back() would be: + vector prefix(move(getPrefix(A))); + // prefix.back() would be: // (Palindrome)abc // ^ - // pattern.back() + 1 would be: + // prefix.back() + 1 would be: // (Palindrome)abc // ^ // Get non palindrome part of s. - string non_palindrome = s.substr(pattern.back() + 1); + string non_palindrome = s.substr(prefix.back() + 1); reverse(non_palindrome.begin(), non_palindrome.end()); return non_palindrome + s; // cba(Palindrome)abc. } From fcd3103ce8ce63d734f70feec73b42f6cdb13170 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Jun 2015 12:03:40 +0800 Subject: [PATCH 0407/1939] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index e880be76a..afc4d142a 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -13,10 +13,10 @@ class Solution { // A would be (Palindrome)abccba(Palindrome). string A = s + rev_s; vector prefix(move(getPrefix(A))); - // prefix.back() would be: - // (Palindrome)abc + // prefix.back() of A would be: + // (Palindrome)abccba(Palindrome) // ^ - // prefix.back() + 1 would be: + // prefix.back() + 1 of s would be: // (Palindrome)abc // ^ // Get non palindrome part of s. From d4742bf821436b054bca4dec7d48aa74b077c7f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Jun 2015 12:10:44 +0800 Subject: [PATCH 0408/1939] Update invert-binary-tree.py --- Python/invert-binary-tree.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/Python/invert-binary-tree.py b/Python/invert-binary-tree.py index d7d69b2eb..5c62fd73f 100644 --- a/Python/invert-binary-tree.py +++ b/Python/invert-binary-tree.py @@ -38,7 +38,6 @@ def size(self): def empty(self): return len(self.data) == 0 - # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): @@ -62,7 +61,6 @@ def invertTree(self, root): nodes.push(node.right) return root - # Time: O(n) # Space: O(h) @@ -83,7 +81,6 @@ def invertTree(self, root): nodes.append(node.right) return root - # Time: O(n) # Space: O(h) From ebd6485c034fc69b5b1521f2f91b5763906fc016 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Jun 2015 14:25:40 +0800 Subject: [PATCH 0409/1939] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index afc4d142a..b8ef6f68c 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -13,10 +13,10 @@ class Solution { // A would be (Palindrome)abccba(Palindrome). string A = s + rev_s; vector prefix(move(getPrefix(A))); - // prefix.back() of A would be: + // The index prefix.back() of A would be: // (Palindrome)abccba(Palindrome) // ^ - // prefix.back() + 1 of s would be: + // The index prefix.back() + 1 of s would be: // (Palindrome)abc // ^ // Get non palindrome part of s. From debe1527911401abb8ac375412dff5aae9978157 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jun 2015 20:58:47 +0800 Subject: [PATCH 0410/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 88d82ed53..ff2d3b3ef 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-12), there are `210` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-23), there are `211` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `226` problems. +Here is the classification of all `227` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -139,7 +139,8 @@ Shell 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || 155| [Min Stack](https://leetcode.com/problems/min-stack/) | [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || 173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || -224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./C++/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Medium || +224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./C++/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Medium || +227| [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | [C++](./C++/basic-calculator-ii.cpp) [Python](./Python/basic-calculator-ii.py) | _O(n)_| _O(n)_| Medium || --- From 56e6bb863aefc2e3b4ae6b1a30b3db12f6a14f3d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jun 2015 20:59:34 +0800 Subject: [PATCH 0411/1939] Create basic-calculator-ii.cpp --- C++/basic-calculator-ii.cpp | 59 +++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/basic-calculator-ii.cpp diff --git a/C++/basic-calculator-ii.cpp b/C++/basic-calculator-ii.cpp new file mode 100644 index 000000000..413b768ad --- /dev/null +++ b/C++/basic-calculator-ii.cpp @@ -0,0 +1,59 @@ +// Time: O(n) +// Space: O(n) + +// Support +, -, *, /. +class Solution { +public: + int calculate(string s) { + stack operands; + stack operators; + string operand; + for (int i = s.length() - 1; i >= 0; --i) { + if (isdigit(s[i])) { + operand.push_back(s[i]); + if (i == 0 || !isdigit(s[i - 1])) { + reverse(operand.begin(), operand.end()); + operands.emplace(stol(operand)); + operand.clear(); + } + } else if (s[i] == ')' || s[i] == '*' || + s[i] == '/') { + operators.emplace(s[i]); + } else if (s[i] == '+' || s[i] == '-') { + while (!operators.empty() && (operators.top() == '*' || + operators.top() == '/')) { + compute(operands, operators); + } + operators.emplace(s[i]); + } else if (s[i] == '(') { + // operators at least one element, i.e. ')'. + while (operators.top() != ')') { + compute(operands, operators); + } + operators.pop(); + } + } + while (!operators.empty()) { + compute(operands, operators); + } + return operands.top(); + } + + void compute(stack& operands, stack& operators) { + const int64_t left = operands.top(); + operands.pop(); + const int64_t right = operands.top(); + operands.pop(); + const char op = operators.top(); + operators.pop(); + if (op == '+') { + operands.push(left + right); + } else if (op == '-') { + operands.push(left - right); + } else if (op == '*') { + operands.push(left * right); + } else if (op == '/') { + operands.push(left / right); + } + } +}; From 3b4b0f781e3f5662ca7887a80c2d1e69ad4d24b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jun 2015 21:00:31 +0800 Subject: [PATCH 0412/1939] Update basic-calculator.cpp --- C++/basic-calculator.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/basic-calculator.cpp b/C++/basic-calculator.cpp index 01a04722b..6e12399a3 100644 --- a/C++/basic-calculator.cpp +++ b/C++/basic-calculator.cpp @@ -5,7 +5,7 @@ class Solution { public: int calculate(string s) { - stack operands; + stack operands; stack operators; string operand; for (int i = s.length() - 1; i >= 0; --i) { @@ -13,7 +13,7 @@ class Solution { operand.push_back(s[i]); if (i == 0 || !isdigit(s[i - 1])) { reverse(operand.begin(), operand.end()); - operands.emplace(stoi(operand)); + operands.emplace(stol(operand)); operand.clear(); } } else if (s[i] == ')' || s[i] == '*' || @@ -39,10 +39,10 @@ class Solution { return operands.top(); } - void compute(stack& operands, stack& operators) { - const int left = operands.top(); + void compute(stack& operands, stack& operators) { + const int64_t left = operands.top(); operands.pop(); - const int right = operands.top(); + const int64_t right = operands.top(); operands.pop(); const char op = operators.top(); operators.pop(); From 76d52e91507aacc342919d23fa3f2ecd99904af0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jun 2015 21:07:44 +0800 Subject: [PATCH 0413/1939] Update basic-calculator-ii.cpp --- C++/basic-calculator-ii.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/basic-calculator-ii.cpp b/C++/basic-calculator-ii.cpp index 413b768ad..e9cb14484 100644 --- a/C++/basic-calculator-ii.cpp +++ b/C++/basic-calculator-ii.cpp @@ -47,13 +47,13 @@ class Solution { const char op = operators.top(); operators.pop(); if (op == '+') { - operands.push(left + right); + operands.emplace(left + right); } else if (op == '-') { - operands.push(left - right); + operands.emplace(left - right); } else if (op == '*') { - operands.push(left * right); + operands.emplace(left * right); } else if (op == '/') { - operands.push(left / right); + operands.emplace(left / right); } } }; From fd7666c92267b76bdaad4bbc7c4bf61e6bbd62a9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jun 2015 21:08:23 +0800 Subject: [PATCH 0414/1939] Update basic-calculator.cpp --- C++/basic-calculator.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/basic-calculator.cpp b/C++/basic-calculator.cpp index 6e12399a3..1201fe524 100644 --- a/C++/basic-calculator.cpp +++ b/C++/basic-calculator.cpp @@ -47,13 +47,13 @@ class Solution { const char op = operators.top(); operators.pop(); if (op == '+') { - operands.push(left + right); + operands.emplace(left + right); } else if (op == '-') { - operands.push(left - right); + operands.emplace(left - right); } else if (op == '*') { - operands.push(left * right); + operands.emplace(left * right); } else if (op == '/') { - operands.push(left / right); + operands.emplace(left / right); } } }; @@ -98,9 +98,9 @@ class Solution2 { const char op = operators.top(); operators.pop(); if (op == '+') { - operands.push(left + right); + operands.emplace(left + right); } else if (op == '-') { - operands.push(left - right); + operands.emplace(left - right); } } }; From f40e0feb7828a0385c965ab555cc17ea85d4fd16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jun 2015 21:16:27 +0800 Subject: [PATCH 0415/1939] Create basic-calculator-ii.py --- Python/basic-calculator-ii.py | 57 +++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Python/basic-calculator-ii.py diff --git a/Python/basic-calculator-ii.py b/Python/basic-calculator-ii.py new file mode 100644 index 000000000..6f0606a9a --- /dev/null +++ b/Python/basic-calculator-ii.py @@ -0,0 +1,57 @@ +# Time: O(n) +# Space: O(n) +# +# Implement a basic calculator to evaluate a simple expression string. +# +# The expression string contains only non-negative integers, +, -, *, / +# operators and empty spaces . The integer division should truncate toward zero. +# +# You may assume that the given expression is always valid. +# +# Some examples: +# "3+2*2" = 7 +# " 3/2 " = 1 +# " 3+5 / 2 " = 5 +# Note: Do not use the eval built-in library function. +# + +class Solution: + # @param {string} s + # @return {integer} + def calculate(self, s): + operands, operators = [], [] + operand = "" + for i in reversed(xrange(len(s))): + if s[i].isdigit(): + operand += s[i] + if i == 0 or not s[i-1].isdigit(): + operands.append(int(operand[::-1])) + operand = "" + elif s[i] == ')' or s[i] == '*' or s[i] == '/': + operators.append(s[i]) + elif s[i] == '+' or s[i] == '-': + while operators and \ + (operators[-1] == '*' or operators[-1] == '/'): + self.compute(operands, operators) + operators.append(s[i]) + elif s[i] == '(': + while operators[-1] != ')': + self.compute(operands, operators) + operators.pop() + + while operators: + self.compute(operands, operators) + + return operands[-1] + + def compute(self, operands, operators): + left, right = operands.pop(), operands.pop() + op = operators.pop() + if op == '+': + operands.append(left + right) + elif op == '-': + operands.append(left - right) + elif op == '*': + operands.append(left * right) + elif op == '/': + operands.append(left / right) From 727c266d123d7c6afdd4697e72d79a7e3659f9a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jun 2015 21:17:25 +0800 Subject: [PATCH 0416/1939] Update basic-calculator-ii.py --- Python/basic-calculator-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/basic-calculator-ii.py b/Python/basic-calculator-ii.py index 6f0606a9a..4575b8a69 100644 --- a/Python/basic-calculator-ii.py +++ b/Python/basic-calculator-ii.py @@ -32,7 +32,7 @@ def calculate(self, s): elif s[i] == '+' or s[i] == '-': while operators and \ (operators[-1] == '*' or operators[-1] == '/'): - self.compute(operands, operators) + self.compute(operands, operators) operators.append(s[i]) elif s[i] == '(': while operators[-1] != ')': From d9a1070261b75fb97327df887d50e97394ca2c28 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jun 2015 10:05:20 +0800 Subject: [PATCH 0417/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 3a1ff1142..1fc948979 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -12,14 +12,14 @@ class Solution { }; vector > getSkyline(vector >& buildings) { - map> point_to_height; // Ordered, no duplicates. + map> point_to_height; // Ordered, no duplicates. for (const auto& building : buildings) { point_to_height[building[start]].emplace_back(Endpoint{building[height], true}); point_to_height[building[end]].emplace_back(Endpoint{building[height], false}); } vector> res; - map height_to_count; // BST. + map height_to_count; // BST. int curr_max = 0; // Enumerate each point in increasing order. for (const auto& kvp : point_to_height) { @@ -122,8 +122,8 @@ class Solution2 { } else { // aaa ++b_idx; // abb } - } else if (a[height] == b[height]) { // abb - b[start] = a[start], ++a_idx; // abb + } else if (a[height] == b[height]) { // abb + b[start] = a[start], ++a_idx; // abb } else { // a[height] < b[height]. if (a[start] != b[start]) { // bb merged.emplace_back(move(vector{a[start], b[start], a[height]})); // |a|bb From 3c14764a341e5ec3e5b42828d885e1b0a0da326c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Jun 2015 21:50:31 +0800 Subject: [PATCH 0418/1939] Create summary-ranges.cpp --- C++/summary-ranges.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/summary-ranges.cpp diff --git a/C++/summary-ranges.cpp b/C++/summary-ranges.cpp new file mode 100644 index 000000000..cf199e94b --- /dev/null +++ b/C++/summary-ranges.cpp @@ -0,0 +1,36 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector summaryRanges(vector& nums) { + vector ranges; + if (nums.empty()) { + return ranges; + } + + int start = nums[0], end = nums[0]; + for (const auto& num : nums) { + if (num > end + 1) { + add_range(start, end, &ranges); + start = end = num; + } else { + end = num; + } + if (num == nums.back()) { + add_range(start, end, &ranges); + } + } + + return ranges; + } + + void add_range(const int start, const int end, + vector *ranges) { + if (start != end) { + ranges->emplace_back(to_string(start) + "->" + to_string(end)); + } else { + ranges->emplace_back(to_string(start)); + } + } +}; From 6be29d428c6b18c067d02310828d18769922854e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Jun 2015 21:58:43 +0800 Subject: [PATCH 0419/1939] Create summary-ranges.py --- Python/summary-ranges.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/summary-ranges.py diff --git a/Python/summary-ranges.py b/Python/summary-ranges.py new file mode 100644 index 000000000..fe59cd1d7 --- /dev/null +++ b/Python/summary-ranges.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(1) +# +# Given a sorted integer array without duplicates, +# return the summary of its ranges. +# +# For example, given [0,1,2,4,5,7], +# return ["0->2","4->5","7"]. +# + +class Solution: + # @param {integer[]} nums + # @return {string[]} + def summaryRanges(self, nums): + ranges = [] + if not nums: + return ranges + + start, end = nums[0], nums[0] + for num in nums: + if num > end + 1: + self.add_range(start, end, ranges) + start, end = num, num + else: + end = num + if num == nums[-1]: + self.add_range(start, end, ranges) + + return ranges + + def add_range(self, start, end, ranges): + if start != end: + ranges.append("{}->{}".format(start, end)) + else: + ranges.append("{}".format(start)) From ee3b9ebd1aee587d80162fc70c8db760ff3bea9d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Jun 2015 22:00:20 +0800 Subject: [PATCH 0420/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ff2d3b3ef..da0434a56 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-23), there are `211` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-26), there are `212` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `227` problems. +Here is the classification of all `228` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -86,6 +86,7 @@ Shell 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| +228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Easy | | --- From ae595c3ed704fddcba69fa340cab8b0bed5119ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Jun 2015 22:18:19 +0800 Subject: [PATCH 0421/1939] Update summary-ranges.py --- Python/summary-ranges.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Python/summary-ranges.py b/Python/summary-ranges.py index fe59cd1d7..015da9ae9 100644 --- a/Python/summary-ranges.py +++ b/Python/summary-ranges.py @@ -33,3 +33,12 @@ def add_range(self, start, end, ranges): ranges.append("{}->{}".format(start, end)) else: ranges.append("{}".format(start)) + +# Time: O(n) +# Space: O(1) +class Solution2: + # @param {integer[]} nums + # @return {string[]} + def summaryRanges(self, nums): + return [re.sub('->.*>', '->', '->'.join(`n` for _, n in g)) + for _, g in itertools.groupby(enumerate(nums), lambda (i, n): n-i)] From 3562bd10f36d3cce47fc177dd0b48d24cba84494 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Jun 2015 23:22:15 +0800 Subject: [PATCH 0422/1939] Update summary-ranges.cpp --- C++/summary-ranges.cpp | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/C++/summary-ranges.cpp b/C++/summary-ranges.cpp index cf199e94b..108027acb 100644 --- a/C++/summary-ranges.cpp +++ b/C++/summary-ranges.cpp @@ -10,27 +10,19 @@ class Solution { } int start = nums[0], end = nums[0]; - for (const auto& num : nums) { - if (num > end + 1) { - add_range(start, end, &ranges); - start = end = num; - } else { - end = num; - } - if (num == nums.back()) { - add_range(start, end, &ranges); + for (int i = 1; i <= nums.size(); ++i) { + if (i < nums.size() && nums[i] == end + 1) { + end = nums[i]; + } else { + string range = to_string(start); + if (start != end) { + range.append("->" + to_string(end)); + } + ranges.emplace_back(range); + start = end = nums[i]; } } return ranges; } - - void add_range(const int start, const int end, - vector *ranges) { - if (start != end) { - ranges->emplace_back(to_string(start) + "->" + to_string(end)); - } else { - ranges->emplace_back(to_string(start)); - } - } }; From e40d14f4a9c42ed6bf93f701f6e872acadf40a6f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Jun 2015 23:32:38 +0800 Subject: [PATCH 0423/1939] Update summary-ranges.cpp --- C++/summary-ranges.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/C++/summary-ranges.cpp b/C++/summary-ranges.cpp index 108027acb..30b834516 100644 --- a/C++/summary-ranges.cpp +++ b/C++/summary-ranges.cpp @@ -19,7 +19,9 @@ class Solution { range.append("->" + to_string(end)); } ranges.emplace_back(range); - start = end = nums[i]; + if (i < nums.size()) { + start = end = nums[i]; + } } } From 2784ba70cb637800bacf90a13e691c2fa449a215 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Jun 2015 23:33:24 +0800 Subject: [PATCH 0424/1939] Update summary-ranges.py --- Python/summary-ranges.py | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/Python/summary-ranges.py b/Python/summary-ranges.py index 015da9ae9..f964cbcfc 100644 --- a/Python/summary-ranges.py +++ b/Python/summary-ranges.py @@ -17,22 +17,18 @@ def summaryRanges(self, nums): return ranges start, end = nums[0], nums[0] - for num in nums: - if num > end + 1: - self.add_range(start, end, ranges) - start, end = num, num + for i in xrange(1, len(nums) + 1): + if i < len(nums) and nums[i] == end + 1: + end = nums[i] else: - end = num - if num == nums[-1]: - self.add_range(start, end, ranges) + interval = `start` + if start != end: + interval += "->{}".format(end) + ranges.append(interval) + if i < len(nums): + start = end = nums[i] return ranges - - def add_range(self, start, end, ranges): - if start != end: - ranges.append("{}->{}".format(start, end)) - else: - ranges.append("{}".format(start)) # Time: O(n) # Space: O(1) From e5f01e45a8bd2756422702a615c074db31b37cff Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Jun 2015 23:34:19 +0800 Subject: [PATCH 0425/1939] Update summary-ranges.py --- Python/summary-ranges.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/summary-ranges.py b/Python/summary-ranges.py index f964cbcfc..83f410f9b 100644 --- a/Python/summary-ranges.py +++ b/Python/summary-ranges.py @@ -23,7 +23,7 @@ def summaryRanges(self, nums): else: interval = `start` if start != end: - interval += "->{}".format(end) + interval += "->" + `end` ranges.append(interval) if i < len(nums): start = end = nums[i] From ddd5822778c1e4e01cfbc7d6ecd66ba23f74b755 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 27 Jun 2015 12:03:40 +0800 Subject: [PATCH 0426/1939] Update summary-ranges.py --- Python/summary-ranges.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/summary-ranges.py b/Python/summary-ranges.py index 83f410f9b..a72706fac 100644 --- a/Python/summary-ranges.py +++ b/Python/summary-ranges.py @@ -31,7 +31,7 @@ def summaryRanges(self, nums): return ranges # Time: O(n) -# Space: O(1) +# Space: O(n) class Solution2: # @param {integer[]} nums # @return {string[]} From b40e24b9f502cd29c2b8232b87bdf102be5b401b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 27 Jun 2015 21:45:56 +0800 Subject: [PATCH 0427/1939] Update summary-ranges.py --- Python/summary-ranges.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/summary-ranges.py b/Python/summary-ranges.py index a72706fac..f602a5282 100644 --- a/Python/summary-ranges.py +++ b/Python/summary-ranges.py @@ -21,9 +21,9 @@ def summaryRanges(self, nums): if i < len(nums) and nums[i] == end + 1: end = nums[i] else: - interval = `start` + interval = str(start) if start != end: - interval += "->" + `end` + interval += "->" + str(end) ranges.append(interval) if i < len(nums): start = end = nums[i] From 8997a55abf101154b57887fa12bf61137666f021 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 09:32:19 +0800 Subject: [PATCH 0428/1939] Create majority-element-ii.cpp --- C++/majority-element-ii.cpp | 51 +++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 C++/majority-element-ii.cpp diff --git a/C++/majority-element-ii.cpp b/C++/majority-element-ii.cpp new file mode 100644 index 000000000..82c7edbe2 --- /dev/null +++ b/C++/majority-element-ii.cpp @@ -0,0 +1,51 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector majorityElement(vector& nums) { + int k = 3; + const int n = nums.size(); + unordered_map hash; + + for (const auto& i : nums) { + ++hash[i]; + // Detecting k items in hash, at least one of them must have exactly + // one in it. We will discard those k items by one for each. + // This action keeps the same mojority numbers in the remaining numbers. + // Because if x / n > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true. + if (hash.size() == k) { + auto it = hash.begin(); + while (it != hash.end()) { + if (--(it->second) == 0) { + hash.erase(it++); + } else { + ++it; + } + } + } + } + + // Resets hash for the following counting. + for (auto& it : hash) { + it.second = 0; + } + + // Counts the occurrence of each candidate integer. + for (const auto& i : nums) { + auto it = hash.find(i); + if (it != hash.end()) { + ++it->second; + } + } + + // Selects the integer which occurs > n / k times. + vector ret; + for (const pair& it : hash) { + if (it.second > static_cast(n) / k) { + ret.emplace_back(it.first); + } + } + return ret; + } +}; From 7c64d637972a36bc6f7a10abc2dfe684d6822594 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 09:44:25 +0800 Subject: [PATCH 0429/1939] Create majority-element-ii.py --- Python/majority-element-ii.py | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/majority-element-ii.py diff --git a/Python/majority-element-ii.py b/Python/majority-element-ii.py new file mode 100644 index 000000000..bf8a3cbe9 --- /dev/null +++ b/Python/majority-element-ii.py @@ -0,0 +1,44 @@ +# Time: O(n) +# Space: O(1) +# +# Given an integer array of size n, +# find all elements that appear more than ⌊ n/3 ⌋ times. +# The algorithm should run in linear time and in O(1) space. +# + +class Solution: + # @param {integer[]} nums + # @return {integer[]} + def majorityElement(self, nums): + k, n, hash = 3, len(nums), {} + + for i in nums: + if i not in hash: + hash[i] = 1 + else: + hash[i] += 1 + # Detecting k items in hash, at least one of them must have exactly + # one in it. We will discard those k items by one for each. + # This action keeps the same mojority numbers in the remaining numbers. + # Because if x / n > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true. + if len(hash) == k: + for i in hash.keys(): + if hash[i] == 0: + del hash[i] + + # Resets hash for the following counting. + for i in hash.keys(): + hash[i] = 0 + + # Counts the occurrence of each candidate integer. + for i in nums: + if i in hash: + hash[i] += 1 + + # Selects the integer which occurs > n / k times. + ret = [] + for i in hash.keys(): + if hash[i] > n / k: + ret.append(i) + + return ret From 33633ee3e7d311a6f9f19e30abf1cadb958ad91b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 09:44:52 +0800 Subject: [PATCH 0430/1939] Update majority-element-ii.cpp --- C++/majority-element-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/majority-element-ii.cpp b/C++/majority-element-ii.cpp index 82c7edbe2..93406d205 100644 --- a/C++/majority-element-ii.cpp +++ b/C++/majority-element-ii.cpp @@ -39,10 +39,10 @@ class Solution { } } - // Selects the integer which occurs > n / k times. + // Selects the integer which occurs > [n / k] times. vector ret; for (const pair& it : hash) { - if (it.second > static_cast(n) / k) { + if (it.second > n / k) { ret.emplace_back(it.first); } } From eb707f90e7d685eedb69571f449b7b1623d493fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 09:45:14 +0800 Subject: [PATCH 0431/1939] Update majority-element-ii.py --- Python/majority-element-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/majority-element-ii.py b/Python/majority-element-ii.py index bf8a3cbe9..ce93267ef 100644 --- a/Python/majority-element-ii.py +++ b/Python/majority-element-ii.py @@ -35,7 +35,7 @@ def majorityElement(self, nums): if i in hash: hash[i] += 1 - # Selects the integer which occurs > n / k times. + # Selects the integer which occurs > [n / k] times. ret = [] for i in hash.keys(): if hash[i] > n / k: From 49bb82c403de47539d815483ec127a4246cad1c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 09:46:18 +0800 Subject: [PATCH 0432/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index da0434a56..1f2c0a06c 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-26), there are `212` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-26), there are `213` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `228` problems. +Here is the classification of all `229` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -87,6 +87,7 @@ Shell 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Easy | | +229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./Python/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | --- From 6ef114e38df6f6a49e1fd8ac6da16947e7a0c42f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 09:46:42 +0800 Subject: [PATCH 0433/1939] Update majority-element-ii.py --- Python/majority-element-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/majority-element-ii.py b/Python/majority-element-ii.py index ce93267ef..3a0d51fac 100644 --- a/Python/majority-element-ii.py +++ b/Python/majority-element-ii.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given an integer array of size n, -# find all elements that appear more than ⌊ n/3 ⌋ times. +# find all elements that appear more than [n/3] times. # The algorithm should run in linear time and in O(1) space. # From a7aa252b67f18b90becc4a290e0855f3223ed574 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 09:52:20 +0800 Subject: [PATCH 0434/1939] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1f2c0a06c..3f9e6dbfb 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,8 @@ Shell 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Easy | | -229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./Python/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | +229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./ +C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | --- From 7d59731f846f78566f7d5308cb2c5e01d2a50a70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 09:52:37 +0800 Subject: [PATCH 0435/1939] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 3f9e6dbfb..82da204ea 100644 --- a/README.md +++ b/README.md @@ -87,8 +87,7 @@ Shell 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Easy | | -229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./ -C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | +229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | --- From 5275f0a0d46cf32b105b18e21457f7c16511fe59 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 11:39:32 +0800 Subject: [PATCH 0436/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 82da204ea..337d62895 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-06-26), there are `213` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-06-29), there are `213` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. Here is the classification of all `229` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 4bafcd0d04cb39fa485ec54a87930abf3deab09f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 21:26:50 +0800 Subject: [PATCH 0437/1939] Update number-of-islands.py --- Python/number-of-islands.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/number-of-islands.py b/Python/number-of-islands.py index 2528d6887..c4889c5d9 100644 --- a/Python/number-of-islands.py +++ b/Python/number-of-islands.py @@ -23,10 +23,10 @@ # class Solution: - # @param grid, a list of list of characters - # @return an integer + # @param {boolean[][]} grid a boolean 2D matrix + # @return {int} an integer def numIslands(self, grid): - if grid == []: + if not grid: return 0 row = len(grid) @@ -36,14 +36,14 @@ def numIslands(self, grid): count = 0 for i in xrange(row): for j in xrange(col): - if grid[i][j] == '1' and not used[i][j]: + if grid[i][j] == 1 and not used[i][j]: self.dfs(grid, used, row, col, i, j) count += 1 return count def dfs(self, grid, used, row, col, x, y): - if grid[x][y] == '0' or used[x][y]: - return 0 + if grid[x][y] == 0 or used[x][y]: + return used[x][y] = True if x != 0: From 067f9f8580d2f4365c05cbe9db17ab1e82f8d8e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jun 2015 21:40:01 +0800 Subject: [PATCH 0438/1939] Update number-of-islands.py --- Python/number-of-islands.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/number-of-islands.py b/Python/number-of-islands.py index c4889c5d9..03d93dd0b 100644 --- a/Python/number-of-islands.py +++ b/Python/number-of-islands.py @@ -36,13 +36,13 @@ def numIslands(self, grid): count = 0 for i in xrange(row): for j in xrange(col): - if grid[i][j] == 1 and not used[i][j]: + if grid[i][j] == '1' and not used[i][j]: self.dfs(grid, used, row, col, i, j) count += 1 return count def dfs(self, grid, used, row, col, x, y): - if grid[x][y] == 0 or used[x][y]: + if grid[x][y] == '0' or used[x][y]: return used[x][y] = True From d30fe682b9829ec045a25298785908b8ebfcdb92 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Jul 2015 14:35:36 +0800 Subject: [PATCH 0439/1939] Create kth-smallest-element-in-a-bst.cpp --- C++/kth-smallest-element-in-a-bst.cpp | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/kth-smallest-element-in-a-bst.cpp diff --git a/C++/kth-smallest-element-in-a-bst.cpp b/C++/kth-smallest-element-in-a-bst.cpp new file mode 100644 index 000000000..aadc1cdb9 --- /dev/null +++ b/C++/kth-smallest-element-in-a-bst.cpp @@ -0,0 +1,35 @@ +// Time: O(n) +// Space: O(h) + +/** + * 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: + int kthSmallest(TreeNode* root, int k) { + stack s; + TreeNode *cur = root; + int rank = 0; + while (!s.empty() || cur) { + if (cur) { + s.emplace(cur); + cur = cur->left; + } else { + cur = s.top(); + s.pop(); + if (++rank == k) { + return cur->val; + } + cur = cur->right; + } + } + + return INT_MIN; + } +}; From bcf8ad819dd1750217fd03124d675f1f791ebed2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Jul 2015 14:38:09 +0800 Subject: [PATCH 0440/1939] Update kth-smallest-element-in-a-bst.cpp --- C++/kth-smallest-element-in-a-bst.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/kth-smallest-element-in-a-bst.cpp b/C++/kth-smallest-element-in-a-bst.cpp index aadc1cdb9..fdf2d1d62 100644 --- a/C++/kth-smallest-element-in-a-bst.cpp +++ b/C++/kth-smallest-element-in-a-bst.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(min(h, k)) // Space: O(h) /** From 4e70fc07b6a9837d17bd3c8ce40606f67b59df51 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Jul 2015 14:42:50 +0800 Subject: [PATCH 0441/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 337d62895..8e9fe9392 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-06-29), there are `213` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-02), there are `214` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `229` problems. +Here is the classification of all `230` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -164,6 +164,7 @@ Shell 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || +230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(min(h, k))_ | _O(h)_ | Medium || --- From 1ae5c2550a4637ab24670df3677683f4148ce30d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Jul 2015 14:45:03 +0800 Subject: [PATCH 0442/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8e9fe9392..8493cd2e4 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,7 @@ Shell 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || -230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(min(h, k))_ | _O(h)_ | Medium || +230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(min(h, k))_ | _O(h)_ | Medium || --- From 05bd68517cd9d6467fdb8108f37ec782ba5d0309 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Jul 2015 14:57:10 +0800 Subject: [PATCH 0443/1939] Create kth-smallest-element-in-a-bst.py --- Python/kth-smallest-element-in-a-bst.py | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/kth-smallest-element-in-a-bst.py diff --git a/Python/kth-smallest-element-in-a-bst.py b/Python/kth-smallest-element-in-a-bst.py new file mode 100644 index 000000000..e3c5d975d --- /dev/null +++ b/Python/kth-smallest-element-in-a-bst.py @@ -0,0 +1,39 @@ +# Time: O(min(h, k)) +# Space: O(h) + +# Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. +# +# Note: +# You may assume k is always valid, 1 ≤ k ≤ BST's total elements. +# +# Follow up: +# What if the BST is modified (insert/delete operations) often and +# you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? +# + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param {TreeNode} root + # @param {integer} k + # @return {integer} + def kthSmallest(self, root, k): + s, cur, rank = [], root, 0 + + while s or cur: + if cur: + s.append(cur) + cur = cur.left + else: + cur = s.pop() + rank += 1 + if rank == k: + return cur.val + cur = cur.right + + return float("-inf") From acde2233e647eb1a58e046c7e34a62ef0bf72f4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Jul 2015 16:30:31 +0800 Subject: [PATCH 0444/1939] Update kth-smallest-element-in-a-bst.cpp --- C++/kth-smallest-element-in-a-bst.cpp | 32 ++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/C++/kth-smallest-element-in-a-bst.cpp b/C++/kth-smallest-element-in-a-bst.cpp index fdf2d1d62..2b0e1e245 100644 --- a/C++/kth-smallest-element-in-a-bst.cpp +++ b/C++/kth-smallest-element-in-a-bst.cpp @@ -1,5 +1,5 @@ // Time: O(min(h, k)) -// Space: O(h) +// Space: O(min(h, k)) /** * Definition for a binary tree node. @@ -10,7 +10,37 @@ * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ + class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + deque s; + TreeNode *cur = root; + int rank = 0; + while (!s.empty() || cur) { + if (cur) { + s.emplace_back(cur); + if (s.size() > k) { + s.pop_front(); + } + cur = cur->left; + } else { + cur = s.back(); + s.pop_back(); + if (++rank == k) { + return cur->val; + } + cur = cur->right; + } + } + + return INT_MIN; + } +}; + +// Time: O(min(h, k)) +// Space: O(h) +class Solution2 { public: int kthSmallest(TreeNode* root, int k) { stack s; From 5fe7fbd3027ac1018e881e32729e0b10f3ca0c07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Jul 2015 16:32:43 +0800 Subject: [PATCH 0445/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8493cd2e4..00feeca54 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,7 @@ Shell 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || -230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(min(h, k))_ | _O(h)_ | Medium || +230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(max(h, k))_ | _O(max(h, k))_ | Medium || --- From 3099bc2eca6ce9cfaaa2eeed4d4d59c488a23b75 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Jul 2015 16:34:11 +0800 Subject: [PATCH 0446/1939] Update kth-smallest-element-in-a-bst.cpp --- C++/kth-smallest-element-in-a-bst.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/kth-smallest-element-in-a-bst.cpp b/C++/kth-smallest-element-in-a-bst.cpp index 2b0e1e245..57901862d 100644 --- a/C++/kth-smallest-element-in-a-bst.cpp +++ b/C++/kth-smallest-element-in-a-bst.cpp @@ -1,4 +1,4 @@ -// Time: O(min(h, k)) +// Time: O(max(h, k)) // Space: O(min(h, k)) /** @@ -38,7 +38,7 @@ class Solution { } }; -// Time: O(min(h, k)) +// Time: O(max(h, k)) // Space: O(h) class Solution2 { public: From 29d784e65e398aa1ea539ded80eb443dd30ad34e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Jul 2015 16:34:44 +0800 Subject: [PATCH 0447/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 00feeca54..28addd849 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,7 @@ Shell 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || -230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(max(h, k))_ | _O(max(h, k))_ | Medium || +230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(max(h, k))_ | _O(min(h, k))_ | Medium || --- From 72d1c68ad97f9d8d72994ffe9c25d3225bf5952d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Jul 2015 16:34:58 +0800 Subject: [PATCH 0448/1939] Update kth-smallest-element-in-a-bst.py --- Python/kth-smallest-element-in-a-bst.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/kth-smallest-element-in-a-bst.py b/Python/kth-smallest-element-in-a-bst.py index e3c5d975d..ee7216094 100644 --- a/Python/kth-smallest-element-in-a-bst.py +++ b/Python/kth-smallest-element-in-a-bst.py @@ -1,4 +1,4 @@ -# Time: O(min(h, k)) +# Time: O(max(h, k)) # Space: O(h) # Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. From 0a26c94c5574982dc13daf0e139beb173b862ec3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jul 2015 13:37:14 +0800 Subject: [PATCH 0449/1939] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index b8ef6f68c..c3d25c2a4 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -53,7 +53,7 @@ class Solution2 { vector P(n); int C = 0, R = 0; for (int i = 1; i < n - 1; ++i) { - int i_mirror = 2*C-i; // equals to i' = C - (i-C) + int i_mirror = 2 * C - i; // equals to i' = C - (i-C) P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; From aea72c36058feebfd57bf826b7f6371d319607a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jul 2015 02:58:46 +0800 Subject: [PATCH 0450/1939] Create power-of-two.cpp --- C++/power-of-two.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 C++/power-of-two.cpp diff --git a/C++/power-of-two.cpp b/C++/power-of-two.cpp new file mode 100644 index 000000000..018476ef8 --- /dev/null +++ b/C++/power-of-two.cpp @@ -0,0 +1,9 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && (n & (n - 1)) == 0; + } +}; From 2ac092382c1bed9be3d4447110a01e4456feb376 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jul 2015 03:00:01 +0800 Subject: [PATCH 0451/1939] Create power-of-two.py --- Python/power-of-two.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Python/power-of-two.py diff --git a/Python/power-of-two.py b/Python/power-of-two.py new file mode 100644 index 000000000..38c738e1e --- /dev/null +++ b/Python/power-of-two.py @@ -0,0 +1,11 @@ +# Time: O(1) +# Space: O(1) +# +# Given an integer, write a function to determine if it is a power of two. +# + +class Solution: + # @param {integer} n + # @return {boolean} + def isPowerOfTwo(self, n): + return n > 0 and (n & (n - 1)) == 0 From 021ee34f884765cda64cf6cb7a7a4fe1a49a6214 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jul 2015 03:01:59 +0800 Subject: [PATCH 0452/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 28addd849..177e6c686 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-02), there are `214` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-06), there are `215` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `230` problems. +Here is the classification of all `231` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -56,6 +56,7 @@ Shell 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || 191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || +231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | --- From f4052cd0cc5b3d7b2a8b32683c2c5c82b59a4939 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jul 2015 17:12:34 +0800 Subject: [PATCH 0453/1939] Create implement-queue-using-stacks.cpp --- C++/implement-queue-using-stacks.cpp | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/implement-queue-using-stacks.cpp diff --git a/C++/implement-queue-using-stacks.cpp b/C++/implement-queue-using-stacks.cpp new file mode 100644 index 000000000..0392d858c --- /dev/null +++ b/C++/implement-queue-using-stacks.cpp @@ -0,0 +1,39 @@ +// Time: O(1), amortized +// Space: O(n) + +class Queue { +public: + // Push element x to the back of queue. + void push(int x) { + A_.emplace(x); + } + + // Removes the element from in front of queue. + void pop(void) { + peek(); + B_.pop(); + } + + // Get the front element. + int peek(void) { + if (B_.empty()) { + // Transfers the elements in A_ to B_. + while (!A_.empty()) { + B_.emplace(A_.top()); + A_.pop(); + } + } + if (B_.empty()) { // B_ is still empty! + throw length_error("empty queue"); + } + return B_.top(); + } + + // Return whether the queue is empty. + bool empty(void) { + return A_.empty() && B_.empty(); + } + + private: + stack A_, B_; +}; From f8754c2d1b8f1b78c814e5081cbb7f8fb035e24b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jul 2015 17:14:58 +0800 Subject: [PATCH 0454/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 177e6c686..7f6cd512d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-06), there are `215` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-07), there are `216` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `231` problems. +Here is the classification of all `232` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -144,6 +144,7 @@ Shell 173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || 224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./C++/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Medium || 227| [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | [C++](./C++/basic-calculator-ii.cpp) [Python](./Python/basic-calculator-ii.py) | _O(n)_| _O(n)_| Medium || +232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| East | EPI, LintCode | --- From 9c04aff0b892fed88f6ab3048ab2e1e80a3938de Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jul 2015 17:15:20 +0800 Subject: [PATCH 0455/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f6cd512d..a1eceb140 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ Shell 173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || 224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./C++/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Medium || 227| [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | [C++](./C++/basic-calculator-ii.cpp) [Python](./Python/basic-calculator-ii.py) | _O(n)_| _O(n)_| Medium || -232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| East | EPI, LintCode | +232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| Easy | EPI, LintCode | --- From a320ff726b4e21909af589e6bfc2b9c951ae9142 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jul 2015 17:20:59 +0800 Subject: [PATCH 0456/1939] Create implement-queue-using-stacks.py --- Python/implement-queue-using-stacks.py | 45 ++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/implement-queue-using-stacks.py diff --git a/Python/implement-queue-using-stacks.py b/Python/implement-queue-using-stacks.py new file mode 100644 index 000000000..1cfeb014d --- /dev/null +++ b/Python/implement-queue-using-stacks.py @@ -0,0 +1,45 @@ +# Time: O(1), amortized +# Space: O(n) +# +# Implement the following operations of a queue using stacks. +# +# push(x) -- Push element x to the back of queue. +# pop() -- Removes the element from in front of queue. +# peek() -- Get the front element. +# empty() -- Return whether the queue is empty. +# +# Notes: +# You must use only standard operations of a stack +# -- which means only push to top, peek/pop from top, size, and is empty operations are valid. +# Depending on your language, stack may not be supported natively. +# You may simulate a stack by using a list or deque (double-ended queue), +# as long as you use only standard operations of a stack. +# You may assume that all operations are valid +# (for example, no pop or peek operations will be called on an empty queue). +# + +class Queue: + # initialize your data structure here. + def __init__(self): + self.A, self.B = [], [] + + # @param x, an integer + # @return nothing + def push(self, x): + self.A.append(x) + + # @return nothing + def pop(self): + self.peek() + self.B.pop() + + # @return an integer + def peek(self): + if not self.B: + while self.A: + self.B.append(self.A.pop()) + return self.B[-1] + + # @return an boolean + def empty(self): + return not self.A and not self.B From 269fbb2116c5bf1a4a3d960f5902ff4c6b61c0c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 09:59:48 +0800 Subject: [PATCH 0457/1939] Create number-of-digit-one.cpp --- C++/number-of-digit-one.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/number-of-digit-one.cpp diff --git a/C++/number-of-digit-one.cpp b/C++/number-of-digit-one.cpp new file mode 100644 index 000000000..c13ebbefc --- /dev/null +++ b/C++/number-of-digit-one.cpp @@ -0,0 +1,34 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int countDigitOne(int n) { + const int k = 1; + int cnt = 0, multiplier = 1, left_part = n; + + while (left_part > 0) { + // split number into: left_part, curr, right_part + int curr = left_part % 10; + int right_part = n % multiplier; + + // count of (c000 ~ oooc000) = (ooo + (k < curr)? 1 : 0) * 1000 + cnt += (left_part / 10 + (k < curr)) * multiplier; + + // if k == 0, oooc000 = (ooo - 1) * 1000 + if (k == 0 && multiplier > 1) { + cnt -= multiplier; + } + + // count of (oook000 ~ oookxxx): count += xxx + 1 + if (curr == k) { + cnt += right_part + 1; + } + + left_part /= 10; + multiplier *= 10; + } + + return cnt; + } +}; From be4feb1edf1a16a5c847c1315cf5b08d70dc9798 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 10:02:48 +0800 Subject: [PATCH 0458/1939] Create number-of-digit-one.py --- Python/number-of-digit-one.py | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/number-of-digit-one.py diff --git a/Python/number-of-digit-one.py b/Python/number-of-digit-one.py new file mode 100644 index 000000000..97dcab395 --- /dev/null +++ b/Python/number-of-digit-one.py @@ -0,0 +1,39 @@ +# Time: O(logn) +# Space: O(1) +# +# Given an integer n, count the total number of digit 1 appearing +# in all non-negative integers less than or equal to n. +# +# For example: +# Given n = 13, +# Return 6, because digit 1 occurred in the following numbers: +# 1, 10, 11, 12, 13. +# + +class Solution: + # @param {integer} n + # @return {integer} + def countDigitOne(self, n): + k = 1; + cnt, multiplier, left_part = 0, 1, n + + while left_part > 0: + # split number into: left_part, curr, right_part + curr = left_part % 10 + right_part = n % multiplier + + # count of (c000 ~ oooc000) = (ooo + (k < curr)? 1 : 0) * 1000 + cnt += (left_part / 10 + (k < curr)) * multiplier + + # if k == 0, oooc000 = (ooo - 1) * 1000 + if k == 0 and multiplier > 1: + cnt -= multiplier + + # count of (oook000 ~ oookxxx): count += xxx + 1 + if curr == k: + cnt += right_part + 1 + + left_part /= 10 + multiplier *= 10 + + return cnt From 68d9c184d9b49872a361d22044a927a3321a6bee Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 10:08:11 +0800 Subject: [PATCH 0459/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a1eceb140..df37bfb44 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-07), there are `216` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-07), there are `217` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `232` problems. +Here is the classification of all `233` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -215,6 +215,7 @@ Shell 171| [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || 172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || 223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C++](./C++/rectangle-area.cpp) [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || +233| [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | [C++](./C++/number-of-digit-one.cpp) [Python](./Python/number-of-digit-one.py) | _O(logn)_ | _O(1)_ | Medium | CTCI, LintCode| --- From 88d9ae1380a19ec9788b426ab3f883de83f4289d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 10:08:25 +0800 Subject: [PATCH 0460/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index df37bfb44..7f038e05f 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-07-07), there are `217` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-08), there are `217` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. Here is the classification of all `233` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From cd4b738d06b017050c9228463ee85fc40cf40a5f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 13:53:56 +0800 Subject: [PATCH 0461/1939] Update combination-sum.py --- Python/combination-sum.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Python/combination-sum.py b/Python/combination-sum.py index 6d5edd50b..8d35822c9 100644 --- a/Python/combination-sum.py +++ b/Python/combination-sum.py @@ -1,4 +1,4 @@ -# Time: O(n^m) +# Time: O(m * n^m) # Space: O(m) # # Given a set of candidate numbers (C) and a target number (T), @@ -27,9 +27,11 @@ def combinationSum(self, candidates, target): def combinationSumRecu(self, candidates, result, start, intermediate, target): if target == 0: - result.append(intermediate) + result.append(list(intermediate)) while start < len(candidates) and candidates[start] <= target: - self.combinationSumRecu(candidates, result, start, intermediate + [candidates[start]], target - candidates[start]) + intermediate.append(candidates[start]) + self.combinationSumRecu(candidates, result, start, intermediate, target - candidates[start]) + intermediate.pop() start += 1 if __name__ == "__main__": From 0aed6376a16fb75f981abfd4ef4f28c00fd93034 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 13:55:04 +0800 Subject: [PATCH 0462/1939] Update combination-sum-ii.py --- Python/combination-sum-ii.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Python/combination-sum-ii.py b/Python/combination-sum-ii.py index 592f55544..79a63ef9f 100644 --- a/Python/combination-sum-ii.py +++ b/Python/combination-sum-ii.py @@ -1,4 +1,4 @@ -# Time: O(n! / m!(n-m)!) +# Time: O(m * C(n, m)) # Space: O(m) # # Given a collection of candidate numbers (C) and a target number (T), @@ -29,11 +29,13 @@ def combinationSum2(self, candidates, target): def combinationSumRecu(self, candidates, result, start, intermediate, target): if target == 0: - result.append(intermediate) + result.append(list(intermediate)) prev = 0 while start < len(candidates) and candidates[start] <= target: if prev != candidates[start]: - self.combinationSumRecu(candidates, result, start + 1, intermediate + [candidates[start]], target - candidates[start]) + intermediate.append(candidates[start]) + self.combinationSumRecu(candidates, result, start + 1, intermediate, target - candidates[start]) + intermediate.pop() prev = candidates[start] start += 1 From 2dcc657cc5e4269cc758f48a68ad6e7af9a5d440 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 13:56:43 +0800 Subject: [PATCH 0463/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7f038e05f..7ff5cd55c 100644 --- a/README.md +++ b/README.md @@ -323,8 +323,8 @@ Shell -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || 37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || -39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(n^m)_ | _O(m)_ | Medium || -40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(n! / m!(n-m)!)_| _O(m)_ | Medium || +39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(m * n^m)_ | _O(m)_ | Medium || +40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(m * C(n, m))_| _O(m)_ | Medium || 51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || 52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || 77| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || From 17427cbabef7872f2cea3558df55d80d3e37fe71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 13:57:33 +0800 Subject: [PATCH 0464/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7ff5cd55c..a197cb888 100644 --- a/README.md +++ b/README.md @@ -323,8 +323,8 @@ Shell -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || 37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || -39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(m * n^m)_ | _O(m)_ | Medium || -40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(m * C(n, m))_| _O(m)_ | Medium || +39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(k * n^k)_ | _O(k)_ | Medium || +40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(k * C(n, k))_| _O(k)_ | Medium || 51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || 52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || 77| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || From a4fecb9a7d442daec01484d80b40aaf61f3cf3d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 13:57:59 +0800 Subject: [PATCH 0465/1939] Update combination-sum.py --- Python/combination-sum.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/combination-sum.py b/Python/combination-sum.py index 8d35822c9..ce0d14f11 100644 --- a/Python/combination-sum.py +++ b/Python/combination-sum.py @@ -1,5 +1,5 @@ -# Time: O(m * n^m) -# Space: O(m) +# Time: O(k * n^k) +# Space: O(k) # # Given a set of candidate numbers (C) and a target number (T), # find all unique combinations in C where the candidate numbers sums to T. From 98fbedcfad1f4229b81ad74924b3f3a16736fd6f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 13:58:19 +0800 Subject: [PATCH 0466/1939] Update combination-sum-ii.py --- Python/combination-sum-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/combination-sum-ii.py b/Python/combination-sum-ii.py index 79a63ef9f..d11d74295 100644 --- a/Python/combination-sum-ii.py +++ b/Python/combination-sum-ii.py @@ -1,5 +1,5 @@ -# Time: O(m * C(n, m)) -# Space: O(m) +# Time: O(k * C(n, k)) +# Space: O(k) # # Given a collection of candidate numbers (C) and a target number (T), # find all unique combinations in C where the candidate numbers sums to T. From 41cc22761a8921c3d26f6474947ca14296c82a86 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 13:59:12 +0800 Subject: [PATCH 0467/1939] Update combination-sum-iii.cpp --- C++/combination-sum-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/combination-sum-iii.cpp b/C++/combination-sum-iii.cpp index ff297a253..b9009b338 100644 --- a/C++/combination-sum-iii.cpp +++ b/C++/combination-sum-iii.cpp @@ -1,4 +1,4 @@ -// Time: O(C(n, k)) +// Time: O(k * C(n, k)) // Space: O(k) class Solution { From a8e181b42bc78305597f29501c41bb8121d1172b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 13:59:28 +0800 Subject: [PATCH 0468/1939] Update combination-sum-iii.py --- Python/combination-sum-iii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/combination-sum-iii.py b/Python/combination-sum-iii.py index eb2ce4407..ddc4ba260 100644 --- a/Python/combination-sum-iii.py +++ b/Python/combination-sum-iii.py @@ -1,4 +1,4 @@ -# Time: O(C(n, k)) +# Time: O(k * C(n, k)) # Space: O(k) # # Find all possible combinations of k numbers that add up to a number n, From b1e793f1fd66da296acb1bef25437e0332d6a5f7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Jul 2015 13:59:47 +0800 Subject: [PATCH 0469/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a197cb888..201ce9043 100644 --- a/README.md +++ b/README.md @@ -335,7 +335,7 @@ Shell 131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || 199| [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || -216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(C(n, k))_ | _O(k)_ | Medium || +216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(k * C(n, k))_ | _O(k)_ | Medium || --- From 72b2004ec81ad56c3c5c3e4d95f3052a131ef502 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 10 Jul 2015 11:09:15 +0800 Subject: [PATCH 0470/1939] Create palindrome-linked-list.py --- Python/palindrome-linked-list.py | 38 ++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/palindrome-linked-list.py diff --git a/Python/palindrome-linked-list.py b/Python/palindrome-linked-list.py new file mode 100644 index 000000000..96033406e --- /dev/null +++ b/Python/palindrome-linked-list.py @@ -0,0 +1,38 @@ +# Time: O(n) +# Space: O(1) +# +# Given a singly linked list, determine if it is a palindrome. +# +# Follow up: +# Could you do it in O(n) time and O(1) space? +# +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None +# + +class Solution: + # @param {ListNode} head + # @return {boolean} + def isPalindrome(self, head): + # Reverse the first half part of the list. + reverse, fast = None, head + while fast and fast.next: + fast = fast.next.next + reverse, reverse.next, head = head, reverse, head.next + + # If the number of the nodes is odd, + # set the head of the tail list to the next of the median node. + tail = head.next if fast else head + + # Compare the reversed first half list with the second half list. + # And restore the reversed first half list. + is_palindrome = True + while reverse: + is_palindrome = is_palindrome and reverse.val == tail.val + head, head.next, reverse = reverse, head, reverse.next + tail = tail.next + + return is_palindrome From f7a17c2f10a5f6bf0986f345ec70a93429c39d17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 10 Jul 2015 11:10:27 +0800 Subject: [PATCH 0471/1939] Update palindrome-linked-list.py --- Python/palindrome-linked-list.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/palindrome-linked-list.py b/Python/palindrome-linked-list.py index 96033406e..1a00630da 100644 --- a/Python/palindrome-linked-list.py +++ b/Python/palindrome-linked-list.py @@ -17,7 +17,7 @@ class Solution: # @param {ListNode} head # @return {boolean} def isPalindrome(self, head): - # Reverse the first half part of the list. + # Reverse the first half list. reverse, fast = None, head while fast and fast.next: fast = fast.next.next From 9487b62371b79b6d842e3fa4f6cd3576a475a073 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 10 Jul 2015 11:45:17 +0800 Subject: [PATCH 0472/1939] Update palindrome-linked-list.py --- Python/palindrome-linked-list.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/palindrome-linked-list.py b/Python/palindrome-linked-list.py index 1a00630da..21f542737 100644 --- a/Python/palindrome-linked-list.py +++ b/Python/palindrome-linked-list.py @@ -17,11 +17,11 @@ class Solution: # @param {ListNode} head # @return {boolean} def isPalindrome(self, head): - # Reverse the first half list. reverse, fast = None, head + # Reverse the first half part of the list. while fast and fast.next: fast = fast.next.next - reverse, reverse.next, head = head, reverse, head.next + head.next, reverse, head = reverse, head, head.next # If the number of the nodes is odd, # set the head of the tail list to the next of the median node. @@ -32,7 +32,7 @@ def isPalindrome(self, head): is_palindrome = True while reverse: is_palindrome = is_palindrome and reverse.val == tail.val - head, head.next, reverse = reverse, head, reverse.next + reverse.next, head, reverse = head, reverse, reverse.next tail = tail.next return is_palindrome From e2c1597c324b19273f185125d4fa7e7efa112479 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 10 Jul 2015 11:47:44 +0800 Subject: [PATCH 0473/1939] Create palindrome-linked-list.cpp --- C++/palindrome-linked-list.cpp | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 C++/palindrome-linked-list.cpp diff --git a/C++/palindrome-linked-list.cpp b/C++/palindrome-linked-list.cpp new file mode 100644 index 000000000..881fa6e94 --- /dev/null +++ b/C++/palindrome-linked-list.cpp @@ -0,0 +1,43 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool isPalindrome(ListNode* head) { + // Reverse the first half list. + ListNode *reverse = nullptr, *fast = head; + while (fast && fast->next) { + fast = fast->next->next; + auto head_next = head->next; + head->next = reverse; + reverse = head; + head = head_next; + } + + // If the number of the nodes is odd, + // set the head of the tail list to the next of the median node. + ListNode *tail = fast ? head->next : head; + + // Compare the reversed first half list with the second half list. + // And restore the reversed first half list. + bool is_palindrome = true; + while (reverse) { + is_palindrome = is_palindrome && reverse->val == tail->val; + auto reverse_next = reverse->next; + reverse->next = head; + head = reverse; + reverse = reverse_next; + tail = tail->next; + } + + return is_palindrome; + } +}; From 3c18dfa1bf651cfc270c3a35e9a0ac9dcd7e2f44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 10 Jul 2015 11:53:23 +0800 Subject: [PATCH 0474/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 201ce9043..5c5bddae5 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-08), there are `217` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-10), there are `218` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `233` problems. +Here is the classification of all `234` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -129,6 +129,7 @@ Shell 160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || 203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || 206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || +234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || --- From 63dab6e5a773cf24ac330a637ea386e01ff5539e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 10 Jul 2015 13:48:04 +0800 Subject: [PATCH 0475/1939] Update palindrome-linked-list.cpp --- C++/palindrome-linked-list.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/palindrome-linked-list.cpp b/C++/palindrome-linked-list.cpp index 881fa6e94..af5feef28 100644 --- a/C++/palindrome-linked-list.cpp +++ b/C++/palindrome-linked-list.cpp @@ -16,7 +16,7 @@ class Solution { ListNode *reverse = nullptr, *fast = head; while (fast && fast->next) { fast = fast->next->next; - auto head_next = head->next; + const auto head_next = head->next; head->next = reverse; reverse = head; head = head_next; @@ -31,7 +31,7 @@ class Solution { bool is_palindrome = true; while (reverse) { is_palindrome = is_palindrome && reverse->val == tail->val; - auto reverse_next = reverse->next; + const auto reverse_next = reverse->next; reverse->next = head; head = reverse; reverse = reverse_next; From 1ce2360bde1091f5b61bbb092b85d68257181b77 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jul 2015 11:03:36 +0800 Subject: [PATCH 0476/1939] Create lowest-common-ancestor-of-a-binary-search-tree.cpp --- ...ommon-ancestor-of-a-binary-search-tree.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/lowest-common-ancestor-of-a-binary-search-tree.cpp diff --git a/C++/lowest-common-ancestor-of-a-binary-search-tree.cpp b/C++/lowest-common-ancestor-of-a-binary-search-tree.cpp new file mode 100644 index 000000000..5865a265b --- /dev/null +++ b/C++/lowest-common-ancestor-of-a-binary-search-tree.cpp @@ -0,0 +1,27 @@ +// Time: O(n) +// Space: O(1) + +/** + * 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: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + auto s = min(p->val, q->val); + auto b = max(p->val, q->val); + + while (root->val < s || root->val > b) { + // Keep searching since root is outside of [s, b]. + root = s <= root->val ? root->left : root->right; + } + + // s <= root->val && root->val <= b. + return root; + } +}; From 365c6fed7343f8933c37d6a3ff2d411d28fe517d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jul 2015 11:08:04 +0800 Subject: [PATCH 0477/1939] Create lowest-common-ancestor-of-a-binary-search-tree.ph --- ...common-ancestor-of-a-binary-search-tree.ph | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/lowest-common-ancestor-of-a-binary-search-tree.ph diff --git a/Python/lowest-common-ancestor-of-a-binary-search-tree.ph b/Python/lowest-common-ancestor-of-a-binary-search-tree.ph new file mode 100644 index 000000000..fab9e33a7 --- /dev/null +++ b/Python/lowest-common-ancestor-of-a-binary-search-tree.ph @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(1) +# +# Given a binary search tree (BST), find the lowest common ancestor (LCA) +# of two given nodes in the BST. +# +# According to the definition of LCA on Wikipedia: “The lowest common ancestor +# is defined between two nodes v and w as the lowest node in T that has both v +# and w as descendants (where we allow a node to be a descendant of itself).” +# +# _______6______ +# / \ +# ___2__ ___8__ +# / \ / \ +# 0 _4 7 9 +# / \ +# 3 5 +# For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. +# Another example is LCA of nodes 2 and 4 is 2, since a node can be a +# descendant of itself according to the LCA definition. +# +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param {TreeNode} root + # @param {TreeNode} p + # @param {TreeNode} q + # @return {TreeNode} + def lowestCommonAncestor(self, root, p, q): + s, b = sorted([p.val, q.val]) + while not s <= root.val <= b: + # Keep searching since root is outside of [s, b]. + root = root.left if s <= root.val else root.right + # s <= root.val <= b. + return root From 10b7f0668278ff6d054dabd180deea754f94d2d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jul 2015 11:14:48 +0800 Subject: [PATCH 0478/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5c5bddae5..ba3264d34 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-10), there are `218` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-11), there are `219` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `234` problems. +Here is the classification of all `235` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -167,7 +167,6 @@ Shell 211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || -230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(max(h, k))_ | _O(min(h, k))_ | Medium || --- @@ -301,6 +300,8 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) [Python](./Python/contains-duplicate-iii.py) | _O(nlogk)_ | _O(k)_ | medium || +230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(max(h, k))_ | _O(min(h, k))_ | Medium || +235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-search-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-search-tree.py) | _O(h)_ | _O(1)_ | Easy || --- From 93dc1a4da4571d8134153a3e4dec7fe9e3a7eaff Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jul 2015 11:15:08 +0800 Subject: [PATCH 0479/1939] Update lowest-common-ancestor-of-a-binary-search-tree.cpp --- C++/lowest-common-ancestor-of-a-binary-search-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lowest-common-ancestor-of-a-binary-search-tree.cpp b/C++/lowest-common-ancestor-of-a-binary-search-tree.cpp index 5865a265b..ef1f95021 100644 --- a/C++/lowest-common-ancestor-of-a-binary-search-tree.cpp +++ b/C++/lowest-common-ancestor-of-a-binary-search-tree.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(h) // Space: O(1) /** From 6932efe46ca339d78ab20acccba158ae1bc301b0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jul 2015 11:16:14 +0800 Subject: [PATCH 0480/1939] Rename lowest-common-ancestor-of-a-binary-search-tree.ph to lowest-common-ancestor-of-a-binary-search-tree.py --- ...-tree.ph => lowest-common-ancestor-of-a-binary-search-tree.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{lowest-common-ancestor-of-a-binary-search-tree.ph => lowest-common-ancestor-of-a-binary-search-tree.py} (100%) diff --git a/Python/lowest-common-ancestor-of-a-binary-search-tree.ph b/Python/lowest-common-ancestor-of-a-binary-search-tree.py similarity index 100% rename from Python/lowest-common-ancestor-of-a-binary-search-tree.ph rename to Python/lowest-common-ancestor-of-a-binary-search-tree.py From 8dd2e98de70ad069654d3797cad9ff8794b86f06 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jul 2015 11:18:10 +0800 Subject: [PATCH 0481/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ba3264d34..f874a689e 100644 --- a/README.md +++ b/README.md @@ -301,7 +301,7 @@ Shell -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) [Python](./Python/contains-duplicate-iii.py) | _O(nlogk)_ | _O(k)_ | medium || 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(max(h, k))_ | _O(min(h, k))_ | Medium || -235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-search-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-search-tree.py) | _O(h)_ | _O(1)_ | Easy || +235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-search-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-search-tree.py) | _O(h)_ | _O(1)_ | Easy | EPI | --- From a691d7405e823e1ab9a6144db80beedb36b446a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jul 2015 09:51:49 +0800 Subject: [PATCH 0482/1939] Create lowest-common-ancestor-of-a-binary-tree.cpp --- ...owest-common-ancestor-of-a-binary-tree.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/lowest-common-ancestor-of-a-binary-tree.cpp diff --git a/C++/lowest-common-ancestor-of-a-binary-tree.cpp b/C++/lowest-common-ancestor-of-a-binary-tree.cpp new file mode 100644 index 000000000..16eea4451 --- /dev/null +++ b/C++/lowest-common-ancestor-of-a-binary-tree.cpp @@ -0,0 +1,29 @@ +// Time: O(h) +// Space: O(h) + +/** + * 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: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (!root || root == p || root == q) { + return root; + } + TreeNode *left = lowestCommonAncestor(root->left, p, q); + TreeNode *right = lowestCommonAncestor(root->right, p, q); + // 1. If the current subtree contains both p and q, + // then result is their LCA. + // 2. If only one of them is in that subtree, + // the result is that one of them. + // 3. If neither of them is in that subtree, + // the result is the node of that subtree. + return left ? (right ? root : left) : right; + } +}; From dc9f6498ae40b6a39cba9dc343ed8ea27bfd6737 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jul 2015 09:52:51 +0800 Subject: [PATCH 0483/1939] Update lowest-common-ancestor-of-a-binary-tree.cpp --- C++/lowest-common-ancestor-of-a-binary-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lowest-common-ancestor-of-a-binary-tree.cpp b/C++/lowest-common-ancestor-of-a-binary-tree.cpp index 16eea4451..01f41d250 100644 --- a/C++/lowest-common-ancestor-of-a-binary-tree.cpp +++ b/C++/lowest-common-ancestor-of-a-binary-tree.cpp @@ -19,7 +19,7 @@ class Solution { TreeNode *left = lowestCommonAncestor(root->left, p, q); TreeNode *right = lowestCommonAncestor(root->right, p, q); // 1. If the current subtree contains both p and q, - // then result is their LCA. + // the result is their LCA. // 2. If only one of them is in that subtree, // the result is that one of them. // 3. If neither of them is in that subtree, From 6104646af091eddf1be06981f7c8532eed09fcf3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jul 2015 10:01:07 +0800 Subject: [PATCH 0484/1939] Create lowest-common-ancestor-of-a-binary-tree.py --- ...lowest-common-ancestor-of-a-binary-tree.py | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/lowest-common-ancestor-of-a-binary-tree.py diff --git a/Python/lowest-common-ancestor-of-a-binary-tree.py b/Python/lowest-common-ancestor-of-a-binary-tree.py new file mode 100644 index 000000000..2059f78dd --- /dev/null +++ b/Python/lowest-common-ancestor-of-a-binary-tree.py @@ -0,0 +1,47 @@ +# Time: O(h) +# Space: O(h) +# +# Given a binary tree, find the lowest common ancestor (LCA) +# of two given nodes in the tree. +# +# According to the definition of LCA on Wikipedia: “The lowest +# common ancestor is defined between two nodes v and w as the +# lowest node in T that has both v and w as descendants (where we +# allow a node to be a descendant of itself).” +# +# _______3______ +# / \ +# ___5__ ___1__ +# / \ / \ +# 6 _2 0 8 +# / \ +# 7 4 +# For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. +# Another example is LCA of nodes 5 and 4 is 5, since a node can be a +# descendant of itself according to the LCA definition. +# +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param {TreeNode} root + # @param {TreeNode} p + # @param {TreeNode} q + # @return {TreeNode} + def lowestCommonAncestor(self, root, p, q): + if root in (None, p, q): + return root + + left, right = [self.lowestCommonAncestor(child, p, q) \ + for child in (root.left, root.right)] + # 1. If the current subtree contains both p and q, + # return their LCA. + # 2. If only one of them is in that subtree, + # return one of them. + # 3. If neither of them is in that subtree, + # return the node of that subtree. + return root if left and right else left or right From e54d42b29d2abe753496efb704789486ef76993d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jul 2015 10:01:29 +0800 Subject: [PATCH 0485/1939] Update lowest-common-ancestor-of-a-binary-tree.cpp --- C++/lowest-common-ancestor-of-a-binary-tree.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/lowest-common-ancestor-of-a-binary-tree.cpp b/C++/lowest-common-ancestor-of-a-binary-tree.cpp index 01f41d250..af65f6921 100644 --- a/C++/lowest-common-ancestor-of-a-binary-tree.cpp +++ b/C++/lowest-common-ancestor-of-a-binary-tree.cpp @@ -19,11 +19,11 @@ class Solution { TreeNode *left = lowestCommonAncestor(root->left, p, q); TreeNode *right = lowestCommonAncestor(root->right, p, q); // 1. If the current subtree contains both p and q, - // the result is their LCA. + // return their LCA. // 2. If only one of them is in that subtree, - // the result is that one of them. + // return that one of them. // 3. If neither of them is in that subtree, - // the result is the node of that subtree. + // return the node of that subtree. return left ? (right ? root : left) : right; } }; From e3d00a4e19210f26144a025931fa225e8d50f49e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jul 2015 10:02:02 +0800 Subject: [PATCH 0486/1939] Update lowest-common-ancestor-of-a-binary-tree.py --- Python/lowest-common-ancestor-of-a-binary-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/lowest-common-ancestor-of-a-binary-tree.py b/Python/lowest-common-ancestor-of-a-binary-tree.py index 2059f78dd..1b5e75d47 100644 --- a/Python/lowest-common-ancestor-of-a-binary-tree.py +++ b/Python/lowest-common-ancestor-of-a-binary-tree.py @@ -41,7 +41,7 @@ def lowestCommonAncestor(self, root, p, q): # 1. If the current subtree contains both p and q, # return their LCA. # 2. If only one of them is in that subtree, - # return one of them. + # return that one of them. # 3. If neither of them is in that subtree, # return the node of that subtree. return root if left and right else left or right From 7fb3f16ed8859b691be8666696b902a9ada6f797 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jul 2015 10:03:20 +0800 Subject: [PATCH 0487/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f874a689e..0ac409009 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-11), there are `219` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-13), there are `220` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `235` problems. +Here is the classification of all `236` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -338,6 +338,7 @@ Shell 199| [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || 216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(k * C(n, k))_ | _O(k)_ | Medium || +236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-tree.py) | _O(h)_ | _O(h)_ | Medium | EPI | --- From 3c67bb4a98604881bc3e61ef8939976f199ceab0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jul 2015 09:19:09 +0800 Subject: [PATCH 0488/1939] Create delete-node-in-a-linked-list.cpp --- C++/delete-node-in-a-linked-list.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/delete-node-in-a-linked-list.cpp diff --git a/C++/delete-node-in-a-linked-list.cpp b/C++/delete-node-in-a-linked-list.cpp new file mode 100644 index 000000000..17f100faf --- /dev/null +++ b/C++/delete-node-in-a-linked-list.cpp @@ -0,0 +1,23 @@ +// Time: O(1) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + void deleteNode(ListNode* node) { + if (!node || !node->next) { + return; + } + auto node_to_delete = node->next; + node->val = node->next->val; + node->next = node->next->next; + delete node_to_delete; + } +}; From 4e06d4f8f0cedd7bae21865c3652da4b6dc294c5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jul 2015 09:27:23 +0800 Subject: [PATCH 0489/1939] Create delete-node-in-a-linked-list.py --- Python/delete-node-in-a-linked-list.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/delete-node-in-a-linked-list.py diff --git a/Python/delete-node-in-a-linked-list.py b/Python/delete-node-in-a-linked-list.py new file mode 100644 index 000000000..9c3cce66b --- /dev/null +++ b/Python/delete-node-in-a-linked-list.py @@ -0,0 +1,24 @@ +# Time: O(1) +# Space: O(1) +# +# Write a function to delete a node (except the tail) in a singly linked list, +# given only access to that node. +# +# Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node +# with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. +# +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param {ListNode} node + # @return {void} Do not return anything, modify node in-place instead. + def deleteNode(self, node): + if node and node.next: + node_to_delete = node.next + node.val = node_to_delete.val + node.next = node_to_delete.next + del node_to_delete From 9569c14f4a9100775365c180e05bd7e013f54994 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jul 2015 09:29:10 +0800 Subject: [PATCH 0490/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0ac409009..dc3fb2655 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-13), there are `220` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-15), there are `221` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `236` problems. +Here is the classification of all `237` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -129,7 +129,8 @@ Shell 160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || 203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || 206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || -234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || +234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || +237| [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./C++/delete-node-in-a-linked-list.cpp) [Python](./Python/delete-node-in-a-linked-list.py) | _O(1)_ | _O(1)_ | Easy | LintCode | --- From 35571db2e66578c28fa22c5954e06a278b3cea70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jul 2015 09:58:50 +0800 Subject: [PATCH 0491/1939] Create product-of-array-except-self.cpp --- C++/product-of-array-except-self.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/product-of-array-except-self.cpp diff --git a/C++/product-of-array-except-self.cpp b/C++/product-of-array-except-self.cpp new file mode 100644 index 000000000..e1d120ce1 --- /dev/null +++ b/C++/product-of-array-except-self.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector productExceptSelf(vector& nums) { + if (nums.empty()) { + return {}; + } + + vector left_product(nums.size()); + + left_product[0] = 1; + for (int i = 1; i < nums.size(); ++i) { + left_product[i] = left_product[i - 1] * nums[i - 1]; + } + + int right_product = 1; + for (int j = nums.size() - 2; j >= 0; --j) { + right_product *= nums[j + 1]; + left_product[j] = left_product[j] * right_product; + } + + return left_product; + } +}; From 9555331ea4dd398496a044b1b321bf9201dd31f6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jul 2015 10:09:20 +0800 Subject: [PATCH 0492/1939] Update product-of-array-except-self.cpp --- C++/product-of-array-except-self.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/product-of-array-except-self.cpp b/C++/product-of-array-except-self.cpp index e1d120ce1..e9b218fa7 100644 --- a/C++/product-of-array-except-self.cpp +++ b/C++/product-of-array-except-self.cpp @@ -16,9 +16,9 @@ class Solution { } int right_product = 1; - for (int j = nums.size() - 2; j >= 0; --j) { - right_product *= nums[j + 1]; - left_product[j] = left_product[j] * right_product; + for (int i = nums.size() - 2; i >= 0; --i) { + right_product *= nums[i + 1]; + left_product[i] = left_product[i] * right_product; } return left_product; From e6900939ff980338087044f0f7dcd3aa6c384b54 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jul 2015 10:12:11 +0800 Subject: [PATCH 0493/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index dc3fb2655..57dfe2cc7 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-15), there are `221` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-15), there are `222` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `237` problems. +Here is the classification of all `238` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -88,7 +88,8 @@ Shell 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Easy | | -229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | +229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | | +238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [C++](./C++/product-of-array-except-self.cpp) [Python](./Python/product-of-array-except-self.py) | _O(n)_ | _O(1)_ | Medium | LintCode | --- From c405337cfbe655a71f9f3f0af2565b62dd478a8a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jul 2015 10:13:20 +0800 Subject: [PATCH 0494/1939] Update product-of-array-except-self.cpp --- C++/product-of-array-except-self.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/product-of-array-except-self.cpp b/C++/product-of-array-except-self.cpp index e9b218fa7..0d516b10e 100644 --- a/C++/product-of-array-except-self.cpp +++ b/C++/product-of-array-except-self.cpp @@ -16,7 +16,7 @@ class Solution { } int right_product = 1; - for (int i = nums.size() - 2; i >= 0; --i) { + for (int i = static_cast(nums.size()) - 2; i >= 0; --i) { right_product *= nums[i + 1]; left_product[i] = left_product[i] * right_product; } From bd0b777cdab7e6ef4de4474c74f542372837ce7b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jul 2015 10:13:48 +0800 Subject: [PATCH 0495/1939] Create product-of-array-except-self.py --- Python/product-of-array-except-self.py | 35 ++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/product-of-array-except-self.py diff --git a/Python/product-of-array-except-self.py b/Python/product-of-array-except-self.py new file mode 100644 index 000000000..f9646d83a --- /dev/null +++ b/Python/product-of-array-except-self.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(1) +# +# Given an array of n integers where n > 1, nums, +# return an array output such that output[i] is equal to +# the product of all the elements of nums except nums[i]. +# +# Solve it without division and in O(n). +# +# For example, given [1,2,3,4], return [24,12,8,6]. +# +# +# Follow up: +# Could you solve it with constant space complexity? +# (Note: The output array does not count as extra space +# for the purpose of space complexity analysis.) +# + +class Solution: + # @param {integer[]} nums + # @return {integer[]} + def productExceptSelf(self, nums): + if not nums: + return [] + + left_product = [1 for _ in xrange(len(nums))] + for i in xrange(1, len(nums)): + left_product[i] = left_product[i - 1] * nums[i - 1] + + right_product = 1 + for i in xrange(len(nums) - 2, -1, -1): + right_product *= nums[i + 1] + left_product[i] = left_product[i] * right_product + + return left_product From 8f89c0ed66f1378f21a5704e15a09769b3587602 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jul 2015 10:29:24 +0800 Subject: [PATCH 0496/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 57dfe2cc7..e81693bcd 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-07-15), there are `222` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-16), https://sites.google.com/site/greproject/there are `222` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. Here is the classification of all `238` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 17d820a15ef2ee41872c042bd9aa2dbb2af55b7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jul 2015 10:30:27 +0800 Subject: [PATCH 0497/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e81693bcd..cef284161 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-07-16), https://sites.google.com/site/greproject/there are `222` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-16), there are `222` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. Here is the classification of all `238` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 9c93b82664559ee0ea33da7575ccc870f0c9e896 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jul 2015 12:11:06 +0800 Subject: [PATCH 0498/1939] Create sliding-window-maximum.cpp --- C++/sliding-window-maximum.cpp | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/sliding-window-maximum.cpp diff --git a/C++/sliding-window-maximum.cpp b/C++/sliding-window-maximum.cpp new file mode 100644 index 000000000..f92542a27 --- /dev/null +++ b/C++/sliding-window-maximum.cpp @@ -0,0 +1,36 @@ +// Time: O(n) +// Space: O(k) + +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + const int n = nums.size(); + deque q; + vector max_numbers; + + for (int i = 0; i < k; ++i) { + while (!q.empty() && nums[i] >= nums[q.back()]) { + q.pop_back(); + } + q.emplace_back(i); + } + + for (int i = k; i < n; ++i) { + max_numbers.emplace_back(nums[q.front()]); + + while (!q.empty() && nums[i] >= nums[q.back()]) { + q.pop_back(); + } + while (!q.empty() && q.front() <= i - k) { + q.pop_front(); + } + q.emplace_back(i); + } + + if (!q.empty()) { + max_numbers.emplace_back(nums[q.front()]); + } + + return max_numbers; + } +}; From 85299d6551188f939eb300b020b5c6efe4985ae9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jul 2015 12:16:11 +0800 Subject: [PATCH 0499/1939] Update README.md --- README.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cef284161..f3483ea49 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-16), there are `222` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-18), there are `223` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `238` problems. +Here is the classification of all `239` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -17,6 +17,7 @@ Algorithms * [String](https://github.com/kamyu104/LeetCode#string) * [Linked List](https://github.com/kamyu104/LeetCode#linked-list) * [Stack](https://github.com/kamyu104/LeetCode#stack) +* [Queue](https://github.com/kamyu104/LeetCode#queue) * [Heap](https://github.com/kamyu104/LeetCode#heap) * [Tree](https://github.com/kamyu104/LeetCode#tree) * [Hash Table](https://github.com/kamyu104/LeetCode#hash-table) @@ -151,6 +152,13 @@ Shell --- +##Queue + # | Problem | Solution | Time | Space | Difficulty | Tag | Note +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard || + +--- + ##Heap # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- From ebe2c9905d9eb56ea3f1243e3b75a8ccfdc34156 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jul 2015 12:26:05 +0800 Subject: [PATCH 0500/1939] Create sliding-window-maximum.cpp --- Python/sliding-window-maximum.cpp | 58 +++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Python/sliding-window-maximum.cpp diff --git a/Python/sliding-window-maximum.cpp b/Python/sliding-window-maximum.cpp new file mode 100644 index 000000000..1818c2a36 --- /dev/null +++ b/Python/sliding-window-maximum.cpp @@ -0,0 +1,58 @@ +# Time: O(n) +# Space: O(k) +# +# Given an array nums, there is a sliding window of size k +# which is moving from the very left of the array to the +# very right. You can only see the k numbers in the window. +# Each time the sliding window moves right by one position. +# +# For example, +# Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. +# +# Window position Max +# --------------- ----- +# [1 3 -1] -3 5 3 6 7 3 +# 1 [3 -1 -3] 5 3 6 7 3 +# 1 3 [-1 -3 5] 3 6 7 5 +# 1 3 -1 [-3 5 3] 6 7 5 +# 1 3 -1 -3 [5 3 6] 7 6 +# 1 3 -1 -3 5 [3 6 7] 7 +# Therefore, return the max sliding window as [3,3,5,5,6,7]. +# +# Note: +# You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array. +# +# Follow up: +# Could you solve it in linear time? +# + +from collections import deque + +class Solution: + # @param {integer[]} nums + # @param {integer} k + # @return {integer[]} + def maxSlidingWindow(self, nums, k): + q = deque() + max_numbers = [] + + for i in xrange(k): + while q and nums[i] >= nums[q[-1]]: + q.pop() + q.append(i) + + for i in xrange(k, len(nums)): + max_numbers.append(nums[q[0]]) + + while q and nums[i] >= nums[q[-1]]: + q.pop() + + while q and q[0] <= i - k: + q.popleft() + + q.append(i) + + if q: + max_numbers.append(nums[q[0]]) + + return max_numbers From cb8cc55c475a93f6d987da04bbe78ef944a80454 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jul 2015 12:26:40 +0800 Subject: [PATCH 0501/1939] Rename sliding-window-maximum.cpp to sliding-window-maximum.py --- Python/{sliding-window-maximum.cpp => sliding-window-maximum.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{sliding-window-maximum.cpp => sliding-window-maximum.py} (100%) diff --git a/Python/sliding-window-maximum.cpp b/Python/sliding-window-maximum.py similarity index 100% rename from Python/sliding-window-maximum.cpp rename to Python/sliding-window-maximum.py From 00693bc9015c3d51825738f76a80b7bdd21807f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jul 2015 12:28:09 +0800 Subject: [PATCH 0502/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f3483ea49..37837a5fa 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Shell ##Queue # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard || +239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard | EPI, LintCode | --- From 81084d98be377911d33c7c85d525e6002ba7a197 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jul 2015 19:47:53 +0800 Subject: [PATCH 0503/1939] Create copy-books.cpp --- C++/copy-books.cpp | 50 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 C++/copy-books.cpp diff --git a/C++/copy-books.cpp b/C++/copy-books.cpp new file mode 100644 index 000000000..72a719d1d --- /dev/null +++ b/C++/copy-books.cpp @@ -0,0 +1,50 @@ +// Time: O(nlogp), p is total pages. +// Space: O(1) + +class Solution { +public: + /** + * @param pages: a vector of integers + * @param k: an integer + * @return: an integer + */ + int copyBooks(vector &pages, int k) { + if (k >= pages.size()) { + return *max_element(pages.cbegin(), pages.cend()); + } + + int sum = 0; + for (const auto& page : pages) { + sum += page; + } + int average = sum / k; // Lower bound. + return binary_search(pages, k, average, sum); + } + + int binary_search(const vector &pages, + const int k, int left, int right) { + while (left <= right) { + int mid = left + (right - left) / 2; + if (valid(pages, k, mid)) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } + + // Check whether everyone copying at most x pages works or not. + bool valid(const vector &pages, const int k, const int x) { + int sum = 0; + int people = 0; + for (int i = 0; i < pages.size() && people < k; ++i) { + if (sum + pages[i] > x) { + sum = 0; + ++people; + } + sum += pages[i]; + } + return people < k && sum <= x; + } +}; From 3c99b19f0516aa879f2c0f4dbfef4e69332473fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jul 2015 19:48:36 +0800 Subject: [PATCH 0504/1939] Delete copy-books.cpp --- C++/copy-books.cpp | 50 ---------------------------------------------- 1 file changed, 50 deletions(-) delete mode 100644 C++/copy-books.cpp diff --git a/C++/copy-books.cpp b/C++/copy-books.cpp deleted file mode 100644 index 72a719d1d..000000000 --- a/C++/copy-books.cpp +++ /dev/null @@ -1,50 +0,0 @@ -// Time: O(nlogp), p is total pages. -// Space: O(1) - -class Solution { -public: - /** - * @param pages: a vector of integers - * @param k: an integer - * @return: an integer - */ - int copyBooks(vector &pages, int k) { - if (k >= pages.size()) { - return *max_element(pages.cbegin(), pages.cend()); - } - - int sum = 0; - for (const auto& page : pages) { - sum += page; - } - int average = sum / k; // Lower bound. - return binary_search(pages, k, average, sum); - } - - int binary_search(const vector &pages, - const int k, int left, int right) { - while (left <= right) { - int mid = left + (right - left) / 2; - if (valid(pages, k, mid)) { - right = mid - 1; - } else { - left = mid + 1; - } - } - return left; - } - - // Check whether everyone copying at most x pages works or not. - bool valid(const vector &pages, const int k, const int x) { - int sum = 0; - int people = 0; - for (int i = 0; i < pages.size() && people < k; ++i) { - if (sum + pages[i] > x) { - sum = 0; - ++people; - } - sum += pages[i]; - } - return people < k && sum <= x; - } -}; From 31746f814f980e4c3d68340adbbb7ee918360d93 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Jul 2015 13:31:49 +0800 Subject: [PATCH 0505/1939] Update reverse-integer.py --- Python/reverse-integer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index 69692d017..154445314 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -28,10 +28,10 @@ def reverse(self, x): while x: ans = ans * 10 + x % 10 x /= 10 - return ans + return ans if ans <= 2147483647 else 0 # Handle overflow. else: return -self.reverse(-x) if __name__ == "__main__": print Solution().reverse(123) - print Solution().reverse(-321) \ No newline at end of file + print Solution().reverse(-321) From b5acf0c72d5dab6a13d685056631594e57759cc2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jul 2015 09:02:23 +0800 Subject: [PATCH 0506/1939] Create search-a-2d-matrix-ii.cpp --- C++/search-a-2d-matrix-ii.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/search-a-2d-matrix-ii.cpp diff --git a/C++/search-a-2d-matrix-ii.cpp b/C++/search-a-2d-matrix-ii.cpp new file mode 100644 index 000000000..81e6df6c0 --- /dev/null +++ b/C++/search-a-2d-matrix-ii.cpp @@ -0,0 +1,30 @@ +// Time: O(m + n) +// Space: O(1) + +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + const int m = matrix.size(); + if (m == 0) { + return 0; + } + const int n = matrix[0].size(); + if (n == 0) { + return 0; + } + int count = 0; + + int i = 0, j = n - 1; + while (i < m && j >= 0) { + if (matrix[i][j] == target) { + return true; + } else if (matrix[i][j] > target) { + --j; + } else { + ++i; + } + } + + return false; + } +}; From 68ad994b12d6954fc458b9deae923d04d22abd2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jul 2015 09:04:57 +0800 Subject: [PATCH 0507/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 37837a5fa..6c5aa7dce 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-18), there are `223` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-18), there are `224` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `239` problems. +Here is the classification of all `240` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -91,6 +91,7 @@ Shell 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Easy | | 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [C++](./C++/product-of-array-except-self.cpp) [Python](./Python/product-of-array-except-self.py) | _O(n)_ | _O(1)_ | Medium | LintCode | +240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) | [C++](./C++/search-a-2d-matrix-ii.cpp) [Python](./Python/search-a-2d-matrix-ii.py) | _O(m + n)_ | _O(1)_ | Medium | EPI, LintCode | --- From b3caf0eec84fb6128384fb60dff6e887a74740af Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jul 2015 09:05:14 +0800 Subject: [PATCH 0508/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6c5aa7dce..e47dcc688 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-07-18), there are `224` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-23), there are `224` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. Here is the classification of all `240` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 125fb2bbd57ed7f18a73b2fb5e1fa7bc31bd6a94 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jul 2015 09:13:25 +0800 Subject: [PATCH 0509/1939] Create search-a-2d-matrix-ii.py --- Python/search-a-2d-matrix-ii.py | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/search-a-2d-matrix-ii.py diff --git a/Python/search-a-2d-matrix-ii.py b/Python/search-a-2d-matrix-ii.py new file mode 100644 index 000000000..520f7030a --- /dev/null +++ b/Python/search-a-2d-matrix-ii.py @@ -0,0 +1,47 @@ +# Time: O(m + n) +# Space: O(1) +# +# Write an efficient algorithm that searches for a value in an m x n matrix. +# This matrix has the following properties: +# +# Integers in each row are sorted in ascending from left to right. +# Integers in each column are sorted in ascending from top to bottom. +# For example, +# +# Consider the following matrix: +# +# [ +# [1, 4, 7, 11, 15], +# [2, 5, 8, 12, 19], +# [3, 6, 9, 16, 22], +# [10, 13, 14, 17, 24], +# [18, 21, 23, 26, 30] +# ] +# Given target = 5, return true. +# +# Given target = 20, return false. +# + +class Solution: + # @param {integer[][]} matrix + # @param {integer} target + # @return {boolean} + def searchMatrix(self, matrix, target): + m = len(matrix) + if m == 0: + return False + + n = len(matrix[0]) + if n == 0: + return False + + count, i, j = 0, 0, n - 1 + while i < m and j >= 0: + if matrix[i][j] == target: + return True + elif matrix[i][j] > target: + j -= 1 + else: + i += 1 + + return False From 07afc25cb734983464cc3566bb00823816234cbc Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jul 2015 09:13:54 +0800 Subject: [PATCH 0510/1939] Update search-a-2d-matrix-ii.cpp --- C++/search-a-2d-matrix-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/search-a-2d-matrix-ii.cpp b/C++/search-a-2d-matrix-ii.cpp index 81e6df6c0..e2af261ce 100644 --- a/C++/search-a-2d-matrix-ii.cpp +++ b/C++/search-a-2d-matrix-ii.cpp @@ -6,11 +6,11 @@ class Solution { bool searchMatrix(vector>& matrix, int target) { const int m = matrix.size(); if (m == 0) { - return 0; + return false; } const int n = matrix[0].size(); if (n == 0) { - return 0; + return false; } int count = 0; From 2c462e67b506886b70b879d09f167895f9e202c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 22:27:08 +0800 Subject: [PATCH 0511/1939] Create different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 132 ++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 C++/different-ways-to-add-parentheses.cpp diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp new file mode 100644 index 000000000..0531d3b4f --- /dev/null +++ b/C++/different-ways-to-add-parentheses.cpp @@ -0,0 +1,132 @@ +// Time: O(n * (C(2n, n) - C(2n, n - 1))) +// Space: O(n^2 * (C(2n, n) - C(2n, n - 1))) + +class Solution { + public: + vector diffWaysToCompute(string input) { + vector>> lookup(input.length() + 1, + vector>(input.length() + 1, vector())); + return diffWaysToComputeRecu(input, 0, input.length(), lookup); + } + + vector diffWaysToComputeRecu(const string& input, + const int start, const int end, + vector>>& lookup) { + if (start == end) { + return {}; + } + + if (!lookup[start][end].empty()) { + return lookup[start][end]; + } + + vector result; + int i = start; + while (i < end && !isOperator(input[i])) { + ++i; + } + if (i == end) { + result.emplace_back(move(stoi(input.substr(start, end - start)))); + return result; + } + + i = start; + while (i < end) { + while (i < end && !isOperator(input[i])) { + ++i; + } + if (i < end) { + vector left = diffWaysToComputeRecu(input, start, i, lookup); + vector right = diffWaysToComputeRecu(input, i + 1, end, lookup); + for (int j = 0; j < left.size(); ++j) { + for(int k = 0; k < right.size(); ++k) { + result.emplace_back(move(compute(input[i],left[j], right[k]))); + } + } + } + ++i; + } + lookup[start][end] = move(result); + return lookup[start][end]; + } + + bool isOperator(const char c){ + return string("+-*").find(string(1, c)) != string::npos; + } + + int compute(const char c, const int left, const int right){ + switch (c) { + case '+': + return left + right; + case '-': + return left - right; + case '*': + return left * right; + default: + return 0; + } + return 0; + } +}; + +// Time: O(n^2 * (C(2n, n) - C(2n, n - 1))) +// Space: O(C(2n, n) - C(2n, n - 1)) +class Solution2 { + public: + vector diffWaysToCompute(string input) { + return diffWaysToComputeRecu(input, 0, input.length()); + } + + vector diffWaysToComputeRecu(const string& input, + const int start, const int end) { + if (start == end) { + return {}; + } + + vector result; + int i = start; + while (i < end && !isOperator(input[i])) { + ++i; + } + if (i == end) { + result.emplace_back(move(stoi(input.substr(start, end - start)))); + return result; + } + + i = start; + while (i < end) { + while (i < end && !isOperator(input[i])) { + ++i; + } + if (i < end) { + vector left = diffWaysToComputeRecu(input, start, i); + vector right = diffWaysToComputeRecu(input, i + 1, end); + for (int j = 0; j < left.size(); ++j) { + for(int k = 0; k < right.size(); ++k) { + result.emplace_back(move(compute(input[i],left[j], right[k]))); + } + } + } + ++i; + } + return result; + } + + bool isOperator(const char c){ + return string("+-*").find(string(1, c)) != string::npos; + } + + int compute(const char c, const int left, const int right){ + switch (c) { + case '+': + return left + right; + case '-': + return left - right; + case '*': + return left * right; + default: + return 0; + } + return 0; + } +}; From 63059317aff12b4fbbae5a26c58a7c93854b7f25 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 22:28:24 +0800 Subject: [PATCH 0512/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 0531d3b4f..0510015db 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -1,4 +1,4 @@ -// Time: O(n * (C(2n, n) - C(2n, n - 1))) +// Time: O(C(2n, n) - C(2n, n - 1)) // Space: O(n^2 * (C(2n, n) - C(2n, n - 1))) class Solution { From eb8c5e5f25917e8209899d54bd870167ae115326 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 22:35:40 +0800 Subject: [PATCH 0513/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 0510015db..0531d3b4f 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -1,4 +1,4 @@ -// Time: O(C(2n, n) - C(2n, n - 1)) +// Time: O(n * (C(2n, n) - C(2n, n - 1))) // Space: O(n^2 * (C(2n, n) - C(2n, n - 1))) class Solution { From b31f55570dd6881ec66af4485fac931f01dc53c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 22:41:58 +0800 Subject: [PATCH 0514/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 66 +++++++---------------- 1 file changed, 18 insertions(+), 48 deletions(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 0531d3b4f..5393e2c37 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -74,59 +74,29 @@ class Solution { class Solution2 { public: vector diffWaysToCompute(string input) { - return diffWaysToComputeRecu(input, 0, input.length()); - } - - vector diffWaysToComputeRecu(const string& input, - const int start, const int end) { - if (start == end) { - return {}; - } - vector result; - int i = start; - while (i < end && !isOperator(input[i])) { - ++i; - } - if (i == end) { - result.emplace_back(move(stoi(input.substr(start, end - start)))); - return result; - } - - i = start; - while (i < end) { - while (i < end && !isOperator(input[i])) { - ++i; - } - if (i < end) { - vector left = diffWaysToComputeRecu(input, start, i); - vector right = diffWaysToComputeRecu(input, i + 1, end); - for (int j = 0; j < left.size(); ++j) { - for(int k = 0; k < right.size(); ++k) { - result.emplace_back(move(compute(input[i],left[j], right[k]))); + for (int i = 0; i < input.size(); ++i) { + char cur = input[i]; + if (cur == '+' || cur == '-' || cur == '*') { + vector left = diffWaysToCompute(input.substr(0, i)); + vector right = diffWaysToCompute(input.substr(i + 1)); + for (const auto& num1 : left) { + for (const auto& num2 : right) { + if (cur == '+') { + result.emplace_back(num1 + num2); + } else if (cur == '-') { + result.emplace_back(num1 - num2); + } else { + result.emplace_back(num1 * num2); + } } } } - ++i; } - return result; - } - - bool isOperator(const char c){ - return string("+-*").find(string(1, c)) != string::npos; - } - - int compute(const char c, const int left, const int right){ - switch (c) { - case '+': - return left + right; - case '-': - return left - right; - case '*': - return left * right; - default: - return 0; + // if the input string contains only number + if (result.empty()) { + result.emplace_back(stoi(input)); } - return 0; + return result; } }; From caea6e08180171c37abbbc2093b29c1162fe5f0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 22:42:56 +0800 Subject: [PATCH 0515/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 5393e2c37..949ccab80 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -76,7 +76,7 @@ class Solution2 { vector diffWaysToCompute(string input) { vector result; for (int i = 0; i < input.size(); ++i) { - char cur = input[i]; + const auto cur = input[i]; if (cur == '+' || cur == '-' || cur == '*') { vector left = diffWaysToCompute(input.substr(0, i)); vector right = diffWaysToCompute(input.substr(i + 1)); From 4f1f250a52d170c6e84d7f27bbb8a14a31a80b89 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 22:47:50 +0800 Subject: [PATCH 0516/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 58 +++++++---------------- 1 file changed, 16 insertions(+), 42 deletions(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 949ccab80..8e7a960a5 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -12,61 +12,35 @@ class Solution { vector diffWaysToComputeRecu(const string& input, const int start, const int end, vector>>& lookup) { - if (start == end) { - return {}; - } - if (!lookup[start][end].empty()) { return lookup[start][end]; } - vector result; - int i = start; - while (i < end && !isOperator(input[i])) { - ++i; - } - if (i == end) { - result.emplace_back(move(stoi(input.substr(start, end - start)))); - return result; - } - - i = start; - while (i < end) { - while (i < end && !isOperator(input[i])) { - ++i; - } - if (i < end) { + for (int i = start; i < end; ++i) { + const auto cur = input[i]; + if (cur == '+' || cur == '-' || cur == '*') { vector left = diffWaysToComputeRecu(input, start, i, lookup); vector right = diffWaysToComputeRecu(input, i + 1, end, lookup); - for (int j = 0; j < left.size(); ++j) { - for(int k = 0; k < right.size(); ++k) { - result.emplace_back(move(compute(input[i],left[j], right[k]))); + for (const auto& num1 : left) { + for (const auto& num2 : right) { + if (cur == '+') { + result.emplace_back(num1 + num2); + } else if (cur == '-') { + result.emplace_back(num1 - num2); + } else { + result.emplace_back(num1 * num2); + } } } } - ++i; + } + // if the input string contains only number + if (result.empty()) { + result.emplace_back(stoi(input.substr(start, end - start))); } lookup[start][end] = move(result); return lookup[start][end]; } - - bool isOperator(const char c){ - return string("+-*").find(string(1, c)) != string::npos; - } - - int compute(const char c, const int left, const int right){ - switch (c) { - case '+': - return left + right; - case '-': - return left - right; - case '*': - return left * right; - default: - return 0; - } - return 0; - } }; // Time: O(n^2 * (C(2n, n) - C(2n, n - 1))) From 2180bfc0eb6b669b41b2ac64cf40c39b88cb53e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 22:48:39 +0800 Subject: [PATCH 0517/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 8e7a960a5..0d801c111 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -34,7 +34,7 @@ class Solution { } } } - // if the input string contains only number + // If the input string contains only number. if (result.empty()) { result.emplace_back(stoi(input.substr(start, end - start))); } @@ -67,7 +67,7 @@ class Solution2 { } } } - // if the input string contains only number + // If the input string contains only number. if (result.empty()) { result.emplace_back(stoi(input)); } From 76b81aed34e9a9a70168afdc8514d801c51261eb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 22:51:20 +0800 Subject: [PATCH 0518/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 0d801c111..f27c393da 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -19,8 +19,8 @@ class Solution { for (int i = start; i < end; ++i) { const auto cur = input[i]; if (cur == '+' || cur == '-' || cur == '*') { - vector left = diffWaysToComputeRecu(input, start, i, lookup); - vector right = diffWaysToComputeRecu(input, i + 1, end, lookup); + vector left = move(diffWaysToComputeRecu(input, start, i, lookup)); + vector right = movediffWaysToComputeRecu(input, i + 1, end, lookup)); for (const auto& num1 : left) { for (const auto& num2 : right) { if (cur == '+') { @@ -52,8 +52,8 @@ class Solution2 { for (int i = 0; i < input.size(); ++i) { const auto cur = input[i]; if (cur == '+' || cur == '-' || cur == '*') { - vector left = diffWaysToCompute(input.substr(0, i)); - vector right = diffWaysToCompute(input.substr(i + 1)); + vector left = move(diffWaysToCompute(input.substr(0, i))); + vector right = move(diffWaysToCompute(input.substr(i + 1))); for (const auto& num1 : left) { for (const auto& num2 : right) { if (cur == '+') { From afd4726aed28d4d560869d1c36ee2311b97f934c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:02:43 +0800 Subject: [PATCH 0519/1939] Create different-ways-to-add-parentheses.py --- Python/different-ways-to-add-parentheses.py | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/different-ways-to-add-parentheses.py diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py new file mode 100644 index 000000000..6c3f74f07 --- /dev/null +++ b/Python/different-ways-to-add-parentheses.py @@ -0,0 +1,48 @@ +# Time: O(n * 4^n / n^(3/2)) ~= n * (Catalan numbers) = n * (C(2n, n) - C(2n, n - 1)) +# Space: O(n^2 * 4^n / n^(3/2)) +# +# Given a string of numbers and operators, return all possible +# results from computing all the different possible ways to +# group numbers and operators. The valid operators are +, - and *. +# +# +# Example 1 +# Input: "2-1-1". +# +# ((2-1)-1) = 0 +# (2-(1-1)) = 2 +# Output: [0, 2] +# +# +# Example 2 +# Input: "2*3-4*5" +# +# (2*(3-(4*5))) = -34 +# ((2*3)-(4*5)) = -14 +# ((2*(3-4))*5) = -10 +# (2*((3-4)*5)) = -10 +# (((2*3)-4)*5) = 10 +# Output: [-34, -14, -10, -10, 10] +# + +class Solution: + # @param {string} input + # @return {integer[]} + def diffWaysToCompute(self, input): + tokens = re.split('(\D)', input) + nums = map(int, tokens[::2]) + ops = map({'+': operator.add, '-': operator.sub, '*': operator.mul}.get, tokens[1::2]) + lookup = [[None for _ in xrange(len(nums))] for _ in xrange(len(nums))] + + def diffWaysToComputeRecu(left, right): + if left == right: + return [nums[left]] + if lookup[left][right]: + return lookup[left][right] + lookup[left][right] = [ops[i](x, y) + for i in xrange(left, right) + for x in diffWaysToComputeRecu(left, i) + for y in diffWaysToComputeRecu(i + 1, right)] + return lookup[left][right] + + return diffWaysToComputeRecu(0, len(nums) - 1) From 5b3c28c994ef25f71685e5aa33f168c59b88a5d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:05:59 +0800 Subject: [PATCH 0520/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index f27c393da..5110eba69 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -20,7 +20,7 @@ class Solution { const auto cur = input[i]; if (cur == '+' || cur == '-' || cur == '*') { vector left = move(diffWaysToComputeRecu(input, start, i, lookup)); - vector right = movediffWaysToComputeRecu(input, i + 1, end, lookup)); + vector right = move(diffWaysToComputeRecu(input, i + 1, end, lookup)); for (const auto& num1 : left) { for (const auto& num2 : right) { if (cur == '+') { From 655100a11713f41053a429055f2ad581a7f11579 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:20:21 +0800 Subject: [PATCH 0521/1939] Update different-ways-to-add-parentheses.py --- Python/different-ways-to-add-parentheses.py | 24 +++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py index 6c3f74f07..3e4b1b1f1 100644 --- a/Python/different-ways-to-add-parentheses.py +++ b/Python/different-ways-to-add-parentheses.py @@ -46,3 +46,27 @@ def diffWaysToComputeRecu(left, right): return lookup[left][right] return diffWaysToComputeRecu(0, len(nums) - 1) + +class Solution2: + # @param {string} input + # @return {integer[]} + def diffWaysToCompute(self, input): + lookup = [[None for _ in xrange(len(input) + 1)] for _ in xrange(len(input) + 1)] + ops = {'+': operator.add, '-': operator.sub, '*': operator.mul} + + def diffWaysToComputeRecu(left, right): + if lookup[left][right]: + return lookup[left][right] + result = [] + for i in xrange(left, right): + if input[i] in "+-*": + for x in diffWaysToComputeRecu(left, i): + for y in diffWaysToComputeRecu(i + 1, right): + result.append(ops[input[i]](x, y)) + + if not result: + result = [int(input[left:right])] + lookup[left][right] = result + return lookup[left][right] + + return diffWaysToComputeRecu(0, len(input)) From a65720cc48acd1eaaed0379a44d7dda983b13cb6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:24:02 +0800 Subject: [PATCH 0522/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e47dcc688..3b07fc047 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-23), there are `224` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-07-27), there are `225` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `240` problems. +Here is the classification of all `241` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -287,6 +287,7 @@ Shell 124| [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || 129| [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || 156| [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| +241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n^2 * 4^n / n^(3/2))_ | Medium |📖| --- From f3c812a4a24e9d65ed4c21b13c99a90373ce76c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:26:32 +0800 Subject: [PATCH 0523/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 5110eba69..2f64ea6b7 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -43,7 +43,7 @@ class Solution { } }; -// Time: O(n^2 * (C(2n, n) - C(2n, n - 1))) +// Time: O(n * (C(2n, n) - C(2n, n - 1))) // Space: O(C(2n, n) - C(2n, n - 1)) class Solution2 { public: From 34d4b49f26e1c73715903838f8f556721a2c8309 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:29:58 +0800 Subject: [PATCH 0524/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 2f64ea6b7..55682be38 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -1,4 +1,4 @@ -// Time: O(n * (C(2n, n) - C(2n, n - 1))) +// Time: O(C(2n, n) - C(2n, n - 1)) // Space: O(n^2 * (C(2n, n) - C(2n, n - 1))) class Solution { From 6cc803f68876689629fa2c2bae1413d46a0d2002 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:30:34 +0800 Subject: [PATCH 0525/1939] Update different-ways-to-add-parentheses.py --- Python/different-ways-to-add-parentheses.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py index 3e4b1b1f1..1365fab70 100644 --- a/Python/different-ways-to-add-parentheses.py +++ b/Python/different-ways-to-add-parentheses.py @@ -1,4 +1,4 @@ -# Time: O(n * 4^n / n^(3/2)) ~= n * (Catalan numbers) = n * (C(2n, n) - C(2n, n - 1)) +# Time: O(4^n / n^(3/2)) ~= Catalan numbers = C(2n, n) - C(2n, n - 1) # Space: O(n^2 * 4^n / n^(3/2)) # # Given a string of numbers and operators, return all possible From 9b25950489a50a1e6ba68c3d73d812b5a702ea02 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:38:29 +0800 Subject: [PATCH 0526/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 55682be38..2f64ea6b7 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -1,4 +1,4 @@ -// Time: O(C(2n, n) - C(2n, n - 1)) +// Time: O(n * (C(2n, n) - C(2n, n - 1))) // Space: O(n^2 * (C(2n, n) - C(2n, n - 1))) class Solution { From cffc719d1b751928cc51e379ff105af94ec0fa7d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:39:07 +0800 Subject: [PATCH 0527/1939] Update different-ways-to-add-parentheses.py --- Python/different-ways-to-add-parentheses.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py index 1365fab70..df9b92db5 100644 --- a/Python/different-ways-to-add-parentheses.py +++ b/Python/different-ways-to-add-parentheses.py @@ -1,4 +1,4 @@ -# Time: O(4^n / n^(3/2)) ~= Catalan numbers = C(2n, n) - C(2n, n - 1) +# Time: O(n * 4^n / n^(3/2)) ~= n * Catalan numbers = n * (C(2n, n) - C(2n, n - 1)) # Space: O(n^2 * 4^n / n^(3/2)) # # Given a string of numbers and operators, return all possible From 642af3cebb4db949f77125e3d0592aead5edeee3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:45:02 +0800 Subject: [PATCH 0528/1939] Update different-ways-to-add-parentheses.py --- Python/different-ways-to-add-parentheses.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py index df9b92db5..48a3d7202 100644 --- a/Python/different-ways-to-add-parentheses.py +++ b/Python/different-ways-to-add-parentheses.py @@ -1,5 +1,5 @@ # Time: O(n * 4^n / n^(3/2)) ~= n * Catalan numbers = n * (C(2n, n) - C(2n, n - 1)) -# Space: O(n^2 * 4^n / n^(3/2)) +# Space: O(n * 4^n / n^(3/2)) # # Given a string of numbers and operators, return all possible # results from computing all the different possible ways to From b32106810e6be8ec25d2419f12b774f6c329d28d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:45:32 +0800 Subject: [PATCH 0529/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 2f64ea6b7..bbac05520 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -1,5 +1,5 @@ // Time: O(n * (C(2n, n) - C(2n, n - 1))) -// Space: O(n^2 * (C(2n, n) - C(2n, n - 1))) +// Space: O(n * (C(2n, n) - C(2n, n - 1))) class Solution { public: From 81bafb386ff6de604643e00a252f31738c06ec59 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:47:23 +0800 Subject: [PATCH 0530/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3b07fc047..75136a9e3 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,7 @@ Shell 124| [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || 129| [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || 156| [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| -241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n^2 * 4^n / n^(3/2))_ | Medium |📖| +241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n * 4^n / n^(3/2))_ | Medium |📖| --- From ab3df48a569e8c71accedde41259e5de9209bc85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:50:50 +0800 Subject: [PATCH 0531/1939] Update different-ways-to-add-parentheses.py --- Python/different-ways-to-add-parentheses.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py index 48a3d7202..ac96bb623 100644 --- a/Python/different-ways-to-add-parentheses.py +++ b/Python/different-ways-to-add-parentheses.py @@ -1,4 +1,7 @@ -# Time: O(n * 4^n / n^(3/2)) ~= n * Catalan numbers = n * (C(2n, n) - C(2n, n - 1)) +# Time: O(n * 4^n / n^(3/2)) ~= n * Catalan numbers = n * (C(2n, n) - C(2n, n - 1)), +# due to the size of the results is Catalan numbers, +# and every way of evaluation is the length of the string, +# so time complexity is n * Catalan numbers. # Space: O(n * 4^n / n^(3/2)) # # Given a string of numbers and operators, return all possible From 7f4346a2e467bc272bef503e79993760ce02aa51 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:53:10 +0800 Subject: [PATCH 0532/1939] Update different-ways-to-add-parentheses.py --- Python/different-ways-to-add-parentheses.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py index ac96bb623..5d3f0c7bc 100644 --- a/Python/different-ways-to-add-parentheses.py +++ b/Python/different-ways-to-add-parentheses.py @@ -1,8 +1,8 @@ # Time: O(n * 4^n / n^(3/2)) ~= n * Catalan numbers = n * (C(2n, n) - C(2n, n - 1)), # due to the size of the results is Catalan numbers, # and every way of evaluation is the length of the string, -# so time complexity is n * Catalan numbers. -# Space: O(n * 4^n / n^(3/2)) +# so the time complexity is at most n * Catalan numbers. +# Space: O(n * 4^n / n^(3/2)), the cache size is at most n * Catalan numbers. # # Given a string of numbers and operators, return all possible # results from computing all the different possible ways to From 56b57f016a950b6bffa3eb8ada3db1d8acad57c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:53:46 +0800 Subject: [PATCH 0533/1939] Update different-ways-to-add-parentheses.py --- Python/different-ways-to-add-parentheses.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py index 5d3f0c7bc..1d91bce2f 100644 --- a/Python/different-ways-to-add-parentheses.py +++ b/Python/different-ways-to-add-parentheses.py @@ -2,7 +2,7 @@ # due to the size of the results is Catalan numbers, # and every way of evaluation is the length of the string, # so the time complexity is at most n * Catalan numbers. -# Space: O(n * 4^n / n^(3/2)), the cache size is at most n * Catalan numbers. +# Space: O(n * 4^n / n^(3/2)), the cache size of lookup is at most n * Catalan numbers. # # Given a string of numbers and operators, return all possible # results from computing all the different possible ways to From 6232b50292f4b070d273836452dced1f92cc7083 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:55:34 +0800 Subject: [PATCH 0534/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index bbac05520..432939f0e 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -1,4 +1,4 @@ -// Time: O(n * (C(2n, n) - C(2n, n - 1))) +// Time: O(n * (C(2n, n) - C(2n, n - 1))), at most time // Space: O(n * (C(2n, n) - C(2n, n - 1))) class Solution { @@ -43,7 +43,7 @@ class Solution { } }; -// Time: O(n * (C(2n, n) - C(2n, n - 1))) +// Time: O(n * (C(2n, n) - C(2n, n - 1))), at least time // Space: O(C(2n, n) - C(2n, n - 1)) class Solution2 { public: From 9d2e38baf87c5a22d3fbdaccbe31b04e64eabe76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:56:44 +0800 Subject: [PATCH 0535/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 432939f0e..69578a43e 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -1,4 +1,4 @@ -// Time: O(n * (C(2n, n) - C(2n, n - 1))), at most time +// Time: O(n * (C(2n, n) - C(2n, n - 1))), this is at most // Space: O(n * (C(2n, n) - C(2n, n - 1))) class Solution { @@ -43,7 +43,7 @@ class Solution { } }; -// Time: O(n * (C(2n, n) - C(2n, n - 1))), at least time +// Time: O(n * (C(2n, n) - C(2n, n - 1))), this is at least // Space: O(C(2n, n) - C(2n, n - 1)) class Solution2 { public: From efdf01132ccc549d2ae57bc5143996ac22e97bec Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jul 2015 23:58:02 +0800 Subject: [PATCH 0536/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75136a9e3..080523d04 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,7 @@ Shell 124| [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| [Python](./Python/binary-tree-maximum-path-sum.py) | _O(n)_| _O(h)_| Hard || 129| [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || 156| [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| -241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n * 4^n / n^(3/2))_ | Medium |📖| +241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n * 4^n / n^(3/2))_ | Medium || --- From 2d33dae86bceb5ce3ed3662714c2a0a93ebd7510 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jul 2015 00:10:44 +0800 Subject: [PATCH 0537/1939] Update different-ways-to-add-parentheses.py --- Python/different-ways-to-add-parentheses.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py index 1d91bce2f..b83604fbf 100644 --- a/Python/different-ways-to-add-parentheses.py +++ b/Python/different-ways-to-add-parentheses.py @@ -62,7 +62,7 @@ def diffWaysToComputeRecu(left, right): return lookup[left][right] result = [] for i in xrange(left, right): - if input[i] in "+-*": + if input[i] in ops: for x in diffWaysToComputeRecu(left, i): for y in diffWaysToComputeRecu(i + 1, right): result.append(ops[input[i]](x, y)) From 359eb97f5aae057a2afde3f9a910fad771b3a35d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jul 2015 01:21:33 +0800 Subject: [PATCH 0538/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 69578a43e..a9056b3e3 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -5,7 +5,7 @@ class Solution { public: vector diffWaysToCompute(string input) { vector>> lookup(input.length() + 1, - vector>(input.length() + 1, vector())); + vector>(input.length() + 1)); return diffWaysToComputeRecu(input, 0, input.length(), lookup); } From 253e38e59acfd41e5888bff2ef004981a03cb336 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jul 2015 01:31:08 +0800 Subject: [PATCH 0539/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index a9056b3e3..5409a0367 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -19,8 +19,8 @@ class Solution { for (int i = start; i < end; ++i) { const auto cur = input[i]; if (cur == '+' || cur == '-' || cur == '*') { - vector left = move(diffWaysToComputeRecu(input, start, i, lookup)); - vector right = move(diffWaysToComputeRecu(input, i + 1, end, lookup)); + auto left = diffWaysToComputeRecu(input, start, i, lookup); + auto right = diffWaysToComputeRecu(input, i + 1, end, lookup); for (const auto& num1 : left) { for (const auto& num2 : right) { if (cur == '+') { @@ -38,7 +38,7 @@ class Solution { if (result.empty()) { result.emplace_back(stoi(input.substr(start, end - start))); } - lookup[start][end] = move(result); + lookup[start][end] = result; return lookup[start][end]; } }; @@ -52,8 +52,8 @@ class Solution2 { for (int i = 0; i < input.size(); ++i) { const auto cur = input[i]; if (cur == '+' || cur == '-' || cur == '*') { - vector left = move(diffWaysToCompute(input.substr(0, i))); - vector right = move(diffWaysToCompute(input.substr(i + 1))); + auto left = diffWaysToCompute(input.substr(0, i)); + auto right = diffWaysToCompute(input.substr(i + 1)); for (const auto& num1 : left) { for (const auto& num2 : right) { if (cur == '+') { From 664c458beebf01361a51702b39c52a39e1e63116 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jul 2015 01:35:06 +0800 Subject: [PATCH 0540/1939] Update the-skyline-problem.cpp --- C++/the-skyline-problem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/the-skyline-problem.cpp b/C++/the-skyline-problem.cpp index 1fc948979..626963c95 100644 --- a/C++/the-skyline-problem.cpp +++ b/C++/the-skyline-problem.cpp @@ -56,7 +56,7 @@ class Solution2 { enum {start, end, height}; vector> getSkyline(vector>& buildings) { - const auto intervals = move(ComputeSkylineInInterval(buildings, 0, buildings.size())); + const auto intervals = ComputeSkylineInInterval(buildings, 0, buildings.size()); vector> res; int last_end = -1; @@ -81,8 +81,8 @@ class Solution2 { buildings.cbegin() + right_endpoint}; } int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2); - auto left_skyline = move(ComputeSkylineInInterval(buildings, left_endpoint, mid)); - auto right_skyline = move(ComputeSkylineInInterval(buildings, mid, right_endpoint)); + auto left_skyline = ComputeSkylineInInterval(buildings, left_endpoint, mid); + auto right_skyline = ComputeSkylineInInterval(buildings, mid, right_endpoint); return MergeSkylines(left_skyline, right_skyline); } From fd896c899f918dffbf2459911c9f2f05a2f896ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jul 2015 02:12:08 +0800 Subject: [PATCH 0541/1939] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index c3d25c2a4..10fee886c 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -12,7 +12,7 @@ class Solution { // Assume s is (Palindrome)abc, // A would be (Palindrome)abccba(Palindrome). string A = s + rev_s; - vector prefix(move(getPrefix(A))); + auto prefix = getPrefix(A); // The index prefix.back() of A would be: // (Palindrome)abccba(Palindrome) // ^ From 5ad09271233831b91ab4942e7dc12843c93c6337 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jul 2015 02:59:10 +0800 Subject: [PATCH 0542/1939] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index ba5f67df8..aa366cb02 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -22,8 +22,10 @@ def shortestPalindrome(self, s): A = s + s[::-1] prefix = self.getPrefix(A) - - return s[prefix[-1]+1:][::-1] + s + i = prefix[-1] + while i > len(s) - 1: + i = prefix[i] + return s[i+1:][::-1] + s def getPrefix(self, pattern): prefix = [-1] * len(pattern) From bc4e39b51d24105cde2c676650002604f4d2be67 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jul 2015 03:01:08 +0800 Subject: [PATCH 0543/1939] Update shortest-palindrome.cpp --- C++/shortest-palindrome.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/C++/shortest-palindrome.cpp b/C++/shortest-palindrome.cpp index 10fee886c..094d6df5e 100644 --- a/C++/shortest-palindrome.cpp +++ b/C++/shortest-palindrome.cpp @@ -20,7 +20,11 @@ class Solution { // (Palindrome)abc // ^ // Get non palindrome part of s. - string non_palindrome = s.substr(prefix.back() + 1); + int i = prefix.back(); + while (i >= s.length()) { + i = prefix[i]; + } + string non_palindrome = s.substr(i + 1); reverse(non_palindrome.begin(), non_palindrome.end()); return non_palindrome + s; // cba(Palindrome)abc. } From d12510c5635926bc4914226c19bb9245083f2738 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jul 2015 03:02:43 +0800 Subject: [PATCH 0544/1939] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index aa366cb02..45639926a 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -23,7 +23,7 @@ def shortestPalindrome(self, s): A = s + s[::-1] prefix = self.getPrefix(A) i = prefix[-1] - while i > len(s) - 1: + while i >= len(s): i = prefix[i] return s[i+1:][::-1] + s From 3123fac79c1c74f53ef94b1f6969b164d3b6252f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jul 2015 09:40:40 +0800 Subject: [PATCH 0545/1939] Update different-ways-to-add-parentheses.cpp --- C++/different-ways-to-add-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/different-ways-to-add-parentheses.cpp b/C++/different-ways-to-add-parentheses.cpp index 5409a0367..91f62e9ae 100644 --- a/C++/different-ways-to-add-parentheses.cpp +++ b/C++/different-ways-to-add-parentheses.cpp @@ -49,7 +49,7 @@ class Solution2 { public: vector diffWaysToCompute(string input) { vector result; - for (int i = 0; i < input.size(); ++i) { + for (int i = 0; i < input.length(); ++i) { const auto cur = input[i]; if (cur == '+' || cur == '-' || cur == '*') { auto left = diffWaysToCompute(input.substr(0, i)); From bb1b92a70407a59c04da66e076fe7de05d1619e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Aug 2015 17:38:35 +0800 Subject: [PATCH 0546/1939] Create valid-anagram.cpp --- C++/valid-anagram.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/valid-anagram.cpp diff --git a/C++/valid-anagram.cpp b/C++/valid-anagram.cpp new file mode 100644 index 000000000..3b32f2526 --- /dev/null +++ b/C++/valid-anagram.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool isAnagram(string s, string t) { + if (s.length() != t.length()) { + return false; + } + + unordered_map count; + + for (const auto& c: s) { + ++count[tolower(c)]; + } + + for (const auto& c: t) { + --count[tolower(c)]; + if (count[tolower(c)] < 0) { + return false; + } + } + + return true; + } +}; From 53617403a982dd89c86ec92dd96417792dbf5821 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Aug 2015 17:46:49 +0800 Subject: [PATCH 0547/1939] Create valid-anagram.py --- Python/valid-anagram.py | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/valid-anagram.py diff --git a/Python/valid-anagram.py b/Python/valid-anagram.py new file mode 100644 index 000000000..5fe61e61e --- /dev/null +++ b/Python/valid-anagram.py @@ -0,0 +1,48 @@ +# Time: O(n) +# Space: O(1) +# +# Given two strings s and t, write a function to +# determine if t is an anagram of s. +# +# For example, +# s = "anagram", t = "nagaram", return true. +# s = "rat", t = "car", return false. +# +# Note: +# You may assume the string contains only lowercase alphabets. +# + +class Solution: + # @param {string} s + # @param {string} t + # @return {boolean} + def isAnagram(self, s, t): + if len(s) != len(t): + return False + + count = {} + + for c in s: + if c.lower() in count: + count[c.lower()] += 1 + else: + count[c.lower()] = 1 + + for c in t: + if c.lower() in count: + count[c.lower()] -= 1 + else: + count[c.lower()] = -1 + if count[c.lower()] < 0: + return False + + return True + +# Time: O(nlogn) +# Space: O(n) +class Solution2: + # @param {string} s + # @param {string} t + # @return {boolean} + def isAnagram(self, s, t): + return sorted(s) == sorted(t) From 60fc56206eaa18f9ca139f98679e1209647c015d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Aug 2015 17:49:16 +0800 Subject: [PATCH 0548/1939] Update valid-anagram.cpp --- C++/valid-anagram.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/C++/valid-anagram.cpp b/C++/valid-anagram.cpp index 3b32f2526..290375884 100644 --- a/C++/valid-anagram.cpp +++ b/C++/valid-anagram.cpp @@ -24,3 +24,19 @@ class Solution { return true; } }; + +// Time: O(nlogn) +// Space: O(n) +class Solution2 { +public: + bool isAnagram(string s, string t) { + if (s.length() != t.length()) { + return false; + } + + sort(s.begin(), s.end()); + sort(t.begin(), t.end()); + + return s == t; + } +}; From b9567f3fed9d370f1ec5639c42efbd1403094be4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Aug 2015 17:51:02 +0800 Subject: [PATCH 0549/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 080523d04..8907abd2b 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-07-27), there are `225` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-01), there are `226` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). The number of problems is increasing recently. -Here is the classification of all `241` problems. +Here is the classification of all `242` problems. For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you have to buy the book from LeetCode. ) @@ -134,6 +134,7 @@ Shell 206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 237| [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./C++/delete-node-in-a-linked-list.cpp) [Python](./Python/delete-node-in-a-linked-list.py) | _O(1)_ | _O(1)_ | Easy | LintCode | +242| [Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./C++/valid-anagram.cpp) [Python](./Python/valid-anagram.py) | _O(n)_ | _O(1)_ | Easy | LintCode | --- From 331b879530c104aa33d29591ff38002cf2adfb61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:12:27 +0800 Subject: [PATCH 0550/1939] Create strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 87 ++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 C++/strobogrammatic-number-iii.cpp diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp new file mode 100644 index 000000000..030c17356 --- /dev/null +++ b/C++/strobogrammatic-number-iii.cpp @@ -0,0 +1,87 @@ +// Time: O(5^n) +// Space: O(n) + +class Solution { +public: + int strobogrammaticInRange(string low, string high) { + int count = countStrobogrammaticUntil(high, false) - + countStrobogrammaticUntil(low, false) + + isStrobogrammatic(low); + return count >= 0 ? count : 0; + } + + int countStrobogrammaticUntil(string num, bool canStartWith0) { + int count = 0; + if (num.length() == 1) { + for (const auto& c : {'0', '1', '8'}) { + if (num.front() >= c) { + ++count; + } + } + return count; + } + + for (const auto& kvp : lookup) { + if (canStartWith0 || kvp.first != '0') { + if (num.front() > kvp.first) { + if (num.length() == 2) { // num is like "21" + ++count; + } else { // num is like "201" + count += countStrobogrammaticUntil(string(num.length() - 2, '9'), true); + } + } else if (num.front() == kvp.first) { + if (num.length() == 2) { // num is like 12". + count += num.back() >= kvp.second; + } else { + if (num.back() >= kvp.second) { // num is like "102". + count += countStrobogrammaticUntil(getMid(num), true); + } else if (getMid(num) != string(num.length() - 2, '0')) { // num is like "110". + count += countStrobogrammaticUntil(getMid(num), true); + } + } + } + } + } + + if (!canStartWith0) { // Sum up each length. + for (int i = num.length() - 1; i > 0; --i) { + count += countStrobogrammaticByLength(i); + } + } + + return count; + } + + string getMid(const string& num) { + return num.substr(1, num.length() - 2); + } + + int countStrobogrammaticByLength(int n) { + switch (n) { + case 1: + return 3; + case 2: + return 4; + case 3: + return 4 * 3; + default: + return 5 * countStrobogrammaticByLength(n - 2); + } + } + + bool isStrobogrammatic(const string& num) { + const int n = num.size(); + for (int i = 0; i <= n - 1 - i; ++i) { + const auto it = lookup.find(num[n - 1 - i]); + if (it == lookup.end() || num[i] != it->second) { + return false; + } + } + return true; + } + +private: + const unordered_map lookup{{'0', '0'}, {'1', '1'}, + {'6', '9'}, {'8', '8'}, + {'9', '6'}}; +}; From 523059b7ccab32f4e02f7f6fd8326a5664273d76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:12:45 +0800 Subject: [PATCH 0551/1939] Update strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp index 030c17356..c8985f190 100644 --- a/C++/strobogrammatic-number-iii.cpp +++ b/C++/strobogrammatic-number-iii.cpp @@ -1,4 +1,4 @@ -// Time: O(5^n) +// Time: O(5^n) // Space: O(n) class Solution { From 5dc293baefe956be17e712a018106ea604d3039c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:13:22 +0800 Subject: [PATCH 0552/1939] Update strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp index c8985f190..2098e31e3 100644 --- a/C++/strobogrammatic-number-iii.cpp +++ b/C++/strobogrammatic-number-iii.cpp @@ -26,7 +26,7 @@ class Solution { if (num.front() > kvp.first) { if (num.length() == 2) { // num is like "21" ++count; - } else { // num is like "201" + } else { // num is like "201" count += countStrobogrammaticUntil(string(num.length() - 2, '9'), true); } } else if (num.front() == kvp.first) { From fda091c533e3d071c3cc0ea1c6556dc53cdaf398 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:18:35 +0800 Subject: [PATCH 0553/1939] Update strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp index 2098e31e3..82c19a9b0 100644 --- a/C++/strobogrammatic-number-iii.cpp +++ b/C++/strobogrammatic-number-iii.cpp @@ -36,7 +36,7 @@ class Solution { if (num.back() >= kvp.second) { // num is like "102". count += countStrobogrammaticUntil(getMid(num), true); } else if (getMid(num) != string(num.length() - 2, '0')) { // num is like "110". - count += countStrobogrammaticUntil(getMid(num), true); + count += countStrobogrammaticUntil(getMid(num), true) - isStrobogrammatic(getMid(num)); } } } From 07734c66febc94e613acace2c84ebb9800125246 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:27:39 +0800 Subject: [PATCH 0554/1939] Create flatten-2d-vector.cpp --- C++/flatten-2d-vector.cpp | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/flatten-2d-vector.cpp diff --git a/C++/flatten-2d-vector.cpp b/C++/flatten-2d-vector.cpp new file mode 100644 index 000000000..fed61dca3 --- /dev/null +++ b/C++/flatten-2d-vector.cpp @@ -0,0 +1,42 @@ +// Time: O(1) +// Space: O(1) + +class Vector2D { +public: + Vector2D(vector>& vec2d) { + it1 = vec2d.begin(); + it1_end = vec2d.end(); + if (it1 != it1_end) { + it2 = it1->begin(); + it2_end = it1->end(); + adjustNextIter(); + } + } + + int next() { + const auto ret = *it2; + ++it2; + adjustNextIter(); + return ret; + } + + bool hasNext() { + return it1 != it1_end && it2 != it2_end; + } + + void adjustNextIter() { + while (it1 != it1_end && it2 == it2_end) { + ++it1; + if (it1 != it1_end) { + it2 = it1->begin(); + it2_end = it1->end(); + } + } + } + +private: + vector>::iterator it1; + vector>::iterator it1_end; + vector::iterator it2; + vector::iterator it2_end; +}; From 26be9d630868fbad94728444f6851db12c9d997f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:29:05 +0800 Subject: [PATCH 0555/1939] Create count-univalue-subtrees.cpp --- C++/count-univalue-subtrees.cpp | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/count-univalue-subtrees.cpp diff --git a/C++/count-univalue-subtrees.cpp b/C++/count-univalue-subtrees.cpp new file mode 100644 index 000000000..7d939d25e --- /dev/null +++ b/C++/count-univalue-subtrees.cpp @@ -0,0 +1,38 @@ +// Time: O(n) +// Space: O(h) + +/** + * 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: + int countUnivalSubtrees(TreeNode* root) { + int count = 0; + isUnivalSubtrees(root, &count); + return count; + } + + bool isUnivalSubtrees(TreeNode* root, int *count) { + if (root == nullptr) { + return true; + } + bool left = isUnivalSubtrees(root->left, count); + bool right = isUnivalSubtrees(root->right, count); + if (isSame(root, root->left, left) && + isSame(root, root->right, right)) { + ++(*count); + return true; + } + return false; + } + + bool isSame(TreeNode* root, TreeNode* child, bool isUni) { + return child == nullptr || (isUni && root->val == child->val); + } +}; From a134600479c5e6139ee9909e21c764c63b50ec44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:30:07 +0800 Subject: [PATCH 0556/1939] Create group-shifted-strings.cpp --- C++/group-shifted-strings.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/group-shifted-strings.cpp diff --git a/C++/group-shifted-strings.cpp b/C++/group-shifted-strings.cpp new file mode 100644 index 000000000..47dd9e7e1 --- /dev/null +++ b/C++/group-shifted-strings.cpp @@ -0,0 +1,31 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + vector> groupStrings(vector& strings) { + unordered_map> groups; + for (const auto& str : strings) { // Grouping. + groups[hashStr(str)].insert(str); + } + + vector> result; + for (const auto& kvp : groups) { + vector group; + for (auto& str : kvp.second) { // Sorted in a group. + group.emplace_back(move(str)); + } + result.emplace_back(move(group)); + } + + return result; + } + + string hashStr(string str) { + const char base = str[0]; + for (auto& c : str) { + c = 'a' + ((c - base) >= 0 ? c - base : c - base + 26); + } + return str; + } +}; From 9b84f0a600e8b037ff7978cb94f0b8e9aa8b8cdb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:31:10 +0800 Subject: [PATCH 0557/1939] Update strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp index 82c19a9b0..c1faca964 100644 --- a/C++/strobogrammatic-number-iii.cpp +++ b/C++/strobogrammatic-number-iii.cpp @@ -1,4 +1,4 @@ -// Time: O(5^n) +// Time: O(5^(n/2)) // Space: O(n) class Solution { From ce9f2fce906726a16e2edbdcad4590a06d2758d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:32:48 +0800 Subject: [PATCH 0558/1939] Create strobogrammatic-number-ii.cpp --- C++/strobogrammatic-number-ii.cpp | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/strobogrammatic-number-ii.cpp diff --git a/C++/strobogrammatic-number-ii.cpp b/C++/strobogrammatic-number-ii.cpp new file mode 100644 index 000000000..065d0402d --- /dev/null +++ b/C++/strobogrammatic-number-ii.cpp @@ -0,0 +1,33 @@ +// Time: O(n^2 * 5^(n/2)) +// Space: O(n) + +class Solution { +public: + vector findStrobogrammatic(int n) { + return findStrobogrammaticRecu(n, n); + } + + vector findStrobogrammaticRecu(const int n, int k) { + if (k == 0) { + return {""}; + } else if (k == 1) { + return {"0", "1", "8"}; + } + + vector result; + for (const auto& num : findStrobogrammaticRecu(n, k - 2)) { + for (const auto& kvp : lookup) { + if (n == k && kvp.first == "0") { + continue; + } + result.emplace_back(kvp.first + num + kvp.second); + } + } + return result; + } + +private: + const unordered_map lookup{{"0", "0"}, {"1", "1"}, + {"6", "9"}, {"8", "8"}, + {"9", "6"}}; +}; From e7d1fbdce1225519b13b88781a8875992bea791a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:34:13 +0800 Subject: [PATCH 0559/1939] Create strobogrammatic-number.cpp --- C++/strobogrammatic-number.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/strobogrammatic-number.cpp diff --git a/C++/strobogrammatic-number.cpp b/C++/strobogrammatic-number.cpp new file mode 100644 index 000000000..6d62376b8 --- /dev/null +++ b/C++/strobogrammatic-number.cpp @@ -0,0 +1,21 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool isStrobogrammatic(string num) { + const int n = num.size(); + for (int i = 0; i <= n - 1 - i; ++i) { + const auto it = lookup.find(num[n - 1 - i]); + if (it == lookup.end() || num[i] != it->second) { + return false; + } + } + return true; + } + +private: + const unordered_map lookup{{'0', '0'}, {'1', '1'}, + {'6', '9'}, {'8', '8'}, + {'9', '6'}}; +}; From 372b9a25240b77aacc7fbea2c091bfc4f9f26db8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:34:53 +0800 Subject: [PATCH 0560/1939] Create shortest-word-distance-iii.cpp --- C++/shortest-word-distance-iii.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/shortest-word-distance-iii.cpp diff --git a/C++/shortest-word-distance-iii.cpp b/C++/shortest-word-distance-iii.cpp new file mode 100644 index 000000000..6c8a60392 --- /dev/null +++ b/C++/shortest-word-distance-iii.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int shortestWordDistance(vector& words, string word1, string word2) { + int dist = INT_MAX; + for (int i = 0, index1 = -1, index2 = -1; i < words.size(); ++i) { + if (words[i] == word1) { + if (index1 != -1) { + dist = min(dist, abs(index1 - i)); + } + index1 = i; + } else if (words[i] == word2) { + index2 = i; + } + if (index1 != -1 && index2 != -1) { + dist = min(dist, abs(index1 - index2)); + } + } + return dist; + } +}; From f8599a92dd1ae93ddf7ced4954e210eda4f1bea7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:37:24 +0800 Subject: [PATCH 0561/1939] Create shortest-word-distance-ii.cpp --- C++/shortest-word-distance-ii.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/shortest-word-distance-ii.cpp diff --git a/C++/shortest-word-distance-ii.cpp b/C++/shortest-word-distance-ii.cpp new file mode 100644 index 000000000..a402d7b15 --- /dev/null +++ b/C++/shortest-word-distance-ii.cpp @@ -0,0 +1,26 @@ +// Time: ctor: O(n), shortest: O(a + b), a, b is occurences of word1, word2 +// Space: O(n) + +class WordDistance { +public: + WordDistance(vector words) { + for (int i = 0; i < words.size(); ++i) { + wordIndex[words[i]].emplace_back(i); + } + } + + int shortest(string word1, string word2) { + const vector& indexes1 = wordIndex[word1]; + const vector& indexes2 = wordIndex[word2]; + + int i = 0, j = 0, dist = INT_MAX; + while (i < indexes1.size() && j < indexes2.size()) { + dist = min(dist, abs(indexes1[i] - indexes2[j])); + indexes1[i] < indexes2[j] ? ++i : ++j; + } + return dist; + } + +private: + unordered_map> wordIndex; +}; From 26dcf7b7671f35632e9aafa717e753ffa764823e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 03:38:50 +0800 Subject: [PATCH 0562/1939] Create shortest-word-distance.cpp --- C++/shortest-word-distance.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/shortest-word-distance.cpp diff --git a/C++/shortest-word-distance.cpp b/C++/shortest-word-distance.cpp new file mode 100644 index 000000000..cd7957e2d --- /dev/null +++ b/C++/shortest-word-distance.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int shortestDistance(vector& words, string word1, string word2) { + int dist = INT_MAX; + for (int i = 0, index1 = -1, index2 = -1; i < words.size(); ++i) { + if (words[i] == word1) { + index1 = i; + } else if (words[i] == word2) { + index2 = i; + } + if (index1 != -1 && index2 != -1) { + dist = min(dist, abs(index1 - index2)); + } + } + return dist; + } +}; From b2836f3b467b3ab45025958a732b2f952aec7cc1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 21:23:30 +0800 Subject: [PATCH 0563/1939] Create shortest-word-distance.py --- Python/shortest-word-distance.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Python/shortest-word-distance.py diff --git a/Python/shortest-word-distance.py b/Python/shortest-word-distance.py new file mode 100644 index 000000000..c57352eb7 --- /dev/null +++ b/Python/shortest-word-distance.py @@ -0,0 +1,22 @@ +# Time: O(n) +# Space: O(1) + +class Solution: + # @param {string[]} words + # @param {string} word1 + # @param {string} word2 + # @return {integer} + def shortestDistance(self, words, word1, word2): + dist = float("inf") + i, index1, index2 = 0, None, None + while i < len(words): + if words[i] == word1: + index1 = i + elif words[i] == word2: + index2 = i + + if index1 is not None and index2 is not None: + dist = min(dist, abs(index1 - index2)) + i += 1 + + return dist From 30dc04ad1058a019b449d2951c2fa62223f4faf2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 21:36:24 +0800 Subject: [PATCH 0564/1939] Create shortest-word-distance-ii.py --- Python/shortest-word-distance-ii.py | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/shortest-word-distance-ii.py diff --git a/Python/shortest-word-distance-ii.py b/Python/shortest-word-distance-ii.py new file mode 100644 index 000000000..494c9c682 --- /dev/null +++ b/Python/shortest-word-distance-ii.py @@ -0,0 +1,31 @@ +# Time: init: O(n), lookup: O(a + b), a, b is occurences of word1, word2 +# Space: O(n) + +class WordDistance: + # initialize your data structure here. + # @param {string[]} words + def __init__(self, words): + self.wordIndex = {} + for i in xrange(len(words)): + if words[i] not in self.wordIndex: + self.wordIndex[words[i]] = [i] + else: + self.wordIndex[words[i]].append(i) + + # @param {string} word1 + # @param {string} word2 + # @return {integer} + # Adds a word into the data structure. + def shortest(self, word1, word2): + indexes1 = self.wordIndex[word1] + indexes2 = self.wordIndex[word2] + + i, j, dist = 0, 0, float("inf") + while i < len(indexes1) and j < len(indexes2): + dist = min(dist, abs(indexes1[i] - indexes2[j])) + if indexes1[i] < indexes2[j]: + i += 1 + else: + j += 1 + + return dist From 92b476a45ec46d5f19b708b0a81c3011594ff11e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 21:39:13 +0800 Subject: [PATCH 0565/1939] Create shortest-word-distance-iii.py --- Python/shortest-word-distance-iii.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/shortest-word-distance-iii.py diff --git a/Python/shortest-word-distance-iii.py b/Python/shortest-word-distance-iii.py new file mode 100644 index 000000000..d0ba8d235 --- /dev/null +++ b/Python/shortest-word-distance-iii.py @@ -0,0 +1,24 @@ +# Time: O(n) +# Space: O(1) + +class Solution: + # @param {string[]} words + # @param {string} word1 + # @param {string} word2 + # @return {integer} + def shortestWordDistance(self, words, word1, word2): + dist = float("inf") + i, index1, index2 = 0, None, None + while i < len(words): + if words[i] == word1: + if index1 is not None: + dist = min(dist, abs(index1 - i)) + index1 = i + elif words[i] == word2: + index2 = i + + if index1 is not None and index2 is not None: + dist = min(dist, abs(index1 - index2)) + i += 1 + + return dist From 87e0604c956c95bce3c7c30bcb38202f0a249154 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 21:47:34 +0800 Subject: [PATCH 0566/1939] Create strobogrammatic-number-ii.py --- Python/strobogrammatic-number-ii.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/strobogrammatic-number-ii.py diff --git a/Python/strobogrammatic-number-ii.py b/Python/strobogrammatic-number-ii.py new file mode 100644 index 000000000..47858b605 --- /dev/null +++ b/Python/strobogrammatic-number-ii.py @@ -0,0 +1,17 @@ +# Time: O(n) +# Space: O(1) + +class Solution: + lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'} + + # @param {string} num + # @return {boolean} + def isStrobogrammatic(self, num): + n = len(num) + i = 0 + while i <= n - 1 - i: + if num[n - 1 - i] not in self.lookup or\ + num[i] != self.lookup[num[n - 1 - i]]: + return False + i += 1 + return True From 3cd50c474eb3830960e8d1492ffea0c2b0562215 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 21:48:26 +0800 Subject: [PATCH 0567/1939] Rename strobogrammatic-number-ii.py to strobogrammatic-number.py --- .../{strobogrammatic-number-ii.py => strobogrammatic-number.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{strobogrammatic-number-ii.py => strobogrammatic-number.py} (100%) diff --git a/Python/strobogrammatic-number-ii.py b/Python/strobogrammatic-number.py similarity index 100% rename from Python/strobogrammatic-number-ii.py rename to Python/strobogrammatic-number.py From 349f5faba751e8d90a3d8d52b60fc023200f5472 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 22:02:40 +0800 Subject: [PATCH 0568/1939] Update strobogrammatic-number-ii.cpp --- C++/strobogrammatic-number-ii.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/strobogrammatic-number-ii.cpp b/C++/strobogrammatic-number-ii.cpp index 065d0402d..4c5b610e0 100644 --- a/C++/strobogrammatic-number-ii.cpp +++ b/C++/strobogrammatic-number-ii.cpp @@ -17,10 +17,9 @@ class Solution { vector result; for (const auto& num : findStrobogrammaticRecu(n, k - 2)) { for (const auto& kvp : lookup) { - if (n == k && kvp.first == "0") { - continue; + if (n != k || kvp.first != "0") { + result.emplace_back(kvp.first + num + kvp.second); } - result.emplace_back(kvp.first + num + kvp.second); } } return result; From 7a8ff155f3ee9c805c9d2d62552e493e6b235f5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 22:03:31 +0800 Subject: [PATCH 0569/1939] Create strobogrammatic-number-ii.py --- Python/strobogrammatic-number-ii.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/strobogrammatic-number-ii.py diff --git a/Python/strobogrammatic-number-ii.py b/Python/strobogrammatic-number-ii.py new file mode 100644 index 000000000..da089c481 --- /dev/null +++ b/Python/strobogrammatic-number-ii.py @@ -0,0 +1,24 @@ +# Time: O(n^2 * 5^(n/2)) +# Space: O(n) + +class Solution: + lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'} + + # @param {integer} n + # @return {string[]} + def findStrobogrammatic(self, n): + return self.findStrobogrammaticRecu(n, n) + + def findStrobogrammaticRecu(self, n, k): + if k == 0: + return [''] + elif k == 1: + return ['0', '1', '8'] + + result = [] + for num in self.findStrobogrammaticRecu(n, k - 2): + for key, val in self.lookup.iteritems(): + if n != k or key != '0': + result.append(key + num + val) + + return result From 40bc449e5d8f2c9375c7b01885a95028b56b5fc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 22:48:24 +0800 Subject: [PATCH 0570/1939] Create strobogrammatic-number-iii.py --- Python/strobogrammatic-number-iii.py | 67 ++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Python/strobogrammatic-number-iii.py diff --git a/Python/strobogrammatic-number-iii.py b/Python/strobogrammatic-number-iii.py new file mode 100644 index 000000000..b5d620a1a --- /dev/null +++ b/Python/strobogrammatic-number-iii.py @@ -0,0 +1,67 @@ +# Time: O(5^(n/2)) +# Space: O(n) + +class Solution: + lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'} + + # @param {string} low + # @param {string} high + # @return {integer} + def strobogrammaticInRange(self, low, high): + count = self.countStrobogrammaticUntil(high, False) - \ + self.countStrobogrammaticUntil(low, False) + \ + self.isStrobogrammatic(low) + return count if count >= 0 else 0 + + def countStrobogrammaticUntil(self, num, canStartWith0): + count = 0 + if len(num) == 1: + for c in ['0', '1', '8']: + if num[0] >= c: + count += 1 + return count + + for key, val in self.lookup.iteritems(): + if canStartWith0 or key != '0': + if num[0] > key: + if len(num) == 2: # num is like "21" + count += 1 + else: # num is like "201" + count += self.countStrobogrammaticUntil('9' * (len(num) - 2), True) + elif num[0] == key: + if len(num) == 2: # num is like 12". + if num[-1] >= val: + count += 1 + else: + if num[-1] >= val: # num is like "102". + count += self.countStrobogrammaticUntil(self.getMid(num), True); + elif (self.getMid(num) != '0' * (len(num) - 2)): # num is like "110". + count += self.countStrobogrammaticUntil(self.getMid(num), True) - \ + self.isStrobogrammatic(self.getMid(num)) + + if not canStartWith0: # Sum up each length. + for i in xrange(len(num) - 1, 0, -1): + count += self.countStrobogrammaticByLength(i) + + return count + + def getMid(self, num): + return num[1:len(num) - 1] + + def countStrobogrammaticByLength(self, n): + if n == 1: + return 3 + elif n == 2: + return 4 + elif n == 3: + return 4 * 3 + else: + return 5 * self.countStrobogrammaticByLength(n - 2) + + def isStrobogrammatic(self, num): + n = len(num) + for i in xrange((n+1) / 2): + if num[n-1-i] not in self.lookup or \ + num[i] != self.lookup[num[n-1-i]]: + return False + return True From 0bbf59e3ee69a7361c89996a61cf1c38240167ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 22:49:45 +0800 Subject: [PATCH 0571/1939] Update strobogrammatic-number.py --- Python/strobogrammatic-number.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Python/strobogrammatic-number.py b/Python/strobogrammatic-number.py index 47858b605..26fdcb3b8 100644 --- a/Python/strobogrammatic-number.py +++ b/Python/strobogrammatic-number.py @@ -8,10 +8,9 @@ class Solution: # @return {boolean} def isStrobogrammatic(self, num): n = len(num) - i = 0 - while i <= n - 1 - i: - if num[n - 1 - i] not in self.lookup or\ - num[i] != self.lookup[num[n - 1 - i]]: + for i in xrange((n+1) / 2): + if num[n-1-i] not in self.lookup or\ + num[i] != self.lookup[num[n-1-i]]: return False i += 1 return True From 4a85a33e23016dd5b06bced2858b2aee3e146aaf Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 22:50:04 +0800 Subject: [PATCH 0572/1939] Update strobogrammatic-number.py --- Python/strobogrammatic-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/strobogrammatic-number.py b/Python/strobogrammatic-number.py index 26fdcb3b8..37a542b93 100644 --- a/Python/strobogrammatic-number.py +++ b/Python/strobogrammatic-number.py @@ -9,7 +9,7 @@ class Solution: def isStrobogrammatic(self, num): n = len(num) for i in xrange((n+1) / 2): - if num[n-1-i] not in self.lookup or\ + if num[n-1-i] not in self.lookup or \ num[i] != self.lookup[num[n-1-i]]: return False i += 1 From f2f0bc1f111bbb9035728854ee194f3c024f5723 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 23:08:00 +0800 Subject: [PATCH 0573/1939] Create group-shifted-strings.py --- Python/group-shifted-strings.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/group-shifted-strings.py diff --git a/Python/group-shifted-strings.py b/Python/group-shifted-strings.py new file mode 100644 index 000000000..c3aa782fb --- /dev/null +++ b/Python/group-shifted-strings.py @@ -0,0 +1,29 @@ +# Time: O(nlogn) +# Space: O(n) + +class Solution: + # @param {string[]} strings + # @return {string[][]} + def groupStrings(self, strings): + groups = {}; + for s in strings: # Grouping. + if self.hashStr(s) not in groups: + groups[self.hashStr(s)] = [s] + else: + groups[self.hashStr(s)].append(s) + + result = [] + for key, val in groups.iteritems(): + result.append(sorted(val)) + + return result + + def hashStr(self, s): + base = ord(s[0]) + hashcode = "" + for i in xrange(len(s)): + if ord(s[i]) - base >= 0: + hashcode += unichr(ord('a') + ord(s[i]) - base) + else: + hashcode += unichr(ord('a') + ord(s[i]) - base + 26) + return hashcode From 95d244211b8547a2624ba57ebb0ab8553f45bf02 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 23:14:32 +0800 Subject: [PATCH 0574/1939] Create count-univalue-subtrees.py --- Python/count-univalue-subtrees.py | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/count-univalue-subtrees.py diff --git a/Python/count-univalue-subtrees.py b/Python/count-univalue-subtrees.py new file mode 100644 index 000000000..a6ea7823a --- /dev/null +++ b/Python/count-univalue-subtrees.py @@ -0,0 +1,32 @@ +# Time: O(n) +# Space: O(h) +# +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param {TreeNode} root + # @return {integer} + def countUnivalSubtrees(self, root): + [is_uni, count] = self.isUnivalSubtrees(root, 0); + return count; + + def isUnivalSubtrees(self, root, count): + if not root: + return [True, count] + + [left, count] = self.isUnivalSubtrees(root.left, count) + [right, count] = self.isUnivalSubtrees(root.right, count) + if self.isSame(root, root.left, left) and \ + self.isSame(root, root.right, right): + count += 1 + return [True, count] + + return [False, count] + + def isSame(self, root, child, isUni): + return not child or (isUni and root.val == child.val) From b73a07b80e155dcc7e1ea8b0e53fa4b9f9caa297 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 23:15:12 +0800 Subject: [PATCH 0575/1939] Update count-univalue-subtrees.py --- Python/count-univalue-subtrees.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/count-univalue-subtrees.py b/Python/count-univalue-subtrees.py index a6ea7823a..a393f4304 100644 --- a/Python/count-univalue-subtrees.py +++ b/Python/count-univalue-subtrees.py @@ -28,5 +28,5 @@ def isUnivalSubtrees(self, root, count): return [False, count] - def isSame(self, root, child, isUni): - return not child or (isUni and root.val == child.val) + def isSame(self, root, child, is_uni): + return not child or (is_uni and root.val == child.val) From e9311b35bd40a57205154b80cac2ce116781f2b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Aug 2015 23:15:50 +0800 Subject: [PATCH 0576/1939] Update count-univalue-subtrees.cpp --- C++/count-univalue-subtrees.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/count-univalue-subtrees.cpp b/C++/count-univalue-subtrees.cpp index 7d939d25e..899047aab 100644 --- a/C++/count-univalue-subtrees.cpp +++ b/C++/count-univalue-subtrees.cpp @@ -32,7 +32,7 @@ class Solution { return false; } - bool isSame(TreeNode* root, TreeNode* child, bool isUni) { - return child == nullptr || (isUni && root->val == child->val); + bool isSame(TreeNode* root, TreeNode* child, bool is_uni) { + return child == nullptr || (is_uni && root->val == child->val); } }; From d148cb0f518f5a706409d0ee8d560837855c8eca Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 6 Aug 2015 23:49:15 +0800 Subject: [PATCH 0577/1939] add solution --- Python/flatten-2d-vector.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/flatten-2d-vector.py diff --git a/Python/flatten-2d-vector.py b/Python/flatten-2d-vector.py new file mode 100644 index 000000000..44e8ef5ec --- /dev/null +++ b/Python/flatten-2d-vector.py @@ -0,0 +1,36 @@ +# Time: O(1) +# Space: O(1) + +class Vector2D: + x, x_len = 0, 0 + y, y_len = 0, 0 + vec = None + + # Initialize your data structure here. + # @param {integer[][]} vec2d + def __init__(self, vec2d): + self.vec = vec2d + self.x = 0 + self.x_len = len(self.vec) + if self.x != self.x_len: + self.y = 0 + self.y_len = len(self.vec[self.x]) + self.adjustNextIter() + + # @return {integer} + def next(self): + ret = self.vec[self.x][self.y] + self.y += 1 + self.adjustNextIter() + return ret + + # @return {boolean} + def hasNext(self): + return self.x != self.x_len and self.y != self.y_len + + def adjustNextIter(self): + while self.x != self.x_len and self.y == self.y_len: + self.x += 1 + if self.x != self.x_len: + self.y = 0 + self.y_len = len(self.vec[self.x]) From 6cb656aa15b71597312947f46ddeb381fd1ad235 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 00:21:11 +0800 Subject: [PATCH 0578/1939] Update flatten-2d-vector.py --- Python/flatten-2d-vector.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/Python/flatten-2d-vector.py b/Python/flatten-2d-vector.py index 44e8ef5ec..7b40db259 100644 --- a/Python/flatten-2d-vector.py +++ b/Python/flatten-2d-vector.py @@ -2,8 +2,7 @@ # Space: O(1) class Vector2D: - x, x_len = 0, 0 - y, y_len = 0, 0 + x, y = 0, 0 vec = None # Initialize your data structure here. @@ -11,10 +10,8 @@ class Vector2D: def __init__(self, vec2d): self.vec = vec2d self.x = 0 - self.x_len = len(self.vec) - if self.x != self.x_len: + if self.x != len(self.vec): self.y = 0 - self.y_len = len(self.vec[self.x]) self.adjustNextIter() # @return {integer} @@ -26,11 +23,10 @@ def next(self): # @return {boolean} def hasNext(self): - return self.x != self.x_len and self.y != self.y_len + return self.x != len(self.vec) and self.y != len(self.vec[self.x]) def adjustNextIter(self): - while self.x != self.x_len and self.y == self.y_len: + while self.x != len(self.vec) and self.y == len(self.vec[self.x]): self.x += 1 - if self.x != self.x_len: + if self.x != len(self.vec): self.y = 0 - self.y_len = len(self.vec[self.x]) From 5c8b6562470fee3740c83d769883bd02be521a2a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 00:27:50 +0800 Subject: [PATCH 0579/1939] Update flatten-2d-vector.cpp --- C++/flatten-2d-vector.cpp | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/C++/flatten-2d-vector.cpp b/C++/flatten-2d-vector.cpp index fed61dca3..55c3780bb 100644 --- a/C++/flatten-2d-vector.cpp +++ b/C++/flatten-2d-vector.cpp @@ -3,40 +3,36 @@ class Vector2D { public: - Vector2D(vector>& vec2d) { - it1 = vec2d.begin(); - it1_end = vec2d.end(); - if (it1 != it1_end) { - it2 = it1->begin(); - it2_end = it1->end(); + Vector2D(vector>& vec2d) : vec(vec2d) { + x = vec.begin(); + if (x != vec.end()) { + y = x->begin(); adjustNextIter(); } } int next() { - const auto ret = *it2; - ++it2; + const auto ret = *y; + ++y; adjustNextIter(); return ret; } bool hasNext() { - return it1 != it1_end && it2 != it2_end; + return x != vec.end() && y != x->end(); } void adjustNextIter() { - while (it1 != it1_end && it2 == it2_end) { - ++it1; - if (it1 != it1_end) { - it2 = it1->begin(); - it2_end = it1->end(); + while (x != vec.end() && y == x->end()) { + ++x; + if (x != vec.end()) { + y = x->begin(); } } } private: - vector>::iterator it1; - vector>::iterator it1_end; - vector::iterator it2; - vector::iterator it2_end; + vector>& vec; + vector>::iterator x; + vector::iterator y; }; From c9d596134dd902932f460dac274c681ee9c6678c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 00:42:36 +0800 Subject: [PATCH 0580/1939] Update README.md --- README.md | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8907abd2b..4776442af 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ LeetCode ======== -Up to date (2015-08-01), there are `226` Algorithms / `12` Database / `4` Shell problems on [LeetCode Online Judge](https://leetcode.com/). -The number of problems is increasing recently. -Here is the classification of all `242` problems. -For extra problems and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. +Up to date (2015-08-05), there are `235` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +The number of questions is increasing recently. +Here is the classification of all `251` questions. +For extra questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. -(Notes: "📖" means you have to buy the book from LeetCode. ) +(Notes: "📖" means you need to subscribe to `LeetCode premium membership` for the access to premium questions. ) --- Algorithms @@ -92,6 +92,9 @@ Shell 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [C++](./C++/product-of-array-except-self.cpp) [Python](./Python/product-of-array-except-self.py) | _O(n)_ | _O(1)_ | Medium | LintCode | 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) | [C++](./C++/search-a-2d-matrix-ii.cpp) [Python](./Python/search-a-2d-matrix-ii.py) | _O(m + n)_ | _O(1)_ | Medium | EPI, LintCode | +243| [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [C++](./C++/shortest-word-distance.cpp) [Python](./Python/shortest-word-distance.py) | _O(n)_ | _O(1)_ | Easy ||📖| +245| [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance III/) | [C++](./C++/shortest-word-distance-iii.cpp) [Python](./Python/shortest-word-distance-iii.py) | _O(n)_ | _O(1)_ | Medium ||📖| +251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium ||📖| --- @@ -200,6 +203,9 @@ Shell 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || 219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || +244| [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [C++](./C++/shortest-word-distance-ii.cpp) [Python](./Python/shortest-word-distance-ii.py) | ctor: _O(n)_, lookup: _O(a + b)_ | _O(n)_ | Medium ||📖| +246| [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | [C++](./C++/strobogrammatic-number.cpp) [Python](./Python/strobogrammatic-number.py) | _O(n)_ | _O(1)_ | Easy ||📖| +249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy ||📖| --- @@ -228,6 +234,7 @@ Shell 172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || 223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C++](./C++/rectangle-area.cpp) [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || 233| [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | [C++](./C++/number-of-digit-one.cpp) [Python](./Python/number-of-digit-one.py) | _O(logn)_ | _O(1)_ | Medium | CTCI, LintCode| +248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(1)_ | Hard ||📖| --- @@ -352,6 +359,8 @@ Shell 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || 216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(k * C(n, k))_ | _O(k)_ | Medium || 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-tree.py) | _O(h)_ | _O(h)_ | Medium | EPI | +247| [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/) | [C++](./C++/strobogrammatic-number-ii.cpp) [Python](./Python/strobogrammatic-number-ii.py) | _O(n^2 * 5^(n/2))_ | _O(n)_ | Medium ||📖| +250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtreescpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium ||📖| --- From d5477a3a6a14082a93eb7eda491e64360b298456 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 00:46:37 +0800 Subject: [PATCH 0581/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4776442af..720060c95 100644 --- a/README.md +++ b/README.md @@ -234,7 +234,7 @@ Shell 172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || 223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C++](./C++/rectangle-area.cpp) [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || 233| [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | [C++](./C++/number-of-digit-one.cpp) [Python](./Python/number-of-digit-one.py) | _O(logn)_ | _O(1)_ | Medium | CTCI, LintCode| -248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(1)_ | Hard ||📖| +248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard ||📖| --- From 9b471415ef8397a44b43cf7988ae7a10f62904b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 01:03:35 +0800 Subject: [PATCH 0582/1939] Update strobogrammatic-number-iii.py --- Python/strobogrammatic-number-iii.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/strobogrammatic-number-iii.py b/Python/strobogrammatic-number-iii.py index b5d620a1a..63caff747 100644 --- a/Python/strobogrammatic-number-iii.py +++ b/Python/strobogrammatic-number-iii.py @@ -13,7 +13,7 @@ def strobogrammaticInRange(self, low, high): self.isStrobogrammatic(low) return count if count >= 0 else 0 - def countStrobogrammaticUntil(self, num, canStartWith0): + def countStrobogrammaticUntil(self, num, can_start_with_0): count = 0 if len(num) == 1: for c in ['0', '1', '8']: @@ -22,7 +22,7 @@ def countStrobogrammaticUntil(self, num, canStartWith0): return count for key, val in self.lookup.iteritems(): - if canStartWith0 or key != '0': + if can_start_with_0 or key != '0': if num[0] > key: if len(num) == 2: # num is like "21" count += 1 @@ -39,7 +39,7 @@ def countStrobogrammaticUntil(self, num, canStartWith0): count += self.countStrobogrammaticUntil(self.getMid(num), True) - \ self.isStrobogrammatic(self.getMid(num)) - if not canStartWith0: # Sum up each length. + if not can_start_with_0: # Sum up each length. for i in xrange(len(num) - 1, 0, -1): count += self.countStrobogrammaticByLength(i) From 23e11e53feb7fa0513c4c09e61711f8fc67e3495 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 01:05:00 +0800 Subject: [PATCH 0583/1939] Update strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp index c1faca964..713a637c4 100644 --- a/C++/strobogrammatic-number-iii.cpp +++ b/C++/strobogrammatic-number-iii.cpp @@ -10,7 +10,7 @@ class Solution { return count >= 0 ? count : 0; } - int countStrobogrammaticUntil(string num, bool canStartWith0) { + int countStrobogrammaticUntil(string num, bool can_start_with_0) { int count = 0; if (num.length() == 1) { for (const auto& c : {'0', '1', '8'}) { @@ -22,7 +22,7 @@ class Solution { } for (const auto& kvp : lookup) { - if (canStartWith0 || kvp.first != '0') { + if (can_start_with_0 || kvp.first != '0') { if (num.front() > kvp.first) { if (num.length() == 2) { // num is like "21" ++count; @@ -43,7 +43,7 @@ class Solution { } } - if (!canStartWith0) { // Sum up each length. + if (!can_start_with_0) { // Sum up each length. for (int i = num.length() - 1; i > 0; --i) { count += countStrobogrammaticByLength(i); } From 3f538b009248f08301081cdab6896a5f26d36c26 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 01:05:34 +0800 Subject: [PATCH 0584/1939] Update strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp index 713a637c4..45e1ec85b 100644 --- a/C++/strobogrammatic-number-iii.cpp +++ b/C++/strobogrammatic-number-iii.cpp @@ -36,7 +36,8 @@ class Solution { if (num.back() >= kvp.second) { // num is like "102". count += countStrobogrammaticUntil(getMid(num), true); } else if (getMid(num) != string(num.length() - 2, '0')) { // num is like "110". - count += countStrobogrammaticUntil(getMid(num), true) - isStrobogrammatic(getMid(num)); + count += countStrobogrammaticUntil(getMid(num), true) - + isStrobogrammatic(getMid(num)); } } } From 22a6a4860cdc5346da95ad16db2975f0c74c6fbd Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 01:26:31 +0800 Subject: [PATCH 0585/1939] Update README.md --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 720060c95..c05cd092a 100644 --- a/README.md +++ b/README.md @@ -92,9 +92,9 @@ Shell 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [C++](./C++/product-of-array-except-self.cpp) [Python](./Python/product-of-array-except-self.py) | _O(n)_ | _O(1)_ | Medium | LintCode | 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) | [C++](./C++/search-a-2d-matrix-ii.cpp) [Python](./Python/search-a-2d-matrix-ii.py) | _O(m + n)_ | _O(1)_ | Medium | EPI, LintCode | -243| [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [C++](./C++/shortest-word-distance.cpp) [Python](./Python/shortest-word-distance.py) | _O(n)_ | _O(1)_ | Easy ||📖| -245| [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance III/) | [C++](./C++/shortest-word-distance-iii.cpp) [Python](./Python/shortest-word-distance-iii.py) | _O(n)_ | _O(1)_ | Medium ||📖| -251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium ||📖| +243| [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [C++](./C++/shortest-word-distance.cpp) [Python](./Python/shortest-word-distance.py) | _O(n)_ | _O(1)_ | Easy |📖|| +245| [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance III/) | [C++](./C++/shortest-word-distance-iii.cpp) [Python](./Python/shortest-word-distance-iii.py) | _O(n)_ | _O(1)_ | Medium |📖|| +251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium |📖|| --- @@ -203,9 +203,9 @@ Shell 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || 219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || -244| [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [C++](./C++/shortest-word-distance-ii.cpp) [Python](./Python/shortest-word-distance-ii.py) | ctor: _O(n)_, lookup: _O(a + b)_ | _O(n)_ | Medium ||📖| -246| [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | [C++](./C++/strobogrammatic-number.cpp) [Python](./Python/strobogrammatic-number.py) | _O(n)_ | _O(1)_ | Easy ||📖| -249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy ||📖| +244| [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [C++](./C++/shortest-word-distance-ii.cpp) [Python](./Python/shortest-word-distance-ii.py) | ctor: _O(n)_, lookup: _O(a + b)_ | _O(n)_ | Medium |📖|| +246| [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | [C++](./C++/strobogrammatic-number.cpp) [Python](./Python/strobogrammatic-number.py) | _O(n)_ | _O(1)_ | Easy |📖|| +249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |📖|| --- @@ -234,7 +234,7 @@ Shell 172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.py) | _O(logn)_ | _O(1)_ | Easy || 223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C++](./C++/rectangle-area.cpp) [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || 233| [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | [C++](./C++/number-of-digit-one.cpp) [Python](./Python/number-of-digit-one.py) | _O(logn)_ | _O(1)_ | Medium | CTCI, LintCode| -248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard ||📖| +248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard |📖|| --- @@ -359,8 +359,8 @@ Shell 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || 216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(k * C(n, k))_ | _O(k)_ | Medium || 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-tree.py) | _O(h)_ | _O(h)_ | Medium | EPI | -247| [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/) | [C++](./C++/strobogrammatic-number-ii.cpp) [Python](./Python/strobogrammatic-number-ii.py) | _O(n^2 * 5^(n/2))_ | _O(n)_ | Medium ||📖| -250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtreescpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium ||📖| +247| [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/) | [C++](./C++/strobogrammatic-number-ii.cpp) [Python](./Python/strobogrammatic-number-ii.py) | _O(n^2 * 5^(n/2))_ | _O(n)_ | Medium |📖|| +250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtreescpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| --- From 5affcf003299307419adcf95ea3f3ec17eda295e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 01:30:04 +0800 Subject: [PATCH 0586/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c05cd092a..7ef9354ea 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ The number of questions is increasing recently. Here is the classification of all `251` questions. For extra questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. -(Notes: "📖" means you need to subscribe to `LeetCode premium membership` for the access to premium questions. ) +(Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) --- Algorithms From 6274f002cdc6da63282f391aed13d3bf47602318 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 01:31:40 +0800 Subject: [PATCH 0587/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7ef9354ea..8a369eae8 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ LeetCode Up to date (2015-08-05), there are `235` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `251` questions. -For extra questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. +For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From c2b07f91caf7594fc2c232a54aaee6d3e473cf4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 12:32:09 +0800 Subject: [PATCH 0588/1939] Update strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp index 45e1ec85b..bca283c79 100644 --- a/C++/strobogrammatic-number-iii.cpp +++ b/C++/strobogrammatic-number-iii.cpp @@ -60,11 +60,11 @@ class Solution { int countStrobogrammaticByLength(int n) { switch (n) { case 1: - return 3; + return 3; // "0", "1", "8" case 2: - return 4; + return 4; // "11", "69", "88", "96" case 3: - return 4 * 3; + return 4 * 3; // "101", "111", "181", ... default: return 5 * countStrobogrammaticByLength(n - 2); } From bbaa441d52d850ca44cd7d053f09321383d43c31 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 7 Aug 2015 12:32:23 +0800 Subject: [PATCH 0589/1939] Update strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp index bca283c79..19f66e099 100644 --- a/C++/strobogrammatic-number-iii.cpp +++ b/C++/strobogrammatic-number-iii.cpp @@ -64,7 +64,7 @@ class Solution { case 2: return 4; // "11", "69", "88", "96" case 3: - return 4 * 3; // "101", "111", "181", ... + return 4 * 3; // "101", "111", "181", ... default: return 5 * countStrobogrammaticByLength(n - 2); } From cc946a0f030ff9e0cb6b8408ff1fdae095f6a567 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Aug 2015 15:59:11 +0800 Subject: [PATCH 0590/1939] Create meeting-rooms-ii.cpp --- C++/meeting-rooms-ii.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/meeting-rooms-ii.cpp diff --git a/C++/meeting-rooms-ii.cpp b/C++/meeting-rooms-ii.cpp new file mode 100644 index 000000000..e6489db1b --- /dev/null +++ b/C++/meeting-rooms-ii.cpp @@ -0,0 +1,40 @@ +// Time: O(nlogn) +// Space: O(n) + +/** + * Definition for an interval. + * struct Interval { + * int start; + * int end; + * Interval() : start(0), end(0) {} + * Interval(int s, int e) : start(s), end(e) {} + * }; + */ +class Solution { +public: + int minMeetingRooms(vector& intervals) { + vector starts, ends; + for (const auto& i : intervals) { + starts.emplace_back(i.start); + ends.emplace_back(i.end); + } + + sort(starts.begin(), starts.end()); + sort(ends.begin(), ends.end()); + + int min_rooms = 0, cnt_rooms = 0; + int s = 0, e = 0; + while (s < starts.size()) { + if (starts[s] < ends[e]) { + ++cnt_rooms; // Acquire a room. + // Update the min number of rooms. + min_rooms = max(min_rooms, cnt_rooms); + ++s; + } else { + --cnt_rooms; // Release a room. + ++e; + } + } + return min_rooms; + } +}; From 057821040e3099c1ee945bd1d4c9ecf48c54f76b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Aug 2015 16:01:06 +0800 Subject: [PATCH 0591/1939] Create meeting-rooms.cpp --- C++/meeting-rooms.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/meeting-rooms.cpp diff --git a/C++/meeting-rooms.cpp b/C++/meeting-rooms.cpp new file mode 100644 index 000000000..dcfaa784f --- /dev/null +++ b/C++/meeting-rooms.cpp @@ -0,0 +1,25 @@ +// Time: O(nlogn) +// Space: O(n) + +/** + * Definition for an interval. + * struct Interval { + * int start; + * int end; + * Interval() : start(0), end(0) {} + * Interval(int s, int e) : start(s), end(e) {} + * }; + */ +class Solution { +public: + bool canAttendMeetings(vector& intervals) { + sort(intervals.begin(), intervals.end(), + [](const Interval& x, const Interval& y) { return x.start < y.start; }); + for (int i = 1; i < intervals.size(); ++i) { + if (intervals[i].start < intervals[i-1].end) { + return false; + } + } + return true; + } +}; From fd1fe461e0a14afff282c87e997f41e504e7c496 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Aug 2015 16:01:52 +0800 Subject: [PATCH 0592/1939] Create meeting-rooms.py --- Python/meeting-rooms.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Python/meeting-rooms.py diff --git a/Python/meeting-rooms.py b/Python/meeting-rooms.py new file mode 100644 index 000000000..f8ef52f66 --- /dev/null +++ b/Python/meeting-rooms.py @@ -0,0 +1,19 @@ +# Time: O(nlogn) +# Space: O(n) +# +# Definition for an interval. +# class Interval: +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution: + # @param {Interval[]} intervals + # @return {boolean} + def canAttendMeetings(self, intervals): + intervals.sort(key=lambda x: x.start) + + for i in xrange(1, len(intervals)): + if intervals[i].start < intervals[i-1].end: + return False + return True From 418250b2e7d8f21f37fd9bf22e79c70253f5a971 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Aug 2015 16:05:00 +0800 Subject: [PATCH 0593/1939] Create meeting-rooms-ii.py --- Python/meeting-rooms-ii.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/meeting-rooms-ii.py diff --git a/Python/meeting-rooms-ii.py b/Python/meeting-rooms-ii.py new file mode 100644 index 000000000..5d6903447 --- /dev/null +++ b/Python/meeting-rooms-ii.py @@ -0,0 +1,34 @@ +# Time: O(nlogn) +# Space: O(n) + +# Definition for an interval. +# class Interval: +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution: + # @param {Interval[]} intervals + # @return {integer} + def minMeetingRooms(self, intervals): + starts, ends = [], [] + for i in intervals: + starts.append(i.start) + ends.append(i.end) + + starts.sort() + ends.sort() + + s, e = 0, 0 + min_rooms, cnt_rooms = 0, 0 + while s < len(starts): + if starts[s] < ends[e]: + cnt_rooms += 1 # Acquire a room. + # Update the min number of rooms. + min_rooms = max(min_rooms, cnt_rooms) + s += 1 + else: + cnt_rooms -= 1 # Release a room. + e += 1 + + return min_rooms From 8d64446ca95799438f473f9535d4a514bc19cfc1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Aug 2015 16:10:12 +0800 Subject: [PATCH 0594/1939] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8a369eae8..2fa6cc4e8 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-05), there are `235` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-08), there are `237` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `251` questions. +Here is the classification of all `253` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -250,7 +250,9 @@ Shell 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky 179| [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || -218| [The Skyline Problem ](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard | Sort, BST| +218| [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard || Sort, BST| +252| [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [C++](./C++/meeting-rooms.cpp) [Python](./Python/meeting-rooms.py) | _O(nlogn)_ | _O(n)_ | Easy |📖| | +253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |📖| | --- From 903b56617651427e3e0ea4f84f354cd2dce3b42e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Aug 2015 16:11:14 +0800 Subject: [PATCH 0595/1939] Update meeting-rooms.cpp --- C++/meeting-rooms.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/meeting-rooms.cpp b/C++/meeting-rooms.cpp index dcfaa784f..7568e7990 100644 --- a/C++/meeting-rooms.cpp +++ b/C++/meeting-rooms.cpp @@ -16,7 +16,7 @@ class Solution { sort(intervals.begin(), intervals.end(), [](const Interval& x, const Interval& y) { return x.start < y.start; }); for (int i = 1; i < intervals.size(); ++i) { - if (intervals[i].start < intervals[i-1].end) { + if (intervals[i].start < intervals[i - 1].end) { return false; } } From 61087c4a34c58ae476db5e20cd7b767e7041b325 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Aug 2015 16:28:05 +0800 Subject: [PATCH 0596/1939] Update strobogrammatic-number-iii.cpp --- C++/strobogrammatic-number-iii.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/C++/strobogrammatic-number-iii.cpp b/C++/strobogrammatic-number-iii.cpp index 19f66e099..0510a5c00 100644 --- a/C++/strobogrammatic-number-iii.cpp +++ b/C++/strobogrammatic-number-iii.cpp @@ -11,6 +11,10 @@ class Solution { } int countStrobogrammaticUntil(string num, bool can_start_with_0) { + if (can_start_with_0 && cache.find(num) != cache.end()) { + return cache[num]; + } + int count = 0; if (num.length() == 1) { for (const auto& c : {'0', '1', '8'}) { @@ -18,6 +22,7 @@ class Solution { ++count; } } + cache[num] = count; return count; } @@ -48,6 +53,8 @@ class Solution { for (int i = num.length() - 1; i > 0; --i) { count += countStrobogrammaticByLength(i); } + } else { + cache[num] = count; } return count; @@ -85,4 +92,5 @@ class Solution { const unordered_map lookup{{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}}; + unordered_map cache; }; From 9c32772fb0ade6ceb4bfd1659286ef33d48a3e6a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Aug 2015 16:32:33 +0800 Subject: [PATCH 0597/1939] Update strobogrammatic-number-iii.py --- Python/strobogrammatic-number-iii.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Python/strobogrammatic-number-iii.py b/Python/strobogrammatic-number-iii.py index 63caff747..d45aa3d49 100644 --- a/Python/strobogrammatic-number-iii.py +++ b/Python/strobogrammatic-number-iii.py @@ -3,6 +3,7 @@ class Solution: lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'} + cache = {} # @param {string} low # @param {string} high @@ -14,11 +15,15 @@ def strobogrammaticInRange(self, low, high): return count if count >= 0 else 0 def countStrobogrammaticUntil(self, num, can_start_with_0): + if can_start_with_0 and num in self.cache: + return self.cache[num] + count = 0 if len(num) == 1: for c in ['0', '1', '8']: if num[0] >= c: count += 1 + self.cache[num] = count return count for key, val in self.lookup.iteritems(): @@ -42,6 +47,8 @@ def countStrobogrammaticUntil(self, num, can_start_with_0): if not can_start_with_0: # Sum up each length. for i in xrange(len(num) - 1, 0, -1): count += self.countStrobogrammaticByLength(i) + else: + self.cache[num] = count return count From eb7a9eeed4ef269bf84efd225dceb65c854d392e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 11 Aug 2015 19:16:38 +0800 Subject: [PATCH 0598/1939] Create factor-combinations.cpp --- C++/factor-combinations.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/factor-combinations.cpp diff --git a/C++/factor-combinations.cpp b/C++/factor-combinations.cpp new file mode 100644 index 000000000..a177f2aa1 --- /dev/null +++ b/C++/factor-combinations.cpp @@ -0,0 +1,26 @@ +// Time: O(nlogn) = logn * n^(1/2) * n^(1/4) * ... * 1 +// Space: O(logn) + +// DFS solution. +class Solution { + public: + vector> getFactors(int n) { + vector> result; + vector factors; + getResult(n, &result, &factors); + return result; + } + + void getResult(const int n, vector> *result, vector *factors) { + for (int i = factors->empty() ? 2 : factors->back(); i <= n / i; ++i) { + if (n % i == 0) { + factors->emplace_back(i); + factors->emplace_back(n / i); + result->emplace_back(*factors); + factors->pop_back(); + getResult(n / i, result, factors); + factors->pop_back(); + } + } + } + }; From 74b8d95b5b30274b833c50475bdeb558c1de0dc6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 11 Aug 2015 19:17:17 +0800 Subject: [PATCH 0599/1939] Create factor-combinations.py --- Python/factor-combinations.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Python/factor-combinations.py diff --git a/Python/factor-combinations.py b/Python/factor-combinations.py new file mode 100644 index 000000000..9e2c1a687 --- /dev/null +++ b/Python/factor-combinations.py @@ -0,0 +1,23 @@ +# Time: O(nlogn) +# Space: O(logn) + +class Solution: + # @param {integer} n + # @return {integer[][]} + def getFactors(self, n): + result = [] + factors = [] + self.getResult(n, result, factors) + return result + + def getResult(self, n, result, factors): + i = 2 if not factors else factors[-1] + while i <= n / i: + if n % i == 0: + factors.append(i); + factors.append(n / i); + result.append(list(factors)); + factors.pop(); + self.getResult(n / i, result, factors); + factors.pop() + i += 1 From a8c93ead3db7fe86c66b4aee9a8c67cc71cf95ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 11 Aug 2015 19:19:24 +0800 Subject: [PATCH 0600/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2fa6cc4e8..6f8e4c807 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-08), there are `237` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-11), there are `238` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `253` questions. +Here is the classification of all `254` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -362,7 +362,8 @@ Shell 216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(k * C(n, k))_ | _O(k)_ | Medium || 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-tree.py) | _O(h)_ | _O(h)_ | Medium | EPI | 247| [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/) | [C++](./C++/strobogrammatic-number-ii.cpp) [Python](./Python/strobogrammatic-number-ii.py) | _O(n^2 * 5^(n/2))_ | _O(n)_ | Medium |📖|| -250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtreescpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| +250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtrees.cpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| +254| [Factor Combinations](https://leetcode.com/problems/factor-combinations) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| --- From 27d65e5129f5fced477bb8e3c776a64d39c3fbe6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 13 Aug 2015 21:53:15 +0800 Subject: [PATCH 0601/1939] Create verify-preorder-sequence-in-binary-search-tree.cpp --- ...reorder-sequence-in-binary-search-tree.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/verify-preorder-sequence-in-binary-search-tree.cpp diff --git a/C++/verify-preorder-sequence-in-binary-search-tree.cpp b/C++/verify-preorder-sequence-in-binary-search-tree.cpp new file mode 100644 index 000000000..40e5e4130 --- /dev/null +++ b/C++/verify-preorder-sequence-in-binary-search-tree.cpp @@ -0,0 +1,40 @@ +// Time: O(n) +// Soace: O(1) + +class Solution { +public: + bool verifyPreorder(vector& preorder) { + int low = INT_MIN, i = -1; + for (auto& p : preorder) { + if (p < low) { + return false; + } + while (i >= 0 && p > preorder[i]) { + low = preorder[i--]; + } + preorder[++i] = p; + } + return true; + } +}; + +// Time: O(n) +// Soace: O(n) +class Solution2 { +public: + bool verifyPreorder(vector& preorder) { + int low = INT_MIN, i = -1; + stack path; + for (auto& p : preorder) { + if (p < low) { + return false; + } + while (!path.empty() && p > path.top()) { + low = path.top(); + path.pop(); + } + path.emplace(p); + } + return true; + } +}; From 781f09543eb0636fc6431dd393a78caa0c8103d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 13 Aug 2015 21:55:08 +0800 Subject: [PATCH 0602/1939] Update verify-preorder-sequence-in-binary-search-tree.cpp --- C++/verify-preorder-sequence-in-binary-search-tree.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/verify-preorder-sequence-in-binary-search-tree.cpp b/C++/verify-preorder-sequence-in-binary-search-tree.cpp index 40e5e4130..a8f50de58 100644 --- a/C++/verify-preorder-sequence-in-binary-search-tree.cpp +++ b/C++/verify-preorder-sequence-in-binary-search-tree.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Soace: O(1) +// Space: O(1) class Solution { public: @@ -19,7 +19,7 @@ class Solution { }; // Time: O(n) -// Soace: O(n) +// Space: O(n) class Solution2 { public: bool verifyPreorder(vector& preorder) { From 2ea3e6520dfc45a2b2c6da476593b37541eba199 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 13 Aug 2015 21:56:04 +0800 Subject: [PATCH 0603/1939] Update verify-preorder-sequence-in-binary-search-tree.cpp --- C++/verify-preorder-sequence-in-binary-search-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/verify-preorder-sequence-in-binary-search-tree.cpp b/C++/verify-preorder-sequence-in-binary-search-tree.cpp index a8f50de58..b8345aa23 100644 --- a/C++/verify-preorder-sequence-in-binary-search-tree.cpp +++ b/C++/verify-preorder-sequence-in-binary-search-tree.cpp @@ -23,7 +23,7 @@ class Solution { class Solution2 { public: bool verifyPreorder(vector& preorder) { - int low = INT_MIN, i = -1; + int low = INT_MIN; stack path; for (auto& p : preorder) { if (p < low) { From ccbc54653e2289cc0b06731199dca36419470512 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 13 Aug 2015 21:57:40 +0800 Subject: [PATCH 0604/1939] Create verify-preorder-sequence-in-binary-search-tree.py --- ...y-preorder-sequence-in-binary-search-tree.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/verify-preorder-sequence-in-binary-search-tree.py diff --git a/Python/verify-preorder-sequence-in-binary-search-tree.py b/Python/verify-preorder-sequence-in-binary-search-tree.py new file mode 100644 index 000000000..9ebd9e27c --- /dev/null +++ b/Python/verify-preorder-sequence-in-binary-search-tree.py @@ -0,0 +1,17 @@ +# Time: O(n) +# Space: O(1) + +class Solution: + # @param {integer[]} preorder + # @return {boolean} + def verifyPreorder(self, preorder): + low, i = float("-inf"), -1; + for p in preorder: + if p < low: + return False + while i >= 0 and p > preorder[i]: + low = preorder[i] + i -= 1 + i += 1 + preorder[i] = p + return True From fbec2f38ff3e8c6de1aad46ab66c9fc56371d32a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 13 Aug 2015 22:01:33 +0800 Subject: [PATCH 0605/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6f8e4c807..a27157844 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-11), there are `238` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-13), there are `239` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `254` questions. +Here is the classification of all `255` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -154,6 +154,7 @@ Shell 224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./C++/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Medium || 227| [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | [C++](./C++/basic-calculator-ii.cpp) [Python](./Python/basic-calculator-ii.py) | _O(n)_| _O(n)_| Medium || 232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| Easy | EPI, LintCode | +255| [Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/verify-preorder-sequence-in-binary-search-tree.cpp) [Python](./Python/verify-preorder-sequence-in-binary-search-tree.py) | _O(n)_| _O(1)_| Medium |📖|| --- From 1bfe66defa956297d4fafdccceb5a3fc174deeaa Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 13 Aug 2015 22:05:02 +0800 Subject: [PATCH 0606/1939] Update verify-preorder-sequence-in-binary-search-tree.py --- ...preorder-sequence-in-binary-search-tree.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/Python/verify-preorder-sequence-in-binary-search-tree.py b/Python/verify-preorder-sequence-in-binary-search-tree.py index 9ebd9e27c..8ca30d01a 100644 --- a/Python/verify-preorder-sequence-in-binary-search-tree.py +++ b/Python/verify-preorder-sequence-in-binary-search-tree.py @@ -5,7 +5,7 @@ class Solution: # @param {integer[]} preorder # @return {boolean} def verifyPreorder(self, preorder): - low, i = float("-inf"), -1; + low, i = float("-inf"), -1 for p in preorder: if p < low: return False @@ -15,3 +15,20 @@ def verifyPreorder(self, preorder): i += 1 preorder[i] = p return True + +# Time: O(n) +# Space: O(n) +class Solution2: + # @param {integer[]} preorder + # @return {boolean} + def verifyPreorder(self, preorder): + low = float("-inf") + path = [] + for p in preorder: + if p < low: + return False + while path and p > path[-1]: + low = path[-1] + path.pop() + path.append(p) + return True From 01fe74cc10147cd6c94b76c225854830c4f8733a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Aug 2015 00:18:19 +0800 Subject: [PATCH 0607/1939] Update verify-preorder-sequence-in-binary-search-tree.cpp --- C++/verify-preorder-sequence-in-binary-search-tree.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/verify-preorder-sequence-in-binary-search-tree.cpp b/C++/verify-preorder-sequence-in-binary-search-tree.cpp index b8345aa23..436c3e8bf 100644 --- a/C++/verify-preorder-sequence-in-binary-search-tree.cpp +++ b/C++/verify-preorder-sequence-in-binary-search-tree.cpp @@ -30,6 +30,9 @@ class Solution2 { return false; } while (!path.empty() && p > path.top()) { + // Traverse to its right subtree now. + // Use the popped values as a lower bound because + // we shouldn't come across a smaller number anymore. low = path.top(); path.pop(); } From bf739f605ff23830c93cc02f97d3e674f0c1795b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Aug 2015 01:08:23 +0800 Subject: [PATCH 0608/1939] Update verify-preorder-sequence-in-binary-search-tree.cpp --- C++/verify-preorder-sequence-in-binary-search-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/verify-preorder-sequence-in-binary-search-tree.cpp b/C++/verify-preorder-sequence-in-binary-search-tree.cpp index 436c3e8bf..9e66bee98 100644 --- a/C++/verify-preorder-sequence-in-binary-search-tree.cpp +++ b/C++/verify-preorder-sequence-in-binary-search-tree.cpp @@ -19,7 +19,7 @@ class Solution { }; // Time: O(n) -// Space: O(n) +// Space: O(h) class Solution2 { public: bool verifyPreorder(vector& preorder) { From 2af52e62c9d0dcd6fc7a0d43a7ee31c2016b894f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Aug 2015 01:08:48 +0800 Subject: [PATCH 0609/1939] Update verify-preorder-sequence-in-binary-search-tree.py --- Python/verify-preorder-sequence-in-binary-search-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/verify-preorder-sequence-in-binary-search-tree.py b/Python/verify-preorder-sequence-in-binary-search-tree.py index 8ca30d01a..8da8deeb2 100644 --- a/Python/verify-preorder-sequence-in-binary-search-tree.py +++ b/Python/verify-preorder-sequence-in-binary-search-tree.py @@ -17,7 +17,7 @@ def verifyPreorder(self, preorder): return True # Time: O(n) -# Space: O(n) +# Space: O(h) class Solution2: # @param {integer[]} preorder # @return {boolean} From 32f1d2a807f60e026e66b9979b403cd3b6c72486 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Aug 2015 19:44:00 +0800 Subject: [PATCH 0610/1939] Create paint-house.cpp --- C++/paint-house.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 C++/paint-house.cpp diff --git a/C++/paint-house.cpp b/C++/paint-house.cpp new file mode 100644 index 000000000..d153127cb --- /dev/null +++ b/C++/paint-house.cpp @@ -0,0 +1,47 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int minCost(vector>& costs) { + if (costs.empty()) { + return 0; + } + + vector> min_cost(2); + min_cost[0] = costs[0]; + + const int n = costs.size(); + for (int i = 1; i < n; ++i) { + min_cost[i % 2][0] = costs[i][0] + + min(min_cost[(i - 1) % 2][1], min_cost[(i - 1) % 2][2]); + min_cost[i % 2][1] = costs[i][1] + + min(min_cost[(i - 1) % 2][0], min_cost[(i - 1) % 2][2]); + min_cost[i % 2][2] = costs[i][2] + + min(min_cost[(i - 1) % 2][0], min_cost[(i - 1) % 2][1]); + } + + return min(min_cost[(n - 1) % 2][0], + min(min_cost[(n - 1) % 2][1], min_cost[(n - 1) % 2][2])); + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { +public: + int minCost(vector>& costs) { + if (costs.empty()) { + return 0; + } + + const int n = costs.size(); + for (int i = 1; i < n; ++i) { + costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]); + costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]); + costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]); + } + + return min(costs[n - 1][0], min(costs[n - 1][1], costs[n - 1][2])); + } +}; From 10c06e206acb9fb32aa04d7009deaed67007d4f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Aug 2015 19:44:42 +0800 Subject: [PATCH 0611/1939] Update paint-house.cpp --- C++/paint-house.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/paint-house.cpp b/C++/paint-house.cpp index d153127cb..d93d65527 100644 --- a/C++/paint-house.cpp +++ b/C++/paint-house.cpp @@ -8,8 +8,7 @@ class Solution { return 0; } - vector> min_cost(2); - min_cost[0] = costs[0]; + vector> min_cost(2, costs[0]); const int n = costs.size(); for (int i = 1; i < n; ++i) { From 61e0b9c1d026d92c4a01205647d19365dfc90bbe Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Aug 2015 19:49:06 +0800 Subject: [PATCH 0612/1939] Create paint-house.py --- Python/paint-house.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Python/paint-house.py diff --git a/Python/paint-house.py b/Python/paint-house.py new file mode 100644 index 000000000..4d854d240 --- /dev/null +++ b/Python/paint-house.py @@ -0,0 +1,22 @@ +# Time: O(n) +# Space: O(1) + +class Solution: + # @param {integer[][]} costs + # @return {integer} + def minCost(self, costs): + if not costs: + return 0 + + min_cost = [costs[0], [0, 0, 0]] + + n = len(costs) + for i in xrange(1, n): + min_cost[i % 2][0] = costs[i][0] + \ + min(min_cost[(i - 1) % 2][1], min_cost[(i - 1) % 2][2]) + min_cost[i % 2][1] = costs[i][1] + \ + min(min_cost[(i - 1) % 2][0], min_cost[(i - 1) % 2][2]) + min_cost[i % 2][2] = costs[i][2] + \ + min(min_cost[(i - 1) % 2][0], min_cost[(i - 1) % 2][1]) + + return min(min_cost[(n - 1) % 2][0], min_cost[(n - 1) % 2][1], min_cost[(n - 1) % 2][2]) From 295a906b892c6b381f4d649d979325a5712ef673 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Aug 2015 19:51:09 +0800 Subject: [PATCH 0613/1939] Update paint-house.py --- Python/paint-house.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Python/paint-house.py b/Python/paint-house.py index 4d854d240..cd9f4fbe7 100644 --- a/Python/paint-house.py +++ b/Python/paint-house.py @@ -20,3 +20,22 @@ def minCost(self, costs): min(min_cost[(i - 1) % 2][0], min_cost[(i - 1) % 2][1]) return min(min_cost[(n - 1) % 2][0], min_cost[(n - 1) % 2][1], min_cost[(n - 1) % 2][2]) + +# Time: O(n) +# Space: O(n) +class Solution2: + # @param {integer[][]} costs + # @return {integer} + def minCost(self, costs): + if not costs: + return 0 + + min_cost = [costs[0], [0, 0, 0]] + + n = len(costs) + for i in xrange(1, n): + costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]) + costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]) + costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]) + + return min(costs[n - 1][0], costs[n - 1][1], costs[n - 1][2]) From f36d28e140edf76e81f837079bdafadb647c5c0f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Aug 2015 19:52:52 +0800 Subject: [PATCH 0614/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a27157844..5cb975e7d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-13), there are `239` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-14), there are `240` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `255` questions. +Here is the classification of all `256` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -395,6 +395,7 @@ Shell 198| [House Robber](https://leetcode.com/problems/house-robber/)| [Python](./Python/house-robber.py) | _O(n)_ | _O(1)_ | Easy || 213| [House Robber II](https://leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || 221| [Maximal Square](https://leetcode.com/problems/maximal-square/)| [C++](./C++/maximal-square.cpp) [Python](./Python/maximal-square.py) | _O(n^2)_ | _O(n)_ | Medium | EPI | +256| [Paint House](https://leetcode.com/problems/paint-house/) | [C++](./C++/paint-house.cpp) [Python](./Python/paint-house.py) | _O(n)_| _O(1)_| Medium |📖|| --- From 31fd7b10134fe7f57a0a7ea714716eea841a6fd6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Aug 2015 20:26:35 +0800 Subject: [PATCH 0615/1939] Update paint-house.py --- Python/paint-house.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Python/paint-house.py b/Python/paint-house.py index cd9f4fbe7..d192c0478 100644 --- a/Python/paint-house.py +++ b/Python/paint-house.py @@ -30,8 +30,6 @@ def minCost(self, costs): if not costs: return 0 - min_cost = [costs[0], [0, 0, 0]] - n = len(costs) for i in xrange(1, n): costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]) From 3973911447c902094c27eec5fd475c7b9d7849a9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Aug 2015 19:26:06 +0800 Subject: [PATCH 0616/1939] Update binary-tree-inorder-traversal.py --- Python/binary-tree-inorder-traversal.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index 5f68d1e39..65c94ed4d 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -66,7 +66,7 @@ def inorderTraversal(self, root): if parent.right in (None, last_traversed): if parent.right is None: result.append(parent.val) - last_traversed= stack.pop() + last_traversed = stack.pop() else: result.append(parent.val) current = parent.right From 1fb92b046e7ea25211d000cb49be99aaea163b19 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Aug 2015 19:27:05 +0800 Subject: [PATCH 0617/1939] Update binary-tree-inorder-traversal.py --- Python/binary-tree-inorder-traversal.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index 65c94ed4d..735856061 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -76,7 +76,7 @@ class Solution3: # @param root, a tree node # @return a list of integers def inorderTraversal(self, root): - result, stack, current, last_traversed = [], [], root, None + result, stack, current = [], [], root while stack or current: if current: stack.append(current) From 74f02dffffa205a277757ee6886ac27cf98a8717 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Aug 2015 19:44:56 +0800 Subject: [PATCH 0618/1939] Update binary-tree-inorder-traversal.py --- Python/binary-tree-inorder-traversal.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index 735856061..094ed428b 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -82,8 +82,7 @@ def inorderTraversal(self, root): stack.append(current) current = current.left else: - current = stack[-1] - stack.pop() + current = stack.pop() result.append(current.val) current = current.right return result From 8f0387339619798f1a435370d95332dfc3cf393f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Aug 2015 21:26:02 +0800 Subject: [PATCH 0619/1939] Create binary-tree-paths.py --- Python/binary-tree-paths.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/binary-tree-paths.py diff --git a/Python/binary-tree-paths.py b/Python/binary-tree-paths.py new file mode 100644 index 000000000..40324b412 --- /dev/null +++ b/Python/binary-tree-paths.py @@ -0,0 +1,37 @@ +# Time: O(n * h) +# Space: O(h) +# +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param {TreeNode} root + # @return {string[]} + def binaryTreePaths(self, root): + result, path = [], [] + self.binaryTreePathsRecu(root, path, result) + return result + + def binaryTreePathsRecu(self, node, path, result): + if node is None: + return + + if node.left is node.right is None: + ans = "" + for n in path: + ans += str(n.val) + "->" + resault.append(ans + str(node.val)) + + if node.left: + path.append(node) + self.binaryTreePathsRecu(node.left, path, result) + path.pop() + + if node.right: + path.append(node) + self.binaryTreePathsRecu(node.right, path, result) + path.pop() From 0d63e1741c344e995a922bf68bedcc41651d14d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Aug 2015 21:28:02 +0800 Subject: [PATCH 0620/1939] Create add-digits.py --- Python/add-digits.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Python/add-digits.py diff --git a/Python/add-digits.py b/Python/add-digits.py new file mode 100644 index 000000000..994ba6378 --- /dev/null +++ b/Python/add-digits.py @@ -0,0 +1,8 @@ +# Time: O(1) +# Space: O(1) + +class Solution: + # @param {integer} num + # @return {integer} + def addDigits(self, num): + return (num - 1) % 9 + 1 if num > 0 else 0 From b3098a053e7569db883c2cfaa6b45f01755d760e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Aug 2015 21:29:49 +0800 Subject: [PATCH 0621/1939] Create add-digits.cpp --- C++/add-digits.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 C++/add-digits.cpp diff --git a/C++/add-digits.cpp b/C++/add-digits.cpp new file mode 100644 index 000000000..fe74f6818 --- /dev/null +++ b/C++/add-digits.cpp @@ -0,0 +1,9 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int addDigits(int num) { + return (num - 1) % 9 + 1; + } +}; From 10be21d043dd157f6faad11d7ffa60a42e4bc5b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Aug 2015 21:43:16 +0800 Subject: [PATCH 0622/1939] Create binary-tree-paths.cpp --- C++/binary-tree-paths.cpp | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 C++/binary-tree-paths.cpp diff --git a/C++/binary-tree-paths.cpp b/C++/binary-tree-paths.cpp new file mode 100644 index 000000000..6d51e934f --- /dev/null +++ b/C++/binary-tree-paths.cpp @@ -0,0 +1,47 @@ +// Time: O(n * h) +// Space: O(h) + +/** + * 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: + vector binaryTreePaths(TreeNode* root) { + vector result; + vector path; + binaryTreePathsRecu(root, &path, &result); + return result; + } + + void binaryTreePathsRecu(TreeNode *node, vector *path, vector *result) { + if (node == nullptr) { + return; + } + + if (node->left == nullptr && node->right == nullptr) { + string ans = ""; + for (const auto& n : *path) { + ans.append(to_string(n->val).append("->")); + } + result->emplace_back(move(ans.append(to_string(node->val)))); + } + + if (node->left != nullptr) { + path->emplace_back(node); + binaryTreePathsRecu(node->left, path, result); + path->pop_back(); + } + + if (node->right != nullptr) { + path->emplace_back(node); + binaryTreePathsRecu(node->right, path, result); + path->pop_back(); + } + } +}; From ee4abc9f83e466e1a61ae46baddcc4ae25b6651c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Aug 2015 21:49:32 +0800 Subject: [PATCH 0623/1939] Update README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5cb975e7d..ba24ae9d8 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-14), there are `240` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-16), there are `242` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `256` questions. +Here is the classification of all `258` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -236,6 +236,7 @@ Shell 223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C++](./C++/rectangle-area.cpp) [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || 233| [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | [C++](./C++/number-of-digit-one.cpp) [Python](./Python/number-of-digit-one.py) | _O(logn)_ | _O(1)_ | Medium | CTCI, LintCode| 248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard |📖|| +258| [Add Digits](https://leetcode.com/problems/add-digits/) | [C++](./C++/add-digits.cpp) [Python](./Python/add-digits.py) | _O(1)_ | _O(1)_ | Easy ||| --- @@ -365,6 +366,7 @@ Shell 247| [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/) | [C++](./C++/strobogrammatic-number-ii.cpp) [Python](./Python/strobogrammatic-number-ii.py) | _O(n^2 * 5^(n/2))_ | _O(n)_ | Medium |📖|| 250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtrees.cpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| 254| [Factor Combinations](https://leetcode.com/problems/factor-combinations) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| +257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| --- From d8b7f7b3045c674055e0dec5e11865c68d3d8d4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Aug 2015 21:50:21 +0800 Subject: [PATCH 0624/1939] Update binary-tree-paths.py --- Python/binary-tree-paths.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/binary-tree-paths.py b/Python/binary-tree-paths.py index 40324b412..1314f3730 100644 --- a/Python/binary-tree-paths.py +++ b/Python/binary-tree-paths.py @@ -24,7 +24,7 @@ def binaryTreePathsRecu(self, node, path, result): ans = "" for n in path: ans += str(n.val) + "->" - resault.append(ans + str(node.val)) + result.append(ans + str(node.val)) if node.left: path.append(node) From 104590173083f90489e72c86538a110558b7999d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 08:59:37 +0800 Subject: [PATCH 0625/1939] Update binary-tree-paths.py --- Python/binary-tree-paths.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Python/binary-tree-paths.py b/Python/binary-tree-paths.py index 1314f3730..657e8d579 100644 --- a/Python/binary-tree-paths.py +++ b/Python/binary-tree-paths.py @@ -1,6 +1,20 @@ # Time: O(n * h) # Space: O(h) # +# Given a binary tree, return all root-to-leaf paths. +# +# For example, given the following binary tree: +# +# 1 +# / \ +# 2 3 +# \ +# 5 +# All root-to-leaf paths are: +# +# ["1->2->5", "1->3"] +# +# # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): From 632f39f8379e61465d7157b4f3c581fbaddf2c23 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 09:02:09 +0800 Subject: [PATCH 0626/1939] Update add-digits.py --- Python/add-digits.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/Python/add-digits.py b/Python/add-digits.py index 994ba6378..baaa5cde5 100644 --- a/Python/add-digits.py +++ b/Python/add-digits.py @@ -1,6 +1,23 @@ # Time: O(1) # Space: O(1) - +# +# Given a non-negative integer num, repeatedly add +# all its digits until the result has only one digit. +# +# For example: +# +# Given num = 38, the process is like: 3 + 8 = 11, +# 1 + 1 = 2. Since 2 has only one digit, return it. +# +# Follow up: +# Could you do it without any loop/recursion in O(1) +# runtime? +# +# Hint: +# +# A naive implementation of the above process is trivial. +# Could you come up with other methods? +# class Solution: # @param {integer} num # @return {integer} From 4809e70916dd056c6aef0710b67c256b13c47412 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 21:21:39 +0800 Subject: [PATCH 0627/1939] Create single-number-iii.cpp --- C++/single-number-iii.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/single-number-iii.cpp diff --git a/C++/single-number-iii.cpp b/C++/single-number-iii.cpp new file mode 100644 index 000000000..5d510c144 --- /dev/null +++ b/C++/single-number-iii.cpp @@ -0,0 +1,28 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector singleNumber(vector& nums) { + // Xor all the elements to get x ^ y. + int x_xor_y = 0; + for (const auto& i : nums) { + x_xor_y ^= i; + } + + // Get the last bit where 1 occurs. + const auto bit = x_xor_y & ~(x_xor_y - 1); + + // Get the subset of A where the number has the bit. + // The subset only contains one of the two integers, call it x. + // Xor all the elemets in the subset to get x. + int x = 0; + for (const auto& i : nums) { + if (i & bit) { + x ^= i; + } + } + + return {x, x_xor_y ^ x}; + } +}; From a0286af28c8ac833442a5a03db3978bec8dd0946 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 21:26:13 +0800 Subject: [PATCH 0628/1939] Create single-number-iii.py --- Python/single-number-iii.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/single-number-iii.py diff --git a/Python/single-number-iii.py b/Python/single-number-iii.py new file mode 100644 index 000000000..163bc9f7e --- /dev/null +++ b/Python/single-number-iii.py @@ -0,0 +1,34 @@ +# Time: O(n) +# Space: O(1) +# +# 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? +# + +class Solution: + # @param {integer[]} nums + # @return {integer[]} + def singleNumber(self, nums): + x_xor_y = 0 + for i in nums: + x_xor_y ^= i + + bit = x_xor_y & ~(x_xor_y - 1) + + x = 0 + for i in nums: + if i & bit: + x ^= i + + return [x, x_xor_y ^ x] From a465bcdc5fd86edb8a7fdd245dddbdf1e7a845da Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 21:40:17 +0800 Subject: [PATCH 0629/1939] Create 3sum-smaller.cpp --- C++/3sum-smaller.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/3sum-smaller.cpp diff --git a/C++/3sum-smaller.cpp b/C++/3sum-smaller.cpp new file mode 100644 index 000000000..4494672e0 --- /dev/null +++ b/C++/3sum-smaller.cpp @@ -0,0 +1,25 @@ +// Time: O(n^2) +// Space: O(1) + +class Solution { +public: + int threeSumSmaller(vector& nums, int target) { + sort(nums.begin(), nums.end()); + const int n = nums.size(); + + int count = 0; + for (int k = 2; k < n; ++k) { + int i = 0, j = k - 1; + while (i < j) { // Two Pointers, linear time. + if (nums[i] + nums[j] >= target - nums[k]) { + --j; + } else { + count += j - i; + ++i; + } + } + } + + return count; + } +}; From 8ac29610bbff7c69395c9f85b99742dcbe8dccb4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 21:43:18 +0800 Subject: [PATCH 0630/1939] Update 3sum-smaller.cpp --- C++/3sum-smaller.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/3sum-smaller.cpp b/C++/3sum-smaller.cpp index 4494672e0..db32ead82 100644 --- a/C++/3sum-smaller.cpp +++ b/C++/3sum-smaller.cpp @@ -11,7 +11,7 @@ class Solution { for (int k = 2; k < n; ++k) { int i = 0, j = k - 1; while (i < j) { // Two Pointers, linear time. - if (nums[i] + nums[j] >= target - nums[k]) { + if (nums[i] + nums[j] + nums[k] >= target) { --j; } else { count += j - i; From 34f0e8760a910f4d6645fec9a9e85dd072163edf Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 21:43:58 +0800 Subject: [PATCH 0631/1939] Create 3sum-smaller.py --- Python/3sum-smaller.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Python/3sum-smaller.py diff --git a/Python/3sum-smaller.py b/Python/3sum-smaller.py new file mode 100644 index 000000000..bcc9b533b --- /dev/null +++ b/Python/3sum-smaller.py @@ -0,0 +1,23 @@ +# Time: O(n^2) +# Space: O(1) + +class Solution: + # @param {integer[]} nums + # @param {integer} target + # @return {integer} + def threeSumSmaller(self, nums, target): + nums.sort() + n = len(nums) + + count, k = 0, 2 + while k < n: + i, j = 0, k - 1 + while i < j: # Two Pointers, linear time. + if nums[i] + nums[j] + nums[k] >= target: + j -= 1 + else: + count += j - i + i += 1 + k += 1 + + return count From ce5432955feb43f474ba0b19190d953de173780f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 21:48:44 +0800 Subject: [PATCH 0632/1939] Update README.md --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ba24ae9d8..5e80a2dca 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-16), there are `242` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-17), there are `244` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `258` questions. +Here is the classification of all `260` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -23,7 +23,7 @@ Algorithms * [Hash Table](https://github.com/kamyu104/LeetCode#hash-table) * [Data Structure](https://github.com/kamyu104/LeetCode#data-structure) * [Math](https://github.com/kamyu104/LeetCode#math) -* [Two Pointer](https://github.com/kamyu104/LeetCode#two-pointer) +* [Two Pointers](https://github.com/kamyu104/LeetCode#two-pointers) * [Sort](https://github.com/kamyu104/LeetCode#sort) * [Brute Force Search](https://github.com/kamyu104/LeetCode#brute-force-search) * [Divide and Conquer](https://github.com/kamyu104/LeetCode#divide-and-conquer) @@ -58,6 +58,7 @@ Shell 191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | +260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || --- @@ -258,7 +259,7 @@ Shell --- -##Two Pointer +##Two Pointers # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || @@ -267,6 +268,7 @@ Shell 142| [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || 143| [Reorder List](https://leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || 167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [C++](./C++/3sum-smaller.cpp) [Python](./Python/3sum-smaller.py) | _O(n^2)_ | _O(1)_ | Medium | 📖, LintCode | --- From 43af6f02056c3f6b0cdc54e7eba30c420d5e2cc6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 23:19:21 +0800 Subject: [PATCH 0633/1939] Update reverse-bits.py --- Python/reverse-bits.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py index 4c8a0f36d..c5a6fa4ec 100644 --- a/Python/reverse-bits.py +++ b/Python/reverse-bits.py @@ -3,15 +3,12 @@ # # Reverse bits of a given 32 bits unsigned integer. # -# For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). +# For example, given input 43261596 (represented in binary as +# 00000010100101000001111010011100), return 964176192 (represented in binary +# as 00111001011110000010100101000000). # # Follow up: # If this function is called many times, how would you optimize it? -# -# Related problem: Reverse Integer -# -# Credits: -# Special thanks to @ts for adding this problem and creating all test cases. # class Solution: From 65433caa695deaa508dfec126be4a06786dd0693 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Aug 2015 23:27:04 +0800 Subject: [PATCH 0634/1939] Update number-of-1-bits.py --- Python/number-of-1-bits.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/Python/number-of-1-bits.py b/Python/number-of-1-bits.py index 2b34a304f..c0069d07c 100644 --- a/Python/number-of-1-bits.py +++ b/Python/number-of-1-bits.py @@ -7,9 +7,6 @@ # For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, # so the function should return 3. # -# Credits: -# Special thanks to @ts for adding this problem and creating all test cases. -# class Solution: # @param n, an integer # @return an integer From 1bb32d6795b3a72fb388285a472df497e8cf85d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 18 Aug 2015 10:21:39 +0800 Subject: [PATCH 0635/1939] Create graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 45 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/graph-valid-tree.cpp diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp new file mode 100644 index 000000000..daf0c658e --- /dev/null +++ b/C++/graph-valid-tree.cpp @@ -0,0 +1,45 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + struct node { + int parent; + vectorneighbors; + }; + bool validTree(int n, vector>& edges) { + if (edges.size() != n - 1) { + return false; + } + + unordered_map nodes; + unordered_set visited; + for (const auto& edge : edges) { + nodes[edge.first].neighbors.emplace_back(edge.second); + nodes[edge.second].neighbors.emplace_back(edge.first); + } + for (int i = 0; i < n; ++i) { + nodes[i].parent = -1; + } + + queue q; + q.emplace(0); + visited.insert(0); + while (!q.empty()) { + int i = q.front(); + q.pop(); + for (const auto& n : nodes[i].neighbors) { + if (n != nodes[i].parent) { + if (visited.find(n) != visited.end()) { + return false; + } else { + visited.insert(n); + nodes[n].parent = i; + q.emplace(n); + } + } + } + } + return true; + } +}; From cb611acb4352c5c5019355951943a5312c430739 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 18 Aug 2015 10:25:11 +0800 Subject: [PATCH 0636/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5e80a2dca..2097dd3f9 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-17), there are `244` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-18), there are `245` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `260` questions. +Here is the classification of all `261` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -343,6 +343,7 @@ Shell 133| [Clone Graph](https://leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || 207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | 📖 | --- From 2a660c185d66923122fa5bfb66aa70794098ca3d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 18 Aug 2015 10:25:56 +0800 Subject: [PATCH 0637/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index daf0c658e..330597ba6 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -1,5 +1,5 @@ -// Time: O(n) -// Space: O(n) +// Time: O(|V| + |E|) +// Space: O(|V|) class Solution { public: From 847aed7bfb61f442c486c3636113d138bf41de92 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 18 Aug 2015 10:26:15 +0800 Subject: [PATCH 0638/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2097dd3f9..54f25c981 100644 --- a/README.md +++ b/README.md @@ -343,7 +343,7 @@ Shell 133| [Clone Graph](https://leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || 207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || -261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | 📖 | +261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | --- From 223d1c3c49610e20a3e2bb969591826307d71805 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 18 Aug 2015 12:42:35 +0800 Subject: [PATCH 0639/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index 330597ba6..9f611ea45 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -13,7 +13,6 @@ class Solution { } unordered_map nodes; - unordered_set visited; for (const auto& edge : edges) { nodes[edge.first].neighbors.emplace_back(edge.second); nodes[edge.second].neighbors.emplace_back(edge.first); @@ -22,12 +21,13 @@ class Solution { nodes[i].parent = -1; } + unordered_set visited; queue q; q.emplace(0); - visited.insert(0); while (!q.empty()) { int i = q.front(); q.pop(); + visited.insert(i); for (const auto& n : nodes[i].neighbors) { if (n != nodes[i].parent) { if (visited.find(n) != visited.end()) { From 489aeec0db14b636e01655b4611417422d93c4b0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 18 Aug 2015 12:43:07 +0800 Subject: [PATCH 0640/1939] Create graph-valid-tree.py --- Python/graph-valid-tree.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/graph-valid-tree.py diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py new file mode 100644 index 000000000..e347ae47c --- /dev/null +++ b/Python/graph-valid-tree.py @@ -0,0 +1,33 @@ +# Time: O(|V| + |E|) +# Space: O(|V|) + +class Solution: + # @param {integer} n + # @param {integer[][]} edges + # @return {boolean} + def validTree(self, n, edges): + if len(edges) != n - 1: + return False + + nodes = {} + for i in xrange(n): + nodes[i] = [-1, []] + for edge in edges: + nodes[edge[0]][1].append(edge[1]) + nodes[edge[1]][1].append(edge[0]) + + visited = {} + q = collections.deque() + q.append(0) + while q: + i = q.popleft() + visited[i] = True + for n in nodes[i][1]: + if n != nodes[i][0]: + if n in visited: + return False + else: + visited[n] = True + nodes[n][0] = i + q.append(n) + return True From 20542c0ebb6d9d3bfe68a0f4adff1bd384c72c3a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 18 Aug 2015 12:46:54 +0800 Subject: [PATCH 0641/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index e347ae47c..2d4b17e5e 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -9,12 +9,13 @@ def validTree(self, n, edges): if len(edges) != n - 1: return False + parent, neighbors = 0, 1 nodes = {} for i in xrange(n): nodes[i] = [-1, []] for edge in edges: - nodes[edge[0]][1].append(edge[1]) - nodes[edge[1]][1].append(edge[0]) + nodes[edge[0]][neighbors].append(edge[1]) + nodes[edge[1]][neighbors].append(edge[0]) visited = {} q = collections.deque() @@ -22,12 +23,12 @@ def validTree(self, n, edges): while q: i = q.popleft() visited[i] = True - for n in nodes[i][1]: - if n != nodes[i][0]: + for n in nodes[i][neighbors]: + if n != nodes[i][parent]: if n in visited: return False else: visited[n] = True - nodes[n][0] = i + nodes[n][parent] = i q.append(n) return True From 345ef6c7b5465571a57943f9bf37f0fd9f80d6a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 09:30:38 +0800 Subject: [PATCH 0642/1939] Create ugly-number-ii.cpp --- C++/ugly-number-ii.cpp | 66 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 C++/ugly-number-ii.cpp diff --git a/C++/ugly-number-ii.cpp b/C++/ugly-number-ii.cpp new file mode 100644 index 000000000..6d512e96f --- /dev/null +++ b/C++/ugly-number-ii.cpp @@ -0,0 +1,66 @@ +// Time: O(n) +// Space: O(1) + +// Heap solution. +class Solution { +public: + int nthUglyNumber(int n) { + long long ugly_number = 0; + priority_queue, greater> heap; + + heap.emplace(1); + for (int i = 0; i < n; ++i) { + if (heap.top() % 2 == 0) { + ugly_number = heap.top(); + heap.pop(); + heap.emplace(ugly_number * 2); + } + else if (heap.top() % 3 == 0) { + ugly_number = heap.top(); + heap.pop(); + heap.emplace(ugly_number * 2); + heap.emplace(ugly_number * 3); + } + else { + ugly_number = heap.top(); + heap.pop(); + heap.emplace(ugly_number * 2); + heap.emplace(ugly_number * 3); + heap.emplace(ugly_number * 5); + } + } + return ugly_number; + } +}; + +// BST solution. +class Solution2 { +public: + int nthUglyNumber(int n) { + long long ugly_number = 0; + set bst; + + bst.insert(1); + for (int i = 0; i < n; ++i) { + if (*bst.cbegin() % 2 == 0) { + ugly_number = *bst.cbegin(); + bst.erase(bst.cbegin()); + bst.insert(ugly_number * 2); + } + else if (*bst.cbegin() % 3 == 0) { + ugly_number = *bst.cbegin(); + bst.erase(bst.cbegin()); + bst.insert(ugly_number * 2); + bst.insert(ugly_number * 3); + } + else { + ugly_number = *bst.cbegin(); + bst.erase(bst.cbegin()); + bst.insert(ugly_number * 2); + bst.insert(ugly_number * 3); + bst.insert(ugly_number * 5); + } + } + return ugly_number; + } +}; From d3495314d6e07b5f7f2adcc31ddb3fe40f4ad692 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 09:35:33 +0800 Subject: [PATCH 0643/1939] Create ugly-number.cpp --- C++/ugly-number.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/ugly-number.cpp diff --git a/C++/ugly-number.cpp b/C++/ugly-number.cpp new file mode 100644 index 000000000..b804fc34d --- /dev/null +++ b/C++/ugly-number.cpp @@ -0,0 +1,17 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + bool isUgly(int num) { + if (num == 0) { + return false; + } + for (const auto& i : {2, 3, 5}) { + while (num % i == 0) { + num /= i; + } + } + return num == 1; + } +}; From c01c2be495f6dfb046d97761d2a0a3488a114d98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 09:37:43 +0800 Subject: [PATCH 0644/1939] Create ugly-number.py --- Python/ugly-number.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/ugly-number.py diff --git a/Python/ugly-number.py b/Python/ugly-number.py new file mode 100644 index 000000000..003756ec7 --- /dev/null +++ b/Python/ugly-number.py @@ -0,0 +1,21 @@ +# Time: O(logn) +# Space: O(1) +# +# Write a program to check whether a given number is an ugly number. +# +# Ugly numbers are positive numbers whose prime factors only include +# 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it +# includes another prime factor 7. +# +# Note that 1 is typically treated as an ugly number. +# +class Solution: + # @param {integer} num + # @return {boolean} + def isUgly(self, num): + if num == 0: + return False + for i in [2, 3, 5]: + while num % i == 0: + num /= i + return num == 1 From b6468603b1eeccc3776d5b1328575c19439ba583 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 09:48:19 +0800 Subject: [PATCH 0645/1939] Update ugly-number-ii.cpp --- C++/ugly-number-ii.cpp | 38 +++++++++++++++----------------------- 1 file changed, 15 insertions(+), 23 deletions(-) diff --git a/C++/ugly-number-ii.cpp b/C++/ugly-number-ii.cpp index 6d512e96f..5c3d00ca3 100644 --- a/C++/ugly-number-ii.cpp +++ b/C++/ugly-number-ii.cpp @@ -10,20 +10,16 @@ class Solution { heap.emplace(1); for (int i = 0; i < n; ++i) { - if (heap.top() % 2 == 0) { - ugly_number = heap.top(); - heap.pop(); + ugly_number = heap.top(); + heap.pop(); + if (ugly_number % 2 == 0) { heap.emplace(ugly_number * 2); } - else if (heap.top() % 3 == 0) { - ugly_number = heap.top(); - heap.pop(); + else if (ugly_number % 3 == 0) { heap.emplace(ugly_number * 2); heap.emplace(ugly_number * 3); } else { - ugly_number = heap.top(); - heap.pop(); heap.emplace(ugly_number * 2); heap.emplace(ugly_number * 3); heap.emplace(ugly_number * 5); @@ -40,25 +36,21 @@ class Solution2 { long long ugly_number = 0; set bst; - bst.insert(1); + bst.emplace(1); for (int i = 0; i < n; ++i) { - if (*bst.cbegin() % 2 == 0) { - ugly_number = *bst.cbegin(); - bst.erase(bst.cbegin()); - bst.insert(ugly_number * 2); + ugly_number = *bst.cbegin(); + bst.erase(bst.cbegin()); + if (ugly_number % 2 == 0) { + bst.emplace(ugly_number * 2); } - else if (*bst.cbegin() % 3 == 0) { - ugly_number = *bst.cbegin(); - bst.erase(bst.cbegin()); - bst.insert(ugly_number * 2); - bst.insert(ugly_number * 3); + else if (ugly_number % 3 == 0) { + bst.emplace(ugly_number * 2); + bst.emplace(ugly_number * 3); } else { - ugly_number = *bst.cbegin(); - bst.erase(bst.cbegin()); - bst.insert(ugly_number * 2); - bst.insert(ugly_number * 3); - bst.insert(ugly_number * 5); + bst.emplace(ugly_number * 2); + bst.emplace(ugly_number * 3); + bst.emplace(ugly_number * 5); } } return ugly_number; From 0c4d123241f7ef89565b78e235ee8ae39a462d10 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 09:55:22 +0800 Subject: [PATCH 0646/1939] Update ugly-number-ii.cpp --- C++/ugly-number-ii.cpp | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/C++/ugly-number-ii.cpp b/C++/ugly-number-ii.cpp index 5c3d00ca3..910a209eb 100644 --- a/C++/ugly-number-ii.cpp +++ b/C++/ugly-number-ii.cpp @@ -14,12 +14,10 @@ class Solution { heap.pop(); if (ugly_number % 2 == 0) { heap.emplace(ugly_number * 2); - } - else if (ugly_number % 3 == 0) { + } else if (ugly_number % 3 == 0) { heap.emplace(ugly_number * 2); heap.emplace(ugly_number * 3); - } - else { + } else { heap.emplace(ugly_number * 2); heap.emplace(ugly_number * 3); heap.emplace(ugly_number * 5); @@ -42,12 +40,10 @@ class Solution2 { bst.erase(bst.cbegin()); if (ugly_number % 2 == 0) { bst.emplace(ugly_number * 2); - } - else if (ugly_number % 3 == 0) { + } else if (ugly_number % 3 == 0) { bst.emplace(ugly_number * 2); bst.emplace(ugly_number * 3); - } - else { + } else { bst.emplace(ugly_number * 2); bst.emplace(ugly_number * 3); bst.emplace(ugly_number * 5); From 9150d9f2ddfda7838ad5dd84379a2124793fd688 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:00:21 +0800 Subject: [PATCH 0647/1939] Create ugly-number-ii.py --- ugly-number-ii.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 ugly-number-ii.py diff --git a/ugly-number-ii.py b/ugly-number-ii.py new file mode 100644 index 000000000..6ce4c905c --- /dev/null +++ b/ugly-number-ii.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(1) +# +# Write a program to find the n-th ugly number. +# +# Ugly numbers are positive numbers whose prime factors +# only include 2, 3, 5. For example, +# 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the +# first 10 ugly numbers. +# +# Note that 1 is typically treated as an ugly number. +# +# Hint: +# +# The naive approach is to call isUgly for every number +# until you reach the nth one. Most numbers are not ugly. +# Try to focus your effort on generating only the ugly ones. +# + +import heapq + +class Solution: + # @param {integer} n + # @return {integer} + def nthUglyNumber(self, n): + ugly_number = 0 + + heap = [] + heapq.heappush(heap, 1) + for i in xrange(n): + ugly_number = heapq.heappop(heap) + if ugly_number % 2 == 0: + heapq.heappush(heap, ugly_number * 2) + elif ugly_number % 3 == 0: + heapq.heappush(heap, ugly_number * 2) + heapq.heappush(heap, ugly_number * 3) + else: + heapq.heappush(heap, ugly_number * 2) + heapq.heappush(heap, ugly_number * 3) + heapq.heappush(heap, ugly_number * 5) + + return ugly_number From 50040311d2280643763ce42a5c3c6cd3bf62efee Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:05:26 +0800 Subject: [PATCH 0648/1939] Update README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 54f25c981..d5158b075 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-18), there are `245` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-19), there are `247` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `261` questions. +Here is the classification of all `263` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -170,6 +170,7 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || +264| [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [C++](./C++/ugly-number-ii.cpp) [Python](./Python/ugly-number-ii.py) | _O(n)_ | _O(1)_ | Medium ||| --- @@ -238,6 +239,7 @@ Shell 233| [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | [C++](./C++/number-of-digit-one.cpp) [Python](./Python/number-of-digit-one.py) | _O(logn)_ | _O(1)_ | Medium | CTCI, LintCode| 248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard |📖|| 258| [Add Digits](https://leetcode.com/problems/add-digits/) | [C++](./C++/add-digits.cpp) [Python](./Python/add-digits.py) | _O(1)_ | _O(1)_ | Easy ||| +263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(logn)_ | _O(1)_ | Easy ||| --- From b6538fb78dd1b17ff70d21783b1fc79ff8b9d3f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:06:23 +0800 Subject: [PATCH 0649/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d5158b075..60d2dddb2 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-19), there are `247` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-19), there are `248` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `263` questions. +Here is the classification of all `264` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From bf054460a036afc631e7016f976cc80a6c678703 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:09:21 +0800 Subject: [PATCH 0650/1939] Rename ugly-number-ii.py to Python/ugly-number-ii.py --- ugly-number-ii.py => Python/ugly-number-ii.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ugly-number-ii.py => Python/ugly-number-ii.py (100%) diff --git a/ugly-number-ii.py b/Python/ugly-number-ii.py similarity index 100% rename from ugly-number-ii.py rename to Python/ugly-number-ii.py From 048c108be9836ad4b22016f4cb8465d1ed904002 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:10:04 +0800 Subject: [PATCH 0651/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 60d2dddb2..c6d929138 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-08-19), there are `248` Algorithms / `12` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-19), there are `247` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `264` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From dd4cb7ff53fc069cb4a51395764e99958983db88 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:19:58 +0800 Subject: [PATCH 0652/1939] Create trips-and-users.sql --- MySQL/trips-and-users.sql | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 MySQL/trips-and-users.sql diff --git a/MySQL/trips-and-users.sql b/MySQL/trips-and-users.sql new file mode 100644 index 000000000..ba589a452 --- /dev/null +++ b/MySQL/trips-and-users.sql @@ -0,0 +1,11 @@ +# Time: O((t * u) + tlogt) +# Space: O(t) + +select +t.Request_at Day, +round(sum(case when t.Status like 'cancelled_%' then 1 else 0 end) / count(*), 2) Rate +from Trips t +inner join Users u +on t.Client_Id = u.Users_Id and u.Banned='No' +where t.Request_at between '2013-10-01' and '2013-10-03' +group by t.Request_at From 2849ba903003fa098f686818b226228996fc17e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:21:58 +0800 Subject: [PATCH 0653/1939] Update trips-and-users.sql --- MySQL/trips-and-users.sql | 42 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/MySQL/trips-and-users.sql b/MySQL/trips-and-users.sql index ba589a452..3b73ba425 100644 --- a/MySQL/trips-and-users.sql +++ b/MySQL/trips-and-users.sql @@ -1,6 +1,46 @@ # Time: O((t * u) + tlogt) # Space: O(t) - +# +# The Trips table holds all taxi trips. Each trip has a unique Id, while Client_Id and Driver_Id are both foreign keys to the Users_Id at the Users table. Status is an ENUM type of (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’). +# +# +----+-----------+-----------+---------+--------------------+----------+ +# | Id | Client_Id | Driver_Id | City_Id | Status |Request_at| +# +----+-----------+-----------+---------+--------------------+----------+ +# | 1 | 1 | 10 | 1 | completed |2013-10-01| +# | 2 | 2 | 11 | 1 | cancelled_by_driver|2013-10-01| +# | 3 | 3 | 12 | 6 | completed |2013-10-01| +# | 4 | 4 | 13 | 6 | cancelled_by_client|2013-10-01| +# | 5 | 1 | 10 | 1 | completed |2013-10-02| +# | 6 | 2 | 11 | 6 | completed |2013-10-02| +# | 7 | 3 | 12 | 6 | completed |2013-10-02| +# | 8 | 2 | 12 | 12 | completed |2013-10-03| +# | 9 | 3 | 10 | 12 | completed |2013-10-03| +# | 10 | 4 | 13 | 12 | cancelled_by_driver|2013-10-03| +# +----+-----------+-----------+---------+--------------------+----------+ +# The Users table holds all users. Each user has an unique Users_Id, and Role is an ENUM type of (‘client’, ‘driver’, ‘partner’). +# +# +----------+--------+--------+ +# | Users_Id | Banned | Role | +# +----------+--------+--------+ +# | 1 | No | client | +# | 2 | Yes | client | +# | 3 | No | client | +# | 4 | No | client | +# | 10 | No | driver | +# | 11 | No | driver | +# | 12 | No | driver | +# | 13 | No | driver | +# +----------+--------+--------+ +# Write a SQL query to find the cancellation rate of requests made by unbanned clients between Oct 1, 2013 and Oct 3, 2013. For the above tables, your SQL query should return the following rows with the cancellation rate being rounded to two decimal places. +# +# +------------+-------------------+ +# | Day | Cancellation Rate | +# +------------+-------------------+ +# | 2013-10-01 | 0.33 | +# | 2013-10-02 | 0.00 | +# | 2013-10-03 | 0.50 | +# +------------+-------------------+ +# select t.Request_at Day, round(sum(case when t.Status like 'cancelled_%' then 1 else 0 end) / count(*), 2) Rate From 7b74823f334e841d19aed0987d3c383847d9a3d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:22:37 +0800 Subject: [PATCH 0654/1939] Update trips-and-users.sql --- MySQL/trips-and-users.sql | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/MySQL/trips-and-users.sql b/MySQL/trips-and-users.sql index 3b73ba425..16721f3ad 100644 --- a/MySQL/trips-and-users.sql +++ b/MySQL/trips-and-users.sql @@ -1,7 +1,9 @@ # Time: O((t * u) + tlogt) # Space: O(t) # -# The Trips table holds all taxi trips. Each trip has a unique Id, while Client_Id and Driver_Id are both foreign keys to the Users_Id at the Users table. Status is an ENUM type of (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’). +# The Trips table holds all taxi trips. Each trip has a unique Id, while Client_Id and Driver_Id +# are both foreign keys to the Users_Id at the Users table. Status is an ENUM type of +# (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’). # # +----+-----------+-----------+---------+--------------------+----------+ # | Id | Client_Id | Driver_Id | City_Id | Status |Request_at| @@ -17,7 +19,8 @@ # | 9 | 3 | 10 | 12 | completed |2013-10-03| # | 10 | 4 | 13 | 12 | cancelled_by_driver|2013-10-03| # +----+-----------+-----------+---------+--------------------+----------+ -# The Users table holds all users. Each user has an unique Users_Id, and Role is an ENUM type of (‘client’, ‘driver’, ‘partner’). +# The Users table holds all users. Each user has an unique Users_Id, and Role is an ENUM type of +# (‘client’, ‘driver’, ‘partner’). # # +----------+--------+--------+ # | Users_Id | Banned | Role | @@ -31,7 +34,9 @@ # | 12 | No | driver | # | 13 | No | driver | # +----------+--------+--------+ -# Write a SQL query to find the cancellation rate of requests made by unbanned clients between Oct 1, 2013 and Oct 3, 2013. For the above tables, your SQL query should return the following rows with the cancellation rate being rounded to two decimal places. +# Write a SQL query to find the cancellation rate of requests made by unbanned clients between +# Oct 1, 2013 and Oct 3, 2013. For the above tables, your SQL query should return the following +# rows with the cancellation rate being rounded to two decimal places. # # +------------+-------------------+ # | Day | Cancellation Rate | From b948a24685f43b70b9ed75d3d2b8137a6646b477 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:24:27 +0800 Subject: [PATCH 0655/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c6d929138..7a676e042 100644 --- a/README.md +++ b/README.md @@ -443,6 +443,7 @@ Shell 185| [Department Top Three Salaries](https://leetcode.com/problems/department-top-three-salaries/) | [MySQL](./MySQL/department-top-three-salaries.sql) | _O(n^2)_ | _O(n)_ | Hard || 196| [Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/) | [MySQL](./MySQL/delete-duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || 197| [Rising Temperature](https://leetcode.com/problems/rising-temperature/) | [MySQL](./MySQL/rising-temperature.sql) | _O(n^2)_ | _O(n)_ | Easy || +262| [Trips and Users ](https://leetcode.com/problems/trips-and-users/) | [MySQL](./MySQL/trips-and-users.sql) | _O((t * u) + tlogt)_ | _O(t)_ | Hard || --- From 7edd874bfe474dea18b47b7028b845cf3f40e7c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:26:24 +0800 Subject: [PATCH 0656/1939] Update trips-and-users.sql --- MySQL/trips-and-users.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/trips-and-users.sql b/MySQL/trips-and-users.sql index 16721f3ad..13bd279b4 100644 --- a/MySQL/trips-and-users.sql +++ b/MySQL/trips-and-users.sql @@ -48,7 +48,7 @@ # select t.Request_at Day, -round(sum(case when t.Status like 'cancelled_%' then 1 else 0 end) / count(*), 2) Rate +round(sum(case when t.Status = 'completed' then 0 else 1 end) / count(*), 2) Rate from Trips t inner join Users u on t.Client_Id = u.Users_Id and u.Banned='No' From 6b2626a9ccf1745cbf883c9397aa5ebc14b6a2a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:27:33 +0800 Subject: [PATCH 0657/1939] Update trips-and-users.sql --- MySQL/trips-and-users.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/trips-and-users.sql b/MySQL/trips-and-users.sql index 13bd279b4..751ad9b5c 100644 --- a/MySQL/trips-and-users.sql +++ b/MySQL/trips-and-users.sql @@ -51,6 +51,6 @@ t.Request_at Day, round(sum(case when t.Status = 'completed' then 0 else 1 end) / count(*), 2) Rate from Trips t inner join Users u -on t.Client_Id = u.Users_Id and u.Banned='No' +on t.Client_Id = u.Users_Id and u.Banned = 'No' where t.Request_at between '2013-10-01' and '2013-10-03' group by t.Request_at From 6d91762b481a094419b63279367b0ed2df3accfd Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Aug 2015 10:33:09 +0800 Subject: [PATCH 0658/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7a676e042..a14d1a145 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || -264| [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [C++](./C++/ugly-number-ii.cpp) [Python](./Python/ugly-number-ii.py) | _O(n)_ | _O(1)_ | Medium ||| +264| [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [C++](./C++/ugly-number-ii.cpp) [Python](./Python/ugly-number-ii.py) | _O(n)_ | _O(1)_ | Medium | CTCI, LintCode | BST, Heap | --- From 558e6130fb3483cce81a14a3f81db6c67c9cb2b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 22:13:54 +0800 Subject: [PATCH 0659/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a14d1a145..ff399139c 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-19), there are `247` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-20), there are `248` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `264` questions. +Here is the classification of all `265` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -403,6 +403,7 @@ Shell 213| [House Robber II](https://leetcode.com/problems/house-robber-ii/)| [C++](./C++/house-robber-ii.cpp) [Python](./Python/house-robber-ii.py) | _O(n)_ | _O(1)_ | Medium || 221| [Maximal Square](https://leetcode.com/problems/maximal-square/)| [C++](./C++/maximal-square.cpp) [Python](./Python/maximal-square.py) | _O(n^2)_ | _O(n)_ | Medium | EPI | 256| [Paint House](https://leetcode.com/problems/paint-house/) | [C++](./C++/paint-house.cpp) [Python](./Python/paint-house.py) | _O(n)_| _O(1)_| Medium |📖|| +265| [Paint House II](https://leetcode.com/problems/paint-house-ii/) | [C++](./C++/paint-house-ii.cpp) [Python](./Python/paint-house-ii.py) | _O(n * k)_| _O(k)_| Hard |📖|| --- From 7497acc18294ddfb9a6c901e452f09c23a8a7f76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 22:23:43 +0800 Subject: [PATCH 0660/1939] Update paint-house.py --- Python/paint-house.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/Python/paint-house.py b/Python/paint-house.py index d192c0478..24e42a96b 100644 --- a/Python/paint-house.py +++ b/Python/paint-house.py @@ -1,10 +1,12 @@ # Time: O(n) # Space: O(1) -class Solution: - # @param {integer[][]} costs - # @return {integer} +class Solution(object): def minCost(self, costs): + """ + :type costs: List[List[int]] + :rtype: int + """ if not costs: return 0 @@ -19,14 +21,16 @@ def minCost(self, costs): min_cost[i % 2][2] = costs[i][2] + \ min(min_cost[(i - 1) % 2][0], min_cost[(i - 1) % 2][1]) - return min(min_cost[(n - 1) % 2][0], min_cost[(n - 1) % 2][1], min_cost[(n - 1) % 2][2]) + return min(min_cost[(n - 1) % 2]) # Time: O(n) # Space: O(n) -class Solution2: - # @param {integer[][]} costs - # @return {integer} +class Solution2(object): def minCost(self, costs): + """ + :type costs: List[List[int]] + :rtype: int + """ if not costs: return 0 @@ -36,4 +40,4 @@ def minCost(self, costs): costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]) costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]) - return min(costs[n - 1][0], costs[n - 1][1], costs[n - 1][2]) + return min(costs[n - 1]) From c3db6ce340dacffff1a11c6488d5e311934831ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 23:13:37 +0800 Subject: [PATCH 0661/1939] Create paint-house-ii.py --- Python/paint-house-ii.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/paint-house-ii.py diff --git a/Python/paint-house-ii.py b/Python/paint-house-ii.py new file mode 100644 index 000000000..a1596dcfa --- /dev/null +++ b/Python/paint-house-ii.py @@ -0,0 +1,27 @@ +# Time: O(n * k) +# Space: O(k) + +class Solution(object): + def minCostII(self, costs): + """ + :type costs: List[List[int]] + :rtype: int + """ + if not costs: + return 0 + + n = len(costs) + k = len(costs[0]) + min_cost = [costs[0], [0] * k] + for i in xrange(1, n): + min_1st, min_2nd = float("inf"), float("inf") + for j in xrange(k): + if min_1st >= min_cost[(i - 1) % 2][j]: + min_1st, min_2nd = min_cost[(i - 1) % 2][j], min_1st + elif min_2nd >= min_cost[(i - 1) % 2][j]: + min_2nd = min_cost[(i - 1) % 2][j] + for j in xrange(k): + min_j = min_1st if min_cost[(i - 1) % 2][j] != min_1st else min_2nd + min_cost[i % 2][j] = costs[i][j] + min_j + + return min(min_cost[(n - 1) % 2]) From 527e565b9537f5b010986d88c71bf44acb031509 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 23:27:02 +0800 Subject: [PATCH 0662/1939] Create paint-house-ii.py --- C++/paint-house-ii.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/paint-house-ii.py diff --git a/C++/paint-house-ii.py b/C++/paint-house-ii.py new file mode 100644 index 000000000..f02ee1261 --- /dev/null +++ b/C++/paint-house-ii.py @@ -0,0 +1,33 @@ +// Time: O(n * k) +// Space: O(k) + +class Solution { +public: + int minCostII(vector>& costs) { + if (costs.empty()) { + return 0; + } + + vector> min_cost(2, costs[0]); + + const int n = costs.size(); + const int k = costs[0].size(); + for (int i = 1; i < n; ++i) { + int min_1st = INT_MAX, min_2nd = INT_MAX; + for (int j = 0; j < k; ++j) { + if (min_1st >= min_cost[(i - 1) % 2][j]) { + min_2nd = min_1st; + min_1st = min_cost[(i - 1) % 2][j]; + } else { + min_2nd = min(min_2nd, min_cost[(i - 1) % 2][j]); + } + } + for (int j = 0; j < k; ++j) { + const int min_j = (min_cost[(i - 1) % 2][j] != min_1st) ? min_1st : min_2nd; + min_cost[i % 2][j] = costs[i][j] + min_j; + } + } + + return *min_element(min_cost[(n - 1) % 2].begin(), min_cost[(n - 1) % 2].end()); + } +}; From e05ceeb224215e59c2dd09e40d28ce8aab3dba7d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 23:28:38 +0800 Subject: [PATCH 0663/1939] Rename paint-house-ii.py to paint-house-ii.cpp --- C++/{paint-house-ii.py => paint-house-ii.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{paint-house-ii.py => paint-house-ii.cpp} (100%) diff --git a/C++/paint-house-ii.py b/C++/paint-house-ii.cpp similarity index 100% rename from C++/paint-house-ii.py rename to C++/paint-house-ii.cpp From 1c4db9ac07786df24893bb063396647a6f55490e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 23:30:30 +0800 Subject: [PATCH 0664/1939] Update paint-house-ii.cpp --- C++/paint-house-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/paint-house-ii.cpp b/C++/paint-house-ii.cpp index f02ee1261..5e1bf67af 100644 --- a/C++/paint-house-ii.cpp +++ b/C++/paint-house-ii.cpp @@ -13,7 +13,7 @@ class Solution { const int n = costs.size(); const int k = costs[0].size(); for (int i = 1; i < n; ++i) { - int min_1st = INT_MAX, min_2nd = INT_MAX; + int min_1st = numeric_limits::max(), min_2nd = numeric_limits::max(); for (int j = 0; j < k; ++j) { if (min_1st >= min_cost[(i - 1) % 2][j]) { min_2nd = min_1st; From d2869024f2278ef5627d040a92c26399fac50efa Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 23:34:13 +0800 Subject: [PATCH 0665/1939] Update paint-house-ii.cpp --- C++/paint-house-ii.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/C++/paint-house-ii.cpp b/C++/paint-house-ii.cpp index 5e1bf67af..c0ec048cd 100644 --- a/C++/paint-house-ii.cpp +++ b/C++/paint-house-ii.cpp @@ -13,17 +13,17 @@ class Solution { const int n = costs.size(); const int k = costs[0].size(); for (int i = 1; i < n; ++i) { - int min_1st = numeric_limits::max(), min_2nd = numeric_limits::max(); + int smallest = numeric_limits::max(), second_smallest = numeric_limits::max(); for (int j = 0; j < k; ++j) { - if (min_1st >= min_cost[(i - 1) % 2][j]) { - min_2nd = min_1st; - min_1st = min_cost[(i - 1) % 2][j]; - } else { - min_2nd = min(min_2nd, min_cost[(i - 1) % 2][j]); + if (min_cost[(i - 1) % 2][j] < smallest) { + second_smallest = smallest; + smallest = min_cost[(i - 1) % 2][j]; + } else if (min_cost[(i - 1) % 2][j] < second_smallest) { + second_smallest = min_cost[(i - 1) % 2][j]; } } for (int j = 0; j < k; ++j) { - const int min_j = (min_cost[(i - 1) % 2][j] != min_1st) ? min_1st : min_2nd; + const int min_j = (min_cost[(i - 1) % 2][j] != smallest) ? smallest : second_smallest; min_cost[i % 2][j] = costs[i][j] + min_j; } } From 207790bacd790f55e5cdf8a55141ecad469d1d72 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 23:35:41 +0800 Subject: [PATCH 0666/1939] Update paint-house-ii.py --- Python/paint-house-ii.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/paint-house-ii.py b/Python/paint-house-ii.py index a1596dcfa..7418f417e 100644 --- a/Python/paint-house-ii.py +++ b/Python/paint-house-ii.py @@ -14,14 +14,14 @@ def minCostII(self, costs): k = len(costs[0]) min_cost = [costs[0], [0] * k] for i in xrange(1, n): - min_1st, min_2nd = float("inf"), float("inf") + smallest, second_smallest = float("inf"), float("inf") for j in xrange(k): - if min_1st >= min_cost[(i - 1) % 2][j]: - min_1st, min_2nd = min_cost[(i - 1) % 2][j], min_1st - elif min_2nd >= min_cost[(i - 1) % 2][j]: - min_2nd = min_cost[(i - 1) % 2][j] + if min_cost[(i - 1) % 2][j] < smallest: + smallest, second_smallest = min_cost[(i - 1) % 2][j], smallest + elif min_cost[(i - 1) % 2][j] < second_smallest: + second_smallest = min_cost[(i - 1) % 2][j] for j in xrange(k): - min_j = min_1st if min_cost[(i - 1) % 2][j] != min_1st else min_2nd + min_j = smallest if min_cost[(i - 1) % 2][j] != smallest else second_smallest min_cost[i % 2][j] = costs[i][j] + min_j return min(min_cost[(n - 1) % 2]) From 8849766ece6ae087b379882860e555e1a5c9b46c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 23:53:22 +0800 Subject: [PATCH 0667/1939] Update paint-house-ii.py --- Python/paint-house-ii.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Python/paint-house-ii.py b/Python/paint-house-ii.py index 7418f417e..1fd5f873d 100644 --- a/Python/paint-house-ii.py +++ b/Python/paint-house-ii.py @@ -1,7 +1,21 @@ # Time: O(n * k) # Space: O(k) -class Solution(object): +class Solution2(object): + def minCostII(self, costs): + """ + :type costs: List[List[int]] + :rtype: int + """ + return min(reduce(self.combine, costs)) if costs else 0 + + def combine(self, tmp, house): + smallest, k, i = min(tmp), len(tmp), tmp.index(min(tmp)) + tmp, tmp[i] = [smallest] * k, min(tmp[:i] + tmp[i+1:]) + return map(sum, zip(house, tmp)) + + +class Solution2(object): def minCostII(self, costs): """ :type costs: List[List[int]] From 89eccb206b034f3d30f7b04621bdbbe9ad76302b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Aug 2015 23:56:41 +0800 Subject: [PATCH 0668/1939] Update paint-house-ii.py --- Python/paint-house-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/paint-house-ii.py b/Python/paint-house-ii.py index 1fd5f873d..724de0c42 100644 --- a/Python/paint-house-ii.py +++ b/Python/paint-house-ii.py @@ -12,7 +12,7 @@ def minCostII(self, costs): def combine(self, tmp, house): smallest, k, i = min(tmp), len(tmp), tmp.index(min(tmp)) tmp, tmp[i] = [smallest] * k, min(tmp[:i] + tmp[i+1:]) - return map(sum, zip(house, tmp)) + return map(sum, zip(tmp, house)) class Solution2(object): From 954cab4257fbf9752393bcb648650db8c714f96c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 01:05:23 +0800 Subject: [PATCH 0669/1939] Update paint-house-ii.cpp --- C++/paint-house-ii.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/C++/paint-house-ii.cpp b/C++/paint-house-ii.cpp index c0ec048cd..ddedd58a4 100644 --- a/C++/paint-house-ii.cpp +++ b/C++/paint-house-ii.cpp @@ -31,3 +31,29 @@ class Solution { return *min_element(min_cost[(n - 1) % 2].begin(), min_cost[(n - 1) % 2].end()); } }; + +// Time: O(n * k) +// Space: O(k) +class Solution2{ +public: + int minCostII(vector>& costs) { + if (costs.empty()) { + return 0; + } + auto combine = [](const vector& tmp, const vector& house) { + const int smallest = *min_element(tmp.cbegin(), tmp.cend()); + const int i = distance(tmp.begin(), find(tmp.cbegin(), tmp.cend(), smallest)); + vector tmp2(tmp); + tmp2.erase(tmp2.begin() + i); + const int second_smallest = *min_element(tmp2.cbegin(), tmp2.cend()); + vector min_cost(tmp.size(), smallest); + min_cost[i] = second_smallest; + transform(min_cost.begin(), min_cost.end(), house.begin(), + min_cost.begin(), std::plus()); + return min_cost; + }; + vector min_cost = accumulate(costs.cbegin(), costs.cend(), vector(costs[0].size(), 0), combine); + return *min_element(min_cost.cbegin(), min_cost.cend()); + + } +}; From 2d2277086663842f1ded422cb68253ab00a2891c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 01:07:14 +0800 Subject: [PATCH 0670/1939] Update paint-house-ii.cpp --- C++/paint-house-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/paint-house-ii.cpp b/C++/paint-house-ii.cpp index ddedd58a4..49cb953fa 100644 --- a/C++/paint-house-ii.cpp +++ b/C++/paint-house-ii.cpp @@ -48,7 +48,7 @@ class Solution2{ const int second_smallest = *min_element(tmp2.cbegin(), tmp2.cend()); vector min_cost(tmp.size(), smallest); min_cost[i] = second_smallest; - transform(min_cost.begin(), min_cost.end(), house.begin(), + transform(min_cost.cbegin(), min_cost.cend(), house.cbegin(), min_cost.begin(), std::plus()); return min_cost; }; From 3c7925f7bc23d0c11d1e5623da69020cf0bab338 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 01:20:41 +0800 Subject: [PATCH 0671/1939] Update paint-house-ii.cpp --- C++/paint-house-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/paint-house-ii.cpp b/C++/paint-house-ii.cpp index 49cb953fa..e19f4a573 100644 --- a/C++/paint-house-ii.cpp +++ b/C++/paint-house-ii.cpp @@ -28,7 +28,7 @@ class Solution { } } - return *min_element(min_cost[(n - 1) % 2].begin(), min_cost[(n - 1) % 2].end()); + return *min_element(min_cost[(n - 1) % 2].cbegin(), min_cost[(n - 1) % 2].cend()); } }; From 3cf85994f21541639fb540ea4dbf6aac6ecbc5e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 16:53:34 +0800 Subject: [PATCH 0672/1939] Create palindrome-permutation.py --- Python/palindrome-permutation.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Python/palindrome-permutation.py diff --git a/Python/palindrome-permutation.py b/Python/palindrome-permutation.py new file mode 100644 index 000000000..a614f56a9 --- /dev/null +++ b/Python/palindrome-permutation.py @@ -0,0 +1,10 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def canPermutePalindrome(self, s): + """ + :type s: str + :rtype: bool + """ + return sum(v % 2 for k, v in collections.Counter(s).iteritems()) < 2 From f13c481de4f4fa5de08c8c23b632b6f93fc05348 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 16:57:17 +0800 Subject: [PATCH 0673/1939] Create palindrome-permutation.cpp --- C++/palindrome-permutation.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/palindrome-permutation.cpp diff --git a/C++/palindrome-permutation.cpp b/C++/palindrome-permutation.cpp new file mode 100644 index 000000000..4b6d14edf --- /dev/null +++ b/C++/palindrome-permutation.cpp @@ -0,0 +1,13 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool canPermutePalindrome(string s) { + bitset<256> bit; + for (const auto& c : s) { + bit.flip(c); + } + return bit.count() < 2; + } +}; From c799978f7d0ef84a294ffdeb493d70a987d55fe5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 17:00:29 +0800 Subject: [PATCH 0674/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ff399139c..5a07621cb 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-20), there are `248` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-21), there are `249` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `265` questions. +Here is the classification of all `266` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -209,6 +209,7 @@ Shell 244| [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [C++](./C++/shortest-word-distance-ii.cpp) [Python](./Python/shortest-word-distance-ii.py) | ctor: _O(n)_, lookup: _O(a + b)_ | _O(n)_ | Medium |📖|| 246| [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | [C++](./C++/strobogrammatic-number.cpp) [Python](./Python/strobogrammatic-number.py) | _O(n)_ | _O(1)_ | Easy |📖|| 249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |📖|| +266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(n)_ | Easy |📖|| --- From 675bdcf28ea17f113b5d7d45cdd9035a14d248d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 17:36:04 +0800 Subject: [PATCH 0675/1939] Update palindrome-permutation.cpp --- C++/palindrome-permutation.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/palindrome-permutation.cpp b/C++/palindrome-permutation.cpp index 4b6d14edf..4798f59e8 100644 --- a/C++/palindrome-permutation.cpp +++ b/C++/palindrome-permutation.cpp @@ -4,10 +4,10 @@ class Solution { public: bool canPermutePalindrome(string s) { - bitset<256> bit; + bitset<256> bits; for (const auto& c : s) { - bit.flip(c); + bits.flip(c); } - return bit.count() < 2; + return bits.count() < 2; } }; From 2d8f5fbd558d9d04f6d3c787655236d1c568ab90 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 18:44:43 +0800 Subject: [PATCH 0676/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a07621cb..a46a2b3be 100644 --- a/README.md +++ b/README.md @@ -209,7 +209,7 @@ Shell 244| [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [C++](./C++/shortest-word-distance-ii.cpp) [Python](./Python/shortest-word-distance-ii.py) | ctor: _O(n)_, lookup: _O(a + b)_ | _O(n)_ | Medium |📖|| 246| [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | [C++](./C++/strobogrammatic-number.cpp) [Python](./Python/strobogrammatic-number.py) | _O(n)_ | _O(1)_ | Easy |📖|| 249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |📖|| -266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(n)_ | Easy |📖|| +266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |📖|| --- From 57b0dd23179559e8094aeff0dc110dc933fc31f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 18:46:20 +0800 Subject: [PATCH 0677/1939] Update palindrome-permutation.py --- Python/palindrome-permutation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/palindrome-permutation.py b/Python/palindrome-permutation.py index a614f56a9..e65c083ee 100644 --- a/Python/palindrome-permutation.py +++ b/Python/palindrome-permutation.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(n) +# Space: O(1) class Solution(object): def canPermutePalindrome(self, s): From 12cf79a85f6c51109ede388d32a13508b9debd14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Aug 2015 18:46:58 +0800 Subject: [PATCH 0678/1939] Update palindrome-permutation.cpp --- C++/palindrome-permutation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/palindrome-permutation.cpp b/C++/palindrome-permutation.cpp index 4798f59e8..f68d5cba3 100644 --- a/C++/palindrome-permutation.cpp +++ b/C++/palindrome-permutation.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(n) +// Space: O(1) class Solution { public: From 7c40ccdf4122777d1607f77ac58f36fa14ddbbac Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Aug 2015 21:27:15 +0800 Subject: [PATCH 0679/1939] Update palindrome-permutation.py --- Python/palindrome-permutation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/palindrome-permutation.py b/Python/palindrome-permutation.py index e65c083ee..21df60552 100644 --- a/Python/palindrome-permutation.py +++ b/Python/palindrome-permutation.py @@ -7,4 +7,4 @@ def canPermutePalindrome(self, s): :type s: str :rtype: bool """ - return sum(v % 2 for k, v in collections.Counter(s).iteritems()) < 2 + return sum(v % 2 for v in collections.Counter(s).values()) < 2 From 2b59e1439c6f205106603d333fa94c026d6f9e42 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 14:30:58 +0800 Subject: [PATCH 0680/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a46a2b3be..6809e192b 100644 --- a/README.md +++ b/README.md @@ -279,8 +279,8 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || -46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n!)_ | _O(n)_ | Medium || -47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n!)_ | _O(n)_ | Hard || +46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n * n!)_ | _O(n)_ | Medium || +47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Hard || 78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || 90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || From 3b01da4898a07c2c6dccb2dd8d06f79a6bfe7d69 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 14:34:06 +0800 Subject: [PATCH 0681/1939] Update permutations.py --- Python/permutations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/permutations.py b/Python/permutations.py index f224894c8..03d76be78 100644 --- a/Python/permutations.py +++ b/Python/permutations.py @@ -1,4 +1,4 @@ -# Time: O(n!) +# Time: O(n * n!) # Space: O(n) # # Given a collection of numbers, return all possible permutations. From 26e518ef80f911dd69be7f9ccc4478eefbf7a613 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 14:39:15 +0800 Subject: [PATCH 0682/1939] Update permutations-ii.py --- Python/permutations-ii.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/Python/permutations-ii.py b/Python/permutations-ii.py index 1f473145a..a090b5a00 100644 --- a/Python/permutations-ii.py +++ b/Python/permutations-ii.py @@ -8,8 +8,31 @@ # [1,1,2], [1,2,1], and [2,1,1]. # - -class Solution: +class Solution(object): + def permuteUnique(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + nums.sort() + result = [] + used = [False] * len(nums) + self.permuteRecu(result, used, [], nums) + return result + + def permuteRecu(self, result, used, cur, nums): + if len(cur) == len(nums): + result.append(cur + []) + return + for i in xrange(len(nums)): + if not used[i] and not (i > 0 and nums[i-1] == nums[i] and used[i-1]): + used[i] = True + cur.append(nums[i]) + self.permuteRecu(result, used, cur, nums) + cur.pop() + used[i] = False + +class Solution2: # @param num, a list of integer # @return a list of lists of integers def permuteUnique(self, nums): From b77e93c28682053778e6b1ff557d19067b9e20e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 14:39:30 +0800 Subject: [PATCH 0683/1939] Update permutations-ii.py --- Python/permutations-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/permutations-ii.py b/Python/permutations-ii.py index a090b5a00..17deac83e 100644 --- a/Python/permutations-ii.py +++ b/Python/permutations-ii.py @@ -1,4 +1,4 @@ -# Time: O(n!) +# Time: O(n * n!) # Space: O(n) # # Given a collection of numbers that might contain duplicates, return all possible unique permutations. From 745ddf9b39b2d1de307a0ce30942641f6b5aae98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 14:53:56 +0800 Subject: [PATCH 0684/1939] Create palindrome-permutation-ii.py --- Python/palindrome-permutation-ii.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Python/palindrome-permutation-ii.py diff --git a/Python/palindrome-permutation-ii.py b/Python/palindrome-permutation-ii.py new file mode 100644 index 000000000..345c108ca --- /dev/null +++ b/Python/palindrome-permutation-ii.py @@ -0,0 +1,14 @@ +# Time: O(n * n!) +# Space: O(n) + +class Solution(object): + def generatePalindromes(self, s): + """ + :type s: str + :rtype: List[str] + """ + cnt = collections.Counter(s) + mid = tuple(k for k, v in cnt.iteritems() if v % 2) + chars = ''.join(k * (v / 2) for k, v in cnt.iteritems()) + return [''.join(half_palindrome + mid + half_palindrome[::-1]) \ + for half_palindrome in set(itertools.permutations(chars))] if len(mid) < 2 else [] From 9062dbe7fcb39a63f12b5ea5490749edf95b79a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 15:25:11 +0800 Subject: [PATCH 0685/1939] Update palindrome-permutation-ii.py --- Python/palindrome-permutation-ii.py | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Python/palindrome-permutation-ii.py b/Python/palindrome-permutation-ii.py index 345c108ca..c4f7854b1 100644 --- a/Python/palindrome-permutation-ii.py +++ b/Python/palindrome-permutation-ii.py @@ -2,6 +2,36 @@ # Space: O(n) class Solution(object): + def generatePalindromes(self, s): + """ + :type s: str + :rtype: List[str] + """ + cnt = collections.Counter(s) + mid = [k for k, v in cnt.iteritems() if v % 2] + chars = ''.join(k * (v / 2) for k, v in cnt.iteritems()) + return [''.join(half_palindrome + mid + half_palindrome[::-1]) \ + for half_palindrome in self.permuteUnique(chars)] if len(mid) < 2 else [] + + def permuteUnique(self, nums): + result = [] + used = [False] * len(nums) + self.permuteRecu(result, used, [], nums) + return result + + def permuteRecu(self, result, used, cur, nums): + if len(cur) == len(nums): + result.append(cur + []) + return + for i in xrange(len(nums)): + if not used[i] and not (i > 0 and nums[i-1] == nums[i] and used[i-1]): + used[i] = True + cur.append(nums[i]) + self.permuteRecu(result, used, cur, nums) + cur.pop() + used[i] = False + +class Solution2(object): def generatePalindromes(self, s): """ :type s: str From ccb6c7d6ce272e714aba8f2030a26bfffa7d4edb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 15:29:05 +0800 Subject: [PATCH 0686/1939] Update palindrome-permutation-ii.py --- Python/palindrome-permutation-ii.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/palindrome-permutation-ii.py b/Python/palindrome-permutation-ii.py index c4f7854b1..25f43445c 100644 --- a/Python/palindrome-permutation-ii.py +++ b/Python/palindrome-permutation-ii.py @@ -8,10 +8,10 @@ def generatePalindromes(self, s): :rtype: List[str] """ cnt = collections.Counter(s) - mid = [k for k, v in cnt.iteritems() if v % 2] + mid = ''.join(k for k, v in cnt.iteritems() if v % 2) chars = ''.join(k * (v / 2) for k, v in cnt.iteritems()) - return [''.join(half_palindrome + mid + half_palindrome[::-1]) \ - for half_palindrome in self.permuteUnique(chars)] if len(mid) < 2 else [] + return [half_palindrome + mid + half_palindrome[::-1] \ + for half_palindrome in self.permuteUnique(chars)] if len(mid) < 2 else [] def permuteUnique(self, nums): result = [] From ce82e7353bd050ca30773a45e4bf04d9fd858d6a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 15:52:14 +0800 Subject: [PATCH 0687/1939] Create palindrome-permutation-ii.cpp --- C++/palindrome-permutation-ii.cpp | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/palindrome-permutation-ii.cpp diff --git a/C++/palindrome-permutation-ii.cpp b/C++/palindrome-permutation-ii.cpp new file mode 100644 index 000000000..e0874ab5e --- /dev/null +++ b/C++/palindrome-permutation-ii.cpp @@ -0,0 +1,32 @@ +// Time: O(n * n!) +// Space: O(n) + +class Solution { +public: + vector generatePalindromes(string s) { + unordered_map cnt; + for (const auto& c : s) { + ++cnt[c]; + } + + string mid, chars; + for (const auto& kvp : cnt) { + if (kvp.second % 2) { + if (mid.empty()) { + mid.append(1, kvp.first); + } else { // The count of the middle char is at most one. + return {}; + } + } + chars.append(kvp.second / 2, kvp.first); + } + + vector result; + sort(chars.begin(), chars.end()); + do { + string reverse_chars(chars.crbegin(), chars.crend()); + result.emplace_back(chars + mid + reverse_chars); + } while (next_permutation(chars.begin(), chars.end())); + return result; + } +};\ From 6135e2e222353db9b092722bb9e7635c4d2afdcf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 16:12:50 +0800 Subject: [PATCH 0688/1939] Update palindrome-permutation-ii.cpp --- C++/palindrome-permutation-ii.cpp | 66 ++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/C++/palindrome-permutation-ii.cpp b/C++/palindrome-permutation-ii.cpp index e0874ab5e..244a53935 100644 --- a/C++/palindrome-permutation-ii.cpp +++ b/C++/palindrome-permutation-ii.cpp @@ -1,9 +1,16 @@ // Time: O(n * n!) // Space: O(n) +// Time: O(n * n!) +// Space: O(n) + class Solution { public: vector generatePalindromes(string s) { + if (s.empty()) { + return {}; + } + unordered_map cnt; for (const auto& c : s) { ++cnt[c]; @@ -21,6 +28,63 @@ class Solution { chars.append(kvp.second / 2, kvp.first); } + return permuteUnique(mid, chars); + } + + vector permuteUnique(const string& mid, string& s) { + vector result; + vector used(s.length(), false); + string ans; + + sort(s.begin(), s.end()); + permuteUniqueRecu(mid, s, &used, &ans, &result); + return result; + } + + void permuteUniqueRecu(const string& mid, const string& s, vector *used, + string *ans, vector *result) { + if (ans->length() == s.length()) { + string reverse_ans(ans->crbegin(), ans->crend()); + result->emplace_back(*ans + mid + reverse_ans); + return; + } + + for (int i = 0; i < s.length(); ++i) { + if (!(*used)[i] && !(i != 0 && s[i - 1] == s[i] && (*used)[i - 1])) { + (*used)[i] = true; + ans->push_back(s[i]); + permuteUniqueRecu(mid, s, used, ans, result); + ans->pop_back(); + (*used)[i] = false; + } + } + } +}; + +class Solution2 { +public: + vector generatePalindromes(string s) { + if (s.empty()) { + return {}; + } + + unordered_map cnt; + for (const auto& c : s) { + ++cnt[c]; + } + + string mid, chars; + for (const auto& kvp : cnt) { + if (kvp.second % 2) { + if (mid.empty()) { + mid.push_back(kvp.first); + } else { // The count of the middle char is at most one. + return {}; + } + } + chars.append(kvp.second / 2, kvp.first); + } + vector result; sort(chars.begin(), chars.end()); do { @@ -29,4 +93,4 @@ class Solution { } while (next_permutation(chars.begin(), chars.end())); return result; } -};\ +}; From 1dc765931e1fc5735f43776090cf20e35f8a639a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 16:13:41 +0800 Subject: [PATCH 0689/1939] Update palindrome-permutation-ii.cpp --- C++/palindrome-permutation-ii.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/C++/palindrome-permutation-ii.cpp b/C++/palindrome-permutation-ii.cpp index 244a53935..d8c699e47 100644 --- a/C++/palindrome-permutation-ii.cpp +++ b/C++/palindrome-permutation-ii.cpp @@ -1,9 +1,6 @@ // Time: O(n * n!) // Space: O(n) -// Time: O(n * n!) -// Space: O(n) - class Solution { public: vector generatePalindromes(string s) { From e53ed76c7affe8bedad504b5e3ea0d94a34b522f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 16:19:18 +0800 Subject: [PATCH 0690/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6809e192b..0d81fd527 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-21), there are `249` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-23), there are `250` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `266` questions. +Here is the classification of all `267` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -283,6 +283,7 @@ Shell 47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Hard || 78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || 90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +267| [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) | [C++](./C++/palindrome-permutation-ii.cpp) [Python](./Python/palindrome-permutation-ii.py) | _O(n * n!)_ | _O(n)_ | Medium |📖|| --- From de40d62629eeec730c5778f0d9a5f430e450ce9c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 16:20:54 +0800 Subject: [PATCH 0691/1939] Update palindrome-permutation-ii.cpp --- C++/palindrome-permutation-ii.cpp | 68 +++++++++++++++---------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/C++/palindrome-permutation-ii.cpp b/C++/palindrome-permutation-ii.cpp index d8c699e47..05802d331 100644 --- a/C++/palindrome-permutation-ii.cpp +++ b/C++/palindrome-permutation-ii.cpp @@ -13,6 +13,40 @@ class Solution { ++cnt[c]; } + string mid, chars; + for (const auto& kvp : cnt) { + if (kvp.second % 2) { + if (mid.empty()) { + mid.push_back(kvp.first); + } else { // The count of the middle char is at most one. + return {}; + } + } + chars.append(kvp.second / 2, kvp.first); + } + + vector result; + sort(chars.begin(), chars.end()); + do { + string reverse_chars(chars.crbegin(), chars.crend()); + result.emplace_back(chars + mid + reverse_chars); + } while (next_permutation(chars.begin(), chars.end())); + return result; + } +}; + +class Solution2 { +public: + vector generatePalindromes(string s) { + if (s.empty()) { + return {}; + } + + unordered_map cnt; + for (const auto& c : s) { + ++cnt[c]; + } + string mid, chars; for (const auto& kvp : cnt) { if (kvp.second % 2) { @@ -57,37 +91,3 @@ class Solution { } } }; - -class Solution2 { -public: - vector generatePalindromes(string s) { - if (s.empty()) { - return {}; - } - - unordered_map cnt; - for (const auto& c : s) { - ++cnt[c]; - } - - string mid, chars; - for (const auto& kvp : cnt) { - if (kvp.second % 2) { - if (mid.empty()) { - mid.push_back(kvp.first); - } else { // The count of the middle char is at most one. - return {}; - } - } - chars.append(kvp.second / 2, kvp.first); - } - - vector result; - sort(chars.begin(), chars.end()); - do { - string reverse_chars(chars.crbegin(), chars.crend()); - result.emplace_back(chars + mid + reverse_chars); - } while (next_permutation(chars.begin(), chars.end())); - return result; - } -}; From bd28f7ad5d7a942eb69106802cf3dcd3b5686cfb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 16:24:15 +0800 Subject: [PATCH 0692/1939] Update palindrome-permutation-ii.cpp --- C++/palindrome-permutation-ii.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/C++/palindrome-permutation-ii.cpp b/C++/palindrome-permutation-ii.cpp index 05802d331..806824177 100644 --- a/C++/palindrome-permutation-ii.cpp +++ b/C++/palindrome-permutation-ii.cpp @@ -24,7 +24,10 @@ class Solution { } chars.append(kvp.second / 2, kvp.first); } - + return permuteUnique(mid, chars); + } + + vector permuteUnique(const string& mid, string& chars) { vector result; sort(chars.begin(), chars.end()); do { From b045ccaa68de09e80fc361c4f8e6791d840f658c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 16:34:11 +0800 Subject: [PATCH 0693/1939] Update palindrome-permutation-ii.py --- Python/palindrome-permutation-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/palindrome-permutation-ii.py b/Python/palindrome-permutation-ii.py index 25f43445c..251238ebf 100644 --- a/Python/palindrome-permutation-ii.py +++ b/Python/palindrome-permutation-ii.py @@ -21,7 +21,7 @@ def permuteUnique(self, nums): def permuteRecu(self, result, used, cur, nums): if len(cur) == len(nums): - result.append(cur + []) + result.append(''.join(cur)) return for i in xrange(len(nums)): if not used[i] and not (i > 0 and nums[i-1] == nums[i] and used[i-1]): From fc7f9f6c2ed54a2090ce2cd69e6d7481e0541f52 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 16:41:45 +0800 Subject: [PATCH 0694/1939] Update palindrome-permutation-ii.py --- Python/palindrome-permutation-ii.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Python/palindrome-permutation-ii.py b/Python/palindrome-permutation-ii.py index 251238ebf..4443858db 100644 --- a/Python/palindrome-permutation-ii.py +++ b/Python/palindrome-permutation-ii.py @@ -10,24 +10,24 @@ def generatePalindromes(self, s): cnt = collections.Counter(s) mid = ''.join(k for k, v in cnt.iteritems() if v % 2) chars = ''.join(k * (v / 2) for k, v in cnt.iteritems()) - return [half_palindrome + mid + half_palindrome[::-1] \ - for half_palindrome in self.permuteUnique(chars)] if len(mid) < 2 else [] + return self.permuteUnique(mid, chars) if len(mid) < 2 else [] - def permuteUnique(self, nums): + def permuteUnique(self, mid, nums): result = [] used = [False] * len(nums) - self.permuteRecu(result, used, [], nums) + self.permuteRecu(mid, result, used, [], nums) return result - def permuteRecu(self, result, used, cur, nums): + def permuteRecu(self, mid, result, used, cur, nums): if len(cur) == len(nums): - result.append(''.join(cur)) + half_palindrome = ''.join(cur) + result.append(half_palindrome + mid + half_palindrome[::-1]) return for i in xrange(len(nums)): if not used[i] and not (i > 0 and nums[i-1] == nums[i] and used[i-1]): used[i] = True cur.append(nums[i]) - self.permuteRecu(result, used, cur, nums) + self.permuteRecu(mid, result, used, cur, nums) cur.pop() used[i] = False From 1a5346d8387f2311ee73a9517ad8ed01d919e11b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 16:44:13 +0800 Subject: [PATCH 0695/1939] Update permutations-ii.py --- Python/permutations-ii.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/permutations-ii.py b/Python/permutations-ii.py index 17deac83e..8f1cd2889 100644 --- a/Python/permutations-ii.py +++ b/Python/permutations-ii.py @@ -17,10 +17,10 @@ def permuteUnique(self, nums): nums.sort() result = [] used = [False] * len(nums) - self.permuteRecu(result, used, [], nums) + self.permuteUniqueRecu(result, used, [], nums) return result - def permuteRecu(self, result, used, cur, nums): + def permuteUniqueRecu(self, result, used, cur, nums): if len(cur) == len(nums): result.append(cur + []) return @@ -28,7 +28,7 @@ def permuteRecu(self, result, used, cur, nums): if not used[i] and not (i > 0 and nums[i-1] == nums[i] and used[i-1]): used[i] = True cur.append(nums[i]) - self.permuteRecu(result, used, cur, nums) + self.permuteUniqueRecu(result, used, cur, nums) cur.pop() used[i] = False From bf1c296b7857fb1a988eaa509671bcc932850063 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Aug 2015 16:44:51 +0800 Subject: [PATCH 0696/1939] Update palindrome-permutation-ii.py --- Python/palindrome-permutation-ii.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/palindrome-permutation-ii.py b/Python/palindrome-permutation-ii.py index 4443858db..097f0956a 100644 --- a/Python/palindrome-permutation-ii.py +++ b/Python/palindrome-permutation-ii.py @@ -15,10 +15,10 @@ def generatePalindromes(self, s): def permuteUnique(self, mid, nums): result = [] used = [False] * len(nums) - self.permuteRecu(mid, result, used, [], nums) + self.permuteUniqueRecu(mid, result, used, [], nums) return result - def permuteRecu(self, mid, result, used, cur, nums): + def permuteUniqueRecu(self, mid, result, used, cur, nums): if len(cur) == len(nums): half_palindrome = ''.join(cur) result.append(half_palindrome + mid + half_palindrome[::-1]) @@ -27,7 +27,7 @@ def permuteRecu(self, mid, result, used, cur, nums): if not used[i] and not (i > 0 and nums[i-1] == nums[i] and used[i-1]): used[i] = True cur.append(nums[i]) - self.permuteRecu(mid, result, used, cur, nums) + self.permuteUniqueRecu(mid, result, used, cur, nums) cur.pop() used[i] = False From 8ec68b31fc98c37d305bbdf9bd1b3fbc8dc6617f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 24 Aug 2015 09:10:20 +0800 Subject: [PATCH 0697/1939] Create missing-number.py --- Python/missing-number.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Python/missing-number.py diff --git a/Python/missing-number.py b/Python/missing-number.py new file mode 100644 index 000000000..ff6800ea0 --- /dev/null +++ b/Python/missing-number.py @@ -0,0 +1,11 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def missingNumber(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + return reduce(operator.xor, nums, \ + reduce(operator.xor, xrange(len(nums) + 1))) From 9e1bcafbc928d15d13e93ccc87456b380f4b26a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 24 Aug 2015 09:15:33 +0800 Subject: [PATCH 0698/1939] Create missing-number.cpp --- C++/missing-number.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/missing-number.cpp diff --git a/C++/missing-number.cpp b/C++/missing-number.cpp new file mode 100644 index 000000000..d15306e75 --- /dev/null +++ b/C++/missing-number.cpp @@ -0,0 +1,13 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int missingNumber(vector& nums) { + int num = 0; + for (int i = 0; i < nums.size(); ++i) { + num ^= nums[i] ^ (i + 1); + } + return num; + } +}; From 30c0b2584ec0f54c77718a716ef73a94b06cdd49 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 24 Aug 2015 09:17:21 +0800 Subject: [PATCH 0699/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0d81fd527..36e2d9844 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-23), there are `250` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-24), there are `250` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `267` questions. +Here is the classification of all `268` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -59,6 +59,7 @@ Shell 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || +268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium ||| --- From e0fbcc5714ae3d7d085a2eafc7edfe242fc06517 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 24 Aug 2015 09:24:37 +0800 Subject: [PATCH 0700/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 36e2d9844..3ce0bc647 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Shell 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || -268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium ||| +268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium | LintCode || --- From 0c6e2dc3738e51ad3c36f9e201a2dbf697f07e42 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 24 Aug 2015 09:25:08 +0800 Subject: [PATCH 0701/1939] Update missing-number.py --- Python/missing-number.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Python/missing-number.py b/Python/missing-number.py index ff6800ea0..2abee7bb6 100644 --- a/Python/missing-number.py +++ b/Python/missing-number.py @@ -1,5 +1,16 @@ # Time: O(n) # Space: O(1) +# +# Given an array containing n distinct numbers taken from +# 0, 1, 2, ..., n, find the one that is missing from the array. +# +# For example, +# Given nums = [0, 1, 3] return 2. +# +# Note: +# Your algorithm should run in linear runtime complexity. +# Could you implement it using only constant extra space complexity? +# class Solution(object): def missingNumber(self, nums): From cc97467e5c19fc3c9016b51ed0c550bcfc53baa3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 24 Aug 2015 09:25:57 +0800 Subject: [PATCH 0702/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3ce0bc647..14272741d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-08-24), there are `250` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-24), there are `251` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `268` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 35c2271c5ebdd44cf12eefa80f82d87d12fbbd8c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 10:10:18 +0800 Subject: [PATCH 0703/1939] Create alien-dictionary.cpp --- C++/alien-dictionary.cpp | 98 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 C++/alien-dictionary.cpp diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp new file mode 100644 index 000000000..212904572 --- /dev/null +++ b/C++/alien-dictionary.cpp @@ -0,0 +1,98 @@ +// Time: O(|V|+|E|) = O(26 + 26^2) = O(1) +// Space: O(|E|) = O(26^2) = O(1) + +class Solution { +public: + void findEdges(const string &word1, const string &word2, vector> *graph) { + int len = min(word1.length(), word2.length()); + for (int i = 0; i < len; ++i) { + if (word1[i] != word2[i]) { + (*graph)[word1[i] - 'a'][word2[i] - 'a'] = true; + break; + } + } + } + + // Construct the graph. + void findDependency(const vector& words, vector> *graph) { + for (const auto& c : words[0]) { + (*graph)[c - 'a'][c - 'a'] = true; + } + for (int i = 1; i < words.size(); ++i) { + for (const auto& c : words[i]) { + (*graph)[c - 'a'] [c - 'a'] = true; + } + findEdges(words[i - 1], words[i], graph); + } + } + + // Perform topological sort, return whether there is a cycle. + bool topSortDFS(string *result, vector *visited, + vector> *graph, const int root) { + if ((*visited)[root]) { + *result = ""; + return true; + } + (*visited)[root] = true; + for (int i = 0; i < 26; ++i) { + if (i != root && (*graph)[root][i]) { + if (topSortDFS(result, visited, graph, i)) { + return true; + } + } + } + (*graph)[root][root] = false; + result->push_back(root + 'a'); + return false; + } + + void findOrder(vector> *graph, string *result) { + for (int i = 0; i < 26; ++i) { + // Find a root node. + bool root_node = (*graph)[i][i]; + if ((*graph)[i][i]) { + for (int j = 0; j < 26; ++j) { + if (j != i && (*graph)[j][i]) { + root_node = false; + break; + } + } + } + if (root_node) { + string reversed_order = ""; + vector visited(26, false); + if (topSortDFS(&reversed_order, &visited, graph, i)) { + result->clear(); + return; + } else { + result->append(reversed_order); + } + } + } + + // If there is any unvisited node, return "". + for (int i = 0; i < 26; ++i) { + if ((*graph)[i][i]) { + result->clear(); + return; + } + } + // The order should be reversed. + reverse(result->begin(), result->end()); + } + + string alienOrder(vector& words) { + string result; + if (words.empty()) { + return result; + } + if (words.size() == 1) { + return words[0]; + } + + vector> graph(26, vector(26)); + findDependency(words, &graph); + findOrder(&graph, &result); + return result; + } +}; From 306b91d49408005d0bf90bc672d40e8417368f3c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 10:11:26 +0800 Subject: [PATCH 0704/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 212904572..10dadb298 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -26,7 +26,7 @@ class Solution { } } - // Perform topological sort, return whether there is a cycle. + // Topological sort, return whether there is a cycle. bool topSortDFS(string *result, vector *visited, vector> *graph, const int root) { if ((*visited)[root]) { From a59c5687a55c786b28ce2bc97bf3bcb99a587e62 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 18:45:05 +0800 Subject: [PATCH 0705/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 14272741d..086513f9e 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-24), there are `251` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-25), there are `252` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `268` questions. +Here is the classification of all `269` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -373,8 +373,9 @@ Shell 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-tree.py) | _O(h)_ | _O(h)_ | Medium | EPI | 247| [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/) | [C++](./C++/strobogrammatic-number-ii.cpp) [Python](./Python/strobogrammatic-number-ii.py) | _O(n^2 * 5^(n/2))_ | _O(n)_ | Medium |📖|| 250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtrees.cpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| -254| [Factor Combinations](https://leetcode.com/problems/factor-combinations) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| +254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| +269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(1)_ | _O(1)_ | Medium |📖|| --- From ae3eb0b5b166ecb22ea8b51309acb897c51419a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 21:26:17 +0800 Subject: [PATCH 0706/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 70 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 10dadb298..134f0d26b 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -2,6 +2,74 @@ // Space: O(|E|) = O(26^2) = O(1) class Solution { +public: + void findEdges(const string &word1, const string &word2, + unordered_map> *ancestors) { + // construct the graph + int len = min(word1.length(), word2.length()); + for (int i = 0; i < len; ++i) { + if (word1[i] != word2[i]) { + (*ancestors)[word2[i]].emplace_back(word1[i]); + break; + } + } + } + + bool topSortDFS(const char& root, + const char& node, + unordered_map> *ancestors, + unordered_map *visited, + string *result) { + if (visited->emplace(make_pair(node, root)).second) { + for (auto& ancestor: (*ancestors)[node]) { + if (topSortDFS(root, ancestor, ancestors, visited, result)) { + return true; + } + } + result->push_back(node); + return false; + } else if ((*visited)[node] == root) { + return true; + } + } + + string alienOrder(vector& words) { + if (words.empty()) { + return ""; + } + if (words.size() == 1) { + string word(words[0]); + // Unique characters. + word.erase(unique(word.begin(), word.end()), word.end()); + return word; + } + + // Find ancestors of each node by DFS + unordered_set nodes; + unordered_map> ancestors; + for (int i = 0; i < words.size(); ++i) { + for (char c : words[i]) { + nodes.emplace(c); + } + if (i > 0) { + findEdges(words[i - 1], words[i], &ancestors); + } + } + + // Output topological order by DFS + string result; + unordered_map visited; + for (auto& node : nodes) { + if (topSortDFS(node, node, &ancestors, &visited, &result)) { + return ""; + } + } + + return result; + } +}; + +class Solution2 { public: void findEdges(const string &word1, const string &word2, vector> *graph) { int len = min(word1.length(), word2.length()); @@ -30,7 +98,7 @@ class Solution { bool topSortDFS(string *result, vector *visited, vector> *graph, const int root) { if ((*visited)[root]) { - *result = ""; + result->clear(); return true; } (*visited)[root] = true; From f176c0cce716566610ac0b8409e04e60e597db1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 21:30:37 +0800 Subject: [PATCH 0707/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 134f0d26b..32c8d9b71 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -15,6 +15,7 @@ class Solution { } } + // Topological sort, return whether there is a cycle. bool topSortDFS(const char& root, const char& node, unordered_map> *ancestors, @@ -29,6 +30,8 @@ class Solution { result->push_back(node); return false; } else if ((*visited)[node] == root) { + // Visited from the same root in the DFS path. + // So it is cyclic. return true; } } @@ -69,6 +72,7 @@ class Solution { } }; +// Adjacency matrix method. class Solution2 { public: void findEdges(const string &word1, const string &word2, vector> *graph) { @@ -155,7 +159,10 @@ class Solution2 { return result; } if (words.size() == 1) { - return words[0]; + string word(words[0]); + // Unique characters. + word.erase(unique(word.begin(), word.end()), word.end()); + return word; } vector> graph(26, vector(26)); From 454b3cd17a7e11350a93e6f3d0a5ece4fb499c42 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 21:32:01 +0800 Subject: [PATCH 0708/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 32c8d9b71..cee36e334 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -3,9 +3,9 @@ class Solution { public: + // Construct the graph. void findEdges(const string &word1, const string &word2, unordered_map> *ancestors) { - // construct the graph int len = min(word1.length(), word2.length()); for (int i = 0; i < len; ++i) { if (word1[i] != word2[i]) { From 9f2b511468bd1b98f7610c70644be6d0ca297035 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 21:37:55 +0800 Subject: [PATCH 0709/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index cee36e334..3d08ce937 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -37,16 +37,6 @@ class Solution { } string alienOrder(vector& words) { - if (words.empty()) { - return ""; - } - if (words.size() == 1) { - string word(words[0]); - // Unique characters. - word.erase(unique(word.begin(), word.end()), word.end()); - return word; - } - // Find ancestors of each node by DFS unordered_set nodes; unordered_map> ancestors; @@ -155,16 +145,6 @@ class Solution2 { string alienOrder(vector& words) { string result; - if (words.empty()) { - return result; - } - if (words.size() == 1) { - string word(words[0]); - // Unique characters. - word.erase(unique(word.begin(), word.end()), word.end()); - return word; - } - vector> graph(26, vector(26)); findDependency(words, &graph); findOrder(&graph, &result); From dea10d2495e8460b3d43b6323da82b8960bd8a15 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 21:39:02 +0800 Subject: [PATCH 0710/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 3d08ce937..de5cf98cb 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -28,12 +28,12 @@ class Solution { } } result->push_back(node); - return false; } else if ((*visited)[node] == root) { // Visited from the same root in the DFS path. // So it is cyclic. return true; } + return false; } string alienOrder(vector& words) { From 85d2095a699d494384ca385abbd9d20dde12968a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 22:20:39 +0800 Subject: [PATCH 0711/1939] Create alien-dictionary.py --- Python/alien-dictionary.py | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/alien-dictionary.py diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py new file mode 100644 index 000000000..662be4c05 --- /dev/null +++ b/Python/alien-dictionary.py @@ -0,0 +1,53 @@ +# Time: O(|V|+|E|) = O(26 + 26^2) = O(1) +# Space: O(|E|) = O(26^2) = O(1) + +class Solution(object): + def alienOrder(self, words): + """ + :type words: List[str] + :rtype: str + """ + # Find ancestors of each node by DFS + nodes, ancestors = {}, {} + for i in xrange(len(words)): + for c in words[i]: + nodes[c] = True + + for node in nodes.keys(): + ancestors[node] = [] + + for i in xrange(1, len(words)): + self.findEdges(words[i - 1], words[i], ancestors) + + # Output topological order by DFS + result = [] + visited = {} + for node in nodes.keys(): + if self.topSortDFS(node, node, ancestors, visited, result): + return "" + + return "".join(result) + + + # Construct the graph. + def findEdges(self, word1, word2, ancestors): + str_len = min(len(word1), len(word2)) + for i in xrange(str_len): + if word1[i] != word2[i]: + ancestors[word2[i]].append(word1[i]) + break + + + # Topological sort, return whether there is a cycle. + def topSortDFS(self, root, node, ancestors, visited, result): + if node not in visited: + visited[node] = root + for ancestor in ancestors[node]: + if self.topSortDFS(root, ancestor, ancestors, visited, result): + return True + result.append(node) + elif visited[node] == root: + # Visited from the same root in the DFS path. + # So it is cyclic. + return True + return False From 00a0e875ba709bd667d4b92449cb0e87b04be08d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 22:21:40 +0800 Subject: [PATCH 0712/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 66 +++++++++++++++++++++------------------- 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index de5cf98cb..9e747feea 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -3,6 +3,32 @@ class Solution { public: + string alienOrder(vector& words) { + // Find ancestors of each node by DFS + unordered_set nodes; + unordered_map> ancestors; + for (int i = 0; i < words.size(); ++i) { + for (char c : words[i]) { + nodes.emplace(c); + } + if (i > 0) { + findEdges(words[i - 1], words[i], &ancestors); + } + } + + // Output topological order by DFS + string result; + unordered_map visited; + for (auto& node : nodes) { + if (topSortDFS(node, node, &ancestors, &visited, &result)) { + return ""; + } + } + + return result; + } + +private: // Construct the graph. void findEdges(const string &word1, const string &word2, unordered_map> *ancestors) { @@ -35,36 +61,20 @@ class Solution { } return false; } +}; +// Adjacency matrix method. +class Solution2 { +public: string alienOrder(vector& words) { - // Find ancestors of each node by DFS - unordered_set nodes; - unordered_map> ancestors; - for (int i = 0; i < words.size(); ++i) { - for (char c : words[i]) { - nodes.emplace(c); - } - if (i > 0) { - findEdges(words[i - 1], words[i], &ancestors); - } - } - - // Output topological order by DFS string result; - unordered_map visited; - for (auto& node : nodes) { - if (topSortDFS(node, node, &ancestors, &visited, &result)) { - return ""; - } - } - + vector> graph(26, vector(26)); + findDependency(words, &graph); + findOrder(&graph, &result); return result; } -}; -// Adjacency matrix method. -class Solution2 { -public: +private: void findEdges(const string &word1, const string &word2, vector> *graph) { int len = min(word1.length(), word2.length()); for (int i = 0; i < len; ++i) { @@ -142,12 +152,4 @@ class Solution2 { // The order should be reversed. reverse(result->begin(), result->end()); } - - string alienOrder(vector& words) { - string result; - vector> graph(26, vector(26)); - findDependency(words, &graph); - findOrder(&graph, &result); - return result; - } }; From c8beae6ade7d7ef20c9d51454ecf7eb07d6847d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 22:22:59 +0800 Subject: [PATCH 0713/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 9e747feea..656971d6b 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -4,7 +4,7 @@ class Solution { public: string alienOrder(vector& words) { - // Find ancestors of each node by DFS + // Find ancestors of each node by DFS. unordered_set nodes; unordered_map> ancestors; for (int i = 0; i < words.size(); ++i) { @@ -16,7 +16,7 @@ class Solution { } } - // Output topological order by DFS + // Output topological order by DFS. string result; unordered_map visited; for (auto& node : nodes) { From 68155358cf031b0bb3d2373888edb3fe011cdeec Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 22:26:38 +0800 Subject: [PATCH 0714/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 086513f9e..003c53474 100644 --- a/README.md +++ b/README.md @@ -375,7 +375,7 @@ Shell 250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtrees.cpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| 254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| -269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(1)_ | _O(1)_ | Medium |📖|| +269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(1)_ | _O(1)_ | Medium |📖| Topological Sort | --- From 2754cc141963206f8ed45ef8996cf585c4cc340a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 22:33:11 +0800 Subject: [PATCH 0715/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 656971d6b..721bb077d 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -19,7 +19,7 @@ class Solution { // Output topological order by DFS. string result; unordered_map visited; - for (auto& node : nodes) { + for (const auto& node : nodes) { if (topSortDFS(node, node, &ancestors, &visited, &result)) { return ""; } From 9ac3b5411cc05a8e1787b9f75bce0472a4d76f5c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 22:45:40 +0800 Subject: [PATCH 0716/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index 662be4c05..088080c41 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -8,12 +8,12 @@ def alienOrder(self, words): :rtype: str """ # Find ancestors of each node by DFS - nodes, ancestors = {}, {} + nodes, ancestors = sets.Set(), {} for i in xrange(len(words)): for c in words[i]: - nodes[c] = True + nodes.add(c) - for node in nodes.keys(): + for node in nodes: ancestors[node] = [] for i in xrange(1, len(words)): @@ -22,7 +22,7 @@ def alienOrder(self, words): # Output topological order by DFS result = [] visited = {} - for node in nodes.keys(): + for node in nodes: if self.topSortDFS(node, node, ancestors, visited, result): return "" From 1701e461a60df7eb8ed3e9707d666a10406e858a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 22:46:50 +0800 Subject: [PATCH 0717/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index 088080c41..0705c9a78 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -12,10 +12,8 @@ def alienOrder(self, words): for i in xrange(len(words)): for c in words[i]: nodes.add(c) - for node in nodes: ancestors[node] = [] - for i in xrange(1, len(words)): self.findEdges(words[i - 1], words[i], ancestors) From ba3da40a815cf8a5ccee9c2e1ee09bd16b27ed2b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 22:47:26 +0800 Subject: [PATCH 0718/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index 0705c9a78..c47e5e413 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -7,7 +7,7 @@ def alienOrder(self, words): :type words: List[str] :rtype: str """ - # Find ancestors of each node by DFS + # Find ancestors of each node by DFS. nodes, ancestors = sets.Set(), {} for i in xrange(len(words)): for c in words[i]: @@ -17,7 +17,7 @@ def alienOrder(self, words): for i in xrange(1, len(words)): self.findEdges(words[i - 1], words[i], ancestors) - # Output topological order by DFS + # Output topological order by DFS. result = [] visited = {} for node in nodes: From 6b391b8b7091059979a92099e41562affd21568d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Aug 2015 23:04:41 +0800 Subject: [PATCH 0719/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index c47e5e413..6f3f29b24 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -29,8 +29,8 @@ def alienOrder(self, words): # Construct the graph. def findEdges(self, word1, word2, ancestors): - str_len = min(len(word1), len(word2)) - for i in xrange(str_len): + min_len = min(len(word1), len(word2)) + for i in xrange(min_len): if word1[i] != word2[i]: ancestors[word2[i]].append(word1[i]) break From 8aef287617756e817c47e4d4c14e56a1538765cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 00:14:42 +0800 Subject: [PATCH 0720/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 721bb077d..8105b89ca 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -1,5 +1,5 @@ // Time: O(|V|+|E|) = O(26 + 26^2) = O(1) -// Space: O(|E|) = O(26^2) = O(1) +// Space: O(|V|+|E|) = O(26 + 26^2) = O(1) class Solution { public: From b2f5bcb8f59d47b12b7abdf7af192557bb899fd9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 00:15:13 +0800 Subject: [PATCH 0721/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index 6f3f29b24..68d868fbd 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -1,5 +1,5 @@ # Time: O(|V|+|E|) = O(26 + 26^2) = O(1) -# Space: O(|E|) = O(26^2) = O(1) +# Space: O(|V|+|E|) = O(26 + 26^2) = O(1) class Solution(object): def alienOrder(self, words): From 9c672d95f81c32102c8c4d92105929db5fd05e85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 00:26:48 +0800 Subject: [PATCH 0722/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index 9f611ea45..05e3e0e1a 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -12,7 +12,7 @@ class Solution { return false; } - unordered_map nodes; + unordered_map nodes; for (const auto& edge : edges) { nodes[edge.first].neighbors.emplace_back(edge.second); nodes[edge.second].neighbors.emplace_back(edge.first); From e2a061a4c08e4fd3aaee02c79113057fe4c62bb2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 00:31:11 +0800 Subject: [PATCH 0723/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 003c53474..032c65eb6 100644 --- a/README.md +++ b/README.md @@ -346,8 +346,8 @@ Shell 127| [Word Ladder](https://leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || 130| [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || 133| [Clone Graph](https://leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || -207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || -210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || +207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | Topological Sort | +210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | Topological Sort | 261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | --- From 11a4e0b710b53b8a57e95639ca3ee0e02d2678f6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 00:31:44 +0800 Subject: [PATCH 0724/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 032c65eb6..c398aa5a9 100644 --- a/README.md +++ b/README.md @@ -346,8 +346,8 @@ Shell 127| [Word Ladder](https://leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || 130| [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || 133| [Clone Graph](https://leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || -207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | Topological Sort | -210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium | Topological Sort | +207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | +210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | --- From caaf083dd92f754ae7f2d5023c8c9205a811148d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 00:51:27 +0800 Subject: [PATCH 0725/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 54 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index 68d868fbd..7d928dca6 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -1,7 +1,61 @@ # Time: O(|V|+|E|) = O(26 + 26^2) = O(1) # Space: O(|V|+|E|) = O(26 + 26^2) = O(1) +# BFS solution. class Solution(object): + def alienOrder(self, words): + """ + :type words: List[str] + :rtype: str + """ + # Find ancestors of each node by BFS + result, zero_in_degree_queue, in_degree, out_degree = [], [], {}, {} + nodes = sets.Set() + for i in xrange(len(words)): + for c in words[i]: + nodes.add(c) + + for i in xrange(1, len(words)): + self.findEdges(words[i - 1], words[i], in_degree, out_degree) + + for node in nodes: + if node not in in_degree: + zero_in_degree_queue.append(node) + + while zero_in_degree_queue: + precedence = zero_in_degree_queue.pop() + result.append(precedence) + + if precedence in out_degree: + for course in out_degree[precedence]: + in_degree[course].discard(precedence) + if not in_degree[course]: + zero_in_degree_queue.append(course) + + del out_degree[precedence] + + if out_degree: + return "" + + return "".join(result) + + + # Construct the graph. + def findEdges(self, word1, word2, in_degree, out_degree): + str_len = min(len(word1), len(word2)) + for i in xrange(str_len): + if word1[i] != word2[i]: + if word2[i] not in in_degree: + in_degree[word2[i]] = sets.Set() + if word1[i] not in out_degree: + out_degree[word1[i]] = sets.Set() + in_degree[word2[i]].add(word1[i]) + out_degree[word1[i]].add(word2[i]) + break + + +# DFS solution. +class Solution2(object): def alienOrder(self, words): """ :type words: List[str] From 8c0e714633cf24b227143bceac3ea4b089c805ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 00:53:00 +0800 Subject: [PATCH 0726/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c398aa5a9..96b293bf4 100644 --- a/README.md +++ b/README.md @@ -349,6 +349,7 @@ Shell 207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | +269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(1)_ | _O(1)_ | Medium |📖| Topological Sort, BFS, DFS | --- @@ -375,7 +376,6 @@ Shell 250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtrees.cpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| 254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| -269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(1)_ | _O(1)_ | Medium |📖| Topological Sort | --- From c4a00c593be332389df3d3555fca48704ed3dcfb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 00:55:09 +0800 Subject: [PATCH 0727/1939] Update course-schedule.py --- Python/course-schedule.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Python/course-schedule.py b/Python/course-schedule.py index 80542d46f..a527cf385 100644 --- a/Python/course-schedule.py +++ b/Python/course-schedule.py @@ -39,11 +39,11 @@ def canFinish(self, numCourses, prerequisites): for i, j in prerequisites: if i not in in_degree: - in_degree[i] = {} + in_degree[i] = sets.Set() if j not in out_degree: - out_degree[j] = {} - in_degree[i][j] = True - out_degree[j][i] = True + out_degree[j] = sets.Set() + in_degree[i].add(j) + out_degree[j].add(i) for i in xrange(numCourses): if i not in in_degree: @@ -54,16 +54,16 @@ def canFinish(self, numCourses, prerequisites): if prerequisite in out_degree: for course in out_degree[prerequisite]: - del in_degree[course][prerequisite] + in_degree[course].discard(prerequisite) if not in_degree[course]: zero_in_degree_queue.append(course) del out_degree[prerequisite] - if len(out_degree): + if out_degree: return False return True if __name__ == "__main__": - print Solution().canFinish(1, []) \ No newline at end of file + print Solution().canFinish(1, []) From 3764938f36c4e9f33a367af9a0cd05e19573bf13 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 00:56:43 +0800 Subject: [PATCH 0728/1939] Update course-schedule-ii.py --- Python/course-schedule-ii.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/course-schedule-ii.py b/Python/course-schedule-ii.py index d6701a084..c08ab9809 100644 --- a/Python/course-schedule-ii.py +++ b/Python/course-schedule-ii.py @@ -44,11 +44,11 @@ def findOrder(self, numCourses, prerequisites): for i, j in prerequisites: if i not in in_degree: - in_degree[i] = {} + in_degree[i] = sets.Set() if j not in out_degree: - out_degree[j] = {} - in_degree[i][j] = True - out_degree[j][i] = True + out_degree[j] = sets.Set() + in_degree[i].add(j) + out_degree[j].add(i) for i in xrange(numCourses): if i not in in_degree: @@ -60,13 +60,13 @@ def findOrder(self, numCourses, prerequisites): if prerequisite in out_degree: for course in out_degree[prerequisite]: - del in_degree[course][prerequisite] + in_degree[course].discard(prerequisite) if not in_degree[course]: zero_in_degree_queue.append(course) del out_degree[prerequisite] - if len(out_degree): + if out_degree: return [] return res From 88592e094d3f24a18265ac7f5205f12a02247d53 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:01:51 +0800 Subject: [PATCH 0729/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index 7d928dca6..e770435fd 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -9,7 +9,7 @@ def alienOrder(self, words): :rtype: str """ # Find ancestors of each node by BFS - result, zero_in_degree_queue, in_degree, out_degree = [], [], {}, {} + result, zero_in_degree_queue, in_degree, out_degree = [], collections.deque(), {}, {} nodes = sets.Set() for i in xrange(len(words)): for c in words[i]: @@ -23,7 +23,7 @@ def alienOrder(self, words): zero_in_degree_queue.append(node) while zero_in_degree_queue: - precedence = zero_in_degree_queue.pop() + precedence = zero_in_degree_queue.popleft() result.append(precedence) if precedence in out_degree: From 4ae7c0324ffca04a7dcbd5f9087bee2a5097bb62 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:02:20 +0800 Subject: [PATCH 0730/1939] Update course-schedule-ii.py --- Python/course-schedule-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/course-schedule-ii.py b/Python/course-schedule-ii.py index c08ab9809..0bffc2a61 100644 --- a/Python/course-schedule-ii.py +++ b/Python/course-schedule-ii.py @@ -40,7 +40,7 @@ class Solution: # @param {integer[][]} prerequisites # @return {integer[]} def findOrder(self, numCourses, prerequisites): - res, zero_in_degree_queue, in_degree, out_degree = [], [], {}, {} + res, zero_in_degree_queue, in_degree, out_degree = [], collections.deque(), {}, {} for i, j in prerequisites: if i not in in_degree: @@ -55,7 +55,7 @@ def findOrder(self, numCourses, prerequisites): zero_in_degree_queue.append(i) while zero_in_degree_queue: - prerequisite = zero_in_degree_queue.pop() + prerequisite = zero_in_degree_queue.popleft() res.append(prerequisite) if prerequisite in out_degree: From 1c346f738523a4f5fb8882d6479325dd051d551d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:02:50 +0800 Subject: [PATCH 0731/1939] Update course-schedule.py --- Python/course-schedule.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/course-schedule.py b/Python/course-schedule.py index a527cf385..395adba24 100644 --- a/Python/course-schedule.py +++ b/Python/course-schedule.py @@ -35,7 +35,7 @@ class Solution: # @param {integer[][]} prerequisites # @return {boolean} def canFinish(self, numCourses, prerequisites): - zero_in_degree_queue, in_degree, out_degree = [], {}, {} + zero_in_degree_queue, in_degree, out_degree = collections.deque(), {}, {} for i, j in prerequisites: if i not in in_degree: @@ -50,7 +50,7 @@ def canFinish(self, numCourses, prerequisites): zero_in_degree_queue.append(i) while zero_in_degree_queue: - prerequisite = zero_in_degree_queue.pop() + prerequisite = zero_in_degree_queue.popleft() if prerequisite in out_degree: for course in out_degree[prerequisite]: From 6bc435a0fcc89e4b73daa7f2bea2d5358ceb74bf Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:08:06 +0800 Subject: [PATCH 0732/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index e770435fd..b68af1ca7 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -8,11 +8,10 @@ def alienOrder(self, words): :type words: List[str] :rtype: str """ - # Find ancestors of each node by BFS result, zero_in_degree_queue, in_degree, out_degree = [], collections.deque(), {}, {} nodes = sets.Set() - for i in xrange(len(words)): - for c in words[i]: + for word in words: + for c in word: nodes.add(c) for i in xrange(1, len(words)): From 1d5db4d83865d5b8836957b47c4d053851d712d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:13:36 +0800 Subject: [PATCH 0733/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index b68af1ca7..8b3bfdee8 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -26,10 +26,10 @@ def alienOrder(self, words): result.append(precedence) if precedence in out_degree: - for course in out_degree[precedence]: - in_degree[course].discard(precedence) - if not in_degree[course]: - zero_in_degree_queue.append(course) + for c in out_degree[precedence]: + in_degree[c].discard(precedence) + if not in_degree[c]: + zero_in_degree_queue.append(c) del out_degree[precedence] From b9b2233d31cf356cdc50bc53c71d8af362d8a927 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:22:41 +0800 Subject: [PATCH 0734/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 63 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 8105b89ca..4514ec16a 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -1,7 +1,70 @@ // Time: O(|V|+|E|) = O(26 + 26^2) = O(1) // Space: O(|V|+|E|) = O(26 + 26^2) = O(1) +// BFS solution. class Solution { +public: + string alienOrder(vector& words) { + unordered_set nodes; + unordered_map> in_degree, out_degree; + queue zero_in_degree_queue; + for (const auto& word : words) { + for (char c : word) { + nodes.emplace(c); + } + } + for (int i = 1; i < words.size(); ++i) { + findEdges(words[i - 1], words[i], &in_degree, &out_degree); + } + for (const auto& node : nodes) { + if (in_degree.find(node) == in_degree.end()) { + zero_in_degree_queue.emplace(node); + } + } + + // BFS + string result; + while (!zero_in_degree_queue.empty()) { + const auto& precedence = zero_in_degree_queue.front(); + zero_in_degree_queue.pop(); + result.push_back(precedence); + + if (out_degree.find(precedence) != out_degree.end()) { + for (const auto& c : out_degree[precedence]) { + in_degree[c].erase(precedence); + if (in_degree[c].empty()) { + zero_in_degree_queue.emplace(c); + } + } + out_degree.erase(precedence); + } + } + + if (!out_degree.empty()) { + return ""; + } + + return result; + } + +private: + // Construct the graph. + void findEdges(const string &word1, const string &word2, + unordered_map> *in_degree, + unordered_map> *out_degree) { + int len = min(word1.length(), word2.length()); + for (int i = 0; i < len; ++i) { + if (word1[i] != word2[i]) { + (*in_degree)[word2[i]].emplace(word1[i]); + (*out_degree)[word1[i]].emplace(word2[i]); + break; + } + } + } +}; + +// DFS solution. +class Solution2 { public: string alienOrder(vector& words) { // Find ancestors of each node by DFS. From 3508f15679072407507f250e694d48d01ad8e15e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:23:19 +0800 Subject: [PATCH 0735/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index 4514ec16a..d39a9e7a1 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -126,8 +126,8 @@ class Solution2 { } }; -// Adjacency matrix method. -class Solution2 { +// DFS with adjacency matrix solution. +class Solution3 { public: string alienOrder(vector& words) { string result; From 59c928c497de3fe8f1ff667b3e8de793265386a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:38:31 +0800 Subject: [PATCH 0736/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index d39a9e7a1..cbd326269 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -9,7 +9,7 @@ class Solution { unordered_map> in_degree, out_degree; queue zero_in_degree_queue; for (const auto& word : words) { - for (char c : word) { + for (const auto& c : word) { nodes.emplace(c); } } @@ -71,7 +71,7 @@ class Solution2 { unordered_set nodes; unordered_map> ancestors; for (int i = 0; i < words.size(); ++i) { - for (char c : words[i]) { + for (const auto& c : words[i]) { nodes.emplace(c); } if (i > 0) { From 7d7eec71cb1c10781aafecf94e26955a1c9e06d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:43:00 +0800 Subject: [PATCH 0737/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index cbd326269..be439c543 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -1,4 +1,4 @@ -// Time: O(|V|+|E|) = O(26 + 26^2) = O(1) +// Time: O(n) // Space: O(|V|+|E|) = O(26 + 26^2) = O(1) // BFS solution. From 00c09b7583ebdaeb6aad857b8fcef0480bafbde7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:43:27 +0800 Subject: [PATCH 0738/1939] Update alien-dictionary.py --- Python/alien-dictionary.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index 8b3bfdee8..08178ab1e 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -1,4 +1,4 @@ -# Time: O(|V|+|E|) = O(26 + 26^2) = O(1) +# Time: O(n) # Space: O(|V|+|E|) = O(26 + 26^2) = O(1) # BFS solution. From 487c629a659d3ddefe5fb6b3178625ab6a4ebb4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 01:43:52 +0800 Subject: [PATCH 0739/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 96b293bf4..d23e04348 100644 --- a/README.md +++ b/README.md @@ -349,7 +349,7 @@ Shell 207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | -269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(1)_ | _O(1)_ | Medium |📖| Topological Sort, BFS, DFS | +269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Medium |📖| Topological Sort, BFS, DFS | --- From 51cc157364a2377a652d282495f3830e4d316408 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Aug 2015 14:33:51 +0800 Subject: [PATCH 0740/1939] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index be439c543..f6eb45970 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -52,7 +52,7 @@ class Solution { void findEdges(const string &word1, const string &word2, unordered_map> *in_degree, unordered_map> *out_degree) { - int len = min(word1.length(), word2.length()); + const int len = min(word1.length(), word2.length()); for (int i = 0; i < len; ++i) { if (word1[i] != word2[i]) { (*in_degree)[word2[i]].emplace(word1[i]); @@ -95,7 +95,7 @@ class Solution2 { // Construct the graph. void findEdges(const string &word1, const string &word2, unordered_map> *ancestors) { - int len = min(word1.length(), word2.length()); + const int len = min(word1.length(), word2.length()); for (int i = 0; i < len; ++i) { if (word1[i] != word2[i]) { (*ancestors)[word2[i]].emplace_back(word1[i]); @@ -139,7 +139,7 @@ class Solution3 { private: void findEdges(const string &word1, const string &word2, vector> *graph) { - int len = min(word1.length(), word2.length()); + const int len = min(word1.length(), word2.length()); for (int i = 0; i < len; ++i) { if (word1[i] != word2[i]) { (*graph)[word1[i] - 'a'][word2[i] - 'a'] = true; From b77412ab9814d56e5fba81aec30a2b9069825cbf Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 27 Aug 2015 09:33:27 +0800 Subject: [PATCH 0741/1939] Create closest-binary-search-tree-value.py --- Python/closest-binary-search-tree-value.py | 33 ++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/closest-binary-search-tree-value.py diff --git a/Python/closest-binary-search-tree-value.py b/Python/closest-binary-search-tree-value.py new file mode 100644 index 000000000..58116b5fa --- /dev/null +++ b/Python/closest-binary-search-tree-value.py @@ -0,0 +1,33 @@ +# Time: O(n) +# Space: O(1) + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def closestValue(self, root, target): + """ + :type root: TreeNode + :type target: float + :rtype: int + """ + gap = float("inf") + closet = root + while root: + if target == root.val: + return root.val + elif target < root.val: + if abs(root.val - target) < gap: + gap = abs(root.val - target) + closet = root + root = root.left + else: + if abs(root.val - target) < gap: + gap = abs(root.val - target) + closet = root + root = root.right + return closet.val From 043d9568615b1ef3cfde5c9b63a0a89593f1711b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 27 Aug 2015 09:43:39 +0800 Subject: [PATCH 0742/1939] Update closest-binary-search-tree-value.py --- Python/closest-binary-search-tree-value.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/Python/closest-binary-search-tree-value.py b/Python/closest-binary-search-tree-value.py index 58116b5fa..484f714d9 100644 --- a/Python/closest-binary-search-tree-value.py +++ b/Python/closest-binary-search-tree-value.py @@ -16,18 +16,15 @@ def closestValue(self, root, target): :rtype: int """ gap = float("inf") - closet = root + closet = float("inf") while root: + if abs(root.val - target) < gap: + gap = abs(root.val - target) + closet = root if target == root.val: return root.val elif target < root.val: - if abs(root.val - target) < gap: - gap = abs(root.val - target) - closet = root root = root.left else: - if abs(root.val - target) < gap: - gap = abs(root.val - target) - closet = root root = root.right return closet.val From 5b0bb70e23d495e451daf2e4134f812a7bc1e3b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 27 Aug 2015 09:45:18 +0800 Subject: [PATCH 0743/1939] Create closest-binary-search-tree-value.cpp --- C++/closest-binary-search-tree-value.cpp | 34 ++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/closest-binary-search-tree-value.cpp diff --git a/C++/closest-binary-search-tree-value.cpp b/C++/closest-binary-search-tree-value.cpp new file mode 100644 index 000000000..84df8f200 --- /dev/null +++ b/C++/closest-binary-search-tree-value.cpp @@ -0,0 +1,34 @@ +// Time: O(n) +// Space: O(1) + +/** + * 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: + int closestValue(TreeNode* root, double target) { + double gap = numeric_limits::max(); + int closest = numeric_limits::max(); + + while (root) { + if (abs(static_cast(root->val) - target) < gap) { + gap = abs(root->val - target); + closest = root->val; + } + if (root->val == target) { + return root->val; + } else if (root->val > target) { + root = root->left; + } else { + root = root->right; + } + } + return closest; + } +}; From 1c9d13edfe9112198ffbe915da5a29db71014886 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 27 Aug 2015 09:49:08 +0800 Subject: [PATCH 0744/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d23e04348..2f021e545 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-25), there are `252` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-27), there are `253` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `269` questions. +Here is the classification of all `270` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -333,6 +333,7 @@ Shell 220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) [Python](./Python/contains-duplicate-iii.py) | _O(nlogk)_ | _O(k)_ | medium || 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(max(h, k))_ | _O(min(h, k))_ | Medium || 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-search-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-search-tree.py) | _O(h)_ | _O(1)_ | Easy | EPI | +270| [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/)| [C++](./C++/closest-binary-search-tree-value.cpp) [Python](./Python/closest-binary-search-tree-value.py) | _O(h)_ | _O(1)_ | Easy | 📖 | --- From efe3b1e6707a8549d7c4c683163c2fede839237a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 27 Aug 2015 09:49:25 +0800 Subject: [PATCH 0745/1939] Update closest-binary-search-tree-value.cpp --- C++/closest-binary-search-tree-value.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/closest-binary-search-tree-value.cpp b/C++/closest-binary-search-tree-value.cpp index 84df8f200..c935cb60d 100644 --- a/C++/closest-binary-search-tree-value.cpp +++ b/C++/closest-binary-search-tree-value.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(h) // Space: O(1) /** From f7fadec7f850ec4f2173e8dc3ec5c66fca20cccb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 27 Aug 2015 09:49:45 +0800 Subject: [PATCH 0746/1939] Update closest-binary-search-tree-value.py --- Python/closest-binary-search-tree-value.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/closest-binary-search-tree-value.py b/Python/closest-binary-search-tree-value.py index 484f714d9..26222150a 100644 --- a/Python/closest-binary-search-tree-value.py +++ b/Python/closest-binary-search-tree-value.py @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(h) # Space: O(1) # Definition for a binary tree node. From a78d8d69488a6933583c3c19a5f0c7aac3654dbe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 27 Aug 2015 09:52:30 +0800 Subject: [PATCH 0747/1939] Update closest-binary-search-tree-value.py --- Python/closest-binary-search-tree-value.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/closest-binary-search-tree-value.py b/Python/closest-binary-search-tree-value.py index 26222150a..615361c20 100644 --- a/Python/closest-binary-search-tree-value.py +++ b/Python/closest-binary-search-tree-value.py @@ -22,7 +22,7 @@ def closestValue(self, root, target): gap = abs(root.val - target) closet = root if target == root.val: - return root.val + break elif target < root.val: root = root.left else: From 4dfa950d19253cc0f20087c27a12e0ea5127b635 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 27 Aug 2015 09:52:57 +0800 Subject: [PATCH 0748/1939] Update closest-binary-search-tree-value.cpp --- C++/closest-binary-search-tree-value.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/closest-binary-search-tree-value.cpp b/C++/closest-binary-search-tree-value.cpp index c935cb60d..9b7326d83 100644 --- a/C++/closest-binary-search-tree-value.cpp +++ b/C++/closest-binary-search-tree-value.cpp @@ -22,7 +22,7 @@ class Solution { closest = root->val; } if (root->val == target) { - return root->val; + break; } else if (root->val > target) { root = root->left; } else { From 45ef1260da3249ac3685bd84b5f4822cd1ca4270 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 27 Aug 2015 09:53:43 +0800 Subject: [PATCH 0749/1939] Update closest-binary-search-tree-value.cpp --- C++/closest-binary-search-tree-value.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/closest-binary-search-tree-value.cpp b/C++/closest-binary-search-tree-value.cpp index 9b7326d83..0ab4ebb70 100644 --- a/C++/closest-binary-search-tree-value.cpp +++ b/C++/closest-binary-search-tree-value.cpp @@ -21,9 +21,9 @@ class Solution { gap = abs(root->val - target); closest = root->val; } - if (root->val == target) { + if (target == root->val) { break; - } else if (root->val > target) { + } else if (target < root->val) { root = root->left; } else { root = root->right; From 1aae8eb111598794db54a25d9a57f44956d75087 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 29 Aug 2015 18:15:02 +0800 Subject: [PATCH 0750/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2f021e545..a75429823 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-27), there are `253` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-28), there are `254` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `270` questions. +Here is the classification of all `271` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From 8591404b2390a7c78dfad64fa97ebace8a5db7c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 29 Aug 2015 18:26:53 +0800 Subject: [PATCH 0751/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a75429823..ba85005b1 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-08-28), there are `254` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-29), there are `254` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `271` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 034a877ea5d08f8e78661b8e3286d687eb85455a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Aug 2015 14:42:32 +0800 Subject: [PATCH 0752/1939] Create encode-and-decode-strings.py --- Python/encode-and-decode-strings.py | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/encode-and-decode-strings.py diff --git a/Python/encode-and-decode-strings.py b/Python/encode-and-decode-strings.py new file mode 100644 index 000000000..39445a51a --- /dev/null +++ b/Python/encode-and-decode-strings.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(1) + +class Codec: + + def encode(self, strs): + """Encodes a list of strings to a single string. + + :type strs: List[str] + :rtype: str + """ + encoded_str = "" + for s in strs: + encoded_str += "%0*x" % (8, len(s)) + s + return encoded_str + + + def decode(self, s): + """Decodes a single string to a list of strings. + + :type s: str + :rtype: List[str] + """ + i = 0 + strs = [] + while i < len(s): + l = int(s[i:i+8], 16) + strs.append(s[i+8:i+8+l]) + i += 8+l + return strs From 806b152d2e774c8b6cfe8bd7342a58a85b8a14fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Aug 2015 15:14:35 +0800 Subject: [PATCH 0753/1939] Create encode-and-decode-strings.cpp --- C++/encode-and-decode-strings.cpp | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/encode-and-decode-strings.cpp diff --git a/C++/encode-and-decode-strings.cpp b/C++/encode-and-decode-strings.cpp new file mode 100644 index 000000000..0722b0c5d --- /dev/null +++ b/C++/encode-and-decode-strings.cpp @@ -0,0 +1,42 @@ +// Time: O(n) +// Space: O(1) + +class Codec { +public: + + // Encodes a list of strings to a single string. + string encode(vector& strs) { + string s; + for (size_t i = 0; i < strs.size(); ++i) { + size_t len = strs[i].length(); + string tmp; + for (size_t i = 0, mask = 0xff; i < sizeof(size_t); ++i, mask <<= 8) { + tmp.push_back(len & mask); + } + reverse(tmp.begin(), tmp.end()); + s.append(tmp); + s.append(strs[i]); + } + + return s; + } + + // Decodes a single string to a list of strings. + vector decode(string s) { + vector strs; + size_t pos = 0; + + while (pos + sizeof(size_t) <= s.length()) { + size_t len = 0; + for (size_t i = 0; i < sizeof(size_t); ++i) { + len <<= 8; + len += static_cast(s[pos++]); + } + + strs.push_back(s.substr(pos, len)); + pos += len; + } + + return strs; + } +}; From 6d3e6f88aa5cb4a4c98e656385da134afda13fb9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Aug 2015 15:19:36 +0800 Subject: [PATCH 0754/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ba85005b1..ac4bf64ed 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,7 @@ Shell 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` +271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 📖 | --- From 45abfd753055fd55a6aa1637e334aefc52bd0c98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Aug 2015 18:02:50 +0800 Subject: [PATCH 0755/1939] Create closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 Python/closest-binary-search-tree-value-ii.py diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py new file mode 100644 index 000000000..09acb21af --- /dev/null +++ b/Python/closest-binary-search-tree-value-ii.py @@ -0,0 +1,97 @@ +# Time: O(h + k) +# Space: O(h) + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def closestKValues(self, root, target, k): + """ + :type root: TreeNode + :type target: float + :type k: int + :rtype: List[int] + """ + stack = [] + node = self.closestValue(root, target, stack) + result = [node.val] + + smaller_it, larger_it = BSTIterator(node, stack), BSTIterator(node, stack) + smaller, larger = smaller_it.prev(), larger_it.next() + while len(result) < k: + if abs(smaller - target) < abs(larger - target): + result.append(smaller) + smaller = smaller_it.prev() + else: + result.append(larger) + larger = larger_it.next() + return result + + def closestValue(self, root, target, stack): + """ + :type root: TreeNode + :type target: float + :rtype: int + """ + gap = float("inf") + closet = float("inf") + while root: + stack.append(root) + if abs(root.val - target) < gap: + gap = abs(root.val - target) + closet = root + if target == root.val: + closet = stack.pop() + break + elif target < root.val: + root = root.left + else: + root = root.right + return closet + + +class BSTIterator: + # @param root, a binary search tree's root node + def __init__(self, cur, stack): + self.stack = list(stack) + self.cur = cur + + # @return an integer, the next number + def next(self): + node = None + if self.cur and self.cur.right: + node = self.cur.right + while node.left: + self.stack.append(node) + node = node.left + elif self.stack: + node = self.stack.pop(); + while node: + if node.val > self.cur.val: + break + else: + node = self.stack.pop() if self.stack else None + self.cur = node + return node.val if node else float("inf") + + # @return an integer, the previous number + def prev(self): + node = None + if self.cur and self.cur.left: + node = self.cur.left + while node.right: + self.stack.append(node) + node = node.right + elif self.stack: + node = self.stack.pop(); + while node: + if node.val < self.cur.val: + break + else: + node = self.stack.pop() if self.stack else None + self.cur = node + return node.val if node else float("-inf") From 22c36ffc181c5793e7c90adb2aecdbdc1ba13f7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Aug 2015 18:05:54 +0800 Subject: [PATCH 0756/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ac4bf64ed..efb492eb9 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-29), there are `254` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-29), there are `255` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `271` questions. +Here is the classification of all `272` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -158,6 +158,7 @@ Shell 227| [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | [C++](./C++/basic-calculator-ii.cpp) [Python](./Python/basic-calculator-ii.py) | _O(n)_| _O(n)_| Medium || 232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| Easy | EPI, LintCode | 255| [Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/verify-preorder-sequence-in-binary-search-tree.cpp) [Python](./Python/verify-preorder-sequence-in-binary-search-tree.py) | _O(n)_| _O(1)_| Medium |📖|| +272| [Closest Binary Search Tree Value II ](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(k)_| Hard |📖|| --- From 2ecd126560d3f00415fbd6bccea7cfa7f18dc24f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Aug 2015 19:49:36 +0800 Subject: [PATCH 0757/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 09acb21af..17040d185 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -17,10 +17,10 @@ def closestKValues(self, root, target, k): :rtype: List[int] """ stack = [] - node = self.closestValue(root, target, stack) - result = [node.val] + self.closestValue(root, target, stack) + result = [stack[-1].val] - smaller_it, larger_it = BSTIterator(node, stack), BSTIterator(node, stack) + smaller_it, larger_it = BSTIterator(stack), BSTIterator(stack) smaller, larger = smaller_it.prev(), larger_it.next() while len(result) < k: if abs(smaller - target) < abs(larger - target): @@ -45,36 +45,38 @@ def closestValue(self, root, target, stack): gap = abs(root.val - target) closet = root if target == root.val: - closet = stack.pop() - break + return elif target < root.val: root = root.left else: root = root.right - return closet - + while stack and stack[-1] != closet: + stack.pop() class BSTIterator: # @param root, a binary search tree's root node - def __init__(self, cur, stack): + def __init__(self, stack): self.stack = list(stack) - self.cur = cur + self.cur = self.stack.pop() # @return an integer, the next number def next(self): node = None if self.cur and self.cur.right: + self.stack.append(self.cur) node = self.cur.right while node.left: self.stack.append(node) node = node.left elif self.stack: + prev = self.cur node = self.stack.pop(); while node: - if node.val > self.cur.val: - break + if node.left is prev: + break else: - node = self.stack.pop() if self.stack else None + prev = node + node = self.stack.pop() if self.stack else None self.cur = node return node.val if node else float("inf") @@ -82,16 +84,19 @@ def next(self): def prev(self): node = None if self.cur and self.cur.left: + self.stack.append(self.cur) node = self.cur.left while node.right: self.stack.append(node) node = node.right elif self.stack: + prev = self.cur node = self.stack.pop(); while node: - if node.val < self.cur.val: - break + if node.right is prev: + break else: - node = self.stack.pop() if self.stack else None + prev = node + node = self.stack.pop() if self.stack else None self.cur = node return node.val if node else float("-inf") From 0e54c1445f539ef01e0a34d75543723c9690059d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Aug 2015 19:56:01 +0800 Subject: [PATCH 0758/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 17040d185..6cb37b7eb 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -70,7 +70,7 @@ def next(self): node = node.left elif self.stack: prev = self.cur - node = self.stack.pop(); + node = self.stack.pop() while node: if node.left is prev: break @@ -91,7 +91,7 @@ def prev(self): node = node.right elif self.stack: prev = self.cur - node = self.stack.pop(); + node = self.stack.pop() while node: if node.right is prev: break From f9943782542d5884e7ae0435f435ccb463fb5c62 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 08:54:18 +0800 Subject: [PATCH 0759/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index efb492eb9..e518297b3 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,7 @@ Shell 227| [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | [C++](./C++/basic-calculator-ii.cpp) [Python](./Python/basic-calculator-ii.py) | _O(n)_| _O(n)_| Medium || 232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| Easy | EPI, LintCode | 255| [Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/verify-preorder-sequence-in-binary-search-tree.cpp) [Python](./Python/verify-preorder-sequence-in-binary-search-tree.py) | _O(n)_| _O(1)_| Medium |📖|| -272| [Closest Binary Search Tree Value II ](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(k)_| Hard |📖|| +272| [Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(k)_| Hard |📖|| --- From cfc51d5dded59a013cbaa4df57ef2a41de9ede0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 09:21:05 +0800 Subject: [PATCH 0760/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 53 ++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 6cb37b7eb..7ee0d7600 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -7,8 +7,59 @@ # self.val = x # self.left = None # self.right = None - + class Solution(object): + def closestKValues(self, root, target, k): + """ + :type root: TreeNode + :type target: float + :type k: int + :rtype: List[int] + """ + + # Helper to make a stack to the next node. + def nextNode(stack, child1, child2): + if stack: + if child2(stack): + stack.append(child2(stack)) + while child1(stack): + stack.append(child1(stack)) + else: + child = stack.pop() + while stack and child is child2(stack): + child = stack.pop() + + # The forward or backward iterator. + backward = lambda stack: stack[-1].left + forward = lambda stack: stack[-1].right + + # Build the stack to the closest node. + stack = [] + while root: + stack.append(root) + root = root.left if target < root.val else root.right + dist = lambda node: abs(node.val - target) + forward_stack = stack[:stack.index(min(stack, key=dist))+1] + + # Get the stack to the next smaller node. + backward_stack = list(forward_stack) + nextNode(backward_stack, backward, forward) + + # Get the closest k values by advancing the iterators of the stacks + result = [] + for _ in xrange(k): + if not backward_stack or \ + forward_stack and dist(forward_stack[-1]) < dist(backward_stack[-1]): + result.append(forward_stack[-1].val) + nextNode(forward_stack, forward, backward) + elif not forward_stack or \ + forward_stack and dist(backward_stack[-1]) <= dist(forward_stack[-1]): + result.append(backward_stack[-1].val) + nextNode(backward_stack, backward, forward) + return result + + +class Solution2(object): def closestKValues(self, root, target, k): """ :type root: TreeNode From 26e1716cd627cebde6e74f5eb1583b9bd13bd0ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 09:21:30 +0800 Subject: [PATCH 0761/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 7ee0d7600..6a1af254e 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -45,7 +45,7 @@ def nextNode(stack, child1, child2): backward_stack = list(forward_stack) nextNode(backward_stack, backward, forward) - # Get the closest k values by advancing the iterators of the stacks + # Get the closest k values by advancing the iterators of the stacks. result = [] for _ in xrange(k): if not backward_stack or \ From 362defd976833b10150a4039db4e34e390e34b7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 09:36:18 +0800 Subject: [PATCH 0762/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 64 +++++++------------ 1 file changed, 24 insertions(+), 40 deletions(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 6a1af254e..0e8240c7a 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -71,23 +71,27 @@ def closestKValues(self, root, target, k): self.closestValue(root, target, stack) result = [stack[-1].val] - smaller_it, larger_it = BSTIterator(stack), BSTIterator(stack) - smaller, larger = smaller_it.prev(), larger_it.next() + # The forward or backward iterator. + backward = lambda node: node.left + forward = lambda node: node.right + + smaller_it, larger_it = BSTIterator(stack, backward, forward), BSTIterator(stack, forward, backward) + node = smaller_it.next() + smaller = node.val if node else float("-inf") + node = larger_it.next() + larger = node.val if node else float("inf") while len(result) < k: if abs(smaller - target) < abs(larger - target): result.append(smaller) - smaller = smaller_it.prev() + node = smaller_it.next() + smaller = node.val if node else float("-inf") else: result.append(larger) - larger = larger_it.next() + node = larger_it.next() + larger = node.val if node else float("inf") return result def closestValue(self, root, target, stack): - """ - :type root: TreeNode - :type target: float - :rtype: int - """ gap = float("inf") closet = float("inf") while root: @@ -97,57 +101,37 @@ def closestValue(self, root, target, stack): closet = root if target == root.val: return - elif target < root.val: - root = root.left else: - root = root.right + root = root.left if target < root.val else root.right + while stack and stack[-1] != closet: stack.pop() class BSTIterator: # @param root, a binary search tree's root node - def __init__(self, stack): + def __init__(self, stack, child1, child2): self.stack = list(stack) self.cur = self.stack.pop() + self.child1 = child1 + self.child2 = child2 # @return an integer, the next number def next(self): node = None - if self.cur and self.cur.right: - self.stack.append(self.cur) - node = self.cur.right - while node.left: - self.stack.append(node) - node = node.left - elif self.stack: - prev = self.cur - node = self.stack.pop() - while node: - if node.left is prev: - break - else: - prev = node - node = self.stack.pop() if self.stack else None - self.cur = node - return node.val if node else float("inf") - - # @return an integer, the previous number - def prev(self): - node = None - if self.cur and self.cur.left: + if self.cur and self.child1(self.cur): self.stack.append(self.cur) - node = self.cur.left - while node.right: + node = self.child1(self.cur) + while self.child2(node): self.stack.append(node) - node = node.right + node = self.child2(node) elif self.stack: prev = self.cur node = self.stack.pop() while node: - if node.right is prev: + if self.child2(node) is prev: break else: prev = node node = self.stack.pop() if self.stack else None self.cur = node - return node.val if node else float("-inf") + return node From 4e48d624420dd5b899f6801c0560dbfddc94cb05 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 10:01:25 +0800 Subject: [PATCH 0763/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 0e8240c7a..b70aacb12 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -67,45 +67,45 @@ def closestKValues(self, root, target, k): :type k: int :rtype: List[int] """ + # Build the stack to the closet node. stack = [] - self.closestValue(root, target, stack) - result = [stack[-1].val] + node = self.closestValue(root, target, stack) + result = [node.val] # The forward or backward iterator. backward = lambda node: node.left forward = lambda node: node.right - smaller_it, larger_it = BSTIterator(stack, backward, forward), BSTIterator(stack, forward, backward) - node = smaller_it.next() - smaller = node.val if node else float("-inf") - node = larger_it.next() - larger = node.val if node else float("inf") - while len(result) < k: + smaller_node, larger_node = smaller_it.next(), larger_it.next() + + # Get the closest k values by advancing the iterators of the stacks. + for _ in xrange(k - 1): + smaller = smaller_node.val if smaller_node else float("-inf") + larger = larger_node.val if larger_node else float("inf") if abs(smaller - target) < abs(larger - target): result.append(smaller) - node = smaller_it.next() - smaller = node.val if node else float("-inf") + smaller_node = smaller_it.next() else: result.append(larger) - node = larger_it.next() - larger = node.val if node else float("inf") + larger_node = larger_it.next() return result def closestValue(self, root, target, stack): gap = float("inf") - closet = float("inf") + closet = None while root: stack.append(root) if abs(root.val - target) < gap: gap = abs(root.val - target) closet = root if target == root.val: - return + break else: root = root.left if target < root.val else root.right while stack and stack[-1] != closet: stack.pop() + return closet class BSTIterator: # @param root, a binary search tree's root node @@ -115,7 +115,7 @@ def __init__(self, stack, child1, child2): self.child1 = child1 self.child2 = child2 - # @return an integer, the next number + # @return an integer, the next node def next(self): node = None if self.cur and self.child1(self.cur): From 80c1076b76aa3aa962dd2214deee26f15e171a16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 10:05:26 +0800 Subject: [PATCH 0764/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index b70aacb12..de9719ff2 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -67,7 +67,7 @@ def closestKValues(self, root, target, k): :type k: int :rtype: List[int] """ - # Build the stack to the closet node. + # Build the stack to the closest node. stack = [] node = self.closestValue(root, target, stack) result = [node.val] @@ -92,20 +92,20 @@ def closestKValues(self, root, target, k): def closestValue(self, root, target, stack): gap = float("inf") - closet = None + closest = None while root: stack.append(root) if abs(root.val - target) < gap: gap = abs(root.val - target) - closet = root + closest = root if target == root.val: break else: root = root.left if target < root.val else root.right - while stack and stack[-1] != closet: + while stack and stack[-1] != closest: stack.pop() - return closet + return closest class BSTIterator: # @param root, a binary search tree's root node From 7f16e05eeaf05513b5a6c16457786ff9177ef302 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 10:05:50 +0800 Subject: [PATCH 0765/1939] Update closest-binary-search-tree-value.py --- Python/closest-binary-search-tree-value.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/closest-binary-search-tree-value.py b/Python/closest-binary-search-tree-value.py index 615361c20..15d5a9cfc 100644 --- a/Python/closest-binary-search-tree-value.py +++ b/Python/closest-binary-search-tree-value.py @@ -16,15 +16,15 @@ def closestValue(self, root, target): :rtype: int """ gap = float("inf") - closet = float("inf") + closest = float("inf") while root: if abs(root.val - target) < gap: gap = abs(root.val - target) - closet = root + closest = root if target == root.val: break elif target < root.val: root = root.left else: root = root.right - return closet.val + return closest.val From 8737bc136705ca89ef9c2e1b5a9a075bec06d28c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 10:13:34 +0800 Subject: [PATCH 0766/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 95 ++++++++----------- 1 file changed, 41 insertions(+), 54 deletions(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index de9719ff2..dd1189f96 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -67,71 +67,58 @@ def closestKValues(self, root, target, k): :type k: int :rtype: List[int] """ - # Build the stack to the closest node. + # Build the stack to the closet node. stack = [] - node = self.closestValue(root, target, stack) - result = [node.val] + while root: + stack.append(root) + root = root.left if target < root.val else root.right + dist = lambda node: abs(node.val - target) if node else float("inf") + stack = stack[:stack.index(min(stack, key=dist))+1] # The forward or backward iterator. backward = lambda node: node.left forward = lambda node: node.right - smaller_it, larger_it = BSTIterator(stack, backward, forward), BSTIterator(stack, forward, backward) + smaller_it = self.BSTIterator(stack, backward, forward) + larger_it = self.BSTIterator(stack, forward, backward) smaller_node, larger_node = smaller_it.next(), larger_it.next() # Get the closest k values by advancing the iterators of the stacks. + result = [stack[-1].val] for _ in xrange(k - 1): - smaller = smaller_node.val if smaller_node else float("-inf") - larger = larger_node.val if larger_node else float("inf") - if abs(smaller - target) < abs(larger - target): - result.append(smaller) + if dist(smaller_node) < dist(larger_node): + result.append(smaller_node.val) smaller_node = smaller_it.next() else: - result.append(larger) + result.append(larger_node.val) larger_node = larger_it.next() return result + + class BSTIterator: + # @param root, a binary search tree's root node + def __init__(self, stack, child1, child2): + self.stack = list(stack) + self.cur = self.stack.pop() + self.child1 = child1 + self.child2 = child2 + + # @return an integer, the next node + def next(self): + node = None + if self.cur and self.child1(self.cur): + self.stack.append(self.cur) + node = self.child1(self.cur) + while self.child2(node): + self.stack.append(node) + node = self.child2(node) + elif self.stack: + prev = self.cur + node = self.stack.pop() + while node: + if self.child2(node) is prev: + break + else: + prev = node + node = self.stack.pop() if self.stack else None + self.cur = node + return node - def closestValue(self, root, target, stack): - gap = float("inf") - closest = None - while root: - stack.append(root) - if abs(root.val - target) < gap: - gap = abs(root.val - target) - closest = root - if target == root.val: - break - else: - root = root.left if target < root.val else root.right - - while stack and stack[-1] != closest: - stack.pop() - return closest - -class BSTIterator: - # @param root, a binary search tree's root node - def __init__(self, stack, child1, child2): - self.stack = list(stack) - self.cur = self.stack.pop() - self.child1 = child1 - self.child2 = child2 - - # @return an integer, the next node - def next(self): - node = None - if self.cur and self.child1(self.cur): - self.stack.append(self.cur) - node = self.child1(self.cur) - while self.child2(node): - self.stack.append(node) - node = self.child2(node) - elif self.stack: - prev = self.cur - node = self.stack.pop() - while node: - if self.child2(node) is prev: - break - else: - prev = node - node = self.stack.pop() if self.stack else None - self.cur = node - return node From bf5c148307215fc0058c7f247795e8f2ff68cf56 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 10:17:21 +0800 Subject: [PATCH 0767/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 63 ++++++++++--------- 1 file changed, 32 insertions(+), 31 deletions(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index dd1189f96..724d3d2d5 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -67,6 +67,36 @@ def closestKValues(self, root, target, k): :type k: int :rtype: List[int] """ + # Helper class to make a stack to the next node. + class BSTIterator: + # @param root, a binary search tree's root node + def __init__(self, stack, child1, child2): + self.stack = list(stack) + self.cur = self.stack.pop() + self.child1 = child1 + self.child2 = child2 + + # @return an integer, the next node + def next(self): + node = None + if self.cur and self.child1(self.cur): + self.stack.append(self.cur) + node = self.child1(self.cur) + while self.child2(node): + self.stack.append(node) + node = self.child2(node) + elif self.stack: + prev = self.cur + node = self.stack.pop() + while node: + if self.child2(node) is prev: + break + else: + prev = node + node = self.stack.pop() if self.stack else None + self.cur = node + return node + # Build the stack to the closet node. stack = [] while root: @@ -78,8 +108,7 @@ def closestKValues(self, root, target, k): # The forward or backward iterator. backward = lambda node: node.left forward = lambda node: node.right - smaller_it = self.BSTIterator(stack, backward, forward) - larger_it = self.BSTIterator(stack, forward, backward) + smaller_it, larger_it = BSTIterator(stack, backward, forward), BSTIterator(stack, forward, backward) smaller_node, larger_node = smaller_it.next(), larger_it.next() # Get the closest k values by advancing the iterators of the stacks. @@ -92,33 +121,5 @@ def closestKValues(self, root, target, k): result.append(larger_node.val) larger_node = larger_it.next() return result - - class BSTIterator: - # @param root, a binary search tree's root node - def __init__(self, stack, child1, child2): - self.stack = list(stack) - self.cur = self.stack.pop() - self.child1 = child1 - self.child2 = child2 - - # @return an integer, the next node - def next(self): - node = None - if self.cur and self.child1(self.cur): - self.stack.append(self.cur) - node = self.child1(self.cur) - while self.child2(node): - self.stack.append(node) - node = self.child2(node) - elif self.stack: - prev = self.cur - node = self.stack.pop() - while node: - if self.child2(node) is prev: - break - else: - prev = node - node = self.stack.pop() if self.stack else None - self.cur = node - return node + From d2aa65d2f0f606143fef221c5e3613575fd68d8b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 10:55:54 +0800 Subject: [PATCH 0768/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e518297b3..df5716897 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-29), there are `255` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-08-31), there are `256` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `272` questions. +Here is the classification of all `273` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -121,6 +121,7 @@ Shell 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` 271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +273| [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [Python](./Python/integer-to-english-words.py) | _O(logn)_ | _O(1)_ | Medium | | --- From 4557dd848dfccee664d4cca4bc9dc18c2ceda78a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 10:57:40 +0800 Subject: [PATCH 0769/1939] Create integer-to-english-words.py --- Python/integer-to-english-words.py | 52 ++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/integer-to-english-words.py diff --git a/Python/integer-to-english-words.py b/Python/integer-to-english-words.py new file mode 100644 index 000000000..f84d46bd2 --- /dev/null +++ b/Python/integer-to-english-words.py @@ -0,0 +1,52 @@ +# Time: O(logn), n is the value of the integer +# Space: O(1) +# +# Convert a non-negative integer to its english words representation. +# Given input is guaranteed to be less than 2^31 - 1. +# +# For example, +# 123 -> "One Hundred Twenty Three" +# 12345 -> "Twelve Thousand Three Hundred Forty Five" +# 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" +# + +class Solution(object): + def numberToWords(self, num): + """ + :type num: int + :rtype: str + """ + if num == 0: + return "Zero" + + lookup = {0: "Zero", 1:"One", 2: "Two", 3: "Three", 4: "Four", \ + 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", \ + 10 : "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", \ + 15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen", \ + 20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", \ + 70: "Seventy", 80: "Eighty", 90: "Ninety"} + unit = ["", "Thousand", "Million", "Billion"] + + res, i = [], 0 + while num != 0: + cur = num % 1000 + if num % 1000: + res.append(self.threedigits(cur, lookup, unit[i])) + num //= 1000 + i += 1 + return " ".join(res[::-1]) + + def threedigits(self, num, lookup, unit): + res = [] + if num / 100 != 0: + res = [lookup[num / 100] + " " + "Hundred"] + if num % 100: + res.append(self.twodigits(num % 100, lookup)) + if unit != "": + res.append(unit) + return " ".join(res) + + def twodigits(self, num, lookup): + if num in lookup: + return str(lookup[num]) + return " ".join([lookup[(num / 10) * 10], lookup[num % 10]]) From a4aafb6f224478a10bc245cf8822ffc8b6356a50 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 10:59:11 +0800 Subject: [PATCH 0770/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 724d3d2d5..842840bf4 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -16,7 +16,6 @@ def closestKValues(self, root, target, k): :type k: int :rtype: List[int] """ - # Helper to make a stack to the next node. def nextNode(stack, child1, child2): if stack: From bb56d9e9fa7009eb2baf7ea4ac827c5bba64edd0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 16:18:42 +0800 Subject: [PATCH 0771/1939] Update integer-to-english-words.py --- Python/integer-to-english-words.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/integer-to-english-words.py b/Python/integer-to-english-words.py index f84d46bd2..fc8fa9c3e 100644 --- a/Python/integer-to-english-words.py +++ b/Python/integer-to-english-words.py @@ -48,5 +48,5 @@ def threedigits(self, num, lookup, unit): def twodigits(self, num, lookup): if num in lookup: - return str(lookup[num]) + return lookup[num] return " ".join([lookup[(num / 10) * 10], lookup[num % 10]]) From 23341321bc3d51055a4c64512d5f653e8068d61d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 20:30:10 +0800 Subject: [PATCH 0772/1939] Update integer-to-english-words.py --- Python/integer-to-english-words.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/integer-to-english-words.py b/Python/integer-to-english-words.py index fc8fa9c3e..7e93304d2 100644 --- a/Python/integer-to-english-words.py +++ b/Python/integer-to-english-words.py @@ -21,7 +21,7 @@ def numberToWords(self, num): lookup = {0: "Zero", 1:"One", 2: "Two", 3: "Three", 4: "Four", \ 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", \ - 10 : "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", \ + 10: "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", \ 15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen", \ 20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", \ 70: "Seventy", 80: "Eighty", 90: "Ninety"} From f213f8f43874a0ccdf78696115b2a8a15c6f38d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 20:40:38 +0800 Subject: [PATCH 0773/1939] Update integer-to-english-words.py --- Python/integer-to-english-words.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/integer-to-english-words.py b/Python/integer-to-english-words.py index 7e93304d2..6963de2ed 100644 --- a/Python/integer-to-english-words.py +++ b/Python/integer-to-english-words.py @@ -31,22 +31,22 @@ def numberToWords(self, num): while num != 0: cur = num % 1000 if num % 1000: - res.append(self.threedigits(cur, lookup, unit[i])) + res.append(self.threeDigits(cur, lookup, unit[i])) num //= 1000 i += 1 return " ".join(res[::-1]) - def threedigits(self, num, lookup, unit): + def threeDigits(self, num, lookup, unit): res = [] if num / 100 != 0: res = [lookup[num / 100] + " " + "Hundred"] if num % 100: - res.append(self.twodigits(num % 100, lookup)) + res.append(self.twoDigits(num % 100, lookup)) if unit != "": res.append(unit) return " ".join(res) - def twodigits(self, num, lookup): + def twoDigits(self, num, lookup): if num in lookup: return lookup[num] return " ".join([lookup[(num / 10) * 10], lookup[num % 10]]) From 3e6bee16ad536e0a50c1b12967b9a513d0903158 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 21:14:30 +0800 Subject: [PATCH 0774/1939] Update integer-to-english-words.py --- Python/integer-to-english-words.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/integer-to-english-words.py b/Python/integer-to-english-words.py index 6963de2ed..8a7c7ebcc 100644 --- a/Python/integer-to-english-words.py +++ b/Python/integer-to-english-words.py @@ -28,7 +28,7 @@ def numberToWords(self, num): unit = ["", "Thousand", "Million", "Billion"] res, i = [], 0 - while num != 0: + while num: cur = num % 1000 if num % 1000: res.append(self.threeDigits(cur, lookup, unit[i])) @@ -38,7 +38,7 @@ def numberToWords(self, num): def threeDigits(self, num, lookup, unit): res = [] - if num / 100 != 0: + if num / 100: res = [lookup[num / 100] + " " + "Hundred"] if num % 100: res.append(self.twoDigits(num % 100, lookup)) From 040e9207381176bfe0a608fbf1b943c799c56ab5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 21:16:14 +0800 Subject: [PATCH 0775/1939] Update integer-to-english-words.py --- Python/integer-to-english-words.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/integer-to-english-words.py b/Python/integer-to-english-words.py index 8a7c7ebcc..f5b14089b 100644 --- a/Python/integer-to-english-words.py +++ b/Python/integer-to-english-words.py @@ -49,4 +49,4 @@ def threeDigits(self, num, lookup, unit): def twoDigits(self, num, lookup): if num in lookup: return lookup[num] - return " ".join([lookup[(num / 10) * 10], lookup[num % 10]]) + return lookup[(num / 10) * 10] + " " + lookup[num % 10] From 7a8e641e7adb21cde7c7b3dc7a59c6589943e54b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 21:20:05 +0800 Subject: [PATCH 0776/1939] Create integer-to-english-words.cpp --- C++/integer-to-english-words.cpp | 62 ++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 C++/integer-to-english-words.cpp diff --git a/C++/integer-to-english-words.cpp b/C++/integer-to-english-words.cpp new file mode 100644 index 000000000..64613fc11 --- /dev/null +++ b/C++/integer-to-english-words.cpp @@ -0,0 +1,62 @@ +// Time: O(logn), n is the value of the integer +// Space: O(1) + +class Solution { +public: + string numberToWords(int num) { + if (num == 0) { + return "Zero"; + } + const unordered_map lookup = {{0, "Zero"}, {1, "One"}, {2, "Two"}, + {3, "Three"}, {4, "Four"}, {5, "Five"}, + {6, "Six"}, {7, "Seven"}, {8, "Eight"}, + {9, "Nine"}, {10, "Ten"}, {11, "Eleven"}, + {12, "Twelve"}, {13, "Thirteen"}, {14, "Fourteen"}, + {15, "Fifteen"}, {16, "Sixteen"}, {17, "Seventeen"}, + {18, "Eighteen"}, {19, "Nineteen"}, {20, "Twenty"}, + {30, "Thirty"}, {40, "Forty"}, {50, "Fifty"}, + {60, "Sixty"}, {70, "Seventy"}, {80, "Eighty"}, + {90, "Ninety"}}; + const vector unit{"", "Thousand", "Million", "Billion"}; + + vector res; + int i = 0; + while (num) { + const int cur = num % 1000; + if (num % 1000) { + res.emplace_back(threeDigits(cur, lookup, unit[i])); + } + num /= 1000; + ++i; + } + reverse(res.begin(), res.end()); + return join(res, " "); + } + + string join(const vector& strings, const string& delim) { + ostringstream imploded; + copy(strings.begin(), prev(strings.end()), ostream_iterator(imploded, delim.c_str())); + return imploded.str() + *prev(strings.end()); + } + + string threeDigits(const int& num, const unordered_map& lookup, const string& unit) { + vector res; + if (num / 100) { + res.emplace_back(lookup.find(num / 100)->second + " " + "Hundred"); + } + if (num % 100) { + res.emplace_back(twoDigits(num % 100, lookup)); + } + if (!unit.empty()) { + res.emplace_back(unit); + } + return join(res, " "); + } + + string twoDigits(const int& num, const unordered_map& lookup) { + if (lookup.find(num) != lookup.end()) { + return lookup.find(num)->second; + } + return lookup.find((num / 10) * 10)->second + " " + lookup.find(num % 10)->second; + } +}; From 245e1bcc5addd6b20de0a55f3ee8d4640c0edcb2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 22:04:38 +0800 Subject: [PATCH 0777/1939] Create closest-binary-search-tree-value-ii.cpp --- C++/closest-binary-search-tree-value-ii.cpp | 71 +++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 C++/closest-binary-search-tree-value-ii.cpp diff --git a/C++/closest-binary-search-tree-value-ii.cpp b/C++/closest-binary-search-tree-value-ii.cpp new file mode 100644 index 000000000..1e97951c2 --- /dev/null +++ b/C++/closest-binary-search-tree-value-ii.cpp @@ -0,0 +1,71 @@ +// Time: O(h + k) +// Space: O(h) + +/** + * 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: + vector closestKValues(TreeNode* root, double target, int k) { + // The forward or backward iterator. + const auto backward = [](const vector& s) { return s.back()->left; }; + const auto forward = [](const vector& s) { return s.back()->right; }; + const auto dist = [target](const TreeNode* a, const TreeNode* b) { + return abs(a->val - target) < abs(b->val - target); + }; + + // Build the stack to the closest node. + vector s; + while (root) { + s.emplace_back(root); + root = target < root->val ? root->left : root->right; + } + + // Get the stack to the next smaller node. + vector forward_stack(s.begin(), next(min_element(s.begin(), s.end(), dist))); + vector backward_stack(forward_stack); + nextNode(backward_stack, backward, forward); + + // Get the closest k values by advancing the iterators of the stacks. + vector result; + for (int i = 0; i < k; ++i) { + if (backward_stack.empty() || + !forward_stack.empty() && dist(forward_stack.back(), backward_stack.back())) { + result.emplace_back(forward_stack.back()->val); + nextNode(forward_stack, forward, backward); + } else if (forward_stack.empty() || + !forward_stack.empty() && !dist(forward_stack.back(), backward_stack.back())) { + result.emplace_back(backward_stack.back()->val); + nextNode(backward_stack, backward, forward); + } + } + return result; + } + + // Helper to make a stack to the next node. + void nextNode(vector& s, + const function&)>& child1, + const function&)>& child2) { + if (!s.empty()) { + if (child2(s)) { + s.emplace_back(child2(s)); + while (child1(s)) { + s.emplace_back(child1(s)); + } + } else { + auto child = s.back(); + s.pop_back(); + while (!s.empty() && child == child2(s)) { + child = s.back(); + s.pop_back(); + } + } + } + } +}; From 155e7d7d8b2c3fddb78c15cc3bceb7268962dda2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 22:07:22 +0800 Subject: [PATCH 0778/1939] Update closest-binary-search-tree-value-ii.cpp --- C++/closest-binary-search-tree-value-ii.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/closest-binary-search-tree-value-ii.cpp b/C++/closest-binary-search-tree-value-ii.cpp index 1e97951c2..b9a8d473b 100644 --- a/C++/closest-binary-search-tree-value-ii.cpp +++ b/C++/closest-binary-search-tree-value-ii.cpp @@ -16,7 +16,7 @@ class Solution { // The forward or backward iterator. const auto backward = [](const vector& s) { return s.back()->left; }; const auto forward = [](const vector& s) { return s.back()->right; }; - const auto dist = [target](const TreeNode* a, const TreeNode* b) { + const auto closest = [target](const TreeNode* a, const TreeNode* b) { return abs(a->val - target) < abs(b->val - target); }; @@ -28,7 +28,7 @@ class Solution { } // Get the stack to the next smaller node. - vector forward_stack(s.begin(), next(min_element(s.begin(), s.end(), dist))); + vector forward_stack(s.begin(), next(min_element(s.begin(), s.end(), closest))); vector backward_stack(forward_stack); nextNode(backward_stack, backward, forward); @@ -36,11 +36,11 @@ class Solution { vector result; for (int i = 0; i < k; ++i) { if (backward_stack.empty() || - !forward_stack.empty() && dist(forward_stack.back(), backward_stack.back())) { + !forward_stack.empty() && closest(forward_stack.back(), backward_stack.back())) { result.emplace_back(forward_stack.back()->val); nextNode(forward_stack, forward, backward); } else if (forward_stack.empty() || - !forward_stack.empty() && !dist(forward_stack.back(), backward_stack.back())) { + !forward_stack.empty() && !closest(forward_stack.back(), backward_stack.back())) { result.emplace_back(backward_stack.back()->val); nextNode(backward_stack, backward, forward); } From 1695fa96c1daa1305ba39e07471147a5efd84052 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 22:07:59 +0800 Subject: [PATCH 0779/1939] Update closest-binary-search-tree-value-ii.cpp --- C++/closest-binary-search-tree-value-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/closest-binary-search-tree-value-ii.cpp b/C++/closest-binary-search-tree-value-ii.cpp index b9a8d473b..cef601435 100644 --- a/C++/closest-binary-search-tree-value-ii.cpp +++ b/C++/closest-binary-search-tree-value-ii.cpp @@ -17,8 +17,8 @@ class Solution { const auto backward = [](const vector& s) { return s.back()->left; }; const auto forward = [](const vector& s) { return s.back()->right; }; const auto closest = [target](const TreeNode* a, const TreeNode* b) { - return abs(a->val - target) < abs(b->val - target); - }; + return abs(a->val - target) < abs(b->val - target); + }; // Build the stack to the closest node. vector s; From 5b3c7e572e86e2f76c5734b98c895c17178767f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Aug 2015 22:27:06 +0800 Subject: [PATCH 0780/1939] Update closest-binary-search-tree-value-ii.cpp --- C++/closest-binary-search-tree-value-ii.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/C++/closest-binary-search-tree-value-ii.cpp b/C++/closest-binary-search-tree-value-ii.cpp index cef601435..21a7e5d8c 100644 --- a/C++/closest-binary-search-tree-value-ii.cpp +++ b/C++/closest-binary-search-tree-value-ii.cpp @@ -16,9 +16,9 @@ class Solution { // The forward or backward iterator. const auto backward = [](const vector& s) { return s.back()->left; }; const auto forward = [](const vector& s) { return s.back()->right; }; - const auto closest = [target](const TreeNode* a, const TreeNode* b) { + const auto closest = [&target](const TreeNode* a, const TreeNode* b) { return abs(a->val - target) < abs(b->val - target); - }; + }; // Build the stack to the closest node. vector s; @@ -49,9 +49,8 @@ class Solution { } // Helper to make a stack to the next node. - void nextNode(vector& s, - const function&)>& child1, - const function&)>& child2) { + template + void nextNode(vector& s, const T& child1, const U& child2) { if (!s.empty()) { if (child2(s)) { s.emplace_back(child2(s)); From 1e3c53712aaa3e66479c46f41f44fe4e0d5ebd67 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Sep 2015 09:55:47 +0800 Subject: [PATCH 0781/1939] Update ugly-number-ii.py --- Python/ugly-number-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/ugly-number-ii.py b/Python/ugly-number-ii.py index 6ce4c905c..7afc95156 100644 --- a/Python/ugly-number-ii.py +++ b/Python/ugly-number-ii.py @@ -27,7 +27,7 @@ def nthUglyNumber(self, n): heap = [] heapq.heappush(heap, 1) - for i in xrange(n): + for _ in xrange(n): ugly_number = heapq.heappop(heap) if ugly_number % 2 == 0: heapq.heappush(heap, ugly_number * 2) From 0b4090c511443f29f814a6c76e8c9afda8ad89b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Sep 2015 13:07:33 +0800 Subject: [PATCH 0782/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index df5716897..1eaab15dc 100644 --- a/README.md +++ b/README.md @@ -120,8 +120,8 @@ Shell 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` -271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 📖 | -273| [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [Python](./Python/integer-to-english-words.py) | _O(logn)_ | _O(1)_ | Medium | | +271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [C++](./C++/encode-and-decode-strings.cpp) [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +273| [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [C++](./C++/integer-to-english-words.cpp) [Python](./Python/integer-to-english-words.py) | _O(logn)_ | _O(1)_ | Medium | | --- From 7286d401cde0e06312a8db0602ee24a0d2d39c68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Sep 2015 13:12:37 +0800 Subject: [PATCH 0783/1939] Update integer-to-english-words.cpp --- C++/integer-to-english-words.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/integer-to-english-words.cpp b/C++/integer-to-english-words.cpp index 64613fc11..fef662047 100644 --- a/C++/integer-to-english-words.cpp +++ b/C++/integer-to-english-words.cpp @@ -34,6 +34,9 @@ class Solution { } string join(const vector& strings, const string& delim) { + if (strings.empty()) { + return ""; + } ostringstream imploded; copy(strings.begin(), prev(strings.end()), ostream_iterator(imploded, delim.c_str())); return imploded.str() + *prev(strings.end()); From 8075181c30436da8ba64a0456419115a0f67bbc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Sep 2015 15:08:28 +0800 Subject: [PATCH 0784/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1eaab15dc..5281cec51 100644 --- a/README.md +++ b/README.md @@ -353,7 +353,7 @@ Shell 207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | -269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Medium |📖| Topological Sort, BFS, DFS | +269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Hard |📖| Topological Sort, BFS, DFS | --- From 699db5989268159e2a1f1661e9c98c1ab03a0cb9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Sep 2015 08:48:05 +0800 Subject: [PATCH 0785/1939] Update integer-to-english-words.py --- Python/integer-to-english-words.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Python/integer-to-english-words.py b/Python/integer-to-english-words.py index f5b14089b..8525612f5 100644 --- a/Python/integer-to-english-words.py +++ b/Python/integer-to-english-words.py @@ -9,6 +9,18 @@ # 12345 -> "Twelve Thousand Three Hundred Forty Five" # 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" # +# Hint: +# +# 1. Did you see a pattern in dividing the number into chunk of words? +# For example, 123 and 123000. +# +# 2. Group the number by thousands (3 digits). You can write a helper +# function that takes a number less than 1000 and convert just that chunk to words. +# +# 3. There are many edge cases. What are some good test cases? +# Does your code work with input such as 0? Or 1000010? +# (middle chunk is zero and should not be printed out) +# class Solution(object): def numberToWords(self, num): From c667f8cb748b2e13e3abcfd36934b88487e55ece Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Sep 2015 09:47:12 +0800 Subject: [PATCH 0786/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5281cec51..130a5d5e1 100644 --- a/README.md +++ b/README.md @@ -159,7 +159,7 @@ Shell 227| [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | [C++](./C++/basic-calculator-ii.cpp) [Python](./Python/basic-calculator-ii.py) | _O(n)_| _O(n)_| Medium || 232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| Easy | EPI, LintCode | 255| [Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/verify-preorder-sequence-in-binary-search-tree.cpp) [Python](./Python/verify-preorder-sequence-in-binary-search-tree.py) | _O(n)_| _O(1)_| Medium |📖|| -272| [Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(k)_| Hard |📖|| +272| [Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(h)_| Hard |📖|| --- From 32e729afc893c19b4b4a289ad4fc9f931dfc27e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Sep 2015 10:44:14 +0800 Subject: [PATCH 0787/1939] Update regular-expression-matching.py --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 194fd2f25..14b8fb53b 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -40,7 +40,7 @@ def isMatch(self, s, p): if p[j-1] != '*': result[i % k][j] = result[(i-1) % k][j-1] and (s[i-1] == p[j-1] or p[j-1] == '.') else: - result[i % k][j] = result[i % k][j-2] or (result[(i-1) % k][j] and (s[i-1] == p[j-2] or p[j-2]=='.')) + result[i % k][j] = result[i % k][j-2] or (result[(i-1) % k][j] and (s[i-1] == p[j-2] or p[j-2] == '.')) return result[len(s) % k][len(p)] From 41de0630584e08f91e7bba61f82061f2f6ef3195 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Sep 2015 10:44:59 +0800 Subject: [PATCH 0788/1939] Update regular-expression-matching.py --- Python/regular-expression-matching.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 14b8fb53b..3101c52c7 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -62,7 +62,7 @@ def isMatch(self, s, p): if p[j-1] != '*': result[i][j] = result[i-1][j-1] and (s[i-1] == p[j-1] or p[j-1] == '.') else: - result[i][j] = result[i][j-2] or (result[i-1][j] and (s[i-1] == p[j-2] or p[j-2]=='.')) + result[i][j] = result[i][j-2] or (result[i-1][j] and (s[i-1] == p[j-2] or p[j-2] == '.')) return result[len(s)][len(p)] From ffe0373b619b42abae17e18874fca9be665aeeb3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Sep 2015 14:04:36 +0800 Subject: [PATCH 0789/1939] Update rotate-list.py --- Python/rotate-list.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/rotate-list.py b/Python/rotate-list.py index 7d33a6c84..14b7b2591 100644 --- a/Python/rotate-list.py +++ b/Python/rotate-list.py @@ -33,7 +33,7 @@ def rotateRight(self, head, k): cur.next = head cur = head - shift = len - k % len - 1 + shift = len - k%len - 1 while shift > 0: cur = cur.next shift -= 1 @@ -49,4 +49,4 @@ def rotateRight(self, head, k): head.next.next = ListNode(3) head.next.next.next = ListNode(4) head.next.next.next.next = ListNode(5) - print Solution().rotateRight(head, 2) \ No newline at end of file + print Solution().rotateRight(head, 2) From 9d745722bbbfa2bc7f6942d3bf568e7105e0fed6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Sep 2015 22:26:17 +0800 Subject: [PATCH 0790/1939] Update missing-number.cpp --- C++/missing-number.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/C++/missing-number.cpp b/C++/missing-number.cpp index d15306e75..0f9ede558 100644 --- a/C++/missing-number.cpp +++ b/C++/missing-number.cpp @@ -11,3 +11,15 @@ class Solution { return num; } }; + +// Time: O(n) +// Space: O(n) +class Solution2 { +public: + int missingNumber(vector& nums) { + vector expected(nums.size()); + iota(expected.begin(), expected.end(), 1); // Costs extra space O(n) + return accumulate (nums.cbegin(), nums.cend(), 0, bit_xor()) ^ + accumulate (expected.cbegin(), expected.cend(), 0, bit_xor()); + } +}; From 34914994409a227bdb1e60889af2022c12a46001 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Sep 2015 22:29:40 +0800 Subject: [PATCH 0791/1939] Update closest-binary-search-tree-value-ii.cpp --- C++/closest-binary-search-tree-value-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/closest-binary-search-tree-value-ii.cpp b/C++/closest-binary-search-tree-value-ii.cpp index 21a7e5d8c..6885c709f 100644 --- a/C++/closest-binary-search-tree-value-ii.cpp +++ b/C++/closest-binary-search-tree-value-ii.cpp @@ -28,7 +28,7 @@ class Solution { } // Get the stack to the next smaller node. - vector forward_stack(s.begin(), next(min_element(s.begin(), s.end(), closest))); + vector forward_stack(s.cbegin(), next(min_element(s.cbegin(), s.cend(), closest))); vector backward_stack(forward_stack); nextNode(backward_stack, backward, forward); From 2ca73e508cca2434841b014e49ba9e34fdf76638 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 00:19:04 +0800 Subject: [PATCH 0792/1939] Update single-number-iii.cpp --- C++/single-number-iii.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/C++/single-number-iii.cpp b/C++/single-number-iii.cpp index 5d510c144..eb5e6d336 100644 --- a/C++/single-number-iii.cpp +++ b/C++/single-number-iii.cpp @@ -2,6 +2,25 @@ // Space: O(1) class Solution { +public: + vector singleNumber(vector& nums) { + // Xor all the elements to get x ^ y. + int x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor()); + // Get the last bit where 1 occurs. + x_xor_y &= -x_xor_y; + + // Get the subset of A where the number has the bit. + // The subset only contains one of the two integers, call it x. + // Xor all the elemets in the subset to get x. + vector result(2, 0); + for (const auto& i : nums) { + result[!(i & x_xor_y)] ^= i; + } + return result; + } +}; + +class Solution2 { public: vector singleNumber(vector& nums) { // Xor all the elements to get x ^ y. From a67b79c8bf6f575947969215aa8fcaadfdad59bf Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 00:19:26 +0800 Subject: [PATCH 0793/1939] Update single-number-iii.cpp --- C++/single-number-iii.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/single-number-iii.cpp b/C++/single-number-iii.cpp index eb5e6d336..5c6275a9e 100644 --- a/C++/single-number-iii.cpp +++ b/C++/single-number-iii.cpp @@ -6,6 +6,7 @@ class Solution { vector singleNumber(vector& nums) { // Xor all the elements to get x ^ y. int x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor()); + // Get the last bit where 1 occurs. x_xor_y &= -x_xor_y; From 61250cfecdfd84849400bc9d94b557b21eace118 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 00:30:37 +0800 Subject: [PATCH 0794/1939] Update single-number-iii.py --- Python/single-number-iii.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Python/single-number-iii.py b/Python/single-number-iii.py index 163bc9f7e..35366ff97 100644 --- a/Python/single-number-iii.py +++ b/Python/single-number-iii.py @@ -17,6 +17,17 @@ # class Solution: + # @param {integer[]} nums + # @return {integer[]} + def singleNumber(self, nums): + x_xor_y = reduce(operator.xor, nums) + x_xor_y &= -x_xor_y + result = [0, 0] + for i in nums: + result[not i & x_xor_y] ^= i + return result + +class Solution2: # @param {integer[]} nums # @return {integer[]} def singleNumber(self, nums): @@ -31,4 +42,4 @@ def singleNumber(self, nums): if i & bit: x ^= i - return [x, x_xor_y ^ x] + return [x, x ^ x_xor_y] From 4520c2fd719ad4b6495b9d02e51e30939a011091 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 00:32:31 +0800 Subject: [PATCH 0795/1939] Update single-number-iii.py --- Python/single-number-iii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/single-number-iii.py b/Python/single-number-iii.py index 35366ff97..6c74b36ad 100644 --- a/Python/single-number-iii.py +++ b/Python/single-number-iii.py @@ -24,7 +24,7 @@ def singleNumber(self, nums): x_xor_y &= -x_xor_y result = [0, 0] for i in nums: - result[not i & x_xor_y] ^= i + result[bool(i & x_xor_y)] ^= i return result class Solution2: From 004ee7c4241b6e1eb4de7c9c66a43146b2dff19e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 00:34:04 +0800 Subject: [PATCH 0796/1939] Update single-number-iii.cpp --- C++/single-number-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/single-number-iii.cpp b/C++/single-number-iii.cpp index 5c6275a9e..9993bfe70 100644 --- a/C++/single-number-iii.cpp +++ b/C++/single-number-iii.cpp @@ -15,7 +15,7 @@ class Solution { // Xor all the elemets in the subset to get x. vector result(2, 0); for (const auto& i : nums) { - result[!(i & x_xor_y)] ^= i; + result[static_cast(i & x_xor_y)] ^= i; } return result; } From 56a7c5129c01956279abc4917c7b5aca5d2027c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 00:45:38 +0800 Subject: [PATCH 0797/1939] Update single-number-iii.py --- Python/single-number-iii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/single-number-iii.py b/Python/single-number-iii.py index 6c74b36ad..c90e79bd2 100644 --- a/Python/single-number-iii.py +++ b/Python/single-number-iii.py @@ -21,10 +21,10 @@ class Solution: # @return {integer[]} def singleNumber(self, nums): x_xor_y = reduce(operator.xor, nums) - x_xor_y &= -x_xor_y + bit = x_xor_y & -x_xor_y result = [0, 0] for i in nums: - result[bool(i & x_xor_y)] ^= i + result[bool(i & bit)] ^= i return result class Solution2: From 5812b6708b6c657bbef34d7fe65b9e4246e4b3b0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 00:46:58 +0800 Subject: [PATCH 0798/1939] Update single-number-iii.cpp --- C++/single-number-iii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/single-number-iii.cpp b/C++/single-number-iii.cpp index 9993bfe70..377be0b66 100644 --- a/C++/single-number-iii.cpp +++ b/C++/single-number-iii.cpp @@ -8,14 +8,14 @@ class Solution { int x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor()); // Get the last bit where 1 occurs. - x_xor_y &= -x_xor_y; + const auto bit = x_xor_y & -x_xor_y; // Get the subset of A where the number has the bit. // The subset only contains one of the two integers, call it x. // Xor all the elemets in the subset to get x. vector result(2, 0); for (const auto& i : nums) { - result[static_cast(i & x_xor_y)] ^= i; + result[static_cast(i & bit)] ^= i; } return result; } From 49772bb03cd8e9df661fb22c574fb446225193ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 00:49:09 +0800 Subject: [PATCH 0799/1939] Update single-number-iii.cpp --- C++/single-number-iii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/single-number-iii.cpp b/C++/single-number-iii.cpp index 377be0b66..b1c617c90 100644 --- a/C++/single-number-iii.cpp +++ b/C++/single-number-iii.cpp @@ -12,7 +12,7 @@ class Solution { // Get the subset of A where the number has the bit. // The subset only contains one of the two integers, call it x. - // Xor all the elemets in the subset to get x. + // Xor all the elements in the subset to get x. vector result(2, 0); for (const auto& i : nums) { result[static_cast(i & bit)] ^= i; @@ -35,7 +35,7 @@ class Solution2 { // Get the subset of A where the number has the bit. // The subset only contains one of the two integers, call it x. - // Xor all the elemets in the subset to get x. + // Xor all the elements in the subset to get x. int x = 0; for (const auto& i : nums) { if (i & bit) { From 49717b87ffadfb1b560c665865eec3970efaf9c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 00:52:05 +0800 Subject: [PATCH 0800/1939] Update single-number-iii.cpp --- C++/single-number-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/single-number-iii.cpp b/C++/single-number-iii.cpp index b1c617c90..db14d9d42 100644 --- a/C++/single-number-iii.cpp +++ b/C++/single-number-iii.cpp @@ -5,7 +5,7 @@ class Solution { public: vector singleNumber(vector& nums) { // Xor all the elements to get x ^ y. - int x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor()); + const auto x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor()); // Get the last bit where 1 occurs. const auto bit = x_xor_y & -x_xor_y; From e3a084b7efcebe45480a25575c9535eb6a147210 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 01:15:44 +0800 Subject: [PATCH 0801/1939] Update single-number-iii.cpp --- C++/single-number-iii.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/C++/single-number-iii.cpp b/C++/single-number-iii.cpp index db14d9d42..4764a1930 100644 --- a/C++/single-number-iii.cpp +++ b/C++/single-number-iii.cpp @@ -7,7 +7,9 @@ class Solution { // Xor all the elements to get x ^ y. const auto x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor()); - // Get the last bit where 1 occurs. + // Get the last bit where 1 occurs by "x & ~(x - 1)" + // Becease -(x - 1) = ~(x - 1) + 1 <=> -x = ~(x - 1) + // So we can also get the last bit where 1 occurs by "x & -x" const auto bit = x_xor_y & -x_xor_y; // Get the subset of A where the number has the bit. From 82a74b8d4ba58f0f90ce934ae620b4bd0dc6d28f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 01:17:07 +0800 Subject: [PATCH 0802/1939] Update single-number-iii.cpp --- C++/single-number-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/single-number-iii.cpp b/C++/single-number-iii.cpp index 4764a1930..02893acac 100644 --- a/C++/single-number-iii.cpp +++ b/C++/single-number-iii.cpp @@ -8,7 +8,7 @@ class Solution { const auto x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor()); // Get the last bit where 1 occurs by "x & ~(x - 1)" - // Becease -(x - 1) = ~(x - 1) + 1 <=> -x = ~(x - 1) + // Because -(x - 1) = ~(x - 1) + 1 <=> -x = ~(x - 1) // So we can also get the last bit where 1 occurs by "x & -x" const auto bit = x_xor_y & -x_xor_y; From e3dab704a37cefffb76c5197f46e7ff69007f2ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 01:24:49 +0800 Subject: [PATCH 0803/1939] Update power-of-two.cpp --- C++/power-of-two.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/C++/power-of-two.cpp b/C++/power-of-two.cpp index 018476ef8..d0261cad9 100644 --- a/C++/power-of-two.cpp +++ b/C++/power-of-two.cpp @@ -7,3 +7,10 @@ class Solution { return n > 0 && (n & (n - 1)) == 0; } }; + +class Solution2 { +public: + bool isPowerOfTwo(int n) { + return n > 0 && (n & ~-n) == 0; + } +}; From c751277bb0e9537ac504a67669244b09aeecdde9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 01:27:29 +0800 Subject: [PATCH 0804/1939] Update power-of-two.py --- Python/power-of-two.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Python/power-of-two.py b/Python/power-of-two.py index 38c738e1e..f0eaac76d 100644 --- a/Python/power-of-two.py +++ b/Python/power-of-two.py @@ -9,3 +9,9 @@ class Solution: # @return {boolean} def isPowerOfTwo(self, n): return n > 0 and (n & (n - 1)) == 0 + +class Solution2: + # @param {integer} n + # @return {boolean} + def isPowerOfTwo(self, n): + return n > 0 and (n & ~-n) == 0 From cea82a1f24c7b5e94c1d6b9d43233c28fd16654e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 01:35:33 +0800 Subject: [PATCH 0805/1939] Update spiral-matrix-ii.py --- Python/spiral-matrix-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/spiral-matrix-ii.py b/Python/spiral-matrix-ii.py index 554c9f7a8..ddfabca49 100644 --- a/Python/spiral-matrix-ii.py +++ b/Python/spiral-matrix-ii.py @@ -17,7 +17,7 @@ class Solution: # @return a list of lists of integer def generateMatrix(self, n): - matrix = [[0 for i in range(n)] for i in range(n)] + matrix = [[0 for i in xrange(n)] for i in xrange(n)] left, right, top, bottom, num = 0, n - 1, 0, n - 1, 1 @@ -43,4 +43,4 @@ def generateMatrix(self, n): if __name__ == "__main__": print Solution().generateMatrix(3) - print Solution().generateMatrix(8) \ No newline at end of file + print Solution().generateMatrix(8) From 0bff912c12e324574c7d006d5bacbf53938123b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 23:22:32 +0800 Subject: [PATCH 0806/1939] Create h-index.py --- Python/h-index.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/h-index.py diff --git a/Python/h-index.py b/Python/h-index.py new file mode 100644 index 000000000..be1c8b16b --- /dev/null +++ b/Python/h-index.py @@ -0,0 +1,47 @@ +# Time: O(nlogn) +# Space: O(1) + +# Given an array of citations (each citation is a non-negative integer) +# of a researcher, write a function to compute the researcher's h-index. +# +# According to the definition of h-index on Wikipedia: +# "A scientist has index h if h of his/her N papers have +# at least h citations each, and the other N − h papers have +# no more than h citations each." +# +# For example, given citations = [3, 0, 6, 1, 5], +# which means the researcher has 5 papers in total +# and each of them had received 3, 0, 6, 1, 5 citations respectively. +# Since the researcher has 3 papers with at least 3 citations each and +# the remaining two with no more than 3 citations each, his h-index is 3. +# +# Note: If there are several possible values for h, the maximum one is taken as the h-index. +# + +class Solution(object): + def hIndex(self, citations): + """ + :type citations: List[int] + :rtype: int + """ + citations.sort(reverse=True) + h = 0 + for i, x in enumerate(citations): + if x >= i + 1: + h += 1 + else: + break + return h + +# Time: O(nlogn) +# Space: O(n) +class Solution2(object): + def hIndex(self, citations): + """ + :type citations: List[int] + :rtype: int + """ + sorted(citations, reverse=True) + h = 0 + return sum(1 if x >= i + 1 else 0 for i, x in enumerate(sorted(citations, reverse=True))) + From bc7c328b564df42fdbd9dc47fe160f34b7f4391e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 23:29:35 +0800 Subject: [PATCH 0807/1939] Create h-index.cpp --- C++/h-index.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/h-index.cpp diff --git a/C++/h-index.cpp b/C++/h-index.cpp new file mode 100644 index 000000000..1b59210fb --- /dev/null +++ b/C++/h-index.cpp @@ -0,0 +1,18 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + int hIndex(vector& citations) { + sort(citations.begin(), citations.end(), greater()); + int h = 0; + for (int i = 0; i < citations.size(); ++i) { + if (citations[i] >= i + 1) { + ++h; + } else { + break; + } + } + return h; + } +}; From 4026d575cac94d98f8fa5467674020b18442359d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 23:33:25 +0800 Subject: [PATCH 0808/1939] Update h-index.py --- Python/h-index.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Python/h-index.py b/Python/h-index.py index be1c8b16b..32244acaa 100644 --- a/Python/h-index.py +++ b/Python/h-index.py @@ -41,7 +41,5 @@ def hIndex(self, citations): :type citations: List[int] :rtype: int """ - sorted(citations, reverse=True) - h = 0 return sum(1 if x >= i + 1 else 0 for i, x in enumerate(sorted(citations, reverse=True))) From f0354a2c6001c4d85d30acdefca7b43c5d47a217 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 23:37:36 +0800 Subject: [PATCH 0809/1939] Update h-index.py --- Python/h-index.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/h-index.py b/Python/h-index.py index 32244acaa..3d8ddcc94 100644 --- a/Python/h-index.py +++ b/Python/h-index.py @@ -41,5 +41,5 @@ def hIndex(self, citations): :type citations: List[int] :rtype: int """ - return sum(1 if x >= i + 1 else 0 for i, x in enumerate(sorted(citations, reverse=True))) + return sum(x >= i + 1 for i, x in enumerate(sorted(citations, reverse=True))) From 26b0982d44486f7019ace92799061bd5101954e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 23:48:36 +0800 Subject: [PATCH 0810/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 130a5d5e1..653b32b2c 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-08-31), there are `256` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-03), there are `257` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `273` questions. +Here is the classification of all `274` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -245,6 +245,7 @@ Shell 248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard |📖|| 258| [Add Digits](https://leetcode.com/problems/add-digits/) | [C++](./C++/add-digits.cpp) [Python](./Python/add-digits.py) | _O(1)_ | _O(1)_ | Easy ||| 263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(logn)_ | _O(1)_ | Easy ||| +274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(nlogn)_ | _O(1)_ | Easy ||| --- From 0d8733e5fa5748873cf67352304d990badd45b38 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Sep 2015 23:50:39 +0800 Subject: [PATCH 0811/1939] Update h-index.cpp --- C++/h-index.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/h-index.cpp b/C++/h-index.cpp index 1b59210fb..a6cfaa073 100644 --- a/C++/h-index.cpp +++ b/C++/h-index.cpp @@ -6,8 +6,8 @@ class Solution { int hIndex(vector& citations) { sort(citations.begin(), citations.end(), greater()); int h = 0; - for (int i = 0; i < citations.size(); ++i) { - if (citations[i] >= i + 1) { + for (const auto& x : citations) { + if (x >= h + 1) { ++h; } else { break; From 4afbe68a1c08498ff87984e1b80b7307a9de69a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 00:01:19 +0800 Subject: [PATCH 0812/1939] Update h-index.py --- Python/h-index.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/h-index.py b/Python/h-index.py index 3d8ddcc94..85ace2b96 100644 --- a/Python/h-index.py +++ b/Python/h-index.py @@ -26,8 +26,8 @@ def hIndex(self, citations): """ citations.sort(reverse=True) h = 0 - for i, x in enumerate(citations): - if x >= i + 1: + for x in citations: + if x >= h + 1: h += 1 else: break From e67c705b49987a8497c80946b37630c72a615ee1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 09:23:26 +0800 Subject: [PATCH 0813/1939] Update h-index.cpp --- C++/h-index.cpp | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/C++/h-index.cpp b/C++/h-index.cpp index a6cfaa073..e16aabba3 100644 --- a/C++/h-index.cpp +++ b/C++/h-index.cpp @@ -1,7 +1,34 @@ -// Time: O(nlogn) -// Space: O(1) +// Time: O(n) +// Space: O(n) +// Counting sort. class Solution { +public: + int hIndex(vector& citations) { + const auto n = citations.size(); + vector count(n + 1, 0); + for (const auto& x : citations) { + if(x >= n) { + ++count[n]; + } else { + ++count[x]; + } + } + + int h = 0; + for (int i = n; i >= 0; --i) { + h += count[i]; + if (h >= i) { + return i; + } + } + return h; + } +}; + +// Time: O(nlogn) +// Space: O(1) +class Solution2 { public: int hIndex(vector& citations) { sort(citations.begin(), citations.end(), greater()); From 64b94e0b708495ef13ff3bd3e440e9e7152cf547 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 09:25:12 +0800 Subject: [PATCH 0814/1939] Update h-index.cpp --- C++/h-index.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/h-index.cpp b/C++/h-index.cpp index e16aabba3..54ceda9d4 100644 --- a/C++/h-index.cpp +++ b/C++/h-index.cpp @@ -8,7 +8,7 @@ class Solution { const auto n = citations.size(); vector count(n + 1, 0); for (const auto& x : citations) { - if(x >= n) { + if (x >= n) { ++count[n]; } else { ++count[x]; From ad47fb85e5c2deb47cbe3fc3478e1ae2da93adfe Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 09:29:16 +0800 Subject: [PATCH 0815/1939] Update h-index.py --- Python/h-index.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/Python/h-index.py b/Python/h-index.py index 85ace2b96..c14c8ed6b 100644 --- a/Python/h-index.py +++ b/Python/h-index.py @@ -1,5 +1,5 @@ -# Time: O(nlogn) -# Space: O(1) +# Time: O(n) +# Space: O(n) # Given an array of citations (each citation is a non-negative integer) # of a researcher, write a function to compute the researcher's h-index. @@ -19,6 +19,29 @@ # class Solution(object): + def hIndex(self, citations): + """ + :type citations: List[int] + :rtype: int + """ + n = len(citations); + count = [0] * (n + 1) + for x in citations: + if x >= n: + count[n] += 1 + else: + count[x] += 1 + + h = 0 + for i in reversed(xrange(0, n + 1)): + h += count[i] + if h >= i: + return i + return h + +# Time: O(nlogn) +# Space: O(1) +class Solution2(object): def hIndex(self, citations): """ :type citations: List[int] From f920b162afe4633829d3f66d633b7e712673692a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 09:29:59 +0800 Subject: [PATCH 0816/1939] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 653b32b2c..0b224494c 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,6 @@ Shell 248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard |📖|| 258| [Add Digits](https://leetcode.com/problems/add-digits/) | [C++](./C++/add-digits.cpp) [Python](./Python/add-digits.py) | _O(1)_ | _O(1)_ | Easy ||| 263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(logn)_ | _O(1)_ | Easy ||| -274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(nlogn)_ | _O(1)_ | Easy ||| --- @@ -264,6 +263,8 @@ Shell 218| [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard || Sort, BST| 252| [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [C++](./C++/meeting-rooms.cpp) [Python](./Python/meeting-rooms.py) | _O(nlogn)_ | _O(n)_ | Easy |📖| | 253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |📖| | +274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Easy || Counting Sort | + --- From 4c84997a2414dd874b664f5977700107ebd1cf9b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 09:30:29 +0800 Subject: [PATCH 0817/1939] Update h-index.py --- Python/h-index.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/h-index.py b/Python/h-index.py index c14c8ed6b..0845065e7 100644 --- a/Python/h-index.py +++ b/Python/h-index.py @@ -18,6 +18,7 @@ # Note: If there are several possible values for h, the maximum one is taken as the h-index. # +# Counting sort. class Solution(object): def hIndex(self, citations): """ From 2b58218bf8c9b68c1d367736491dc87e86f42b4b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 09:35:26 +0800 Subject: [PATCH 0818/1939] Update h-index.cpp --- C++/h-index.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/h-index.cpp b/C++/h-index.cpp index 54ceda9d4..2f6d86c42 100644 --- a/C++/h-index.cpp +++ b/C++/h-index.cpp @@ -8,6 +8,7 @@ class Solution { const auto n = citations.size(); vector count(n + 1, 0); for (const auto& x : citations) { + // Put all x >= n in the same bucket. if (x >= n) { ++count[n]; } else { From a73746da1160620ef3e9c05c0ec73ac435ad042d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 09:36:41 +0800 Subject: [PATCH 0819/1939] Update h-index.py --- Python/h-index.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/h-index.py b/Python/h-index.py index 0845065e7..51dcffa6a 100644 --- a/Python/h-index.py +++ b/Python/h-index.py @@ -28,6 +28,7 @@ def hIndex(self, citations): n = len(citations); count = [0] * (n + 1) for x in citations: + # Put all x >= n in the same bucket. if x >= n: count[n] += 1 else: From d21b9a1ba74db078d32c8d3f45f7f67ffe9ab86a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 09:36:56 +0800 Subject: [PATCH 0820/1939] Update h-index.py --- Python/h-index.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/h-index.py b/Python/h-index.py index 51dcffa6a..4ad07afdb 100644 --- a/Python/h-index.py +++ b/Python/h-index.py @@ -60,7 +60,7 @@ def hIndex(self, citations): # Time: O(nlogn) # Space: O(n) -class Solution2(object): +class Solution3(object): def hIndex(self, citations): """ :type citations: List[int] From cc074c4aad1ee3bce07b128bbf6663f523c2da6c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 23:01:08 +0800 Subject: [PATCH 0821/1939] Create h-index-ii.py --- Python/h-index-ii.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/h-index-ii.py diff --git a/Python/h-index-ii.py b/Python/h-index-ii.py new file mode 100644 index 000000000..c20392b38 --- /dev/null +++ b/Python/h-index-ii.py @@ -0,0 +1,26 @@ +# Time: O(logn) +# Space: O(1) +# +# Follow up for H-Index: What if the citations array is sorted in +# ascending order? Could you optimize your algorithm? +# +# Hint: +# +# Expected runtime complexity is in O(log n) and the input is sorted. +# + +class Solution(object): + def hIndex(self, citations): + """ + :type citations: List[int] + :rtype: int + """ + n = len(citations) + left, right = 0, n - 1 + while left <= right: + mid = (left + right) / 2 + if citations[mid] >= n - mid: + right = mid - 1 + else: + left = mid + 1 + return n - left From 78cac3f3ea3c65a9cd0604ac83d66b30a6360094 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 23:01:38 +0800 Subject: [PATCH 0822/1939] Create h-index-ii.cpp --- C++/h-index-ii.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/h-index-ii.cpp diff --git a/C++/h-index-ii.cpp b/C++/h-index-ii.cpp new file mode 100644 index 000000000..c7c7cc9f2 --- /dev/null +++ b/C++/h-index-ii.cpp @@ -0,0 +1,20 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int hIndex(vector& citations) { + const int n = citations.size(); + int left = 0; + int right = n - 1; + while (left <= right) { + const auto mid = left + (right - left) / 2; + if (citations[mid] >= n - mid) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return n - left; + } +}; From 27ed900bf80f8ac53ec1a89f345bb2f0f7f27b78 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 23:03:12 +0800 Subject: [PATCH 0823/1939] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0b224494c..684dc2fb4 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-03), there are `257` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-04), there are `258` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `274` questions. +Here is the classification of all `275` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -263,8 +263,7 @@ Shell 218| [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard || Sort, BST| 252| [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [C++](./C++/meeting-rooms.cpp) [Python](./Python/meeting-rooms.py) | _O(nlogn)_ | _O(n)_ | Easy |📖| | 253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |📖| | -274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Easy || Counting Sort | - +274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Medium || Counting Sort | --- @@ -330,6 +329,7 @@ Shell 154| [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || 162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || 222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./C++/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || +275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | -- ##Binary Search Tree From 6bba6d8f483ff6e47539b99e9440bb1441cd66a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Sep 2015 23:17:07 +0800 Subject: [PATCH 0824/1939] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index e9708c058..8360da215 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -109,7 +109,7 @@ def getKth(self, A, i, B, j, k): else: return A[i + pa - 1] -# using list slicing (O(k)) may be slower than solution1 +# using list slicing (O(k)) may be slower than Solution3 class Solution4: # @return a float def findMedianSortedArrays(self, A, B): From 28ffe9e8642f75738b9cdf2b485451a10be9b7dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Sep 2015 00:55:09 +0800 Subject: [PATCH 0825/1939] Create paint-fence.cpp --- C++/paint-fence.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/paint-fence.cpp diff --git a/C++/paint-fence.cpp b/C++/paint-fence.cpp new file mode 100644 index 000000000..5d9b75e77 --- /dev/null +++ b/C++/paint-fence.cpp @@ -0,0 +1,39 @@ +// Time: O(n) +// Space: O(1) +class Solution { +public: + int numWays(int n, int k) { + if (n == 0) { + return 0; + } else if (n == 1) { + return k; + } + vector ways(3, 0); + ways[0] = k; + ways[1] = (k - 1) * ways[0] + k; + for (int i = 2; i < n; ++i) { + ways[i % 3] = (k - 1) * (ways[(i - 1) % 3] + ways[(i - 2) % 3]); + } + return ways[(n - 1) % 3]; + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { +public: + int numWays(int n, int k) { + if (n == 0) { + return 0; + } else if (n == 1) { + return k; + } + vector ways(n, 0); + ways[0] = k; + ways[1] = (k - 1) * ways[0] + k; + for (int i = 2; i < n; ++i) { + ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2]); + } + return ways[n - 1]; + } +}; From 426ab0987209e9ff5318ae917bda116a55e4cfac Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Sep 2015 00:55:51 +0800 Subject: [PATCH 0826/1939] Update paint-fence.cpp --- C++/paint-fence.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/paint-fence.cpp b/C++/paint-fence.cpp index 5d9b75e77..6dd44afb8 100644 --- a/C++/paint-fence.cpp +++ b/C++/paint-fence.cpp @@ -1,5 +1,7 @@ // Time: O(n) // Space: O(1) + +// DP with rolling window. class Solution { public: int numWays(int n, int k) { @@ -20,6 +22,7 @@ class Solution { // Time: O(n) // Space: O(n) +// DP solution. class Solution2 { public: int numWays(int n, int k) { From 3a01fa0dc6c8603edc4f969b67d4206b8045eeb4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Sep 2015 01:00:21 +0800 Subject: [PATCH 0827/1939] Create paint-fence.py --- Python/paint-fence.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/paint-fence.py diff --git a/Python/paint-fence.py b/Python/paint-fence.py new file mode 100644 index 000000000..be60c6e62 --- /dev/null +++ b/Python/paint-fence.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(1) + +# DP solution with rolling window. +class Solution(object): + def numWays(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + if n == 0: + return 0 + elif n == 1: + return k + ways = [0] * 3 + ways[0] = k + ways[1] = (k - 1) * ways[0] + k + for i in xrange(2, n): + ways[i % 3] = (k - 1) * (ways[(i - 1) % 3] + ways[(i - 2) % 3]) + return ways[(n - 1) % 3] + +# Time: O(n) +# Space: O(n) +# DP solution. +class Solution2(object): + def numWays(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + if n == 0: + return 0 + elif n == 1: + return k + ways = [0] * n + ways[0] = k + ways[1] = (k - 1) * ways[0] + k + for i in xrange(2, n): + ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2]) + return ways[n - 1] From 997327abe99907f57fe57fe9bb08bb796dee23cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Sep 2015 01:03:48 +0800 Subject: [PATCH 0828/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 684dc2fb4..d5aebbd12 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-04), there are `258` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-05), there are `259` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `275` questions. +Here is the classification of all `276` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -414,6 +414,7 @@ Shell 221| [Maximal Square](https://leetcode.com/problems/maximal-square/)| [C++](./C++/maximal-square.cpp) [Python](./Python/maximal-square.py) | _O(n^2)_ | _O(n)_ | Medium | EPI | 256| [Paint House](https://leetcode.com/problems/paint-house/) | [C++](./C++/paint-house.cpp) [Python](./Python/paint-house.py) | _O(n)_| _O(1)_| Medium |📖|| 265| [Paint House II](https://leetcode.com/problems/paint-house-ii/) | [C++](./C++/paint-house-ii.cpp) [Python](./Python/paint-house-ii.py) | _O(n * k)_| _O(k)_| Hard |📖|| +276| [Paint Fence](https://leetcode.com/problems/paint-fence/) | [C++](./C++/paint-fence.cpp) [Python](./Python/paint-fence.py) | _O(n)_| _O(1)_| Easy |📖|| --- From 1ee044d9c61d70683bfe91e93491f26b3c48d60d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Sep 2015 21:31:23 +0800 Subject: [PATCH 0829/1939] Create find-the-celebrity.cpp --- C++/find-the-celebrity.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/find-the-celebrity.cpp diff --git a/C++/find-the-celebrity.cpp b/C++/find-the-celebrity.cpp new file mode 100644 index 000000000..ec96b517d --- /dev/null +++ b/C++/find-the-celebrity.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(1) + +// Forward declaration of the knows API. +bool knows(int a, int b); + +class Solution { +public: + int findCelebrity(int n) { + int candidate = 0; + // Find the candidate. + for (int i = 1; i < n; ++i) { + if (knows(candidate, i)) { + candidate = i; // All candidates < i are not celebrity candidates. + } + } + // Verify the candidate. + for (int i = 0; i < n; ++i) { + if (i != candidate && + (knows(candidate, i) || !knows(i, candidate))) { + return -1; + } + } + return candidate; + } +}; From 510f551567e31e3d769a3102093f95c5215fbfc9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Sep 2015 21:32:26 +0800 Subject: [PATCH 0830/1939] Create find-the-celebrity.py --- Python/find-the-celebrity.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Python/find-the-celebrity.py diff --git a/Python/find-the-celebrity.py b/Python/find-the-celebrity.py new file mode 100644 index 000000000..f74118b79 --- /dev/null +++ b/Python/find-the-celebrity.py @@ -0,0 +1,25 @@ +# Time: O(n) +# Space: O(1) +# +# The knows API is already defined for you. +# @param a, person a +# @param b, person b +# @return a boolean, whether a knows b +# def knows(a, b): +# + +class Solution(object): + def findCelebrity(self, n): + """ + :type n: int + :rtype: int + """ + candidate = 0 + for i in xrange(1, n): + if knows(candidate, i): + candidate = i + for i in xrange(n): + if i != candidate and (knows(candidate, i) \ + or not knows(i, candidate)): + return -1 + return candidate From 374cc61e7d74ea2a531db3503ee54c6a2e53a2de Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Sep 2015 21:35:30 +0800 Subject: [PATCH 0831/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d5aebbd12..ade6f88d0 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-05), there are `259` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-06), there are `260` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `276` questions. +Here is the classification of all `277` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -97,6 +97,7 @@ Shell 243| [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [C++](./C++/shortest-word-distance.cpp) [Python](./Python/shortest-word-distance.py) | _O(n)_ | _O(1)_ | Easy |📖|| 245| [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance III/) | [C++](./C++/shortest-word-distance-iii.cpp) [Python](./Python/shortest-word-distance-iii.py) | _O(n)_ | _O(1)_ | Medium |📖|| 251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium |📖|| +277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |📖, EPI || --- From b3480feacd00d7ba93eb17c116427c37c5e8277c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Sep 2015 00:06:56 +0800 Subject: [PATCH 0832/1939] Update find-the-celebrity.py --- Python/find-the-celebrity.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Python/find-the-celebrity.py b/Python/find-the-celebrity.py index f74118b79..da013af89 100644 --- a/Python/find-the-celebrity.py +++ b/Python/find-the-celebrity.py @@ -15,9 +15,11 @@ def findCelebrity(self, n): :rtype: int """ candidate = 0 + # Find the candidate. for i in xrange(1, n): - if knows(candidate, i): + if knows(candidate, i): # All candidates < i are not celebrity candidates. candidate = i + # Verify the candidate. for i in xrange(n): if i != candidate and (knows(candidate, i) \ or not knows(i, candidate)): From 1ab4fb5a5b8f2d5267097ee071bb038f6c2ceb8f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Sep 2015 21:40:10 +0800 Subject: [PATCH 0833/1939] Create first-bad-version.cpp --- C++/first-bad-version.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/first-bad-version.cpp diff --git a/C++/first-bad-version.cpp b/C++/first-bad-version.cpp new file mode 100644 index 000000000..93112a89e --- /dev/null +++ b/C++/first-bad-version.cpp @@ -0,0 +1,23 @@ +// Time: O(nlogn) +// Space: O(1) + +// Forward declaration of isBadVersion API. +bool isBadVersion(int version); + +class Solution { +public: + int firstBadVersion(int n) { + int left = 1, right = n; + + while (left <= right) { + int mid = left + (right - left) / 2; + // Is target + if (isBadVersion(mid)) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } +}; From 8e470c1c2e8c8d4b5943e016dc2508a25879742a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Sep 2015 21:44:17 +0800 Subject: [PATCH 0834/1939] Create first-bad-version.py --- Python/first-bad-version.py | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/first-bad-version.py diff --git a/Python/first-bad-version.py b/Python/first-bad-version.py new file mode 100644 index 000000000..842c744c0 --- /dev/null +++ b/Python/first-bad-version.py @@ -0,0 +1,39 @@ +# Time: O(logn) +# Space: O(1) +# +# You are a product manager and currently leading a team to +# develop a new product. Unfortunately, the latest version of +# your product fails the quality check. Since each version is +# developed based on the previous version, all the versions +# after a bad version are also bad. +# +# Suppose you have n versions [1, 2, ..., n] and you want to +# find out the first bad one, which causes all the following +# ones to be bad. +# +# You are given an API bool isBadVersion(version) which will +# return whether version is bad. Implement a function to find +# the first bad version. You should minimize the number of +# calls to the API. +# + +# The isBadVersion API is already defined for you. +# @param version, an integer +# @return a bool +# def isBadVersion(version): + +class Solution(object): + def firstBadVersion(self, n): + """ + :type n: int + :rtype: int + """ + left, right = 1, n + + while left <= right: + mid = left + (right - left) / 2 + if isBadVersion(mid): + right = mid - 1 + else: + left = mid + 1 + return left From 5187f76579d74fab31408b6762db22ab7f590712 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Sep 2015 21:44:52 +0800 Subject: [PATCH 0835/1939] Update first-bad-version.cpp --- C++/first-bad-version.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/first-bad-version.cpp b/C++/first-bad-version.cpp index 93112a89e..6479f7450 100644 --- a/C++/first-bad-version.cpp +++ b/C++/first-bad-version.cpp @@ -1,4 +1,4 @@ -// Time: O(nlogn) +// Time: O(logn) // Space: O(1) // Forward declaration of isBadVersion API. @@ -11,7 +11,6 @@ class Solution { while (left <= right) { int mid = left + (right - left) / 2; - // Is target if (isBadVersion(mid)) { right = mid - 1; } else { From 2280dce5340620beac4fc935d4ce56402de82643 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Sep 2015 21:47:55 +0800 Subject: [PATCH 0836/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ade6f88d0..e967bcff4 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-06), there are `260` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-07), there are `261` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `277` questions. +Here is the classification of all `278` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -331,6 +331,7 @@ Shell 162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || 222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./C++/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || 275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | +278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy ||| -- ##Binary Search Tree From f07e4535c191abf7c53103809564dd8f01fa5af7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Sep 2015 21:48:44 +0800 Subject: [PATCH 0837/1939] Update first-bad-version.py --- Python/first-bad-version.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/first-bad-version.py b/Python/first-bad-version.py index 842c744c0..af2bdc0a5 100644 --- a/Python/first-bad-version.py +++ b/Python/first-bad-version.py @@ -29,7 +29,6 @@ def firstBadVersion(self, n): :rtype: int """ left, right = 1, n - while left <= right: mid = left + (right - left) / 2 if isBadVersion(mid): From 7bf31810c243c879f18fadb00e32df4a3f2b047e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Sep 2015 21:49:05 +0800 Subject: [PATCH 0838/1939] Update first-bad-version.cpp --- C++/first-bad-version.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/first-bad-version.cpp b/C++/first-bad-version.cpp index 6479f7450..6d143fef7 100644 --- a/C++/first-bad-version.cpp +++ b/C++/first-bad-version.cpp @@ -8,7 +8,6 @@ class Solution { public: int firstBadVersion(int n) { int left = 1, right = n; - while (left <= right) { int mid = left + (right - left) / 2; if (isBadVersion(mid)) { From a81087b0a3b4200fa7ad9345325199de991ebc38 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Sep 2015 22:05:09 +0800 Subject: [PATCH 0839/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e967bcff4..30c400cc0 100644 --- a/README.md +++ b/README.md @@ -331,7 +331,7 @@ Shell 162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || 222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./C++/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || 275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | -278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy ||| +278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy | LintCode || -- ##Binary Search Tree From e3ba3173a7f0fc51ca2e01d567b4f4011a739da2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 21:40:52 +0800 Subject: [PATCH 0840/1939] Update bitwise-and-of-numbers-range.py --- Python/bitwise-and-of-numbers-range.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Python/bitwise-and-of-numbers-range.py b/Python/bitwise-and-of-numbers-range.py index f8b269d22..369a5a803 100644 --- a/Python/bitwise-and-of-numbers-range.py +++ b/Python/bitwise-and-of-numbers-range.py @@ -8,6 +8,15 @@ # class Solution: + # @param m, an integer + # @param n, an integer + # @return an integer + def rangeBitwiseAnd(self, m, n): + while m < n: + n &= n - 1 + return n + +class Solution2: # @param m, an integer # @param n, an integer # @return an integer From 2b9c05d837981fcc2665a70b2b3be2d9cb4c8e0c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 21:42:45 +0800 Subject: [PATCH 0841/1939] Create bitwise-and-of-numbers-range.cpp --- C++/bitwise-and-of-numbers-range.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 C++/bitwise-and-of-numbers-range.cpp diff --git a/C++/bitwise-and-of-numbers-range.cpp b/C++/bitwise-and-of-numbers-range.cpp new file mode 100644 index 000000000..338dc86a1 --- /dev/null +++ b/C++/bitwise-and-of-numbers-range.cpp @@ -0,0 +1,12 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int rangeBitwiseAnd(int m, int n) { + while (m < n) { + n &= n-1; + } + return n; + } +}; From 16b314226b2be465377f52227ab5de2476ed68fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 21:44:03 +0800 Subject: [PATCH 0842/1939] Update bitwise-and-of-numbers-range.cpp --- C++/bitwise-and-of-numbers-range.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/bitwise-and-of-numbers-range.cpp b/C++/bitwise-and-of-numbers-range.cpp index 338dc86a1..fb2bd1282 100644 --- a/C++/bitwise-and-of-numbers-range.cpp +++ b/C++/bitwise-and-of-numbers-range.cpp @@ -5,7 +5,7 @@ class Solution { public: int rangeBitwiseAnd(int m, int n) { while (m < n) { - n &= n-1; + n &= n - 1; } return n; } From bea08c425dae764ee90baccf76b17f9ad24c24c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 21:46:06 +0800 Subject: [PATCH 0843/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 30c400cc0..4c528c8b8 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Shell 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || 191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || -201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || +201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || 268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium | LintCode || From 7d3c3e8febd2805715e9107fe5b216bac3fa8dcf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 21:54:40 +0800 Subject: [PATCH 0844/1939] Update bitwise-and-of-numbers-range.cpp --- C++/bitwise-and-of-numbers-range.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/bitwise-and-of-numbers-range.cpp b/C++/bitwise-and-of-numbers-range.cpp index fb2bd1282..a05ce4491 100644 --- a/C++/bitwise-and-of-numbers-range.cpp +++ b/C++/bitwise-and-of-numbers-range.cpp @@ -4,7 +4,7 @@ class Solution { public: int rangeBitwiseAnd(int m, int n) { - while (m < n) { + while (m < n) { // Remove the last bit 1 until n <= m. n &= n - 1; } return n; From 2fa62acdf8ddd07b8ebcc901613f9823aa0d0450 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 21:58:39 +0800 Subject: [PATCH 0845/1939] Update reverse-bits.py --- Python/reverse-bits.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py index c5a6fa4ec..7ba6c7aba 100644 --- a/Python/reverse-bits.py +++ b/Python/reverse-bits.py @@ -1,4 +1,4 @@ -# Time : O(n) +# Time : O(logn) # Space: O(1) # # Reverse bits of a given 32 bits unsigned integer. From bf8a49feb3602257f05e64cd6c2ee7bd753c79a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 22:13:44 +0800 Subject: [PATCH 0846/1939] Update number-of-1-bits.py --- Python/number-of-1-bits.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/number-of-1-bits.py b/Python/number-of-1-bits.py index c0069d07c..c5f9e1111 100644 --- a/Python/number-of-1-bits.py +++ b/Python/number-of-1-bits.py @@ -1,4 +1,4 @@ -# Time: O(m) +# Time: O(logn) # Space: O(1) # # Write a function that takes an unsigned integer From 3d6c7ff30c1d6cb7db616fe2ae7d20a5f3ef2a68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 22:14:19 +0800 Subject: [PATCH 0847/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4c528c8b8..83b9e7a5f 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,8 @@ Shell -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || -190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(n)_ | _O(1)_ | Easy || -191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(m)_ | _O(1)_ | Easy || +190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(logn)_ | _O(1)_ | Easy || +191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(logn)_ | _O(1)_ | Easy || 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || From e81ee3f4db971e881e741a4f8abb526da7520a83 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 22:14:36 +0800 Subject: [PATCH 0848/1939] Update reverse-bits.py --- Python/reverse-bits.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py index 7ba6c7aba..4dc5252b9 100644 --- a/Python/reverse-bits.py +++ b/Python/reverse-bits.py @@ -1,4 +1,4 @@ -# Time : O(logn) +# Time : O(logn) = O(32) # Space: O(1) # # Reverse bits of a given 32 bits unsigned integer. From d08409beb62899aa5332639d0255062a03d2b3e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 22:14:58 +0800 Subject: [PATCH 0849/1939] Update number-of-1-bits.py --- Python/number-of-1-bits.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/number-of-1-bits.py b/Python/number-of-1-bits.py index c5f9e1111..1d3f12f2a 100644 --- a/Python/number-of-1-bits.py +++ b/Python/number-of-1-bits.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn) = O(32) # Space: O(1) # # Write a function that takes an unsigned integer From 226553e63ccfb9e80b1798ea69a920d96e183e5b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Sep 2015 22:25:43 +0800 Subject: [PATCH 0850/1939] Update minimum-size-subarray-sum.py --- Python/minimum-size-subarray-sum.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Python/minimum-size-subarray-sum.py b/Python/minimum-size-subarray-sum.py index 229e07aa3..24d56ced0 100644 --- a/Python/minimum-size-subarray-sum.py +++ b/Python/minimum-size-subarray-sum.py @@ -19,16 +19,15 @@ class Solution: def minSubArrayLen(self, s, nums): start = 0 sum = 0 - min_len = float("inf") + min_size = float("inf") for i in xrange(len(nums)): sum += nums[i] while sum >= s: - min_len = min(min_len, i - start + 1) + min_size = min(min_size, i - start + 1) sum -= nums[start] start += 1 - if min_len == float("inf"): - return 0 - return min_len + + return min_size if min_size != float("inf") else 0 # Time: O(nlogn) # Space: O(n) @@ -48,9 +47,8 @@ def minSubArrayLen(self, s, nums): sum_from_start[i] - nums[i] + s) if end < len(sum_from_start): min_size = min(min_size, end - i + 1) - if min_size == float("inf"): - return 0 - return min_size + + return min_size if min_size != float("inf") else 0 def binarySearch(self, compare, A, start, end, target): while start < end: From 8712e901488d17041ff8a82de76ce88c53472de6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Sep 2015 00:27:32 +0800 Subject: [PATCH 0851/1939] Update tenth-line.sh --- Shell/tenth-line.sh | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Shell/tenth-line.sh b/Shell/tenth-line.sh index b8ca175d2..631890a85 100644 --- a/Shell/tenth-line.sh +++ b/Shell/tenth-line.sh @@ -23,4 +23,13 @@ # 2. There's at least three different solutions. Try to explore all possibilities. # # Read from the file file.txt and output the tenth line to stdout. + +# Solution 1 awk '{if(NR==10) print $0}' file.txt +awk 'NR == 10' file.txt + +# Solution 2 +sed -n 10p file.txt + +# Solution 3 +tail -n+10 file.txt | head -1 From 42e675ba29810c6190a1eaf2b65cd9161c9040e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 00:17:59 +0800 Subject: [PATCH 0852/1939] Create perfect-squares.cpp --- C++/perfect-squares.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 C++/perfect-squares.cpp diff --git a/C++/perfect-squares.cpp b/C++/perfect-squares.cpp new file mode 100644 index 000000000..39c04773d --- /dev/null +++ b/C++/perfect-squares.cpp @@ -0,0 +1,16 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int numSquares(int n) { + vector num(n + 1, numeric_limits::max()); + num[0] = 0; + for (int i = 0; i <= n; ++i) { + for (int j = i - 1, k = 1; j >= 0; ++k, j = i - k * k) { + num[i] = min(num[i], num[j] + 1); + } + } + return num[n]; + } +}; From b54d690cf8261c6ddece69f37b86dc38b13b9cfc Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 00:24:59 +0800 Subject: [PATCH 0853/1939] Update perfect-squares.cpp --- C++/perfect-squares.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/perfect-squares.cpp b/C++/perfect-squares.cpp index 39c04773d..7875dc93c 100644 --- a/C++/perfect-squares.cpp +++ b/C++/perfect-squares.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(n * sqrt(n)) // Space: O(n) class Solution { From e9ec7ffc72976a131412575f26ae96b7958a1c82 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 01:02:18 +0800 Subject: [PATCH 0854/1939] Create perfect-squares.py --- Python/perfect-squares.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/perfect-squares.py diff --git a/Python/perfect-squares.py b/Python/perfect-squares.py new file mode 100644 index 000000000..2cee23f58 --- /dev/null +++ b/Python/perfect-squares.py @@ -0,0 +1,21 @@ +# Time: O(n * sqrt(n)) +# Space: O(n) +# +# Given a positive integer n, find the least number of perfect +# square numbers (for example, 1, 4, 9, 16, ...) which sum to n. +# +# For example, given n = 12, return 3 because 12 = 4 + 4 + 4; +# given n = 13, return 2 because 13 = 4 + 9. +# + +class Solution(object): + _num = [0] + def numSquares(self, n): + """ + :type n: int + :rtype: int + """ + num = self._num + while len(num) <= n: + num += min(num[-i*i] for i in xrange(1, int(len(num)**0.5+1))) + 1, + return num[n] From fa7a67cdc7488f1378c1df12d31cb324f9d12aed Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 01:39:19 +0800 Subject: [PATCH 0855/1939] Update perfect-squares.cpp --- C++/perfect-squares.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/C++/perfect-squares.cpp b/C++/perfect-squares.cpp index 7875dc93c..22d9e33ac 100644 --- a/C++/perfect-squares.cpp +++ b/C++/perfect-squares.cpp @@ -2,6 +2,21 @@ // Space: O(n) class Solution { +public: + int numSquares(int n) { + static vector num{0}; + while (num.size() <= n) { + int squares = numeric_limits::max(); + for (int i = 1; i * i <= num.size(); ++i) { + squares = min(squares, num[num.size() - i * i] + 1); + } + num.emplace_back(squares); + } + return num[n]; + } +}; + +class Solution2 { public: int numSquares(int n) { vector num(n + 1, numeric_limits::max()); From 18cf5d63242840b28899f9d111f7b45f255c0092 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 01:45:01 +0800 Subject: [PATCH 0856/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 83b9e7a5f..e59cad30d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-07), there are `261` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-09), there are `262` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `278` questions. +Here is the classification of all `279` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -417,6 +417,7 @@ Shell 256| [Paint House](https://leetcode.com/problems/paint-house/) | [C++](./C++/paint-house.cpp) [Python](./Python/paint-house.py) | _O(n)_| _O(1)_| Medium |📖|| 265| [Paint House II](https://leetcode.com/problems/paint-house-ii/) | [C++](./C++/paint-house-ii.cpp) [Python](./Python/paint-house-ii.py) | _O(n * k)_| _O(k)_| Hard |📖|| 276| [Paint Fence](https://leetcode.com/problems/paint-fence/) | [C++](./C++/paint-fence.cpp) [Python](./Python/paint-fence.py) | _O(n)_| _O(1)_| Easy |📖|| +279| [Perfect Squares](https://leetcode.com/problems/perfect-squares/)| [C++](./C++/perfect-squares.cpp) [Python](./Python/perfect-squares.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium || Hash | --- From d15426e4c94a2a6645b1a8877ca6f345189b9963 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 11:21:41 +0800 Subject: [PATCH 0857/1939] Create wiggle-sort.cpp --- C++/wiggle-sort.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/wiggle-sort.cpp diff --git a/C++/wiggle-sort.cpp b/C++/wiggle-sort.cpp new file mode 100644 index 000000000..92235cfef --- /dev/null +++ b/C++/wiggle-sort.cpp @@ -0,0 +1,24 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + void wiggleSort(vector& nums) { + if (nums.empty()) { + return; + } + int pre = nums[0]; + bool inc = true; + for (int i = 1; i < nums.size(); ++i) { + if ((inc && pre <= nums[i]) || + (!inc && pre >= nums[i])) { + nums[i - 1] = pre; + pre = nums[i]; + } else { + nums[i - 1] = nums[i]; + } + inc = !inc; + } + nums.back() = pre; + } +}; From 54a0a3e3386d9269ef998fdc58704cdf08ff813d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 11:29:15 +0800 Subject: [PATCH 0858/1939] Create wiggle-sort.py --- Python/wiggle-sort.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Python/wiggle-sort.py diff --git a/Python/wiggle-sort.py b/Python/wiggle-sort.py new file mode 100644 index 000000000..e6114ba13 --- /dev/null +++ b/Python/wiggle-sort.py @@ -0,0 +1,23 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def wiggleSort(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + if not nums: + return + + pre = nums[0] + inc = True + for i in xrange(1, len(nums)): + if (inc and pre <= nums[i]) or \ + (not inc and pre >= nums[i]): + nums[i - 1] = pre + pre = nums[i] + else: + nums[i - 1] = nums[i] + inc = not inc + nums[-1] = pre From c61d9b6672da4d906ded4d0bff0c908a13e17fbe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 11:30:48 +0800 Subject: [PATCH 0859/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e59cad30d..8abd2d497 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-09), there are `262` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-10), there are `263` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `279` questions. +Here is the classification of all `280` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -265,6 +265,7 @@ Shell 252| [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [C++](./C++/meeting-rooms.cpp) [Python](./Python/meeting-rooms.py) | _O(nlogn)_ | _O(n)_ | Easy |📖| | 253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |📖| | 274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Medium || Counting Sort | +280| [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) | [C++](./C++/wiggle-sort.cpp) [Python](./Python/wiggle-sort.py) | _O(n)_ | _O(1)_ | Medium |📖| | --- From c55557715c2f8cb3c1799565c04f7f59093ec34c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 13:55:47 +0800 Subject: [PATCH 0860/1939] Update wiggle-sort.py --- Python/wiggle-sort.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Python/wiggle-sort.py b/Python/wiggle-sort.py index e6114ba13..a172ecae3 100644 --- a/Python/wiggle-sort.py +++ b/Python/wiggle-sort.py @@ -2,6 +2,17 @@ # Space: O(1) class Solution(object): + def wiggleSort(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + for i in xrange(1, len(nums)): + if ((i & 1) and nums[i - 1] > nums[i]) or \ + (not (i & 1) and nums[i - 1] < nums[i]): + nums[i - 1], nums[i] = nums[i], nums[i - 1] + +class Solution2(object): def wiggleSort(self, nums): """ :type nums: List[int] From 83f193aa501d0bd29d0581eacc57a7ac67be117d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 13:57:04 +0800 Subject: [PATCH 0861/1939] Update wiggle-sort.cpp --- C++/wiggle-sort.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/C++/wiggle-sort.cpp b/C++/wiggle-sort.cpp index 92235cfef..f635d7438 100644 --- a/C++/wiggle-sort.cpp +++ b/C++/wiggle-sort.cpp @@ -2,6 +2,20 @@ // Space: O(1) class Solution { +public: + void wiggleSort(vector& nums) { + for (int i = 1; i < nums.size(); ++i) { + if (((i & 1) && nums[i] < nums[i - 1]) || + (!(i & 1) && nums[i] > nums[i - 1])) { + // Swap unordered elements. + swap(nums[i], nums[i - 1]); + } + } + } +}; + + +class Solution2 { public: void wiggleSort(vector& nums) { if (nums.empty()) { From de2ca8945c9c0ab78f7692a6b3c0bdbcf0b13600 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 13:59:46 +0800 Subject: [PATCH 0862/1939] Update wiggle-sort.py --- Python/wiggle-sort.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/wiggle-sort.py b/Python/wiggle-sort.py index a172ecae3..0c59cd2be 100644 --- a/Python/wiggle-sort.py +++ b/Python/wiggle-sort.py @@ -12,6 +12,7 @@ def wiggleSort(self, nums): (not (i & 1) and nums[i - 1] < nums[i]): nums[i - 1], nums[i] = nums[i], nums[i - 1] + class Solution2(object): def wiggleSort(self, nums): """ From bf27f5f77edc85ffe28941ff3e321fe7e661e2b9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 14:02:40 +0800 Subject: [PATCH 0863/1939] Update wiggle-sort.cpp --- C++/wiggle-sort.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/wiggle-sort.cpp b/C++/wiggle-sort.cpp index f635d7438..afe332202 100644 --- a/C++/wiggle-sort.cpp +++ b/C++/wiggle-sort.cpp @@ -5,8 +5,8 @@ class Solution { public: void wiggleSort(vector& nums) { for (int i = 1; i < nums.size(); ++i) { - if (((i & 1) && nums[i] < nums[i - 1]) || - (!(i & 1) && nums[i] > nums[i - 1])) { + if (((i % 2) && nums[i] < nums[i - 1]) || + (!(i % 2) && nums[i] > nums[i - 1])) { // Swap unordered elements. swap(nums[i], nums[i - 1]); } From 20e3bf995bc969d68d87d90dad59e0f128434197 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 14:03:01 +0800 Subject: [PATCH 0864/1939] Update wiggle-sort.py --- Python/wiggle-sort.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/wiggle-sort.py b/Python/wiggle-sort.py index 0c59cd2be..13704adca 100644 --- a/Python/wiggle-sort.py +++ b/Python/wiggle-sort.py @@ -8,8 +8,8 @@ def wiggleSort(self, nums): :rtype: void Do not return anything, modify nums in-place instead. """ for i in xrange(1, len(nums)): - if ((i & 1) and nums[i - 1] > nums[i]) or \ - (not (i & 1) and nums[i - 1] < nums[i]): + if ((i % 2) and nums[i - 1] > nums[i]) or \ + (not (i % 2) and nums[i - 1] < nums[i]): nums[i - 1], nums[i] = nums[i], nums[i - 1] From 8bbb170346ee2e016b503a74207295ce543e26d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 14:04:31 +0800 Subject: [PATCH 0865/1939] Update wiggle-sort.cpp --- C++/wiggle-sort.cpp | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/C++/wiggle-sort.cpp b/C++/wiggle-sort.cpp index afe332202..7f550a748 100644 --- a/C++/wiggle-sort.cpp +++ b/C++/wiggle-sort.cpp @@ -13,26 +13,3 @@ class Solution { } } }; - - -class Solution2 { -public: - void wiggleSort(vector& nums) { - if (nums.empty()) { - return; - } - int pre = nums[0]; - bool inc = true; - for (int i = 1; i < nums.size(); ++i) { - if ((inc && pre <= nums[i]) || - (!inc && pre >= nums[i])) { - nums[i - 1] = pre; - pre = nums[i]; - } else { - nums[i - 1] = nums[i]; - } - inc = !inc; - } - nums.back() = pre; - } -}; From de39f25891710ea68b3b8b0ec119dd7b2f2a7015 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 14:04:44 +0800 Subject: [PATCH 0866/1939] Update wiggle-sort.py --- Python/wiggle-sort.py | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/Python/wiggle-sort.py b/Python/wiggle-sort.py index 13704adca..59a05ea64 100644 --- a/Python/wiggle-sort.py +++ b/Python/wiggle-sort.py @@ -11,25 +11,3 @@ def wiggleSort(self, nums): if ((i % 2) and nums[i - 1] > nums[i]) or \ (not (i % 2) and nums[i - 1] < nums[i]): nums[i - 1], nums[i] = nums[i], nums[i - 1] - - -class Solution2(object): - def wiggleSort(self, nums): - """ - :type nums: List[int] - :rtype: void Do not return anything, modify nums in-place instead. - """ - if not nums: - return - - pre = nums[0] - inc = True - for i in xrange(1, len(nums)): - if (inc and pre <= nums[i]) or \ - (not inc and pre >= nums[i]): - nums[i - 1] = pre - pre = nums[i] - else: - nums[i - 1] = nums[i] - inc = not inc - nums[-1] = pre From 28a01b46ccf9bc819337139e91fefc475953e1ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Sep 2015 14:05:37 +0800 Subject: [PATCH 0867/1939] Update wiggle-sort.py --- Python/wiggle-sort.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/wiggle-sort.py b/Python/wiggle-sort.py index 59a05ea64..fd3b0283f 100644 --- a/Python/wiggle-sort.py +++ b/Python/wiggle-sort.py @@ -10,4 +10,5 @@ def wiggleSort(self, nums): for i in xrange(1, len(nums)): if ((i % 2) and nums[i - 1] > nums[i]) or \ (not (i % 2) and nums[i - 1] < nums[i]): + # Swap unordered elements. nums[i - 1], nums[i] = nums[i], nums[i - 1] From 58cb3c941f402491b78daa8aa0b83b08c5e85fbb Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Sep 2015 20:41:46 +0800 Subject: [PATCH 0868/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8abd2d497..1e05d4058 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,8 @@ Shell -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || -190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(logn)_ | _O(1)_ | Easy || -191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(logn)_ | _O(1)_ | Easy || +190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(1)_ | _O(1)_ | Easy || +191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(1)_ | _O(1)_ | Easy || 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || From 43e290f03e3c5a76a6ec95078aa2c29cae27cb1f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 12 Sep 2015 02:01:37 +0800 Subject: [PATCH 0869/1939] Update longest-common-prefix.py --- Python/longest-common-prefix.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/longest-common-prefix.py b/Python/longest-common-prefix.py index 5c39975ab..29520fc63 100644 --- a/Python/longest-common-prefix.py +++ b/Python/longest-common-prefix.py @@ -1,4 +1,4 @@ -# Time: O(n1 + n2 + ...) +# Time: O(n) # Space: O(1) # # Write a function to find the longest common prefix string amongst an array of strings. From 108c80bfde0b754fcc53a287ae9e970c5b1b5e2b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 12 Sep 2015 02:02:01 +0800 Subject: [PATCH 0870/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e05d4058..f9ae3ed5a 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ Shell 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || -14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n1 + n2 + ...)_ | _O(1)_ | Easy || +14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || From d06ec3948d9450a36c0b652c0cb06cf458a4b28b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 10:10:47 +0800 Subject: [PATCH 0871/1939] Create zigzag-iterator.cpp --- C++/zigzag-iterator.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/zigzag-iterator.cpp diff --git a/C++/zigzag-iterator.cpp b/C++/zigzag-iterator.cpp new file mode 100644 index 000000000..04b233d35 --- /dev/null +++ b/C++/zigzag-iterator.cpp @@ -0,0 +1,37 @@ +// Time: O(n) +// Space: O(1) + +class ZigzagIterator { +public: + ZigzagIterator(vector& v1, vector& v2) { + if (!v1.empty()) { + deq.emplace_back(make_pair(v1.size(), v1.begin())); + } + if (!v2.empty()) { + deq.emplace_back(make_pair(v2.size(), v2.begin())); + } + } + + int next() { + const auto len = deq.front().first; + const auto it = deq.front().second; + deq.pop_front(); + if (len > 1) { + deq.emplace_back(make_pair(len - 1, it + 1)); + } + return *it; + } + + bool hasNext() { + return !deq.empty(); + } + +private: + deque::const_iterator>> deq; +}; + +/** + * Your ZigzagIterator object will be instantiated and called as such: + * ZigzagIterator i(v1, v2); + * while (i.hasNext()) cout << i.next(); + */ From 5adebd691c80c4516995765a66852c904e1d21d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 10:15:26 +0800 Subject: [PATCH 0872/1939] Update zigzag-iterator.cpp --- C++/zigzag-iterator.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/zigzag-iterator.cpp b/C++/zigzag-iterator.cpp index 04b233d35..cc1f33958 100644 --- a/C++/zigzag-iterator.cpp +++ b/C++/zigzag-iterator.cpp @@ -5,29 +5,29 @@ class ZigzagIterator { public: ZigzagIterator(vector& v1, vector& v2) { if (!v1.empty()) { - deq.emplace_back(make_pair(v1.size(), v1.begin())); + q.emplace(make_pair(v1.size(), v1.begin())); } if (!v2.empty()) { - deq.emplace_back(make_pair(v2.size(), v2.begin())); + q.emplace(make_pair(v2.size(), v2.begin())); } } int next() { - const auto len = deq.front().first; - const auto it = deq.front().second; - deq.pop_front(); + const auto len = q.front().first; + const auto it = q.front().second; + q.pop(); if (len > 1) { - deq.emplace_back(make_pair(len - 1, it + 1)); + q.emplace(make_pair(len - 1, it + 1)); } return *it; } bool hasNext() { - return !deq.empty(); + return !q.empty(); } private: - deque::const_iterator>> deq; + queue::const_iterator>> q; }; /** From 83dc4f54a1e51d7f219a473f545192ec0a253404 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 10:26:36 +0800 Subject: [PATCH 0873/1939] Create zigzag-iterator.py --- Python/zigzag-iterator.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/zigzag-iterator.py diff --git a/Python/zigzag-iterator.py b/Python/zigzag-iterator.py new file mode 100644 index 000000000..5ac3781ea --- /dev/null +++ b/Python/zigzag-iterator.py @@ -0,0 +1,31 @@ +# Time: O(n) +# Space: O(1) + +class ZigzagIterator(object): + + def __init__(self, v1, v2): + """ + Initialize your q structure here. + :type v1: List[int] + :type v2: List[int] + """ + self.q = collections.deque([(len(v), iter(v)) for v in (v1, v2) if v]) + + def next(self): + """ + :rtype: int + """ + len, iter = self.q.popleft() + if len > 1: + self.q.append((len-1, iter)) + return next(iter) + + def hasNext(self): + """ + :rtype: bool + """ + return bool(self.q) + +# Your ZigzagIterator object will be instantiated and called as such: +# i, v = ZigzagIterator(v1, v2), [] +# while i.hasNext(): v.append(i.next()) From 709610903375a0b4ff440c56a2e9c246c2854cdf Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 10:28:51 +0800 Subject: [PATCH 0874/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f9ae3ed5a..c0c6699e1 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-10), there are `263` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-14), there are `264` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `280` questions. +Here is the classification of all `281` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -168,6 +168,7 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard | EPI, LintCode | +281| [Zigzag Iterator](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/zigzag-iterator.cpp) [Python](./Python/zigzag-iterator.py) | _O(n)_ | _O(1)_ | Medium |📖|| --- From 8f1d546834611548dceb5d682faeffbdf005e4cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 10:56:54 +0800 Subject: [PATCH 0875/1939] Update count-univalue-subtrees.cpp --- C++/count-univalue-subtrees.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-univalue-subtrees.cpp b/C++/count-univalue-subtrees.cpp index 899047aab..885d96cd2 100644 --- a/C++/count-univalue-subtrees.cpp +++ b/C++/count-univalue-subtrees.cpp @@ -28,7 +28,7 @@ class Solution { isSame(root, root->right, right)) { ++(*count); return true; - } + } return false; } From d36b3bba86969111cc690df52a16fbbc97664060 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 15:57:56 +0800 Subject: [PATCH 0876/1939] Update zigzag-iterator.cpp --- C++/zigzag-iterator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/zigzag-iterator.cpp b/C++/zigzag-iterator.cpp index cc1f33958..1a2d0b9c0 100644 --- a/C++/zigzag-iterator.cpp +++ b/C++/zigzag-iterator.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(1) +// Space: O(k) class ZigzagIterator { public: From b6a633870030e3bed0a8fb9721ab35ea9277e169 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 15:58:13 +0800 Subject: [PATCH 0877/1939] Update zigzag-iterator.py --- Python/zigzag-iterator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/zigzag-iterator.py b/Python/zigzag-iterator.py index 5ac3781ea..9936e2d52 100644 --- a/Python/zigzag-iterator.py +++ b/Python/zigzag-iterator.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(1) +# Space: O(k) class ZigzagIterator(object): From 4c90f33e25796981e8dff69bf6e7c7afbeeb012d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 15:58:33 +0800 Subject: [PATCH 0878/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c0c6699e1..29faad213 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,7 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard | EPI, LintCode | -281| [Zigzag Iterator](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/zigzag-iterator.cpp) [Python](./Python/zigzag-iterator.py) | _O(n)_ | _O(1)_ | Medium |📖|| +281| [Zigzag Iterator](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/zigzag-iterator.cpp) [Python](./Python/zigzag-iterator.py) | _O(n)_ | _O(k)_ | Medium |📖|| --- From 768a53dd8e394d3132c7b1dc5777d0dbb2060b2b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 22:03:27 +0800 Subject: [PATCH 0879/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 29faad213..5e5206b64 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,7 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard | EPI, LintCode | -281| [Zigzag Iterator](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/zigzag-iterator.cpp) [Python](./Python/zigzag-iterator.py) | _O(n)_ | _O(k)_ | Medium |📖|| +281| [Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator/)| [C++](./C++/zigzag-iterator.cpp) [Python](./Python/zigzag-iterator.py) | _O(n)_ | _O(k)_ | Medium |📖|| --- From 90da714aa1bf13592474a932027679b0b8c2d38a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Sep 2015 22:44:07 +0800 Subject: [PATCH 0880/1939] Update zigzag-iterator.cpp --- C++/zigzag-iterator.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/zigzag-iterator.cpp b/C++/zigzag-iterator.cpp index 1a2d0b9c0..135c5de69 100644 --- a/C++/zigzag-iterator.cpp +++ b/C++/zigzag-iterator.cpp @@ -5,10 +5,10 @@ class ZigzagIterator { public: ZigzagIterator(vector& v1, vector& v2) { if (!v1.empty()) { - q.emplace(make_pair(v1.size(), v1.begin())); + q.emplace(make_pair(v1.size(), v1.cbegin())); } if (!v2.empty()) { - q.emplace(make_pair(v2.size(), v2.begin())); + q.emplace(make_pair(v2.size(), v2.cbegin())); } } From c1ea1e50a2c54c13f5f4ace36ee8e14708e0387b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 15:04:25 +0800 Subject: [PATCH 0881/1939] Create expression-add-operators.cpp --- C++/expression-add-operators.cpp | 69 ++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 C++/expression-add-operators.cpp diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp new file mode 100644 index 000000000..31096165c --- /dev/null +++ b/C++/expression-add-operators.cpp @@ -0,0 +1,69 @@ +// Time: O(3^n) +// Space: O(n) + +class Solution { +public: + vector addOperators(string num, int target) { + vector result; + vector expr; + addOperatorsDFS(num, target, 0, 0, 0, &expr, &result); + return result; + } + + bool addOperatorsDFS(const string& s, const int& target, const int& pos, + const int& operand1, const int& operand2, vector *expr, + vector *result) { + // Base Case 1 + if (pos == s.length()) { + if (operand1 + operand2 == target) { + string e; + for (int i = 0; i < expr->size(); ++i) { + if (i == 0 && (*expr)[i] == "+") { // Skip '+' at the beginning of the string. + continue; + } + e.append((*expr)[i]); + } + result->emplace_back(move(e)); + return true; + } + return false; + } + + int num = 0; + string num_str = ""; + for (int i = pos; i < s.length(); ++i) { + num_str += s[i]; + // Check if the value exceeds the max of INT. + if (num_str.size() == to_string(numeric_limits::max()).size() && + num_str > to_string(numeric_limits::max())) { + break; + } + + num = num * 10 + s[i] - '0'; + + // Case '+': + expr->emplace_back("+"), expr->emplace_back(num_str); + addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result); + expr->pop_back(), expr->pop_back(); + + + // '-' and '*' could be used only if the expression is not empty. + if (!expr->empty()) { + // Case '-': + expr->emplace_back("-"), expr->emplace_back(num_str); + addOperatorsDFS(s, target, i + 1, operand1 + operand2, -num, expr, result); + expr->pop_back(), expr->pop_back(); + + // Case '*': + expr->emplace_back("*"), expr->emplace_back(num_str); + addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result); + expr->pop_back(), expr->pop_back(); + } + + // Char is '0'. + if (num == 0) { + break; + } + } + } +}; From e137b415d2724d7b8b86b3aab666e9a9466e3e64 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 15:06:29 +0800 Subject: [PATCH 0882/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index 31096165c..edba092e4 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -30,7 +30,7 @@ class Solution { } int num = 0; - string num_str = ""; + string num_str; for (int i = pos; i < s.length(); ++i) { num_str += s[i]; // Check if the value exceeds the max of INT. From dd7dfab185e322d1136d2ba15f4a7ff7a0cffb3d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 15:09:22 +0800 Subject: [PATCH 0883/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5e5206b64..00788afe3 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-14), there are `264` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-15), there are `265` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `281` questions. +Here is the classification of all `282` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -386,6 +386,7 @@ Shell 250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtrees.cpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| 254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| +282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(3^n)_ | _O(n)_ | Hard ||| --- From 9598824029d79bbf216186cf4066e2c40c55b6ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 15:22:09 +0800 Subject: [PATCH 0884/1939] Create expression-add-operators.py --- Python/expression-add-operators.py | 66 ++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Python/expression-add-operators.py diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py new file mode 100644 index 000000000..ce2d029cf --- /dev/null +++ b/Python/expression-add-operators.py @@ -0,0 +1,66 @@ +# Time: O(3^n) +# Space: O(n) +# +# Given a string that contains only digits 0-9 +# and a target value, return all possibilities +# to add operators +, -, 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"] +# "00", 0 -> ["0+0", "0-0", "0*0"] +# "3456237490", 9191 -> [] +# + +class Solution(object): + def addOperators(self, num, target): + """ + :type num: str + :type target: int + :rtype: List[str] + """ + result, expr = [], [] + self.addOperatorsDFS(num, target, 0, 0, 0, expr, result) + return result + + def addOperatorsDFS(self, s, target, pos, operand1, operand2, expr, result): + # Base Case 1 + if pos == len(s): + if operand1 + operand2 == target: + e = "".join(expr) + e = e[1:] if e[0] == '+' else e + result.append(e) + return True + return False + + num, i = 0, pos + num_str = "" + while i < len(s): + num_str += s[i] + num = num * 10 + ord(s[i]) - ord('0') + + # Case '+': + expr.append("+"), expr.append(num_str) + self.addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result) + expr.pop(), expr.pop() + + + # '-' and '*' could be used only if the expression is not empty. + if expr: + # Case '-': + expr.append("-"), expr.append(num_str) + self.addOperatorsDFS(s, target, i + 1, operand1 + operand2, -num, expr, result) + expr.pop(), expr.pop() + + # Case '*': + expr.append("*"), expr.append(num_str) + self.addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result) + expr.pop(), expr.pop() + + # Char is '0'. + if num == 0: + break + + i += 1 + From 4ae401ee8fe0035007d137e70ece2c17973658a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 15:25:50 +0800 Subject: [PATCH 0885/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index edba092e4..fab912c8e 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -32,7 +32,7 @@ class Solution { int num = 0; string num_str; for (int i = pos; i < s.length(); ++i) { - num_str += s[i]; + num_str.push_back(s[i]); // Check if the value exceeds the max of INT. if (num_str.size() == to_string(numeric_limits::max()).size() && num_str > to_string(numeric_limits::max())) { From 2889e2966c08e17a1ae26691ee51db01e7c51c54 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 15:33:01 +0800 Subject: [PATCH 0886/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index fab912c8e..4124d9415 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -16,14 +16,7 @@ class Solution { // Base Case 1 if (pos == s.length()) { if (operand1 + operand2 == target) { - string e; - for (int i = 0; i < expr->size(); ++i) { - if (i == 0 && (*expr)[i] == "+") { // Skip '+' at the beginning of the string. - continue; - } - e.append((*expr)[i]); - } - result->emplace_back(move(e)); + result->emplace_back(move(join(*expr))); return true; } return false; @@ -66,4 +59,15 @@ class Solution { } } } + + string join(const vector& expr) { + string e; + for (int i = 0; i < expr.size(); ++i) { + if (i == 0 && expr[i] == "+") { // Skip '+' at the beginning of the string. + continue; + } + e.append(expr[i]); + } + return e; + } }; From 8ebc2aadfbb8857de0a6dd6e50e3529f1a06ed57 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 15:34:03 +0800 Subject: [PATCH 0887/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index 4124d9415..9f0d0ebeb 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -38,7 +38,6 @@ class Solution { expr->emplace_back("+"), expr->emplace_back(num_str); addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result); expr->pop_back(), expr->pop_back(); - // '-' and '*' could be used only if the expression is not empty. if (!expr->empty()) { From b5ee1f3dfccd3a18698ada03442854479e406d37 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 15:37:24 +0800 Subject: [PATCH 0888/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index ce2d029cf..f06a18ec5 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -44,7 +44,6 @@ def addOperatorsDFS(self, s, target, pos, operand1, operand2, expr, result): expr.append("+"), expr.append(num_str) self.addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result) expr.pop(), expr.pop() - # '-' and '*' could be used only if the expression is not empty. if expr: From c02ef34045fb4fb2c22d3bbf53ac54f8dbc32d00 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 16:37:38 +0800 Subject: [PATCH 0889/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index 9f0d0ebeb..116eab594 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -27,7 +27,7 @@ class Solution { for (int i = pos; i < s.length(); ++i) { num_str.push_back(s[i]); // Check if the value exceeds the max of INT. - if (num_str.size() == to_string(numeric_limits::max()).size() && + if (num_str.length() == to_string(numeric_limits::max()).length() && num_str > to_string(numeric_limits::max())) { break; } From 84fe01a3cf3cd70aba4e6c7a6fa868287e683709 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 16:40:17 +0800 Subject: [PATCH 0890/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index 116eab594..7062b4f7b 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -10,16 +10,15 @@ class Solution { return result; } - bool addOperatorsDFS(const string& s, const int& target, const int& pos, + void addOperatorsDFS(const string& s, const int& target, const int& pos, const int& operand1, const int& operand2, vector *expr, vector *result) { // Base Case 1 if (pos == s.length()) { if (operand1 + operand2 == target) { result->emplace_back(move(join(*expr))); - return true; } - return false; + return; } int num = 0; From aee02d890d5025c6d6cc48d62db87de235c524a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 16:40:58 +0800 Subject: [PATCH 0891/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index f06a18ec5..a8560261f 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -31,8 +31,7 @@ def addOperatorsDFS(self, s, target, pos, operand1, operand2, expr, result): e = "".join(expr) e = e[1:] if e[0] == '+' else e result.append(e) - return True - return False + return num, i = 0, pos num_str = "" From 3434639ee573fb3277655002cef4dc55cec555d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 16:41:48 +0800 Subject: [PATCH 0892/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index a8560261f..17599bc52 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -1,4 +1,4 @@ -# Time: O(3^n) +# Time: O(4^n) # Space: O(n) # # Given a string that contains only digits 0-9 From 2a49aabad7f3d538f4b0ae5257ef185542dbedfb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 16:42:05 +0800 Subject: [PATCH 0893/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index 7062b4f7b..3cb2079eb 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -1,4 +1,4 @@ -// Time: O(3^n) +// Time: O(4^n) // Space: O(n) class Solution { From 23254b09c0fd778cfc16ced78e4ddee2535182d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 16:42:27 +0800 Subject: [PATCH 0894/1939] Update README.md --- README.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 00788afe3..fafbd4cf7 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,7 @@ Here is the classification of all `282` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) - ---- -Algorithms -==== - +2 * [Bit Manipulation](https://github.com/kamyu104/LeetCode#bit-manipulation) * [Array](https://github.com/kamyu104/LeetCode#array) * [String](https://github.com/kamyu104/LeetCode#string) @@ -386,7 +382,7 @@ Shell 250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtrees.cpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| 254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| -282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(3^n)_ | _O(n)_ | Hard ||| +282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| --- From 918ffc72aeff3a94cc04af67d5e8154e2afffbf1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 16:43:42 +0800 Subject: [PATCH 0895/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index 17599bc52..3cf70d711 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -25,7 +25,6 @@ def addOperators(self, num, target): return result def addOperatorsDFS(self, s, target, pos, operand1, operand2, expr, result): - # Base Case 1 if pos == len(s): if operand1 + operand2 == target: e = "".join(expr) From 6583d73e34293b2e38dfd336d391eed487bfb25a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 16:44:04 +0800 Subject: [PATCH 0896/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index 3cb2079eb..e47f44d79 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -13,7 +13,6 @@ class Solution { void addOperatorsDFS(const string& s, const int& target, const int& pos, const int& operand1, const int& operand2, vector *expr, vector *result) { - // Base Case 1 if (pos == s.length()) { if (operand1 + operand2 == target) { result->emplace_back(move(join(*expr))); From 41a7e8c3e48aff1957ff22d07680080cbeb5c64f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 16:48:09 +0800 Subject: [PATCH 0897/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fafbd4cf7..17db29426 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Here is the classification of all `282` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) -2 + * [Bit Manipulation](https://github.com/kamyu104/LeetCode#bit-manipulation) * [Array](https://github.com/kamyu104/LeetCode#array) * [String](https://github.com/kamyu104/LeetCode#string) From 359977390a4491d73a06f7052455525c24b65828 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 22:27:49 +0800 Subject: [PATCH 0898/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index e47f44d79..b5cfa4b53 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -24,13 +24,11 @@ class Solution { string num_str; for (int i = pos; i < s.length(); ++i) { num_str.push_back(s[i]); - // Check if the value exceeds the max of INT. - if (num_str.length() == to_string(numeric_limits::max()).length() && - num_str > to_string(numeric_limits::max())) { + num = num * 10 + s[i] - '0'; + // Avoid overflow and "00...". + if (to_string(num) != num_str) { break; } - - num = num * 10 + s[i] - '0'; // Case '+': expr->emplace_back("+"), expr->emplace_back(num_str); @@ -49,11 +47,6 @@ class Solution { addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result); expr->pop_back(), expr->pop_back(); } - - // Char is '0'. - if (num == 0) { - break; - } } } From 1b616c1b0b7cfb156b7826e35162df20bf39242d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 22:29:16 +0800 Subject: [PATCH 0899/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index b5cfa4b53..d29910c92 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -23,8 +23,8 @@ class Solution { int num = 0; string num_str; for (int i = pos; i < s.length(); ++i) { - num_str.push_back(s[i]); num = num * 10 + s[i] - '0'; + num_str.push_back(s[i]); // Avoid overflow and "00...". if (to_string(num) != num_str) { break; From d67005f597faeabd947085b71569e3b40c4faf21 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 22:30:48 +0800 Subject: [PATCH 0900/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index 3cf70d711..5f7f7014c 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -35,8 +35,10 @@ def addOperatorsDFS(self, s, target, pos, operand1, operand2, expr, result): num, i = 0, pos num_str = "" while i < len(s): - num_str += s[i] num = num * 10 + ord(s[i]) - ord('0') + num_str += s[i] + if str(num) != num_str: + break # Case '+': expr.append("+"), expr.append(num_str) @@ -54,10 +56,6 @@ def addOperatorsDFS(self, s, target, pos, operand1, operand2, expr, result): expr.append("*"), expr.append(num_str) self.addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result) expr.pop(), expr.pop() - - # Char is '0'. - if num == 0: - break i += 1 From fcfb5d2d3499e01bb018533b44e9d1cde345c79d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 22:31:41 +0800 Subject: [PATCH 0901/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index 5f7f7014c..fe420e123 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -37,6 +37,7 @@ def addOperatorsDFS(self, s, target, pos, operand1, operand2, expr, result): while i < len(s): num = num * 10 + ord(s[i]) - ord('0') num_str += s[i] + # Avoid overflow and "00...". if str(num) != num_str: break From 6a76bd01203fddf17ac6320d7fb080dc5ed55925 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 22:49:43 +0800 Subject: [PATCH 0902/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 56 +++++++++++++++++------------- 1 file changed, 31 insertions(+), 25 deletions(-) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index fe420e123..6e0f2b033 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -21,42 +21,48 @@ def addOperators(self, num, target): :rtype: List[str] """ result, expr = [], [] - self.addOperatorsDFS(num, target, 0, 0, 0, expr, result) + val, i = 0, 0 + val_str = "" + while i < len(num): + val = val * 10 + ord(num[i]) - ord('0') + val_str += num[i] + if str(val) != val_str: + break + expr.append(val_str) + self.addOperatorsDFS(num, target, i + 1, 0, val, expr, result) + expr.pop() + i += 1 return result - def addOperatorsDFS(self, s, target, pos, operand1, operand2, expr, result): - if pos == len(s): + def addOperatorsDFS(self, num, target, pos, operand1, operand2, expr, result): + if pos == len(num): if operand1 + operand2 == target: e = "".join(expr) - e = e[1:] if e[0] == '+' else e result.append(e) return - num, i = 0, pos - num_str = "" - while i < len(s): - num = num * 10 + ord(s[i]) - ord('0') - num_str += s[i] - # Avoid overflow and "00...". - if str(num) != num_str: + val, i = 0, pos + val_str = "" + while i < len(num): + val = val * 10 + ord(num[i]) - ord('0') + val_str += num[i] + if str(val) != val_str: break # Case '+': - expr.append("+"), expr.append(num_str) - self.addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result) - expr.pop(), expr.pop() + expr.append("+" + val_str) + self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result) + expr.pop() - # '-' and '*' could be used only if the expression is not empty. - if expr: - # Case '-': - expr.append("-"), expr.append(num_str) - self.addOperatorsDFS(s, target, i + 1, operand1 + operand2, -num, expr, result) - expr.pop(), expr.pop() - - # Case '*': - expr.append("*"), expr.append(num_str) - self.addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result) - expr.pop(), expr.pop() + # Case '-': + expr.append("-" + val_str) + self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result) + expr.pop() + + # Case '*': + expr.append("*" + val_str) + self.addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result) + expr.pop() i += 1 From f8dd88aeef229b18316588bee871ac3c15701bb9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 22:51:59 +0800 Subject: [PATCH 0903/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 50 ++++++++++++++---------------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index 6e0f2b033..455cc57c8 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -35,34 +35,32 @@ def addOperators(self, num, target): return result def addOperatorsDFS(self, num, target, pos, operand1, operand2, expr, result): - if pos == len(num): - if operand1 + operand2 == target: + if pos == len(num) and operand1 + operand2 == target: e = "".join(expr) result.append(e) - return - - val, i = 0, pos - val_str = "" - while i < len(num): - val = val * 10 + ord(num[i]) - ord('0') - val_str += num[i] - if str(val) != val_str: - break - - # Case '+': - expr.append("+" + val_str) - self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result) - expr.pop() - - # Case '-': - expr.append("-" + val_str) - self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result) - expr.pop() + else: + val, i = 0, pos + val_str = "" + while i < len(num): + val = val * 10 + ord(num[i]) - ord('0') + val_str += num[i] + if str(val) != val_str: + break - # Case '*': - expr.append("*" + val_str) - self.addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result) - expr.pop() + # Case '+': + expr.append("+" + val_str) + self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result) + expr.pop() - i += 1 + # Case '-': + expr.append("-" + val_str) + self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result) + expr.pop() + + # Case '*': + expr.append("*" + val_str) + self.addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result) + expr.pop() + + i += 1 From 447cbf6e19166aacfc655ef342098ef2b4942528 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 23:01:53 +0800 Subject: [PATCH 0904/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 68 +++++++++++++++++--------------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index d29910c92..2b54cc27e 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -6,58 +6,62 @@ class Solution { vector addOperators(string num, int target) { vector result; vector expr; - addOperatorsDFS(num, target, 0, 0, 0, &expr, &result); + int val = 0; + string val_str; + for (int i = 0; i < num.length(); ++i) { + val = val * 10 + num[i] - '0'; + val_str.push_back(num[i]); + // Avoid overflow and "00...". + if (to_string(val) != val_str) { + break; + } + expr.emplace_back(val_str); + addOperatorsDFS(num, target, i + 1, 0, val, &expr, &result); + expr.pop_back(); + } return result; } - void addOperatorsDFS(const string& s, const int& target, const int& pos, + void addOperatorsDFS(const string& num, const int& target, const int& pos, const int& operand1, const int& operand2, vector *expr, vector *result) { - if (pos == s.length()) { + if (pos == num.length()) { if (operand1 + operand2 == target) { result->emplace_back(move(join(*expr))); } return; } - int num = 0; - string num_str; - for (int i = pos; i < s.length(); ++i) { - num = num * 10 + s[i] - '0'; - num_str.push_back(s[i]); + int val = 0; + string val_str; + for (int i = pos; i < num.length(); ++i) { + val = val * 10 + num[i] - '0'; + val_str.push_back(num[i]); // Avoid overflow and "00...". - if (to_string(num) != num_str) { + if (to_string(val) != val_str) { break; } // Case '+': - expr->emplace_back("+"), expr->emplace_back(num_str); - addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result); - expr->pop_back(), expr->pop_back(); + expr->emplace_back("+" + val_str); + addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result); + expr->pop_back(); - // '-' and '*' could be used only if the expression is not empty. - if (!expr->empty()) { - // Case '-': - expr->emplace_back("-"), expr->emplace_back(num_str); - addOperatorsDFS(s, target, i + 1, operand1 + operand2, -num, expr, result); - expr->pop_back(), expr->pop_back(); - - // Case '*': - expr->emplace_back("*"), expr->emplace_back(num_str); - addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result); - expr->pop_back(), expr->pop_back(); - } + // Case '-': + expr->emplace_back("-" + val_str); + addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result); + expr->pop_back(); + + // Case '*': + expr->emplace_back("*" + val_str); + addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result); + expr->pop_back(); } } string join(const vector& expr) { - string e; - for (int i = 0; i < expr.size(); ++i) { - if (i == 0 && expr[i] == "+") { // Skip '+' at the beginning of the string. - continue; - } - e.append(expr[i]); - } - return e; + ostringstream stream; + copy(expr.cbegin(), expr.cend(), ostream_iterator(stream)); + return stream.str(); } }; From 1af7e2be85920ad45e2b80cae58bacb5669c3a67 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 23:04:01 +0800 Subject: [PATCH 0905/1939] Update expression-add-operators.cpp --- C++/expression-add-operators.cpp | 59 +++++++++++++++----------------- 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/C++/expression-add-operators.cpp b/C++/expression-add-operators.cpp index 2b54cc27e..7a817a5c3 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -23,39 +23,36 @@ class Solution { } void addOperatorsDFS(const string& num, const int& target, const int& pos, - const int& operand1, const int& operand2, vector *expr, - vector *result) { - if (pos == num.length()) { - if (operand1 + operand2 == target) { - result->emplace_back(move(join(*expr))); - } - return; - } + const int& operand1, const int& operand2, + vector *expr, vector *result) { + if (pos == num.length() && operand1 + operand2 == target) { + result->emplace_back(move(join(*expr))); + } else { + int val = 0; + string val_str; + for (int i = pos; i < num.length(); ++i) { + val = val * 10 + num[i] - '0'; + val_str.push_back(num[i]); + // Avoid overflow and "00...". + if (to_string(val) != val_str) { + break; + } - int val = 0; - string val_str; - for (int i = pos; i < num.length(); ++i) { - val = val * 10 + num[i] - '0'; - val_str.push_back(num[i]); - // Avoid overflow and "00...". - if (to_string(val) != val_str) { - break; - } - - // Case '+': - expr->emplace_back("+" + val_str); - addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result); - expr->pop_back(); - - // Case '-': - expr->emplace_back("-" + val_str); - addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result); - expr->pop_back(); + // Case '+': + expr->emplace_back("+" + val_str); + addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result); + expr->pop_back(); - // Case '*': - expr->emplace_back("*" + val_str); - addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result); - expr->pop_back(); + // Case '-': + expr->emplace_back("-" + val_str); + addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result); + expr->pop_back(); + + // Case '*': + expr->emplace_back("*" + val_str); + addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result); + expr->pop_back(); + } } } From 6cba1243dd0426ec628b3f8c70045dd47f62427d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 23:07:38 +0800 Subject: [PATCH 0906/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index 455cc57c8..27f8117f4 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -26,6 +26,7 @@ def addOperators(self, num, target): while i < len(num): val = val * 10 + ord(num[i]) - ord('0') val_str += num[i] + # Avoid "00...". if str(val) != val_str: break expr.append(val_str) @@ -44,6 +45,7 @@ def addOperatorsDFS(self, num, target, pos, operand1, operand2, expr, result): while i < len(num): val = val * 10 + ord(num[i]) - ord('0') val_str += num[i] + # Avoid "00...". if str(val) != val_str: break From 7e3c32317271946ae73222d515396032e2a96efa Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 23:09:29 +0800 Subject: [PATCH 0907/1939] Update expression-add-operators.py --- Python/expression-add-operators.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index 27f8117f4..15d972d3f 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -37,8 +37,7 @@ def addOperators(self, num, target): def addOperatorsDFS(self, num, target, pos, operand1, operand2, expr, result): if pos == len(num) and operand1 + operand2 == target: - e = "".join(expr) - result.append(e) + result.append("".join(expr)) else: val, i = 0, pos val_str = "" From b24cb7d52d1ec044bb70150f68809b04ec4b9aa8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 23:30:46 +0800 Subject: [PATCH 0908/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 842840bf4..00b28e0fe 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -48,11 +48,11 @@ def nextNode(stack, child1, child2): result = [] for _ in xrange(k): if not backward_stack or \ - forward_stack and dist(forward_stack[-1]) < dist(backward_stack[-1]): + (forward_stack and dist(forward_stack[-1]) < dist(backward_stack[-1])): result.append(forward_stack[-1].val) nextNode(forward_stack, forward, backward) elif not forward_stack or \ - forward_stack and dist(backward_stack[-1]) <= dist(forward_stack[-1]): + (backward_stack and dist(backward_stack[-1]) <= dist(forward_stack[-1])): result.append(backward_stack[-1].val) nextNode(backward_stack, backward, forward) return result From cdf66cc823057cbd0b96cc59307b1e2f5630dbf5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 23:31:57 +0800 Subject: [PATCH 0909/1939] Update closest-binary-search-tree-value-ii.cpp --- C++/closest-binary-search-tree-value-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/closest-binary-search-tree-value-ii.cpp b/C++/closest-binary-search-tree-value-ii.cpp index 6885c709f..528c7c809 100644 --- a/C++/closest-binary-search-tree-value-ii.cpp +++ b/C++/closest-binary-search-tree-value-ii.cpp @@ -36,11 +36,11 @@ class Solution { vector result; for (int i = 0; i < k; ++i) { if (backward_stack.empty() || - !forward_stack.empty() && closest(forward_stack.back(), backward_stack.back())) { + (!forward_stack.empty() && closest(forward_stack.back(), backward_stack.back()))) { result.emplace_back(forward_stack.back()->val); nextNode(forward_stack, forward, backward); } else if (forward_stack.empty() || - !forward_stack.empty() && !closest(forward_stack.back(), backward_stack.back())) { + (!backward_stack.empty() && !closest(forward_stack.back(), backward_stack.back()))) { result.emplace_back(backward_stack.back()->val); nextNode(backward_stack, backward, forward); } From 68a1a55335a10ab0b2da8c1697f0721f147eb3e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 23:37:13 +0800 Subject: [PATCH 0910/1939] Update closest-binary-search-tree-value-ii.cpp --- C++/closest-binary-search-tree-value-ii.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/closest-binary-search-tree-value-ii.cpp b/C++/closest-binary-search-tree-value-ii.cpp index 528c7c809..6b0da1019 100644 --- a/C++/closest-binary-search-tree-value-ii.cpp +++ b/C++/closest-binary-search-tree-value-ii.cpp @@ -35,12 +35,12 @@ class Solution { // Get the closest k values by advancing the iterators of the stacks. vector result; for (int i = 0; i < k; ++i) { - if (backward_stack.empty() || - (!forward_stack.empty() && closest(forward_stack.back(), backward_stack.back()))) { + if (!forward_stack.empty() && + (backward_stack.empty() || closest(forward_stack.back(), backward_stack.back()))) { result.emplace_back(forward_stack.back()->val); nextNode(forward_stack, forward, backward); - } else if (forward_stack.empty() || - (!backward_stack.empty() && !closest(forward_stack.back(), backward_stack.back()))) { + } else if (!backward_stack.empty() && + (forward_stack.empty() || !closest(forward_stack.back(), backward_stack.back()))) { result.emplace_back(backward_stack.back()->val); nextNode(backward_stack, backward, forward); } From fc12ddeaf129dfa780e218972fc01b476bd27728 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Sep 2015 23:40:48 +0800 Subject: [PATCH 0911/1939] Update closest-binary-search-tree-value-ii.py --- Python/closest-binary-search-tree-value-ii.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 00b28e0fe..4672e0cc6 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -47,12 +47,12 @@ def nextNode(stack, child1, child2): # Get the closest k values by advancing the iterators of the stacks. result = [] for _ in xrange(k): - if not backward_stack or \ - (forward_stack and dist(forward_stack[-1]) < dist(backward_stack[-1])): + if forward_stack and \ + (not backward_stack or dist(forward_stack[-1]) < dist(backward_stack[-1])): result.append(forward_stack[-1].val) nextNode(forward_stack, forward, backward) - elif not forward_stack or \ - (backward_stack and dist(backward_stack[-1]) <= dist(forward_stack[-1])): + elif backward_stack and \ + (not forward_stack or dist(backward_stack[-1]) <= dist(forward_stack[-1])): result.append(backward_stack[-1].val) nextNode(backward_stack, backward, forward) return result From ff2ef7938ca32db995c4880adf86abf426e6b081 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 17 Sep 2015 02:14:47 +0800 Subject: [PATCH 0912/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 17db29426..ae94e3d23 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-09-15), there are `265` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-16), there are `265` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `282` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 10c0d038e1fdba95d49da7248e76f52b717893dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Sep 2015 10:48:31 +0800 Subject: [PATCH 0913/1939] Create move-zeros.py --- Python/move-zeros.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/move-zeros.py diff --git a/Python/move-zeros.py b/Python/move-zeros.py new file mode 100644 index 000000000..820f2a5aa --- /dev/null +++ b/Python/move-zeros.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(1) +# +# Given an array nums, write a function to move all 0's +# to the end of it while maintaining the relative order +# of the non-zero elements. +# +# For example, given nums = [0, 1, 0, 3, 12], after +# calling your function, nums should be [1, 3, 12, 0, 0]. +# +# Note: +# You must do this in-place without making a copy of the array. +# Minimize the total number of operations. +# + +class Solution(object): + def moveZeroes(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + pos = 0 + for i in xrange(len(nums)): + if nums[i]: + nums[i], nums[pos] = nums[pos], nums[i] + pos += 1 + + +class Solution2(object): + def moveZeroes(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + pos = 0 + for i in xrange(len(nums)): + if nums[i]: + nums[pos] = nums[i] + pos += 1 + + for i in xrange(pos, len(nums)): + nums[i] = 0 From 1969560f4c8ba47aa76624b7301c471f2ed8655f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Sep 2015 10:55:18 +0800 Subject: [PATCH 0914/1939] Create move-zeros.cpp --- C++/move-zeros.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/move-zeros.cpp diff --git a/C++/move-zeros.cpp b/C++/move-zeros.cpp new file mode 100644 index 000000000..8f984a02e --- /dev/null +++ b/C++/move-zeros.cpp @@ -0,0 +1,27 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + void moveZeroes(vector& nums) { + int pos = 0; + for (auto& num : nums) { + if (num) { + swap(nums[pos++], num); + } + } + } +}; + +class Solution2 { +public: + void moveZeroes(vector& nums) { + int pos = 0; + for (const auto& num : nums) { + if (num) { + nums[pos++] = num; + } + } + fill(next(nums.begin(), pos), nums.end(), 0); + } +}; From 2cc6adefe54ebcdfa638923f434bacd5af342d28 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Sep 2015 11:00:20 +0800 Subject: [PATCH 0915/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ae94e3d23..60f4db3b4 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-16), there are `265` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-18), there are `266` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `282` questions. +Here is the classification of all `283` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -276,6 +276,7 @@ Shell 143| [Reorder List](https://leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || 167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [C++](./C++/3sum-smaller.cpp) [Python](./Python/3sum-smaller.py) | _O(n^2)_ | _O(1)_ | Medium | 📖, LintCode | +283 | [Move Zeros](https://leetcode.com/problems/move-zeros/) | [C++](./C++/move-zeros.cpp) [Python](./Python/move-zeros.py) | _O(n)_ | _O(1)_ | Easy | | --- From 66e4767e2f89865eb9d16fcc046c95c60b3f5cb6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Sep 2015 22:54:56 +0800 Subject: [PATCH 0916/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 60f4db3b4..4213bfcba 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ LeetCode ======== -Up to date (2015-09-18), there are `266` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-19), there are `266` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `283` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 60d7522be7a8b80cd6428d75e2634374cb7d98b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Sep 2015 09:38:04 +0800 Subject: [PATCH 0917/1939] Create peeking-iterator.cpp --- C++/peeking-iterator.cpp | 57 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 C++/peeking-iterator.cpp diff --git a/C++/peeking-iterator.cpp b/C++/peeking-iterator.cpp new file mode 100644 index 000000000..28be71c21 --- /dev/null +++ b/C++/peeking-iterator.cpp @@ -0,0 +1,57 @@ +// Time: O(1) +// Space: O(1) + +// Below is the interface for Iterator, which is already defined for you. +// **DO NOT** modify the interface for Iterator. +class Iterator { + struct Data; + Data* data; +public: + Iterator(const vector& nums); + Iterator(const Iterator& iter); + virtual ~Iterator(); + // Returns the next element in the iteration. + int next(); + // Returns true if the iteration has more elements. + bool hasNext() const; +}; + + +class PeekingIterator : public Iterator { +public: + PeekingIterator(const vector& nums) : Iterator(nums), has_next_(Iterator::hasNext()) { + // Initialize any member here. + // **DO NOT** save a copy of nums and manipulate it directly. + // You should only use the Iterator interface methods. + } + + // Returns the next element in the iteration without advancing the iterator. + int peek() { + if (!has_peeked_) { + has_peeked_ = true; + val_ = Iterator::next(); + } + return val_; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + int next() { + if (!has_peeked_) { + val_ = Iterator::next(); + } else { + has_peeked_ = false; + } + has_next_ = Iterator::hasNext(); + return val_; + } + + bool hasNext() const { + return has_next_; + } + +private: + int val_; + bool has_next_; + bool has_peeked_ = false; +}; From 48d3342a55a6efa63ee8e50a3f8e08940c50fe79 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Sep 2015 09:50:17 +0800 Subject: [PATCH 0918/1939] Create peeking-iterator.py --- Python/peeking-iterator.py | 83 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Python/peeking-iterator.py diff --git a/Python/peeking-iterator.py b/Python/peeking-iterator.py new file mode 100644 index 000000000..f21db1fa3 --- /dev/null +++ b/Python/peeking-iterator.py @@ -0,0 +1,83 @@ +# Time: O(1) per peek(), next(), hasNext() +# Space: O(1) + +# Given an Iterator class interface with methods: next() and hasNext(), +# design and implement a PeekingIterator that support the peek() operation -- +# it essentially peek() at the element that will be returned by the next call to next(). +# +# Here is an example. Assume that the iterator is initialized to the beginning of +# the list: [1, 2, 3]. +# +# Call next() gets you 1, the first element in the list. +# +# Now you call peek() and it returns 2, the next element. Calling next() after that +# still return 2. +# +# You call next() the final time and it returns 3, the last element. Calling hasNext() +# after that should return false. +# + +# Below is the interface for Iterator, which is already defined for you. +# +# class Iterator(object): +# def __init__(self, nums): +# """ +# Initializes an iterator object to the beginning of a list. +# :type nums: List[int] +# """ +# +# def hasNext(self): +# """ +# Returns true if the iteration has more elements. +# :rtype: bool +# """ +# +# def next(self): +# """ +# Returns the next element in the iteration. +# :rtype: int +# """ + +class PeekingIterator(object): + def __init__(self, iterator): + """ + Initialize your data structure here. + :type iterator: Iterator + """ + self.iterator = iterator + self.val_ = None + self.has_next_ = iterator.hasNext() + self.has_peeked_ = False + + + def peek(self): + """ + Returns the next element in the iteration without advancing the iterator. + :rtype: int + """ + if not self.has_peeked_: + self.has_peeked_ = True + self.val_ = self.iterator.next() + return self.val_; + + def next(self): + """ + :rtype: int + """ + self.val_ = self.peek() + self.has_peeked_ = False + self.has_next_ = self.iterator.hasNext() + return self.val_; + + def hasNext(self): + """ + :rtype: bool + """ + return self.has_next_ + + +# Your PeekingIterator object will be instantiated and called as such: +# iter = PeekingIterator(Iterator(nums)) +# while iter.hasNext(): +# val = iter.peek() # Get the next element but not advance the iterator. +# iter.next() # Should return the same value as [val]. From fd52d7da039c77e603083c6110c362762a72e75d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Sep 2015 09:51:48 +0800 Subject: [PATCH 0919/1939] Update peeking-iterator.cpp --- C++/peeking-iterator.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/C++/peeking-iterator.cpp b/C++/peeking-iterator.cpp index 28be71c21..ed7d1a880 100644 --- a/C++/peeking-iterator.cpp +++ b/C++/peeking-iterator.cpp @@ -37,11 +37,8 @@ class PeekingIterator : public Iterator { // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { - if (!has_peeked_) { - val_ = Iterator::next(); - } else { - has_peeked_ = false; - } + val_ = peek(); + has_peeked_ = false; has_next_ = Iterator::hasNext(); return val_; } From 6261268dad0ae5e67b0265c5e0aeed0de022dea5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Sep 2015 09:55:34 +0800 Subject: [PATCH 0920/1939] Update README.md --- README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4213bfcba..2ac7ccc0b 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-19), there are `266` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-21), there are `267` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `283` questions. +Here is the classification of all `284` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -30,6 +30,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates * [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) * [Backtracking](https://github.com/kamyu104/LeetCode#backtracking) * [Greedy](https://github.com/kamyu104/LeetCode#greedy) +* [Design](https://github.com/kamyu104/LeetCode#design) Database @@ -441,6 +442,12 @@ Shell 134| [Gas Station](https://leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || 135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || +--- +##Design + # | Problem | Solution | Time | Space | Difficulty | Tag | Note +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +284| [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [C++](./C++/peeking-iterator.cpp) [Python](./Python/peeking-iterator.py) | _O(1)_ | _O(1)_ | Medium || + --- ##SQL From 47016333ac2c58d81edd980c95b866c408c3f6c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Sep 2015 09:56:24 +0800 Subject: [PATCH 0921/1939] Update peeking-iterator.cpp --- C++/peeking-iterator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/peeking-iterator.cpp b/C++/peeking-iterator.cpp index ed7d1a880..fa5e500be 100644 --- a/C++/peeking-iterator.cpp +++ b/C++/peeking-iterator.cpp @@ -1,4 +1,4 @@ -// Time: O(1) +// Time: O(1) per peek(), next(), hasNext() // Space: O(1) // Below is the interface for Iterator, which is already defined for you. From 8bfc94f852294c7f846b76a81bccc588f90a5463 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Sep 2015 19:42:04 +0800 Subject: [PATCH 0922/1939] Create inorder-successor-in-bst.cpp --- C++/inorder-successor-in-bst.cpp | 38 ++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/inorder-successor-in-bst.cpp diff --git a/C++/inorder-successor-in-bst.cpp b/C++/inorder-successor-in-bst.cpp new file mode 100644 index 000000000..04c85116b --- /dev/null +++ b/C++/inorder-successor-in-bst.cpp @@ -0,0 +1,38 @@ +// Time: O(logn) +// Space: O(1) + +/** + * 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: + TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { + // If it has right subtree. + if (p->right) { + p = p->right; + while (p->left) { + p = p->left; + } + return p; + } + + // Search from root. + TreeNode *successor = nullptr; + while (root && root != p ) { + if (root->val > p->val) { + successor = root; + root = root->left; + } else { + root = root->right; + } + } + + return successor; + } +}; From 24cfce39bf922ab5c237dd2708f8b3e3665bfb21 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Sep 2015 19:45:47 +0800 Subject: [PATCH 0923/1939] Create inorder-successor-in-bst.py --- Python/inorder-successor-in-bst.py | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/inorder-successor-in-bst.py diff --git a/Python/inorder-successor-in-bst.py b/Python/inorder-successor-in-bst.py new file mode 100644 index 000000000..bdd8d7c4e --- /dev/null +++ b/Python/inorder-successor-in-bst.py @@ -0,0 +1,34 @@ +# Time: O(logn) +# Space: O(1) + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def inorderSuccessor(self, root, p): + """ + :type root: TreeNode + :type p: TreeNode + :rtype: TreeNode + """ + # If it has right subtree. + if p.right: + p = p.right + while p.left: + p = p.left + return p + + # Search from root. + successor = None + while root and root != p: + if root.val > p.val: + successor = root + root = root.left + else: + root = root.right + + return successor From 0c95a3e3737d86b847fd06fd32a91e11087604f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Sep 2015 19:51:01 +0800 Subject: [PATCH 0924/1939] Update inorder-successor-in-bst.cpp --- C++/inorder-successor-in-bst.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/inorder-successor-in-bst.cpp b/C++/inorder-successor-in-bst.cpp index 04c85116b..36e2482fc 100644 --- a/C++/inorder-successor-in-bst.cpp +++ b/C++/inorder-successor-in-bst.cpp @@ -24,7 +24,7 @@ class Solution { // Search from root. TreeNode *successor = nullptr; - while (root && root != p ) { + while (root && root != p) { if (root->val > p->val) { successor = root; root = root->left; From c525197d98596bb0931598fc12b8813d9861e7b4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Sep 2015 19:57:17 +0800 Subject: [PATCH 0925/1939] Update inorder-successor-in-bst.py --- Python/inorder-successor-in-bst.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/inorder-successor-in-bst.py b/Python/inorder-successor-in-bst.py index bdd8d7c4e..5ed818cda 100644 --- a/Python/inorder-successor-in-bst.py +++ b/Python/inorder-successor-in-bst.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(h) # Space: O(1) # Definition for a binary tree node. From ab45ce7aceaeb658826472ca573a1bbc76d4f7d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Sep 2015 19:57:42 +0800 Subject: [PATCH 0926/1939] Update inorder-successor-in-bst.cpp --- C++/inorder-successor-in-bst.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/inorder-successor-in-bst.cpp b/C++/inorder-successor-in-bst.cpp index 36e2482fc..87b1b2a7c 100644 --- a/C++/inorder-successor-in-bst.cpp +++ b/C++/inorder-successor-in-bst.cpp @@ -1,4 +1,4 @@ -// Time: O(logn) +// Time: O(h) // Space: O(1) /** From 169841a0e8b6ed14b88312be9e0f788762be6410 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Sep 2015 20:00:37 +0800 Subject: [PATCH 0927/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2ac7ccc0b..65b4425fa 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-21), there are `267` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-22), there are `268` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `284` questions. +Here is the classification of all `285` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -341,6 +341,7 @@ Shell 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(max(h, k))_ | _O(min(h, k))_ | Medium || 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-search-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-search-tree.py) | _O(h)_ | _O(1)_ | Easy | EPI | 270| [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/)| [C++](./C++/closest-binary-search-tree-value.cpp) [Python](./Python/closest-binary-search-tree-value.py) | _O(h)_ | _O(1)_ | Easy | 📖 | +285| [Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/)| [C++](./C++/inorder-successor-in-bst.cpp) [Python](./Python/inorder-successor-in-bst.py) | _O(h)_ | _O(1)_ | Medium | 📖 | --- From 1fff0eaf7702aad0292a52d58fed9bce49f357df Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Sep 2015 20:03:44 +0800 Subject: [PATCH 0928/1939] Update inorder-successor-in-bst.cpp --- C++/inorder-successor-in-bst.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/inorder-successor-in-bst.cpp b/C++/inorder-successor-in-bst.cpp index 87b1b2a7c..7abac51c1 100644 --- a/C++/inorder-successor-in-bst.cpp +++ b/C++/inorder-successor-in-bst.cpp @@ -14,7 +14,7 @@ class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { // If it has right subtree. - if (p->right) { + if (p && p->right) { p = p->right; while (p->left) { p = p->left; From 896a43096db6adda8e7fcf14036974c0c8686744 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Sep 2015 20:04:09 +0800 Subject: [PATCH 0929/1939] Update inorder-successor-in-bst.py --- Python/inorder-successor-in-bst.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/inorder-successor-in-bst.py b/Python/inorder-successor-in-bst.py index 5ed818cda..a3d6ee653 100644 --- a/Python/inorder-successor-in-bst.py +++ b/Python/inorder-successor-in-bst.py @@ -16,7 +16,7 @@ def inorderSuccessor(self, root, p): :rtype: TreeNode """ # If it has right subtree. - if p.right: + if p and p.right: p = p.right while p.left: p = p.left From 03c696d2b24a60c4ff140197cc1c67e5198c6da7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Sep 2015 02:09:34 +0800 Subject: [PATCH 0930/1939] Update missing-number.cpp --- C++/missing-number.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/C++/missing-number.cpp b/C++/missing-number.cpp index 0f9ede558..c6acf3901 100644 --- a/C++/missing-number.cpp +++ b/C++/missing-number.cpp @@ -2,24 +2,24 @@ // Space: O(1) class Solution { -public: - int missingNumber(vector& nums) { - int num = 0; - for (int i = 0; i < nums.size(); ++i) { - num ^= nums[i] ^ (i + 1); - } - return num; + public: + int missingNumber(vector& nums) { + int num = 0; + for (int i = 0; i < nums.size(); ++i) { + num ^= nums[i] ^ (i + 1); } + return num; + } }; // Time: O(n) // Space: O(n) class Solution2 { -public: - int missingNumber(vector& nums) { - vector expected(nums.size()); - iota(expected.begin(), expected.end(), 1); // Costs extra space O(n) - return accumulate (nums.cbegin(), nums.cend(), 0, bit_xor()) ^ - accumulate (expected.cbegin(), expected.cend(), 0, bit_xor()); - } + public: + int missingNumber(vector& nums) { + vector expected(nums.size()); + iota(expected.begin(), expected.end(), 1); // Costs extra space O(n) + return accumulate(nums.cbegin(), nums.cend(), 0, bit_xor()) ^ + accumulate(expected.cbegin(), expected.cend(), 0, bit_xor()); + } }; From ec3becf5549a7b47ec9bca264162f2f2a8cd97f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Sep 2015 22:29:37 +0800 Subject: [PATCH 0931/1939] Update add-binary.py --- Python/add-binary.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/add-binary.py b/Python/add-binary.py index 054570ade..dec7a2e73 100644 --- a/Python/add-binary.py +++ b/Python/add-binary.py @@ -18,9 +18,9 @@ def addBinary(self, a, b): for i in xrange(max(len_a, len_b)): val = carry if i < len_a: - sum += int(a[-(i + 1)]) + val += int(a[-(i + 1)]) if i < len_b: - sum += int(b[-(i + 1)]) + val += int(b[-(i + 1)]) carry, val = val / 2, val % 2 result = "{0}{1}".format(val, result) if carry == 1: From 6e1b7fbf664b5d3d24167c2702f55e3487f89e9c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Sep 2015 22:45:18 +0800 Subject: [PATCH 0932/1939] Update add-binary.py --- Python/add-binary.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/add-binary.py b/Python/add-binary.py index dec7a2e73..dbc83e30a 100644 --- a/Python/add-binary.py +++ b/Python/add-binary.py @@ -22,10 +22,10 @@ def addBinary(self, a, b): if i < len_b: val += int(b[-(i + 1)]) carry, val = val / 2, val % 2 - result = "{0}{1}".format(val, result) + result += str(val) if carry == 1: - result = "1" + result - return result + result += "1" + return result[::-1] if __name__ == '__main__': result = Solution().addBinary('11', '1') From 0ca6c4964a0863a5b670eb00dad4ec6cfbf3d878 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Sep 2015 22:46:45 +0800 Subject: [PATCH 0933/1939] Update add-binary.py --- Python/add-binary.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/add-binary.py b/Python/add-binary.py index dbc83e30a..b23a26250 100644 --- a/Python/add-binary.py +++ b/Python/add-binary.py @@ -14,12 +14,12 @@ class Solution: # @param b, a string # @return a string def addBinary(self, a, b): - result, carry, val, len_a, len_b, i = "", 0, 0, len(a), len(b), 0 - for i in xrange(max(len_a, len_b)): + result, carry, val = "", 0, 0 + for i in xrange(max(len(a), len(b))): val = carry - if i < len_a: + if i < len(a): val += int(a[-(i + 1)]) - if i < len_b: + if i < len(b): val += int(b[-(i + 1)]) carry, val = val / 2, val % 2 result += str(val) From 54c9ac3d47146526387cbdcc18959bfac57f7b1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Sep 2015 22:49:07 +0800 Subject: [PATCH 0934/1939] Update add-binary.py --- Python/add-binary.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/add-binary.py b/Python/add-binary.py index b23a26250..a2585157c 100644 --- a/Python/add-binary.py +++ b/Python/add-binary.py @@ -23,8 +23,8 @@ def addBinary(self, a, b): val += int(b[-(i + 1)]) carry, val = val / 2, val % 2 result += str(val) - if carry == 1: - result += "1" + if carry: + result += str(carry) return result[::-1] if __name__ == '__main__': From 99af200b25159bc40dc88efe91c327e1492e366f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Sep 2015 20:16:10 +0800 Subject: [PATCH 0935/1939] Create walls-and-gates.py --- Python/walls-and-gates.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/walls-and-gates.py diff --git a/Python/walls-and-gates.py b/Python/walls-and-gates.py new file mode 100644 index 000000000..25fd49358 --- /dev/null +++ b/Python/walls-and-gates.py @@ -0,0 +1,24 @@ +# Time: O(n^2) +# Space: O(n) + +from collections import deque + +class Solution(object): + def wallsAndGates(self, a): + """ + :type rooms: List[List[int]] + :rtype: void Do not return anything, modify rooms in-place instead. + """ + for i in xrange(len(a)): + for j in xrange(len(a[0])): + if a[i][j] == 0: + q = deque([(i + 1, j, 1), (i - 1, j, 1), (i, j + 1, 1), (i, j - 1, 1)]) + while q: + ii, jj, dist = q.popleft() + if ii < 0 or jj < 0 or ii >= len(a) or jj >= len(a[0]) or a[ii][jj] <= dist: + continue + a[ii][jj] = dist + q.append((ii + 1, jj, dist + 1)) + q.append((ii - 1, jj, dist + 1)) + q.append((ii, jj + 1, dist + 1)) + q.append((ii, jj - 1, dist + 1)) From 6578df36a3c886888e962d33c29774aae1fed5a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Sep 2015 20:18:21 +0800 Subject: [PATCH 0936/1939] Update walls-and-gates.py --- Python/walls-and-gates.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Python/walls-and-gates.py b/Python/walls-and-gates.py index 25fd49358..5d5b44fd6 100644 --- a/Python/walls-and-gates.py +++ b/Python/walls-and-gates.py @@ -4,20 +4,21 @@ from collections import deque class Solution(object): - def wallsAndGates(self, a): + def wallsAndGates(self, rooms): """ :type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. """ - for i in xrange(len(a)): - for j in xrange(len(a[0])): - if a[i][j] == 0: + for i in xrange(len(rooms)): + for j in xrange(len(rooms[0])): + if rooms[i][j] == 0: q = deque([(i + 1, j, 1), (i - 1, j, 1), (i, j + 1, 1), (i, j - 1, 1)]) while q: ii, jj, dist = q.popleft() - if ii < 0 or jj < 0 or ii >= len(a) or jj >= len(a[0]) or a[ii][jj] <= dist: + if ii < 0 or jj < 0 or ii >= len(rooms) or \ + jj >= len(rooms[0]) or rooms[ii][jj] <= dist: continue - a[ii][jj] = dist + rooms[ii][jj] = dist q.append((ii + 1, jj, dist + 1)) q.append((ii - 1, jj, dist + 1)) q.append((ii, jj + 1, dist + 1)) From 8d506da1afa0345b0e5afbab3d6344a7d195646b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Sep 2015 20:36:12 +0800 Subject: [PATCH 0937/1939] Create walls-and-gates.cpp --- C++/walls-and-gates.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/walls-and-gates.cpp diff --git a/C++/walls-and-gates.cpp b/C++/walls-and-gates.cpp new file mode 100644 index 000000000..eec15e86b --- /dev/null +++ b/C++/walls-and-gates.cpp @@ -0,0 +1,33 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + void wallsAndGates(vector>& rooms) { + for (int i = 0; i < rooms.size(); ++i) { + for (int j = 0; j < rooms[0].size(); ++j) { + if (rooms[i][j] == 0) { + queue> q; + q.emplace(make_tuple(i + 1, j, 1)); + q.emplace(make_tuple(i - 1, j, 1)); + q.emplace(make_tuple(i, j + 1, 1)); + q.emplace(make_tuple(i, j - 1, 1)); + while (!q.empty()) { + int ii, jj, dist; + tie(ii, jj, dist) = q.front(); + q.pop(); + if (ii < 0 || jj < 0 || ii >= rooms.size() || + jj >= rooms[0].size() || rooms[ii][jj] <= dist) { + continue; + } + rooms[ii][jj] = dist; + q.emplace(make_tuple(ii + 1, jj, dist + 1)); + q.emplace(make_tuple(ii - 1, jj, dist + 1)); + q.emplace(make_tuple(ii, jj + 1, dist + 1)); + q.emplace(make_tuple(ii, jj - 1, dist + 1)); + } + } + } + } + } +}; From 0b2ebff2022ee6bafdcfd294daa7864d6edeefb7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Sep 2015 20:44:54 +0800 Subject: [PATCH 0938/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 65b4425fa..f3974d993 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-22), there are `268` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-24), there are `269` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `285` questions. +Here is the classification of all `286` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -359,6 +359,7 @@ Shell 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | 269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Hard |📖| Topological Sort, BFS, DFS | +286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [C++](./C++/walls-and-gates.cpp) [Python](./Python/walls-and-gates.py) | _O(n^2)_ | _O(n)_ | Medium | 📖 | --- From e54d57a2450e4f333c6cd4a5b3f446de1d257c3b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Sep 2015 22:09:31 +0800 Subject: [PATCH 0939/1939] Update walls-and-gates.py --- Python/walls-and-gates.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/walls-and-gates.py b/Python/walls-and-gates.py index 5d5b44fd6..a1d1057e6 100644 --- a/Python/walls-and-gates.py +++ b/Python/walls-and-gates.py @@ -1,5 +1,5 @@ -# Time: O(n^2) -# Space: O(n) +# Time: O(m * n) +# Space: O(m + n) from collections import deque From 2bfe4fc85cd850e86186b8d726022a57c74c19fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Sep 2015 22:10:48 +0800 Subject: [PATCH 0940/1939] Update walls-and-gates.cpp --- C++/walls-and-gates.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/walls-and-gates.cpp b/C++/walls-and-gates.cpp index eec15e86b..e1288e2a1 100644 --- a/C++/walls-and-gates.cpp +++ b/C++/walls-and-gates.cpp @@ -1,5 +1,5 @@ -// Time: O(n^2) -// Space: O(n) +// Time: O(m * n) +// Space: O(m + n) class Solution { public: From a1723ac1b7a9ff351602e5fa83c05d053df901e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Sep 2015 22:12:17 +0800 Subject: [PATCH 0941/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f3974d993..0515d0099 100644 --- a/README.md +++ b/README.md @@ -359,7 +359,7 @@ Shell 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | 269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Hard |📖| Topological Sort, BFS, DFS | -286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [C++](./C++/walls-and-gates.cpp) [Python](./Python/walls-and-gates.py) | _O(n^2)_ | _O(n)_ | Medium | 📖 | +286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [C++](./C++/walls-and-gates.cpp) [Python](./Python/walls-and-gates.py) | _O(m * n)_ | _O(m + n)_ | Medium | 📖 | --- From e3bb69f8f7c62749fb674649bbf8b7b8d27813da Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Sep 2015 00:32:02 +0800 Subject: [PATCH 0942/1939] Update walls-and-gates.py --- Python/walls-and-gates.py | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/Python/walls-and-gates.py b/Python/walls-and-gates.py index a1d1057e6..c96adc575 100644 --- a/Python/walls-and-gates.py +++ b/Python/walls-and-gates.py @@ -1,25 +1,15 @@ # Time: O(m * n) # Space: O(m + n) -from collections import deque - class Solution(object): def wallsAndGates(self, rooms): """ :type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. """ - for i in xrange(len(rooms)): - for j in xrange(len(rooms[0])): - if rooms[i][j] == 0: - q = deque([(i + 1, j, 1), (i - 1, j, 1), (i, j + 1, 1), (i, j - 1, 1)]) - while q: - ii, jj, dist = q.popleft() - if ii < 0 or jj < 0 or ii >= len(rooms) or \ - jj >= len(rooms[0]) or rooms[ii][jj] <= dist: - continue - rooms[ii][jj] = dist - q.append((ii + 1, jj, dist + 1)) - q.append((ii - 1, jj, dist + 1)) - q.append((ii, jj + 1, dist + 1)) - q.append((ii, jj - 1, dist + 1)) + q = [(i, j) for i, row in enumerate(rooms) for j, r in enumerate(row) if not r] + for i, j in q: + for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1): + if 0 <= I < len(rooms) and 0 <= J < len(rooms[0]) and rooms[I][J] == 2147483647: + rooms[I][J] = rooms[i][j] + 1 + q += (I, J), From 22338804fbcbe2da9a265a38f21536a3989c9380 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Sep 2015 00:50:21 +0800 Subject: [PATCH 0943/1939] Update walls-and-gates.cpp --- C++/walls-and-gates.cpp | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/C++/walls-and-gates.cpp b/C++/walls-and-gates.cpp index e1288e2a1..e0ec3aceb 100644 --- a/C++/walls-and-gates.cpp +++ b/C++/walls-and-gates.cpp @@ -4,30 +4,31 @@ class Solution { public: void wallsAndGates(vector>& rooms) { + queue> q; for (int i = 0; i < rooms.size(); ++i) { for (int j = 0; j < rooms[0].size(); ++j) { if (rooms[i][j] == 0) { - queue> q; - q.emplace(make_tuple(i + 1, j, 1)); - q.emplace(make_tuple(i - 1, j, 1)); - q.emplace(make_tuple(i, j + 1, 1)); - q.emplace(make_tuple(i, j - 1, 1)); - while (!q.empty()) { - int ii, jj, dist; - tie(ii, jj, dist) = q.front(); - q.pop(); - if (ii < 0 || jj < 0 || ii >= rooms.size() || - jj >= rooms[0].size() || rooms[ii][jj] <= dist) { - continue; - } - rooms[ii][jj] = dist; - q.emplace(make_tuple(ii + 1, jj, dist + 1)); - q.emplace(make_tuple(ii - 1, jj, dist + 1)); - q.emplace(make_tuple(ii, jj + 1, dist + 1)); - q.emplace(make_tuple(ii, jj - 1, dist + 1)); - } + q.emplace(make_pair(i, j)); + } + } + } + while (!q.empty()) { + int i, j; + tie(i, j) = q.front(); + q.pop(); + for (const pair& d : + vector>{{i + 1, j}, {i - 1, j}, + {i, j + 1}, {i, j - 1}}) { + int I, J; + tie(I, J) = d; + if (I >= 0 && I < rooms.size() && + J >= 0 && J < rooms[0].size() && + rooms[I][J] == numeric_limits::max()) { + rooms[I][J] = rooms[i][j] + 1; + q.emplace(make_pair(I, J)); } } } } }; + From 9cf008eb24b30b24bec481158ab0b4ced7d0f765 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Sep 2015 00:54:15 +0800 Subject: [PATCH 0944/1939] Update walls-and-gates.py --- Python/walls-and-gates.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Python/walls-and-gates.py b/Python/walls-and-gates.py index c96adc575..7a91aa84e 100644 --- a/Python/walls-and-gates.py +++ b/Python/walls-and-gates.py @@ -1,5 +1,6 @@ # Time: O(m * n) # Space: O(m + n) +from collections import deque class Solution(object): def wallsAndGates(self, rooms): @@ -7,9 +8,13 @@ def wallsAndGates(self, rooms): :type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. """ - q = [(i, j) for i, row in enumerate(rooms) for j, r in enumerate(row) if not r] - for i, j in q: + INF = 2147483647 + q = deque([(i, j) for i, row in enumerate(rooms) for j, r in enumerate(row) if not r]) + while q: + (i, j) = q.popleft() for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1): - if 0 <= I < len(rooms) and 0 <= J < len(rooms[0]) and rooms[I][J] == 2147483647: + if 0 <= I < len(rooms) and 0 <= J < len(rooms[0]) \ + and rooms[I][J] == INF: rooms[I][J] = rooms[i][j] + 1 - q += (I, J), + q.append((I, J)) + From aac298e1f9752515162fb02fe195acdd36be9df0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Sep 2015 00:57:06 +0800 Subject: [PATCH 0945/1939] Update walls-and-gates.cpp --- C++/walls-and-gates.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/walls-and-gates.cpp b/C++/walls-and-gates.cpp index e0ec3aceb..3a31f3088 100644 --- a/C++/walls-and-gates.cpp +++ b/C++/walls-and-gates.cpp @@ -4,6 +4,7 @@ class Solution { public: void wallsAndGates(vector>& rooms) { + const int INF = numeric_limits::max(); queue> q; for (int i = 0; i < rooms.size(); ++i) { for (int j = 0; j < rooms[0].size(); ++j) { @@ -23,7 +24,7 @@ class Solution { tie(I, J) = d; if (I >= 0 && I < rooms.size() && J >= 0 && J < rooms[0].size() && - rooms[I][J] == numeric_limits::max()) { + rooms[I][J] == INF) { rooms[I][J] = rooms[i][j] + 1; q.emplace(make_pair(I, J)); } @@ -31,4 +32,3 @@ class Solution { } } }; - From 63bb12ede76d8847082b711cef47e67e0a1e9aa5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Sep 2015 01:03:30 +0800 Subject: [PATCH 0946/1939] Update walls-and-gates.py --- Python/walls-and-gates.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/walls-and-gates.py b/Python/walls-and-gates.py index 7a91aa84e..c1ae72c28 100644 --- a/Python/walls-and-gates.py +++ b/Python/walls-and-gates.py @@ -1,5 +1,6 @@ # Time: O(m * n) # Space: O(m + n) + from collections import deque class Solution(object): From c825861136a2b4ca435c00f76ada1cfc9e69620e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Sep 2015 01:03:59 +0800 Subject: [PATCH 0947/1939] Update walls-and-gates.py --- Python/walls-and-gates.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/walls-and-gates.py b/Python/walls-and-gates.py index c1ae72c28..42b986d16 100644 --- a/Python/walls-and-gates.py +++ b/Python/walls-and-gates.py @@ -14,8 +14,8 @@ def wallsAndGates(self, rooms): while q: (i, j) = q.popleft() for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1): - if 0 <= I < len(rooms) and 0 <= J < len(rooms[0]) \ - and rooms[I][J] == INF: + if 0 <= I < len(rooms) and 0 <= J < len(rooms[0]) and \ + rooms[I][J] == INF: rooms[I][J] = rooms[i][j] + 1 q.append((I, J)) From 3618162d61f89d889c0bfd2d7957d24b1965693d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Sep 2015 01:05:22 +0800 Subject: [PATCH 0948/1939] Update walls-and-gates.py --- Python/walls-and-gates.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/walls-and-gates.py b/Python/walls-and-gates.py index 42b986d16..c3113ffd2 100644 --- a/Python/walls-and-gates.py +++ b/Python/walls-and-gates.py @@ -1,5 +1,5 @@ # Time: O(m * n) -# Space: O(m + n) +# Space: O(g) from collections import deque From 790e74d39ba3926273465ea1ce18806f3975f616 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Sep 2015 01:05:42 +0800 Subject: [PATCH 0949/1939] Update walls-and-gates.cpp --- C++/walls-and-gates.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/walls-and-gates.cpp b/C++/walls-and-gates.cpp index 3a31f3088..b93946378 100644 --- a/C++/walls-and-gates.cpp +++ b/C++/walls-and-gates.cpp @@ -1,5 +1,5 @@ // Time: O(m * n) -// Space: O(m + n) +// Space: O(g) class Solution { public: From 53afc53df380bda46cef1fc88b1d30ba6563c386 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Sep 2015 01:06:03 +0800 Subject: [PATCH 0950/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0515d0099..660a2a813 100644 --- a/README.md +++ b/README.md @@ -359,7 +359,7 @@ Shell 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | 269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Hard |📖| Topological Sort, BFS, DFS | -286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [C++](./C++/walls-and-gates.cpp) [Python](./Python/walls-and-gates.py) | _O(m * n)_ | _O(m + n)_ | Medium | 📖 | +286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [C++](./C++/walls-and-gates.cpp) [Python](./Python/walls-and-gates.py) | _O(m * n)_ | _O(g)_ | Medium | 📖 | --- From 87b06ba718c108293c50ffa8252b7e1b0cf7cb61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 11:49:22 +0800 Subject: [PATCH 0951/1939] Create find-the-duplicate-number.cpp --- C++/find-the-duplicate-number.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/find-the-duplicate-number.cpp diff --git a/C++/find-the-duplicate-number.cpp b/C++/find-the-duplicate-number.cpp new file mode 100644 index 000000000..9d076cd83 --- /dev/null +++ b/C++/find-the-duplicate-number.cpp @@ -0,0 +1,27 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findDuplicate(vector& nums) { + int duplicate = 0; + // Mark the value as visited by negative. + for (auto& num : nums) { + if (nums[abs(num) - 1] > 0) { + nums[abs(num) - 1] *= -1; + } else { + duplicate = abs(num); + break; + } + } + // Rollback the value. + for (auto& num : nums) { + if (nums[abs(num) - 1] < 0) { + nums[abs(num) - 1] *= -1; + } else { + break; + } + } + return duplicate; + } +}; From 36e352a14bf1af01f6982aba2d581f969b0930d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 11:53:12 +0800 Subject: [PATCH 0952/1939] Create find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/find-the-duplicate-number.py diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py new file mode 100644 index 000000000..48d8377f8 --- /dev/null +++ b/Python/find-the-duplicate-number.py @@ -0,0 +1,24 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def findDuplicate(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + duplicate = 0 + # Mark the value as visited by negative. + for num in nums: + if nums[abs(num) - 1] > 0: + nums[abs(num) - 1] *= -1 + else: + duplicate = abs(num) + break + # Rollback the value. + for num in nums: + if nums[abs(num) - 1] < 0: + nums[abs(num) - 1] *= -1 + else: + break + return duplicate From cea283adbf2ec92ac3a82a2861c120fb6fde5959 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 12:08:17 +0800 Subject: [PATCH 0953/1939] Update find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index 48d8377f8..eaddb8cb4 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -1,7 +1,30 @@ -# Time: O(n) +# Time: O(nlogn) # Space: O(1) class Solution(object): + def findDuplicate(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + left, right = 1, len(nums) - 1 + + while left <= right: + mid = left + (right - left) / 2 + # Get count of num <= mid. + count = 0 + for num in nums: + if num <= mid: + count += 1 + if count > mid: + right = mid - 1 + else: + left = mid + 1 + return left + +# Time: O(n) +# Space: O(n) +class Solution2(object): def findDuplicate(self, nums): """ :type nums: List[int] From 35f111dd4925c6da795a134398686cc2688200a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 12:12:01 +0800 Subject: [PATCH 0954/1939] Update find-the-duplicate-number.cpp --- C++/find-the-duplicate-number.cpp | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/C++/find-the-duplicate-number.cpp b/C++/find-the-duplicate-number.cpp index 9d076cd83..0e50a9db2 100644 --- a/C++/find-the-duplicate-number.cpp +++ b/C++/find-the-duplicate-number.cpp @@ -1,7 +1,33 @@ -// Time: O(n) +// Time: O(nlogn) // Space: O(1) class Solution { +public: + int findDuplicate(vector& nums) { + int left = 1, right = nums.size(); + + while (left <= right) { + const int mid = left + (right - left) / 2; + // Get count of num <= mid. + int count = 0; + for (const auto& num : nums) { + if (num <= mid) { + ++count; + } + } + if (count > mid) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { public: int findDuplicate(vector& nums) { int duplicate = 0; From a513b0ce52f5e709b40237603bdad1984b0268cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 12:14:46 +0800 Subject: [PATCH 0955/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 660a2a813..73ea861e0 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-24), there are `269` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-09-28), there are `270` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `286` questions. +Here is the classification of all `287` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -332,6 +332,7 @@ Shell 222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./C++/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || 275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | 278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy | LintCode || +287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(nlogn)_ | _O(1)_ | Hard | 📖 | -- ##Binary Search Tree From e6c386b0645426e673343517fa23f2fbfcb3b87a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 12:17:35 +0800 Subject: [PATCH 0956/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 73ea861e0..5920d7d56 100644 --- a/README.md +++ b/README.md @@ -332,7 +332,7 @@ Shell 222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./C++/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || 275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | 278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy | LintCode || -287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(nlogn)_ | _O(1)_ | Hard | 📖 | +287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(nlogn)_ | _O(1)_ | Medium | 📖 | -- ##Binary Search Tree From 567ad1ddee0aba325eefae846af4e6bbf04c3bc9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 15:25:24 +0800 Subject: [PATCH 0957/1939] Update find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 37 +++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index eaddb8cb4..4f6a38c52 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -1,7 +1,40 @@ -# Time: O(nlogn) +# Time: O(n) # Space: O(1) +# Two pointers method, reference: http://keithschwarz.com/interesting/code/?dir=find-duplicate class Solution(object): + def findDuplicate(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + # The "tortoise and hare" step. We start at the end of the nums and try + # to find an intersection point in the cycle. + slow = nums[len(nums) - 1] + fast = nums[nums[len(nums) - 1] - 1] + + # Keep advancing 'slow' by one step and 'fast' by two steps until they + # meet inside the loop. + while slow != fast: + slow = nums[slow - 1] + fast = nums[nums[fast - 1] - 1] + + # Start up another pointer from the end of the nums and march it forward + # until it hits the pointer inside the nums. + slow = nums[slow - 1] + finder = nums[len(nums) - 1] + while slow != finder: + slow = nums[slow - 1] + finder = nums[finder - 1] + + # If the two hit, the intersection index is the duplicate element. + return slow + + +# Time: O(nlogn) +# Space: O(1) +# Binary search method. +class Solution2(object): def findDuplicate(self, nums): """ :type nums: List[int] @@ -24,7 +57,7 @@ def findDuplicate(self, nums): # Time: O(n) # Space: O(n) -class Solution2(object): +class Solution3(object): def findDuplicate(self, nums): """ :type nums: List[int] From 13776f7b862715255d71d0b57d9922c2c3e75d0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 15:27:37 +0800 Subject: [PATCH 0958/1939] Update find-the-duplicate-number.cpp --- C++/find-the-duplicate-number.cpp | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/C++/find-the-duplicate-number.cpp b/C++/find-the-duplicate-number.cpp index 0e50a9db2..ed116ddf4 100644 --- a/C++/find-the-duplicate-number.cpp +++ b/C++/find-the-duplicate-number.cpp @@ -1,7 +1,30 @@ -// Time: O(nlogn) +// Time: O(n) // Space: O(1) +// Two pointers method, reference: http://keithschwarz.com/interesting/code/?dir=find-duplicate class Solution { +public: + int findDuplicate(vector& nums) { + int slow = nums.size(); + int fast = nums.size(); + do { + slow = nums[slow - 1]; + fast = nums[nums[fast - 1] - 1]; + } while (slow != fast); + + int finder = nums.size(); + do { + slow = nums[slow - 1]; + finder = nums[finder - 1]; + } while (slow != finder); + return slow; + } +}; + +// Time: O(nlogn) +// Space: O(1) +// Binary search method +class Solution2 { public: int findDuplicate(vector& nums) { int left = 1, right = nums.size(); @@ -27,7 +50,7 @@ class Solution { // Time: O(n) // Space: O(n) -class Solution2 { +class Solution3 { public: int findDuplicate(vector& nums) { int duplicate = 0; From 2da9d42d8066b5f3d0797cbb5ba5b914407d761e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 15:28:16 +0800 Subject: [PATCH 0959/1939] Update find-the-duplicate-number.cpp --- C++/find-the-duplicate-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-the-duplicate-number.cpp b/C++/find-the-duplicate-number.cpp index ed116ddf4..e1ea92c6d 100644 --- a/C++/find-the-duplicate-number.cpp +++ b/C++/find-the-duplicate-number.cpp @@ -23,7 +23,7 @@ class Solution { // Time: O(nlogn) // Space: O(1) -// Binary search method +// Binary search method. class Solution2 { public: int findDuplicate(vector& nums) { From 3334adc9dbd51f7d4fd46d7c01fdb7321a1f6427 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 15:29:20 +0800 Subject: [PATCH 0960/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5920d7d56..f68dafbee 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,7 @@ Shell 167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [C++](./C++/3sum-smaller.cpp) [Python](./Python/3sum-smaller.py) | _O(n^2)_ | _O(1)_ | Medium | 📖, LintCode | 283 | [Move Zeros](https://leetcode.com/problems/move-zeros/) | [C++](./C++/move-zeros.cpp) [Python](./Python/move-zeros.py) | _O(n)_ | _O(1)_ | Easy | | +287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Medium | 📖 | Binary Search, Two Pointers | --- @@ -332,7 +333,6 @@ Shell 222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./C++/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || 275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | 278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy | LintCode || -287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(nlogn)_ | _O(1)_ | Medium | 📖 | -- ##Binary Search Tree From 57a6d763f40db8d3f15c90d6270a1ae9f7819571 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 15:51:54 +0800 Subject: [PATCH 0961/1939] Update find-the-duplicate-number.cpp --- C++/find-the-duplicate-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-the-duplicate-number.cpp b/C++/find-the-duplicate-number.cpp index e1ea92c6d..df31beabf 100644 --- a/C++/find-the-duplicate-number.cpp +++ b/C++/find-the-duplicate-number.cpp @@ -1,7 +1,7 @@ // Time: O(n) // Space: O(1) -// Two pointers method, reference: http://keithschwarz.com/interesting/code/?dir=find-duplicate +// Two pointers method, same as Linked List Cycle II class Solution { public: int findDuplicate(vector& nums) { From c7d382543bea0f820cc4e043ae1f4d6e5ba6effa Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 15:53:27 +0800 Subject: [PATCH 0962/1939] Update find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index 4f6a38c52..7d46eeb40 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -1,33 +1,26 @@ # Time: O(n) # Space: O(1) -# Two pointers method, reference: http://keithschwarz.com/interesting/code/?dir=find-duplicate +# Two pointers method, same as Linked List Cycle II. class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ - # The "tortoise and hare" step. We start at the end of the nums and try - # to find an intersection point in the cycle. slow = nums[len(nums) - 1] fast = nums[nums[len(nums) - 1] - 1] - - # Keep advancing 'slow' by one step and 'fast' by two steps until they - # meet inside the loop. + while slow != fast: slow = nums[slow - 1] fast = nums[nums[fast - 1] - 1] - # Start up another pointer from the end of the nums and march it forward - # until it hits the pointer inside the nums. slow = nums[slow - 1] - finder = nums[len(nums) - 1] - while slow != finder: + fast = nums[len(nums) - 1] + while slow != fast: slow = nums[slow - 1] - finder = nums[finder - 1] + fast = nums[fast - 1] - # If the two hit, the intersection index is the duplicate element. return slow From 82c44fa8330ed4ae025ac3379cef0b52ff19198c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 15:53:59 +0800 Subject: [PATCH 0963/1939] Update find-the-duplicate-number.cpp --- C++/find-the-duplicate-number.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/find-the-duplicate-number.cpp b/C++/find-the-duplicate-number.cpp index df31beabf..4ccb4c163 100644 --- a/C++/find-the-duplicate-number.cpp +++ b/C++/find-the-duplicate-number.cpp @@ -1,7 +1,7 @@ // Time: O(n) // Space: O(1) -// Two pointers method, same as Linked List Cycle II +// Two pointers method, same as Linked List Cycle II. class Solution { public: int findDuplicate(vector& nums) { @@ -12,11 +12,11 @@ class Solution { fast = nums[nums[fast - 1] - 1]; } while (slow != fast); - int finder = nums.size(); + fast = nums.size(); do { slow = nums[slow - 1]; - finder = nums[finder - 1]; - } while (slow != finder); + fast = nums[fast - 1]; + } while (slow != fast); return slow; } }; From 3b307506f96f1d40eb6b8eade7e838d4d0597e09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 16:22:55 +0800 Subject: [PATCH 0964/1939] Update find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index 7d46eeb40..359b05343 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -8,6 +8,10 @@ def findDuplicate(self, nums): :type nums: List[int] :rtype: int """ + # Treat each (key, value - 1) pair of the array as the (pointer, next) node of the linked list, + # thus the duplicated number will be the begin of the cycle in the linked list. + # Besides, there is always a cycle in the linked list which + # starts from the last element of the array. slow = nums[len(nums) - 1] fast = nums[nums[len(nums) - 1] - 1] From a3c6b1d66915d6f9e608bf81838d3ea7b66ba10a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 16:34:02 +0800 Subject: [PATCH 0965/1939] Update find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index 359b05343..84a91b9f4 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -9,22 +9,17 @@ def findDuplicate(self, nums): :rtype: int """ # Treat each (key, value - 1) pair of the array as the (pointer, next) node of the linked list, - # thus the duplicated number will be the begin of the cycle in the linked list. - # Besides, there is always a cycle in the linked list which - # starts from the last element of the array. - slow = nums[len(nums) - 1] - fast = nums[nums[len(nums) - 1] - 1] - + # thus the duplicated number will be the begin of the cycle in the linked list.: + slow = nums[0] + fast = nums[nums[0]] while slow != fast: - slow = nums[slow - 1] - fast = nums[nums[fast - 1] - 1] - - slow = nums[slow - 1] - fast = nums[len(nums) - 1] + slow = nums[slow] + fast = nums[nums[fast]] + + fast = 0 while slow != fast: - slow = nums[slow - 1] - fast = nums[fast - 1] - + slow = nums[slow] + fast = nums[fast] return slow From 291f74ac15f1dac3c2108b1c82727c79db1c1e27 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 16:39:46 +0800 Subject: [PATCH 0966/1939] Update find-the-duplicate-number.cpp --- C++/find-the-duplicate-number.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/C++/find-the-duplicate-number.cpp b/C++/find-the-duplicate-number.cpp index 4ccb4c163..964a93c09 100644 --- a/C++/find-the-duplicate-number.cpp +++ b/C++/find-the-duplicate-number.cpp @@ -5,21 +5,21 @@ class Solution { public: int findDuplicate(vector& nums) { - int slow = nums.size(); - int fast = nums.size(); - do { - slow = nums[slow - 1]; - fast = nums[nums[fast - 1] - 1]; - } while (slow != fast); + int slow = nums[0]; + int fast = nums[nums[0]]; + while (slow != fast) { + slow = nums[slow]; + fast = nums[nums[fast]]; + } - fast = nums.size(); - do { - slow = nums[slow - 1]; - fast = nums[fast - 1]; - } while (slow != fast); + fast = 0; + while (slow != fast) { + slow = nums[slow]; + fast = nums[fast]; + } return slow; } -}; +};; // Time: O(nlogn) // Space: O(1) From 7017021113ca5a605fc007d3cc5eb26d8f472a78 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 16:39:59 +0800 Subject: [PATCH 0967/1939] Update find-the-duplicate-number.cpp --- C++/find-the-duplicate-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-the-duplicate-number.cpp b/C++/find-the-duplicate-number.cpp index 964a93c09..958d5e0df 100644 --- a/C++/find-the-duplicate-number.cpp +++ b/C++/find-the-duplicate-number.cpp @@ -19,7 +19,7 @@ class Solution { } return slow; } -};; +}; // Time: O(nlogn) // Space: O(1) From 87a14382781499d5446ce307e7e5e425b5e6a444 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 17:29:18 +0800 Subject: [PATCH 0968/1939] Update find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index 84a91b9f4..a3d942583 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -8,7 +8,7 @@ def findDuplicate(self, nums): :type nums: List[int] :rtype: int """ - # Treat each (key, value - 1) pair of the array as the (pointer, next) node of the linked list, + # Treat each (key, value) pair of the array as the (pointer, next) node of the linked list, # thus the duplicated number will be the begin of the cycle in the linked list.: slow = nums[0] fast = nums[nums[0]] From d7f081fa74e1f93298ecd90273fb4701fea6c532 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 17:32:25 +0800 Subject: [PATCH 0969/1939] Update find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index a3d942583..417339f92 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -9,7 +9,9 @@ def findDuplicate(self, nums): :rtype: int """ # Treat each (key, value) pair of the array as the (pointer, next) node of the linked list, - # thus the duplicated number will be the begin of the cycle in the linked list.: + # thus the duplicated number will be the begin of the cycle in the linked list. + # Besides, there is always a cycle in the linked list which + # starts from the first element of the array. slow = nums[0] fast = nums[nums[0]] while slow != fast: From 6a945c3d344b6ab22b40788a5a5eb622f8dd7ba7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 20:15:34 +0800 Subject: [PATCH 0970/1939] Update find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index 417339f92..a630e0e46 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -1,5 +1,16 @@ # Time: O(n) # Space: O(1) +# +# Given an array nums containing n + 1 integers where each integer +# is between 1 and n (inclusive), prove that at least one duplicate +# element must exist. Assume that there is only one duplicate number, +# find the duplicate one. +# +# Note: +# You must not modify the array (assume the array is read only). +# You must use only constant extra space. +# Your runtime complexity should be less than O(n2). +# # Two pointers method, same as Linked List Cycle II. class Solution(object): From 5455cc22215f0a0c20b624923f1ee709ba50d4cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 20:16:13 +0800 Subject: [PATCH 0971/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f68dafbee..b812b69a7 100644 --- a/README.md +++ b/README.md @@ -278,7 +278,7 @@ Shell 167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [C++](./C++/3sum-smaller.cpp) [Python](./Python/3sum-smaller.py) | _O(n^2)_ | _O(1)_ | Medium | 📖, LintCode | 283 | [Move Zeros](https://leetcode.com/problems/move-zeros/) | [C++](./C++/move-zeros.cpp) [Python](./Python/move-zeros.py) | _O(n)_ | _O(1)_ | Easy | | -287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Medium | 📖 | Binary Search, Two Pointers | +287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search, Two Pointers | --- From 021cc0e5bf4b4efd38a960d69eda7ccb1c80d089 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Sep 2015 20:20:03 +0800 Subject: [PATCH 0972/1939] Update find-the-duplicate-number.py --- Python/find-the-duplicate-number.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index a630e0e46..c7c9fe49d 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -7,9 +7,9 @@ # find the duplicate one. # # Note: -# You must not modify the array (assume the array is read only). -# You must use only constant extra space. -# Your runtime complexity should be less than O(n2). +# - You must not modify the array (assume the array is read only). +# - You must use only constant extra space. +# - Your runtime complexity should be less than O(n^2). # # Two pointers method, same as Linked List Cycle II. From fd76ff71b738783681ec2a37391448894247198f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Sep 2015 09:22:23 +0800 Subject: [PATCH 0973/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b812b69a7..3c578aad5 100644 --- a/README.md +++ b/README.md @@ -278,7 +278,7 @@ Shell 167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [C++](./C++/3sum-smaller.cpp) [Python](./Python/3sum-smaller.py) | _O(n^2)_ | _O(1)_ | Medium | 📖, LintCode | 283 | [Move Zeros](https://leetcode.com/problems/move-zeros/) | [C++](./C++/move-zeros.cpp) [Python](./Python/move-zeros.py) | _O(n)_ | _O(1)_ | Easy | | -287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search, Two Pointers | +287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Hard | | Binary Search, Two Pointers | --- From 8d254dc97022801f63e74875f6b68a8880e69093 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Sep 2015 17:56:03 +0800 Subject: [PATCH 0974/1939] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 3c578aad5..fcd8bc2ba 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ For more questions and solutions, you can see my [LintCode](https://github.com/k I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) + +Algorithms +=== + * [Bit Manipulation](https://github.com/kamyu104/LeetCode#bit-manipulation) * [Array](https://github.com/kamyu104/LeetCode#array) * [String](https://github.com/kamyu104/LeetCode#string) From 4a019d5e7e74a2669e2b55894f0bda1fa967ab00 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Sep 2015 17:58:00 +0800 Subject: [PATCH 0975/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fcd8bc2ba..9304a469d 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ For more questions and solutions, you can see my [LintCode](https://github.com/k I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) - +--- Algorithms === From 47110cb4cc25dc3f01547d3d6c904641ccbbdc0c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Sep 2015 21:28:20 +0800 Subject: [PATCH 0976/1939] Update and rename detectCycle.cpp to linked-list-cycle-ii.cpp --- C++/detectCycle.cpp | 33 --------------------------------- C++/linked-list-cycle-ii.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 33 deletions(-) delete mode 100644 C++/detectCycle.cpp create mode 100644 C++/linked-list-cycle-ii.cpp diff --git a/C++/detectCycle.cpp b/C++/detectCycle.cpp deleted file mode 100644 index 3e066a2da..000000000 --- a/C++/detectCycle.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - public: - ListNode *detectCycle(ListNode *head) { - ListNode *slow = head, *fast = head; - - while(fast && fast->next) { - slow = slow->next; - fast = fast->next->next; - - if(slow == fast) { - ListNode *slow2 = head; - while(slow2 != slow) { - slow2 = slow2->next; - slow = slow->next; - } - return slow2; - } - } - - return NULL; - } -}; diff --git a/C++/linked-list-cycle-ii.cpp b/C++/linked-list-cycle-ii.cpp new file mode 100644 index 000000000..24a4fcb84 --- /dev/null +++ b/C++/linked-list-cycle-ii.cpp @@ -0,0 +1,29 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { + public: + ListNode *detectCycle(ListNode *head) { + ListNode *slow = head, *fast = head; + + while (fast && fast->next) { + slow = slow->next, fast = fast->next->next; + if (slow == fast) { // There is a cycle. + slow = head; + // Both pointers advance at the same time. + while (slow != fast) { + slow = slow->next, fast = fast->next; + } + return slow; // slow is the begin of cycle. + } + return nullptr; // No cycle. + } +}; From e27033e82416e8a80125f3a386add1375ab4447d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Sep 2015 21:28:45 +0800 Subject: [PATCH 0977/1939] Update linked-list-cycle-ii.cpp --- C++/linked-list-cycle-ii.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/C++/linked-list-cycle-ii.cpp b/C++/linked-list-cycle-ii.cpp index 24a4fcb84..c4cf61ba2 100644 --- a/C++/linked-list-cycle-ii.cpp +++ b/C++/linked-list-cycle-ii.cpp @@ -10,20 +10,20 @@ * }; */ class Solution { - public: - ListNode *detectCycle(ListNode *head) { - ListNode *slow = head, *fast = head; +public: + ListNode *detectCycle(ListNode *head) { + ListNode *slow = head, *fast = head; - while (fast && fast->next) { - slow = slow->next, fast = fast->next->next; - if (slow == fast) { // There is a cycle. - slow = head; - // Both pointers advance at the same time. - while (slow != fast) { - slow = slow->next, fast = fast->next; - } - return slow; // slow is the begin of cycle. - } - return nullptr; // No cycle. + while (fast && fast->next) { + slow = slow->next, fast = fast->next->next; + if (slow == fast) { // There is a cycle. + slow = head; + // Both pointers advance at the same time. + while (slow != fast) { + slow = slow->next, fast = fast->next; + } + return slow; // slow is the begin of cycle. } + return nullptr; // No cycle. + } }; From 528156a6af07790f7be27d8770e7d398b524b269 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Sep 2015 21:30:09 +0800 Subject: [PATCH 0978/1939] Update and rename hasCycle.cpp to linked-list-cycle.cpp --- C++/hasCycle.cpp | 27 --------------------------- C++/linked-list-cycle.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 27 deletions(-) delete mode 100644 C++/hasCycle.cpp create mode 100644 C++/linked-list-cycle.cpp diff --git a/C++/hasCycle.cpp b/C++/hasCycle.cpp deleted file mode 100644 index 4b8df99f5..000000000 --- a/C++/hasCycle.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - public: - bool hasCycle(ListNode *head) { - ListNode *slow = head, *fast = head; - - while(fast && fast->next) { - slow = slow->next; - fast = fast->next->next; - - if(slow == fast) - return true; - } - - return false; - } -}; diff --git a/C++/linked-list-cycle.cpp b/C++/linked-list-cycle.cpp new file mode 100644 index 000000000..9025ec000 --- /dev/null +++ b/C++/linked-list-cycle.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + ListNode *slow = head, *fast = head; + + while(fast && fast->next) { + slow = slow->next, fast = fast->next->next; + if (slow == fast) { + return true; + } + } + return false; + } +}; From 422504be1c63319623ef0ad77fb2c325d91e6d47 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Sep 2015 21:30:33 +0800 Subject: [PATCH 0979/1939] Update linked-list-cycle.cpp --- C++/linked-list-cycle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/linked-list-cycle.cpp b/C++/linked-list-cycle.cpp index 9025ec000..9f1116aea 100644 --- a/C++/linked-list-cycle.cpp +++ b/C++/linked-list-cycle.cpp @@ -14,7 +14,7 @@ class Solution { bool hasCycle(ListNode *head) { ListNode *slow = head, *fast = head; - while(fast && fast->next) { + while (fast && fast->next) { slow = slow->next, fast = fast->next->next; if (slow == fast) { return true; From a9c3f7003158e5663ef6f677f2266ea1c9a53cbf Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Sep 2015 21:32:51 +0800 Subject: [PATCH 0980/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9304a469d..0985b4b9a 100644 --- a/README.md +++ b/README.md @@ -276,8 +276,8 @@ Shell -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || 86| [Partition List](https://leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || -141| [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)| [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || -142| [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || +141| [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)| [C++](./C++/linked-list-cycle.cpp) [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Medium || +142| [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [C++](./C++/linked-list-cycle-ii.cpp) [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || 143| [Reorder List](https://leetcode.com/problems/reorder-list/)| [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || 167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [C++](./C++/3sum-smaller.cpp) [Python](./Python/3sum-smaller.py) | _O(n^2)_ | _O(1)_ | Medium | 📖, LintCode | From 6566b18950c8d5c25fdb65f667029d8147ec4f3b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Sep 2015 21:33:41 +0800 Subject: [PATCH 0981/1939] Update linked-list-cycle.cpp --- C++/linked-list-cycle.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/linked-list-cycle.cpp b/C++/linked-list-cycle.cpp index 9f1116aea..84d3a8383 100644 --- a/C++/linked-list-cycle.cpp +++ b/C++/linked-list-cycle.cpp @@ -16,10 +16,10 @@ class Solution { while (fast && fast->next) { slow = slow->next, fast = fast->next->next; - if (slow == fast) { + if (slow == fast) { // There is a cycle. return true; } } - return false; + return false; // No cycle. } }; From 24185dc3ab4e496140408ae7d21ae24104f9fbd5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Oct 2015 21:33:35 +0800 Subject: [PATCH 0982/1939] Create number-of-1-bits.cpp --- C++/number-of-1-bits.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/number-of-1-bits.cpp diff --git a/C++/number-of-1-bits.cpp b/C++/number-of-1-bits.cpp new file mode 100644 index 000000000..38c66af18 --- /dev/null +++ b/C++/number-of-1-bits.cpp @@ -0,0 +1,13 @@ +// Time: O(logn) = O(32) +// Space: O(1) + +class Solution { +public: + int hammingWeight(uint32_t n) { + int count = 0; + for (; n; n &= n - 1) { + ++count; + } + return count; + } +}; From 7604b0ab2dd7692e8e0aae4f3de7ad40bf8856d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Oct 2015 21:38:24 +0800 Subject: [PATCH 0983/1939] Create reverse-bits.cpp --- C++/reverse-bits.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 C++/reverse-bits.cpp diff --git a/C++/reverse-bits.cpp b/C++/reverse-bits.cpp new file mode 100644 index 000000000..6bedc3410 --- /dev/null +++ b/C++/reverse-bits.cpp @@ -0,0 +1,16 @@ +// Time: O(logn) = O(32) +// Space: O(1) + +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t result = 0; + int count = 32; + while (count--) { + result <<= 1; + result |= n & 1; + n >>= 1; + } + return result; + } +}; From b845c5e6f182079bae6024fa7629418e04c4bbea Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Oct 2015 21:41:37 +0800 Subject: [PATCH 0984/1939] Create single-number-ii.cpp --- C++/single-number-ii.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/single-number-ii.cpp diff --git a/C++/single-number-ii.cpp b/C++/single-number-ii.cpp new file mode 100644 index 000000000..be693c446 --- /dev/null +++ b/C++/single-number-ii.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int singleNumber(vector& nums) { + int one = 0, two = 0; + + for (const auto& i : nums) { + int new_one = (~i & one) | (i & ~one & ~two); + int new_two = (~i & two) | (i & one); + one = new_one, two = new_two; + } + + return one; + } +}; From 5d4bf6a77e3da790f4f0ce48145fd4232133b016 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Oct 2015 21:43:06 +0800 Subject: [PATCH 0985/1939] Create single-number.cpp --- C++/single-number.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 C++/single-number.cpp diff --git a/C++/single-number.cpp b/C++/single-number.cpp new file mode 100644 index 000000000..d42eed2cd --- /dev/null +++ b/C++/single-number.cpp @@ -0,0 +1,10 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int singleNumber(vector& nums) { + return accumulate(nums.cbegin(), nums.cend(), + 0, std::bit_xor()); + } +}; From 06817e318b56ff969edff992908a357302a9d396 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Oct 2015 21:45:20 +0800 Subject: [PATCH 0986/1939] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0985b4b9a..5356ee090 100644 --- a/README.md +++ b/README.md @@ -53,10 +53,10 @@ Shell ##Bit Manipulation # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || -137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || -190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [Python](./Python/reverse-bits.py) | _O(1)_ | _O(1)_ | Easy || -191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [Python](./Python/number-of-1-bits.py) | _O(1)_ | _O(1)_ | Easy || +136 | [Single Number](https://leetcode.com/problems/single-number/) | [C++](./C++/single-number.cpp) [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || +137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [C++](./C++/single-number-ii.cpp) [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || +190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [C++](./C++/reverse-bits.cpp) [Python](./Python/reverse-bits.py) | _O(1)_ | _O(1)_ | Easy || +191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [C++](./C++/number-of-1-bits.cpp) [Python](./Python/number-of-1-bits.py) | _O(1)_ | _O(1)_ | Easy || 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || From e766cbfd87c2fc75fd9a15df68890b80c1b350c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 00:54:26 +0800 Subject: [PATCH 0987/1939] Create unique-word-abbreviation.cpp --- C++/unique-word-abbreviation.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/unique-word-abbreviation.cpp diff --git a/C++/unique-word-abbreviation.cpp b/C++/unique-word-abbreviation.cpp new file mode 100644 index 000000000..05ec2ca6d --- /dev/null +++ b/C++/unique-word-abbreviation.cpp @@ -0,0 +1,29 @@ +// Time: O(n) for constructor, n is number of words in the dictionary. +// O(1) for lookup +// Space: O(k), k is number of unique words. + +class ValidWordAbbr { +public: + ValidWordAbbr(vector &dictionary) { + for (string& word : dictionary) { + const int len = word.length(); + const string hash_val = word[0] + to_string(len - 2) + word[len - 1]; + lookup_[hash_val].emplace(word); + } + } + + bool isUnique(string word) { + const int len = word.length(); + const string hash_val = word[0] + to_string(len - 2) + word[len - 1]; + return lookup_[hash_val].empty() || + (lookup_[hash_val].count(word) == lookup_[hash_val].size()); + } +private: + unordered_map> lookup_; +}; + + +// Your ValidWordAbbr object will be instantiated and called as such: +// ValidWordAbbr vwa(dictionary); +// vwa.isUnique("hello"); +// vwa.isUnique("anotherWord"); From e5b441a17ed9e8eab33296a245879fb869f24c98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:13:22 +0800 Subject: [PATCH 0988/1939] Create unique-word-abbreviation.py --- Python/unique-word-abbreviation.py | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/unique-word-abbreviation.py diff --git a/Python/unique-word-abbreviation.py b/Python/unique-word-abbreviation.py new file mode 100644 index 000000000..6aefa4beb --- /dev/null +++ b/Python/unique-word-abbreviation.py @@ -0,0 +1,33 @@ +from sets import Set + +class ValidWordAbbr(object): + def __init__(self, dictionary): + """ + initialize your data structure here. + :type dictionary: List[str] + """ + self.lookup_ = {} + for word in dictionary: + hash_val = word[0] + str(len(word)) + word[-1] + if hash_val not in self.lookup_: + self.lookup_[hash_val] = Set([word]) + else: + self.lookup_[hash_val].add(word) + + + def isUnique(self, word): + """ + check if a word is unique. + :type word: str + :rtype: bool + """ + l = len(word) + hash_val = word[0] + str(len(word)) + word[-1] + return hash_val not in self.lookup_ or \ + (word in self.lookup_[hash_val] and len(self.lookup_[hash_val]) == 1) + + +# Your ValidWordAbbr object will be instantiated and called as such: +# vwa = ValidWordAbbr(dictionary) +# vwa.isUnique("word") +# vwa.isUnique("anotherWord") From e7cba2b229707bea050822b31996a9fa4e9eaba8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:14:04 +0800 Subject: [PATCH 0989/1939] Update unique-word-abbreviation.py --- Python/unique-word-abbreviation.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Python/unique-word-abbreviation.py b/Python/unique-word-abbreviation.py index 6aefa4beb..db4b067dc 100644 --- a/Python/unique-word-abbreviation.py +++ b/Python/unique-word-abbreviation.py @@ -1,3 +1,7 @@ +# Time: O(n) for constructor, n is number of words in the dictionary. +# O(1) for lookup +# Space: O(k), k is number of unique words. + from sets import Set class ValidWordAbbr(object): From bd62d65ac5ef265f19f8f9a6a956e95eb004b495 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:16:15 +0800 Subject: [PATCH 0990/1939] Update unique-word-abbreviation.cpp --- C++/unique-word-abbreviation.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/unique-word-abbreviation.cpp b/C++/unique-word-abbreviation.cpp index 05ec2ca6d..0078ff4e7 100644 --- a/C++/unique-word-abbreviation.cpp +++ b/C++/unique-word-abbreviation.cpp @@ -6,15 +6,13 @@ class ValidWordAbbr { public: ValidWordAbbr(vector &dictionary) { for (string& word : dictionary) { - const int len = word.length(); - const string hash_val = word[0] + to_string(len - 2) + word[len - 1]; + const string hash_val = word.front() + to_string(word.length()) + word.back(); lookup_[hash_val].emplace(word); } } bool isUnique(string word) { - const int len = word.length(); - const string hash_val = word[0] + to_string(len - 2) + word[len - 1]; + const string hash_val = word.front() + to_string(word.length()) + word.back(); return lookup_[hash_val].empty() || (lookup_[hash_val].count(word) == lookup_[hash_val].size()); } From e7c7ac10a4fa141be1c4eac67562fd673171fb41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:18:10 +0800 Subject: [PATCH 0991/1939] Update unique-word-abbreviation.cpp --- C++/unique-word-abbreviation.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/C++/unique-word-abbreviation.cpp b/C++/unique-word-abbreviation.cpp index 0078ff4e7..67079588a 100644 --- a/C++/unique-word-abbreviation.cpp +++ b/C++/unique-word-abbreviation.cpp @@ -6,16 +6,21 @@ class ValidWordAbbr { public: ValidWordAbbr(vector &dictionary) { for (string& word : dictionary) { - const string hash_val = word.front() + to_string(word.length()) + word.back(); - lookup_[hash_val].emplace(word); + const string hash_word = hash(word); + lookup_[hash_word].emplace(word); } } bool isUnique(string word) { - const string hash_val = word.front() + to_string(word.length()) + word.back(); - return lookup_[hash_val].empty() || - (lookup_[hash_val].count(word) == lookup_[hash_val].size()); + const string hash_word = hash(word); + return lookup_[hash_word].empty() || + (lookup_[hash_word].count(word) == lookup_[hash_word].size()); } + + string hash(const string& word) { + return word.front() + to_string(word.length()) + word.back();; + } + private: unordered_map> lookup_; }; From 3da539769152c8d284743a184e3f922deb3ffe81 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:18:37 +0800 Subject: [PATCH 0992/1939] Update unique-word-abbreviation.cpp --- C++/unique-word-abbreviation.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/unique-word-abbreviation.cpp b/C++/unique-word-abbreviation.cpp index 67079588a..53f479cbe 100644 --- a/C++/unique-word-abbreviation.cpp +++ b/C++/unique-word-abbreviation.cpp @@ -16,13 +16,13 @@ class ValidWordAbbr { return lookup_[hash_word].empty() || (lookup_[hash_word].count(word) == lookup_[hash_word].size()); } - - string hash(const string& word) { - return word.front() + to_string(word.length()) + word.back();; - } private: unordered_map> lookup_; + + string hash(const string& word) { + return word.front() + to_string(word.length()) + word.back();; + } }; From 45fe5a48cf71c24afe59b4714a739610cd217396 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:21:59 +0800 Subject: [PATCH 0993/1939] Update unique-word-abbreviation.py --- Python/unique-word-abbreviation.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/Python/unique-word-abbreviation.py b/Python/unique-word-abbreviation.py index db4b067dc..aeed08ac0 100644 --- a/Python/unique-word-abbreviation.py +++ b/Python/unique-word-abbreviation.py @@ -12,11 +12,11 @@ def __init__(self, dictionary): """ self.lookup_ = {} for word in dictionary: - hash_val = word[0] + str(len(word)) + word[-1] - if hash_val not in self.lookup_: - self.lookup_[hash_val] = Set([word]) + hash_word = self.hash(word) + if hash_word not in self.lookup_: + self.lookup_[hash_word] = Set([word]) else: - self.lookup_[hash_val].add(word) + self.lookup_[hash_word].add(word) def isUnique(self, word): @@ -26,9 +26,13 @@ def isUnique(self, word): :rtype: bool """ l = len(word) - hash_val = word[0] + str(len(word)) + word[-1] - return hash_val not in self.lookup_ or \ - (word in self.lookup_[hash_val] and len(self.lookup_[hash_val]) == 1) + hash_word = self.hash(word) + return hash_word not in self.lookup_ or \ + (word in self.lookup_[hash_word] and len(self.lookup_[hash_word]) == 1) + + + def hash(self, word): + return word[0] + str(len(word)) + word[-1] # Your ValidWordAbbr object will be instantiated and called as such: From 6b26a91259385a3c4fa90b62c8867d7fa4a9ea27 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:26:08 +0800 Subject: [PATCH 0994/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5356ee090..4bad54c17 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-09-28), there are `270` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-01), there are `271` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `287` questions. +Here is the classification of all `288` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -217,6 +217,7 @@ Shell 246| [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | [C++](./C++/strobogrammatic-number.cpp) [Python](./Python/strobogrammatic-number.py) | _O(n)_ | _O(1)_ | Easy |📖|| 249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |📖|| 266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |📖|| +288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| --- From e51d59fea5f64c60044ab7ccbcc68d1c36665430 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:26:41 +0800 Subject: [PATCH 0995/1939] Update unique-word-abbreviation.cpp --- C++/unique-word-abbreviation.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/unique-word-abbreviation.cpp b/C++/unique-word-abbreviation.cpp index 53f479cbe..36c4d3289 100644 --- a/C++/unique-word-abbreviation.cpp +++ b/C++/unique-word-abbreviation.cpp @@ -1,5 +1,5 @@ -// Time: O(n) for constructor, n is number of words in the dictionary. -// O(1) for lookup +// Time: ctor: O(n), n is number of words in the dictionary. +// lookup: O(1) // Space: O(k), k is number of unique words. class ValidWordAbbr { From a0a9ab4d9d078221f624eb56ee51cc230f0c2289 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:27:09 +0800 Subject: [PATCH 0996/1939] Update unique-word-abbreviation.py --- Python/unique-word-abbreviation.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/unique-word-abbreviation.py b/Python/unique-word-abbreviation.py index aeed08ac0..0554ba281 100644 --- a/Python/unique-word-abbreviation.py +++ b/Python/unique-word-abbreviation.py @@ -1,5 +1,5 @@ -# Time: O(n) for constructor, n is number of words in the dictionary. -# O(1) for lookup +# Time: ctor: O(n), n is number of words in the dictionary. +# lookup: O(1) # Space: O(k), k is number of unique words. from sets import Set From 98dcd0115cfdf615a79d1ad1abe8a1f100dcab12 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Oct 2015 01:51:13 +0800 Subject: [PATCH 0997/1939] Update unique-word-abbreviation.cpp --- C++/unique-word-abbreviation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/unique-word-abbreviation.cpp b/C++/unique-word-abbreviation.cpp index 36c4d3289..66bc349ee 100644 --- a/C++/unique-word-abbreviation.cpp +++ b/C++/unique-word-abbreviation.cpp @@ -21,7 +21,7 @@ class ValidWordAbbr { unordered_map> lookup_; string hash(const string& word) { - return word.front() + to_string(word.length()) + word.back();; + return word.front() + to_string(word.length()) + word.back(); } }; From 6c578808e1793f4b76d1ee0001b59dacfb115808 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 13:57:35 +0800 Subject: [PATCH 0998/1939] Update unique-word-abbreviation.py --- Python/unique-word-abbreviation.py | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Python/unique-word-abbreviation.py b/Python/unique-word-abbreviation.py index 0554ba281..67330b943 100644 --- a/Python/unique-word-abbreviation.py +++ b/Python/unique-word-abbreviation.py @@ -2,22 +2,17 @@ # lookup: O(1) # Space: O(k), k is number of unique words. -from sets import Set - class ValidWordAbbr(object): def __init__(self, dictionary): """ initialize your data structure here. :type dictionary: List[str] """ - self.lookup_ = {} + self.lookup_ = collections.defaultdict(set) for word in dictionary: - hash_word = self.hash(word) - if hash_word not in self.lookup_: - self.lookup_[hash_word] = Set([word]) - else: - self.lookup_[hash_word].add(word) - + abbr = self.abbr(word) + self.lookup_[abbr].add(word) + def isUnique(self, word): """ @@ -26,12 +21,12 @@ def isUnique(self, word): :rtype: bool """ l = len(word) - hash_word = self.hash(word) - return hash_word not in self.lookup_ or \ - (word in self.lookup_[hash_word] and len(self.lookup_[hash_word]) == 1) + abbr = self.abbr(word) + return abbr not in self.lookup_ or \ + self.lookup_[abbr] == set([word]) - def hash(self, word): + def abbr(self, word): return word[0] + str(len(word)) + word[-1] From daf688a72a69cdcc3246903f15c3862e9c1fdaa7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:01:49 +0800 Subject: [PATCH 0999/1939] Update unique-word-abbreviation.py --- Python/unique-word-abbreviation.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/unique-word-abbreviation.py b/Python/unique-word-abbreviation.py index 67330b943..7ab0e62e5 100644 --- a/Python/unique-word-abbreviation.py +++ b/Python/unique-word-abbreviation.py @@ -22,8 +22,7 @@ def isUnique(self, word): """ l = len(word) abbr = self.abbr(word) - return abbr not in self.lookup_ or \ - self.lookup_[abbr] == set([word]) + return self.lookup_[abbr] <= {word} def abbr(self, word): From 63190583f21e5cd8ac283a7d532e2d5fb6f62af0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:04:26 +0800 Subject: [PATCH 1000/1939] Update unique-word-abbreviation.cpp --- C++/unique-word-abbreviation.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/unique-word-abbreviation.cpp b/C++/unique-word-abbreviation.cpp index 66bc349ee..646c46d1d 100644 --- a/C++/unique-word-abbreviation.cpp +++ b/C++/unique-word-abbreviation.cpp @@ -6,21 +6,21 @@ class ValidWordAbbr { public: ValidWordAbbr(vector &dictionary) { for (string& word : dictionary) { - const string hash_word = hash(word); - lookup_[hash_word].emplace(word); + const string abbr = abbreviation(word); + lookup_[abbr].emplace(word); } } bool isUnique(string word) { - const string hash_word = hash(word); - return lookup_[hash_word].empty() || - (lookup_[hash_word].count(word) == lookup_[hash_word].size()); + const string abbr = abbreviation(word); + return lookup_[abbr].empty() || + (lookup_[abbr].count(word) == lookup_[abbr].size()); } private: unordered_map> lookup_; - string hash(const string& word) { + string abbreviation(const string& word) { return word.front() + to_string(word.length()) + word.back(); } }; From a4ac0fa08bef5ad7271e1602f21afb51225b9710 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:10:19 +0800 Subject: [PATCH 1001/1939] Update unique-word-abbreviation.py --- Python/unique-word-abbreviation.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/unique-word-abbreviation.py b/Python/unique-word-abbreviation.py index 7ab0e62e5..b6e84e88d 100644 --- a/Python/unique-word-abbreviation.py +++ b/Python/unique-word-abbreviation.py @@ -10,7 +10,7 @@ def __init__(self, dictionary): """ self.lookup_ = collections.defaultdict(set) for word in dictionary: - abbr = self.abbr(word) + abbr = self.abbreviation(word) self.lookup_[abbr].add(word) @@ -21,11 +21,11 @@ def isUnique(self, word): :rtype: bool """ l = len(word) - abbr = self.abbr(word) + abbr = self.abbreviation(word) return self.lookup_[abbr] <= {word} - def abbr(self, word): + def abbreviation(self, word): return word[0] + str(len(word)) + word[-1] From 9278e7a7e6cb7839af08c5218f454c2897cf993f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:29:02 +0800 Subject: [PATCH 1002/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 2d4b17e5e..a90f50c24 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -1,6 +1,7 @@ # Time: O(|V| + |E|) # Space: O(|V|) +# BFS solution. class Solution: # @param {integer} n # @param {integer[][]} edges @@ -9,14 +10,15 @@ def validTree(self, n, edges): if len(edges) != n - 1: return False - parent, neighbors = 0, 1 - nodes = {} + visited_from, neighbors = 0, 1 + nodes = {} # A structure to track each node's [visited_from, neighbors] for i in xrange(n): nodes[i] = [-1, []] for edge in edges: nodes[edge[0]][neighbors].append(edge[1]) nodes[edge[1]][neighbors].append(edge[0]) + # BFS to check whether the graph is valid tree. visited = {} q = collections.deque() q.append(0) @@ -24,11 +26,11 @@ def validTree(self, n, edges): i = q.popleft() visited[i] = True for n in nodes[i][neighbors]: - if n != nodes[i][parent]: + if n != nodes[i][visited_from]: if n in visited: return False else: visited[n] = True - nodes[n][parent] = i + nodes[n][visited_from] = i q.append(n) return True From 841affdd62a82ff81ca28a914a06f31deea98808 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:35:29 +0800 Subject: [PATCH 1003/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index a90f50c24..1aca46523 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -1,5 +1,5 @@ # Time: O(|V| + |E|) -# Space: O(|V|) +# Space: O(|V| + |E|) # BFS solution. class Solution: @@ -12,9 +12,9 @@ def validTree(self, n, edges): visited_from, neighbors = 0, 1 nodes = {} # A structure to track each node's [visited_from, neighbors] - for i in xrange(n): + for i in xrange(n): # Space: O(|V|) nodes[i] = [-1, []] - for edge in edges: + for edge in edges: # Space: O(|E|) nodes[edge[0]][neighbors].append(edge[1]) nodes[edge[1]][neighbors].append(edge[0]) From 453ca2958cf42ae6e5af80f8dccb359e25d2fd14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:36:02 +0800 Subject: [PATCH 1004/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index 05e3e0e1a..9ed2ab7ab 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -1,5 +1,5 @@ // Time: O(|V| + |E|) -// Space: O(|V|) +// Space: O(|V| + |E|) class Solution { public: From 332d6d19a23f37ab8ac7fd249ce1addc1efcf4b9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:36:56 +0800 Subject: [PATCH 1005/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4bad54c17..181999f49 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,7 @@ Shell 133| [Clone Graph](https://leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || 207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | -261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium | 📖 | +261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\| + \|E\|)_ | Medium | 📖 | 269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Hard |📖| Topological Sort, BFS, DFS | 286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [C++](./C++/walls-and-gates.cpp) [Python](./Python/walls-and-gates.py) | _O(m * n)_ | _O(g)_ | Medium | 📖 | From 1ca05fe2a3d696bc2d211757bcc81c4ec5764a9a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:41:07 +0800 Subject: [PATCH 1006/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 1aca46523..5fbfe7736 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -18,7 +18,7 @@ def validTree(self, n, edges): nodes[edge[0]][neighbors].append(edge[1]) nodes[edge[1]][neighbors].append(edge[0]) - # BFS to check whether the graph is valid tree. + # BFS to check whether the graph is a valid tree. visited = {} q = collections.deque() q.append(0) From ec652d208bb88c0400d6274eeca92ca922c53df4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:42:09 +0800 Subject: [PATCH 1007/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 5fbfe7736..acafa13f8 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -18,7 +18,7 @@ def validTree(self, n, edges): nodes[edge[0]][neighbors].append(edge[1]) nodes[edge[1]][neighbors].append(edge[0]) - # BFS to check whether the graph is a valid tree. + # BFS to check whether these edges make up a valid tree. visited = {} q = collections.deque() q.append(0) From 059e3f4a9d38bff13c4ba50818e874f2f379d930 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Oct 2015 14:48:42 +0800 Subject: [PATCH 1008/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index acafa13f8..933105f98 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -11,7 +11,7 @@ def validTree(self, n, edges): return False visited_from, neighbors = 0, 1 - nodes = {} # A structure to track each node's [visited_from, neighbors] + nodes = {} # A dictionary to track each node's [visited_from, neighbors] for i in xrange(n): # Space: O(|V|) nodes[i] = [-1, []] for edge in edges: # Space: O(|E|) From 244ef7a629c6864e4eb20a599a89df7aa3996ccb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 03:51:29 +0800 Subject: [PATCH 1009/1939] Create game-of-life.cpp --- C++/game-of-life.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/game-of-life.cpp diff --git a/C++/game-of-life.cpp b/C++/game-of-life.cpp new file mode 100644 index 000000000..4c5895e88 --- /dev/null +++ b/C++/game-of-life.cpp @@ -0,0 +1,33 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + void gameOfLife(vector>& board) { + const int m = board.size(), n = m ? board[0].size() : 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int count = 0; + // Count live cells in 3x3 block. + for (int I = max(i - 1, 0); I < min(i + 2, m); ++I) { + for (int J = max(j - 1, 0); J < min(j + 2, n); ++J) { + count += board[I][J] & 1; + } + } + // if (count == 4 && board[i][j]) means: + // Any live cell with three live neighbors lives. + // if (count == 3) means: + // Any live cell with two live neighbors. + // Any dead cell with exactly three live neighbors lives. + if ((count == 4 && board[i][j]) || count == 3) { + board[i][j] |= 2; // Make as live. + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + board[i][j] >>= 1; // Update to the next state. + } + } + } +}; From 3aeba5b598d94c4ef2efedc4f886f594f3d65127 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 03:58:56 +0800 Subject: [PATCH 1010/1939] Create game-of-life.py --- Python/game-of-life.py | 64 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Python/game-of-life.py diff --git a/Python/game-of-life.py b/Python/game-of-life.py new file mode 100644 index 000000000..4a00ab07f --- /dev/null +++ b/Python/game-of-life.py @@ -0,0 +1,64 @@ +# Time: O(m * n) +# Space: O(1) + +# According to the Wikipedia's article: +# "The Game of Life, also known simply as Life, +# is a cellular automaton devised by the British +# mathematician John Horton Conway in 1970." +# +# Given a board with m by n cells, each cell has +# an initial state live (1) or dead (0). +# Each cell interacts with its eight neighbors +# (horizontal, vertical, diagonal) +# using the following four rules +# (taken from the above Wikipedia article): +# +# - Any live cell with fewer than two live neighbors dies, +# as if caused by under-population. +# - Any live cell with two or three live neighbors lives +# on to the next generation. +# - Any live cell with more than three live neighbors dies, +# as if by over-population.. +# - Any dead cell with exactly three live neighbors +# becomes a live cell, as if by reproduction. +# +# Write a function to compute the next state +# (after one update) of the board given its current state. +# +# Follow up: +# - Could you solve it in-place? Remember that the board needs +# to be updated at the same time: You cannot update some cells +# first and then use their updated values to update other cells. +# - In this question, we represent the board using a 2D array. +# In principle, the board is infinite, which would cause problems +# when the active area encroaches the border of the array. +# How would you address these problems? +# + +class Solution(object): + def gameOfLife(self, board): + """ + :type board: List[List[int]] + :rtype: void Do not return anything, modify board in-place instead. + """ + m = len(board) + n = len(board[0]) if m else 0 + for i in xrange(m): + for j in xrange(n): + count = 0 + ## Count live cells in 3x3 block. + for I in xrange(max(i-1, 0), min(i+2, m)): + for J in xrange(max(j-1, 0), min(j+2, n)): + count += board[I][J] & 1 + + # if (count == 4 && board[i][j]) means: + # Any live cell with three live neighbors lives. + # if (count == 3) means: + # Any live cell with two live neighbors. + # Any dead cell with exactly three live neighbors lives. + if (count == 4 and board[i][j]) or count == 3: + board[i][j] |= 2 # Make as live. + + for i in xrange(m): + for j in xrange(n): + board[i][j] >>= 1 # Update to the next state. From ef0b34621dd05096adcb3d1ab128b038b4b86a09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 04:01:07 +0800 Subject: [PATCH 1011/1939] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 181999f49..69b06b8a6 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ LeetCode ======== -Up to date (2015-10-01), there are `271` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-04), there are `272` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `288` questions. +Here is the classification of all `289` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -99,6 +99,7 @@ Shell 245| [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance III/) | [C++](./C++/shortest-word-distance-iii.cpp) [Python](./Python/shortest-word-distance-iii.py) | _O(n)_ | _O(1)_ | Medium |📖|| 251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium |📖|| 277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |📖, EPI || +289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| --- From 3834c825bda68e2f9ae5391889ced277b081fe64 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 04:01:55 +0800 Subject: [PATCH 1012/1939] Update game-of-life.cpp --- C++/game-of-life.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/game-of-life.cpp b/C++/game-of-life.cpp index 4c5895e88..df22a3591 100644 --- a/C++/game-of-life.cpp +++ b/C++/game-of-life.cpp @@ -20,7 +20,7 @@ class Solution { // Any live cell with two live neighbors. // Any dead cell with exactly three live neighbors lives. if ((count == 4 && board[i][j]) || count == 3) { - board[i][j] |= 2; // Make as live. + board[i][j] |= 2; // Mark as live. } } } From 26912248ff1c2dc849a640b0d8a552704b8222a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 04:02:15 +0800 Subject: [PATCH 1013/1939] Update game-of-life.py --- Python/game-of-life.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/game-of-life.py b/Python/game-of-life.py index 4a00ab07f..f569bde1f 100644 --- a/Python/game-of-life.py +++ b/Python/game-of-life.py @@ -57,7 +57,7 @@ def gameOfLife(self, board): # Any live cell with two live neighbors. # Any dead cell with exactly three live neighbors lives. if (count == 4 and board[i][j]) or count == 3: - board[i][j] |= 2 # Make as live. + board[i][j] |= 2 # Mark as live. for i in xrange(m): for j in xrange(n): From 625a06ce69758caabe9cb52d7410352bcf306a7d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 12:12:41 +0800 Subject: [PATCH 1014/1939] Update README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 69b06b8a6..523d61434 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ -LeetCode -======== +# LeetCode + +![Language](https://img.shields.io/badge/language-Python%20-orange.svg) +![Progress](https://img.shields.io/badge/progress-%20289%20%2F%20289%20%20-ff69b4.svg) Up to date (2015-10-04), there are `272` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. From 71f867405c2e8d6d86b6756c40e534362add81d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 12:20:37 +0800 Subject: [PATCH 1015/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 523d61434..884bf6ed8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # LeetCode ![Language](https://img.shields.io/badge/language-Python%20-orange.svg) +![License](https://img.shields.io/github/license/lexrus/ios-dev-playbook.svg?style=flat) ![Progress](https://img.shields.io/badge/progress-%20289%20%2F%20289%20%20-ff69b4.svg) Up to date (2015-10-04), there are `272` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). From 7bd86dda5ee9a77c019ab40e7da53417d20770fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 12:34:52 +0800 Subject: [PATCH 1016/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 884bf6ed8..b78a56206 100644 --- a/README.md +++ b/README.md @@ -229,7 +229,7 @@ Shell # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || -225| [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | [C++](./C++/implement-stack-using-queues.cpp) [Python](./Python/implement-stack-using-queues.py) | Push: _O(n)_, Pop: _O(1)_, Top: _O(1)_ | _O(n)_ | Medium || +225| [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | [C++](./C++/implement-stack-using-queues.cpp) [Python](./Python/implement-stack-using-queues.py) | push: _O(n)_, pop: _O(1)_, top: _O(1)_ | _O(n)_ | Medium || --- From bbcae6336bd55f7adcde7c178c1284d7ed50111c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 17:07:32 +0800 Subject: [PATCH 1017/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b78a56206..6c75c7f1f 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # LeetCode ![Language](https://img.shields.io/badge/language-Python%20-orange.svg) -![License](https://img.shields.io/github/license/lexrus/ios-dev-playbook.svg?style=flat) +![License](https://img.shields.io/badge/license-MIT-blue.svg) ![Progress](https://img.shields.io/badge/progress-%20289%20%2F%20289%20%20-ff69b4.svg) Up to date (2015-10-04), there are `272` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). From 5fac33390318e9ea446759a83870bf098393aee2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Oct 2015 17:11:27 +0800 Subject: [PATCH 1018/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6c75c7f1f..75531563f 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![Language](https://img.shields.io/badge/language-Python%20-orange.svg) ![License](https://img.shields.io/badge/license-MIT-blue.svg) -![Progress](https://img.shields.io/badge/progress-%20289%20%2F%20289%20%20-ff69b4.svg) +![Progress](https://img.shields.io/badge/progress-289%20%2F%20289%20-ff69b4.svg) Up to date (2015-10-04), there are `272` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. From 655f5bc3b499d292b1b6e240dea66e3628d37261 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 5 Oct 2015 23:28:28 +0800 Subject: [PATCH 1019/1939] Create word-pattern.cpp --- C++/word-pattern.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/word-pattern.cpp diff --git a/C++/word-pattern.cpp b/C++/word-pattern.cpp new file mode 100644 index 000000000..419cc2649 --- /dev/null +++ b/C++/word-pattern.cpp @@ -0,0 +1,37 @@ +// Time: O(n) +// Space: O(c), c is unique count of pattern and words + +class Solution { +public: + bool wordPattern(string pattern, string str) { + int word_cnt = str.empty() ? 0 : 1; + for (const auto& c : str) { + if (c == ' ') { + ++word_cnt; + } + } + if (pattern.size() != word_cnt) { + return false; + } + + unordered_map word2pattern; + unordered_map pattern2word; + for (int i = 0, idx = 0, space_idx = 0; + i < pattern.size(); + ++i, idx = space_idx + 1) { + + space_idx = str.find(" ", idx) != string::npos ? + str.find(" ", idx) : + str.length(); + string word = str.substr(idx, space_idx - idx); + if (word2pattern[word] == 0 && + pattern2word[pattern[i]] == "") { + word2pattern[word] = pattern[i]; + pattern2word[pattern[i]] = word; + } else if (word2pattern[word] != pattern[i]) { + return false; + } + } + return true; + } +}; From 513e8d61e8f2f1f924b98314445536e9d7913d31 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:05:47 +0800 Subject: [PATCH 1020/1939] Update word-pattern.cpp --- C++/word-pattern.cpp | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/C++/word-pattern.cpp b/C++/word-pattern.cpp index 419cc2649..34e33fdbf 100644 --- a/C++/word-pattern.cpp +++ b/C++/word-pattern.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(c), c is unique count of pattern and words +// Space: O(c), c is count of pattern class Solution { public: @@ -16,21 +16,20 @@ class Solution { unordered_map word2pattern; unordered_map pattern2word; - for (int i = 0, idx = 0, space_idx = 0; - i < pattern.size(); - ++i, idx = space_idx + 1) { - - space_idx = str.find(" ", idx) != string::npos ? - str.find(" ", idx) : - str.length(); - string word = str.substr(idx, space_idx - idx); - if (word2pattern[word] == 0 && - pattern2word[pattern[i]] == "") { - word2pattern[word] = pattern[i]; - pattern2word[pattern[i]] = word; - } else if (word2pattern[word] != pattern[i]) { + int i = 0, j = 0; + for (const auto& p : pattern) { + j = str.find(" ", i); + if (j == string::npos) { + j = str.length(); + } + string word = str.substr(i, j - i); + if (!word2pattern.count(word) && !pattern2word.count(p)) { + word2pattern[word] = p; + pattern2word[p] = word; + } else if (word2pattern[word] != p) { return false; } + i = j + 1; } return true; } From 8d66fb834068300f5fae7ff3d814ae22aa159cb3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:06:22 +0800 Subject: [PATCH 1021/1939] Update word-pattern.cpp --- C++/word-pattern.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/word-pattern.cpp b/C++/word-pattern.cpp index 34e33fdbf..38472f611 100644 --- a/C++/word-pattern.cpp +++ b/C++/word-pattern.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(c), c is count of pattern +// Space: O(c), c is unique count of pattern and words class Solution { public: From 9a6dd635e6355dbe6619e68fdef42b4fd053a95a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:06:57 +0800 Subject: [PATCH 1022/1939] Update word-pattern.cpp --- C++/word-pattern.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/word-pattern.cpp b/C++/word-pattern.cpp index 38472f611..c0f1e0180 100644 --- a/C++/word-pattern.cpp +++ b/C++/word-pattern.cpp @@ -22,7 +22,7 @@ class Solution { if (j == string::npos) { j = str.length(); } - string word = str.substr(i, j - i); + const string word = str.substr(i, j - i); if (!word2pattern.count(word) && !pattern2word.count(p)) { word2pattern[word] = p; pattern2word[p] = word; From 50fec8a80f3d445e56f5e98efaf8b3b60c0da57a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:09:48 +0800 Subject: [PATCH 1023/1939] Update word-pattern.cpp --- C++/word-pattern.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/C++/word-pattern.cpp b/C++/word-pattern.cpp index c0f1e0180..6f7d1100d 100644 --- a/C++/word-pattern.cpp +++ b/C++/word-pattern.cpp @@ -4,18 +4,18 @@ class Solution { public: bool wordPattern(string pattern, string str) { - int word_cnt = str.empty() ? 0 : 1; + int cnt = str.empty() ? 0 : 1; for (const auto& c : str) { if (c == ' ') { - ++word_cnt; + ++cnt; } } - if (pattern.size() != word_cnt) { + if (pattern.size() != cnt) { return false; } - unordered_map word2pattern; - unordered_map pattern2word; + unordered_map w2p; + unordered_map p2w; int i = 0, j = 0; for (const auto& p : pattern) { j = str.find(" ", i); @@ -23,10 +23,10 @@ class Solution { j = str.length(); } const string word = str.substr(i, j - i); - if (!word2pattern.count(word) && !pattern2word.count(p)) { - word2pattern[word] = p; - pattern2word[p] = word; - } else if (word2pattern[word] != p) { + if (!w2p.count(word) && !p2w.count(p)) { + w2p[word] = p; + p2w[p] = word; + } else if (w2p[word] != p) { return false; } i = j + 1; From 535620eec9c6b57ca21ad34db7d8cc3bec0b003e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:10:48 +0800 Subject: [PATCH 1024/1939] Update word-pattern.cpp --- C++/word-pattern.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/C++/word-pattern.cpp b/C++/word-pattern.cpp index 6f7d1100d..8c7fe92bb 100644 --- a/C++/word-pattern.cpp +++ b/C++/word-pattern.cpp @@ -1,6 +1,9 @@ // Time: O(n) // Space: O(c), c is unique count of pattern and words +// Time: O(n) +// Space: O(c), c is count of pattern + class Solution { public: bool wordPattern(string pattern, string str) { @@ -22,11 +25,11 @@ class Solution { if (j == string::npos) { j = str.length(); } - const string word = str.substr(i, j - i); - if (!w2p.count(word) && !p2w.count(p)) { - w2p[word] = p; - p2w[p] = word; - } else if (w2p[word] != p) { + const string w = str.substr(i, j - i); + if (!w2p.count(w) && !p2w.count(p)) { + w2p[w] = p; + p2w[p] = w; + } else if (w2p[w] != p) { return false; } i = j + 1; From 053d6f08f8077830ed56fd71d3c7a47d86185f8e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:36:11 +0800 Subject: [PATCH 1025/1939] Update word-pattern.cpp --- C++/word-pattern.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/C++/word-pattern.cpp b/C++/word-pattern.cpp index 8c7fe92bb..ee7e2e977 100644 --- a/C++/word-pattern.cpp +++ b/C++/word-pattern.cpp @@ -1,9 +1,6 @@ // Time: O(n) // Space: O(c), c is unique count of pattern and words -// Time: O(n) -// Space: O(c), c is count of pattern - class Solution { public: bool wordPattern(string pattern, string str) { From 64f800842a289983aec6645d4c978be0934df1bd Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:39:28 +0800 Subject: [PATCH 1026/1939] Create word-pattern.py --- Python/word-pattern.py | 61 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/word-pattern.py diff --git a/Python/word-pattern.py b/Python/word-pattern.py new file mode 100644 index 000000000..359c0f5d9 --- /dev/null +++ b/Python/word-pattern.py @@ -0,0 +1,61 @@ +# Time: O(n) +# Space: O(c), c is unique count of pattern and words + +# Given a pattern and a string str, find if str follows the same pattern. +# +# Examples: +# 1. pattern = "abba", str = "dog cat cat dog" should return true. +# 2. pattern = "abba", str = "dog cat cat fish" should return false. +# 3. pattern = "aaaa", str = "dog cat cat dog" should return false. +# 4. pattern = "abba", str = "dog dog dog dog" should return false. +# +# Notes: +# 1. Both pattern and str contains only lowercase alphabetical letters. +# 2. Both pattern and str do not have leading or trailing spaces. +# 3. Each word in str is separated by a single space. +# 4. Each letter in pattern must map to a word with length that is at least 1. + +# Lengthy code but saving more spaces. +class Solution(object): + # Word generates at a time without saving all the words. + class WordGenerator(object): + def __init__(self, str): + self.str = str + + def __iter__(self): + w = "" + for c in self.str: + if c == ' ': + yield w + w = "" + else: + w += c + yield w + + def wordPattern(self, pattern, str): + """ + :type pattern: str + :type str: str + :rtype: bool + """ + if len(pattern) != self.wordCount(str): + return False + + w2p, p2w = {}, {} + for i, w in enumerate(self.WordGenerator(str)): + p = pattern[i] + if w not in w2p and p not in p2w: + # Build mapping. + w2p[w] = p + p2w[p] = w + elif w not in w2p or w2p[w] != p: + # Contradict mapping. + return False + return True + + def wordCount(self, str): + cnt = 1 if str else 0 + for c in str: + if c == ' ': + cnt += 1 + return cnt From a032f7409a159b48f5c8412aba186bdb69c74f08 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:40:00 +0800 Subject: [PATCH 1027/1939] Update word-pattern.py --- Python/word-pattern.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-pattern.py b/Python/word-pattern.py index 359c0f5d9..50c8fd267 100644 --- a/Python/word-pattern.py +++ b/Python/word-pattern.py @@ -15,7 +15,7 @@ # 3. Each word in str is separated by a single space. # 4. Each letter in pattern must map to a word with length that is at least 1. -# Lengthy code but saving more spaces. +# Lengthy code but saving more spaces class Solution(object): # Word generates at a time without saving all the words. class WordGenerator(object): From f574e49403f09fd9ea15141efe9da562fd326343 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:49:24 +0800 Subject: [PATCH 1028/1939] Update word-pattern.py --- Python/word-pattern.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/word-pattern.py b/Python/word-pattern.py index 50c8fd267..3e1221c26 100644 --- a/Python/word-pattern.py +++ b/Python/word-pattern.py @@ -15,7 +15,8 @@ # 3. Each word in str is separated by a single space. # 4. Each letter in pattern must map to a word with length that is at least 1. -# Lengthy code but saving more spaces +from itertools import izip + class Solution(object): # Word generates at a time without saving all the words. class WordGenerator(object): @@ -42,8 +43,7 @@ def wordPattern(self, pattern, str): return False w2p, p2w = {}, {} - for i, w in enumerate(self.WordGenerator(str)): - p = pattern[i] + for p, w in izip(pattern, self.WordGenerator(str)): if w not in w2p and p not in p2w: # Build mapping. w2p[w] = p From b9267493ae79f44b9f2255304d971632a5eeceae Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:51:01 +0800 Subject: [PATCH 1029/1939] Update word-pattern.py --- Python/word-pattern.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Python/word-pattern.py b/Python/word-pattern.py index 3e1221c26..c91b0a817 100644 --- a/Python/word-pattern.py +++ b/Python/word-pattern.py @@ -59,3 +59,28 @@ def wordCount(self, str): if c == ' ': cnt += 1 return cnt + + +# Time: O(n) +# Space: O(n) +class Solution2(object): + def wordPattern(self, pattern, str): + """ + :type pattern: str + :type str: str + :rtype: bool + """ + words = str.split() + if len(pattern) != len(words): + return False + + w2p, p2w = {}, {} + for p, w in izip(pattern, words): + if w not in w2p and p not in p2w: + # Build mapping. + w2p[w] = p + p2w[p] = w + elif w not in w2p or w2p[w] != p: + # Contradict mapping. + return False + return True From 2c988e1f99d996bccad1d1336a3a409d11a5ae57 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 00:54:53 +0800 Subject: [PATCH 1030/1939] Update word-pattern.py --- Python/word-pattern.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Python/word-pattern.py b/Python/word-pattern.py index c91b0a817..084b9b7aa 100644 --- a/Python/word-pattern.py +++ b/Python/word-pattern.py @@ -18,21 +18,6 @@ from itertools import izip class Solution(object): - # Word generates at a time without saving all the words. - class WordGenerator(object): - def __init__(self, str): - self.str = str - - def __iter__(self): - w = "" - for c in self.str: - if c == ' ': - yield w - w = "" - else: - w += c - yield w - def wordPattern(self, pattern, str): """ :type pattern: str @@ -60,6 +45,21 @@ def wordCount(self, str): cnt += 1 return cnt + # Word generates at a time without saving all the words. + class WordGenerator(object): + def __init__(self, str): + self.str = str + + def __iter__(self): + w = "" + for c in self.str: + if c == ' ': + yield w + w = "" + else: + w += c + yield w + # Time: O(n) # Space: O(n) From 50098d8f324b16b2c9c9b4c858fd11a0ed63b008 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 01:01:05 +0800 Subject: [PATCH 1031/1939] Update README.md --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 75531563f..81ab2c8b5 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,11 @@ ![Language](https://img.shields.io/badge/language-Python%20-orange.svg) ![License](https://img.shields.io/badge/license-MIT-blue.svg) -![Progress](https://img.shields.io/badge/progress-289%20%2F%20289%20-ff69b4.svg) +![Progress](https://img.shields.io/badge/progress-290%20%2F%20290%20-ff69b4.svg) -Up to date (2015-10-04), there are `272` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-05), there are `273` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `289` questions. +Here is the classification of all `290` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -124,7 +124,6 @@ Shell 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| 165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | -205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` 271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [C++](./C++/encode-and-decode-strings.cpp) [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 273| [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [C++](./C++/integer-to-english-words.cpp) [Python](./Python/integer-to-english-words.py) | _O(logn)_ | _O(1)_ | Medium | | @@ -215,6 +214,7 @@ Shell 187| [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || 202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || +205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || 219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || 244| [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [C++](./C++/shortest-word-distance-ii.cpp) [Python](./Python/shortest-word-distance-ii.py) | ctor: _O(n)_, lookup: _O(a + b)_ | _O(n)_ | Medium |📖|| @@ -222,6 +222,8 @@ Shell 249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |📖|| 266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |📖|| 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| +290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of `Isomorphic Strings` || + --- From ec5278dae48169051af4676ce9dbd87f6f30dbe8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 01:03:56 +0800 Subject: [PATCH 1032/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 81ab2c8b5..5abdea70c 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,7 @@ Shell 249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |📖|| 266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |📖|| 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| -290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of `Isomorphic Strings` || +290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || --- From 7e294b2199d9929e366bb1b2002e9b8afb941d41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 01:16:21 +0800 Subject: [PATCH 1033/1939] Update word-pattern.py --- Python/word-pattern.py | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/Python/word-pattern.py b/Python/word-pattern.py index 084b9b7aa..79c9cc97f 100644 --- a/Python/word-pattern.py +++ b/Python/word-pattern.py @@ -28,7 +28,7 @@ def wordPattern(self, pattern, str): return False w2p, p2w = {}, {} - for p, w in izip(pattern, self.WordGenerator(str)): + for p, w in izip(pattern, self.wordGenerator(str)): if w not in w2p and p not in p2w: # Build mapping. w2p[w] = p @@ -46,19 +46,15 @@ def wordCount(self, str): return cnt # Word generates at a time without saving all the words. - class WordGenerator(object): - def __init__(self, str): - self.str = str - - def __iter__(self): - w = "" - for c in self.str: - if c == ' ': - yield w - w = "" - else: - w += c - yield w + def wordGenerator(self, str): + w = "" + for c in str: + if c == ' ': + yield w + w = "" + else: + w += c + yield w # Time: O(n) From 933644069ee01bbcca7b5760332a5a86776df6f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 01:18:39 +0800 Subject: [PATCH 1034/1939] Update word-pattern.py --- Python/word-pattern.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/word-pattern.py b/Python/word-pattern.py index 79c9cc97f..67d01e2c4 100644 --- a/Python/word-pattern.py +++ b/Python/word-pattern.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(c), c is unique count of pattern and words +# Space: O(c), c is unique count of pattern # Given a pattern and a string str, find if str follows the same pattern. # @@ -30,7 +30,7 @@ def wordPattern(self, pattern, str): w2p, p2w = {}, {} for p, w in izip(pattern, self.wordGenerator(str)): if w not in w2p and p not in p2w: - # Build mapping. + # Build mapping. Space: O(c) w2p[w] = p p2w[p] = w elif w not in w2p or w2p[w] != p: @@ -66,14 +66,14 @@ def wordPattern(self, pattern, str): :type str: str :rtype: bool """ - words = str.split() + words = str.split() # Space: O(n) if len(pattern) != len(words): return False w2p, p2w = {}, {} for p, w in izip(pattern, words): if w not in w2p and p not in p2w: - # Build mapping. + # Build mapping. Space: O(c) w2p[w] = p p2w[p] = w elif w not in w2p or w2p[w] != p: From 2d22c59607c342f830348bdcce4d2580d21edc76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 01:19:55 +0800 Subject: [PATCH 1035/1939] Update word-pattern.cpp --- C++/word-pattern.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/word-pattern.cpp b/C++/word-pattern.cpp index ee7e2e977..2a0363dbe 100644 --- a/C++/word-pattern.cpp +++ b/C++/word-pattern.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(c), c is unique count of pattern and words +// Space: O(c), c is unique count of pattern class Solution { public: @@ -26,7 +26,7 @@ class Solution { if (!w2p.count(w) && !p2w.count(p)) { w2p[w] = p; p2w[p] = w; - } else if (w2p[w] != p) { + } else if (!w2p.count(w) || w2p[w] != p) { return false; } i = j + 1; From 02c4ae5362ceb53162421bf0871788083b2dcf2e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 01:22:50 +0800 Subject: [PATCH 1036/1939] Update word-pattern.cpp --- C++/word-pattern.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/C++/word-pattern.cpp b/C++/word-pattern.cpp index 2a0363dbe..b4a88d415 100644 --- a/C++/word-pattern.cpp +++ b/C++/word-pattern.cpp @@ -4,6 +4,7 @@ class Solution { public: bool wordPattern(string pattern, string str) { + // Count the words. int cnt = str.empty() ? 0 : 1; for (const auto& c : str) { if (c == ' ') { @@ -18,15 +19,19 @@ class Solution { unordered_map p2w; int i = 0, j = 0; for (const auto& p : pattern) { + // Get a word at a time without saving all the words. j = str.find(" ", i); if (j == string::npos) { j = str.length(); } const string w = str.substr(i, j - i); + if (!w2p.count(w) && !p2w.count(p)) { + // Build mapping. Space: O(c) w2p[w] = p; p2w[p] = w; } else if (!w2p.count(w) || w2p[w] != p) { + // Contradict mapping. return false; } i = j + 1; From 3f074a2ae7d3960646177091485a08601bfdc8cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 01:30:52 +0800 Subject: [PATCH 1037/1939] Update word-pattern.py --- Python/word-pattern.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-pattern.py b/Python/word-pattern.py index 67d01e2c4..f44e3f46e 100644 --- a/Python/word-pattern.py +++ b/Python/word-pattern.py @@ -45,7 +45,7 @@ def wordCount(self, str): cnt += 1 return cnt - # Word generates at a time without saving all the words. + # Generate a word at a time without saving all the words. def wordGenerator(self, str): w = "" for c in str: From 12744aecfd990a551f8891aec914bd48abeffc0f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 01:31:41 +0800 Subject: [PATCH 1038/1939] Update word-pattern.py --- Python/word-pattern.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-pattern.py b/Python/word-pattern.py index f44e3f46e..7bace4ebd 100644 --- a/Python/word-pattern.py +++ b/Python/word-pattern.py @@ -15,7 +15,7 @@ # 3. Each word in str is separated by a single space. # 4. Each letter in pattern must map to a word with length that is at least 1. -from itertools import izip +from itertools import izip # Generator version of zip. class Solution(object): def wordPattern(self, pattern, str): From f74af129991f963d7f4acd0d1e063c93edbc80ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Oct 2015 01:40:34 +0800 Subject: [PATCH 1039/1939] Update isomorphic-strings.py --- Python/isomorphic-strings.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/isomorphic-strings.py b/Python/isomorphic-strings.py index d65bdb00d..c66061412 100644 --- a/Python/isomorphic-strings.py +++ b/Python/isomorphic-strings.py @@ -31,10 +31,10 @@ def isIsomorphic(self, s, t): return self.halfIsom(s, t) and self.halfIsom(t, s) def halfIsom(self, s, t): - res = {} + lookup = {} for i in xrange(len(s)): - if s[i] not in res: - res[s[i]] = t[i] - elif res[s[i]] != t[i]: + if s[i] not in lookup: + lookup[s[i]] = t[i] + elif lookup[s[i]] != t[i]: return False return True From 3e56a89aab4a31ee39d95034f170e18327ae9b46 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:03:18 +0800 Subject: [PATCH 1040/1939] Update 4sum.py --- Python/4sum.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Python/4sum.py b/Python/4sum.py index a1a77ef20..0ad8b8075 100644 --- a/Python/4sum.py +++ b/Python/4sum.py @@ -19,11 +19,9 @@ class Solution: # @return a list of lists of length 4, [[val1,val2,val3,val4]] def fourSum(self, nums, target): - nums, result, lookup = sorted(nums), [], {} + nums, result, lookup = sorted(nums), [], collections.defaultdict(list) for i in xrange(0, len(nums) - 1): for j in xrange(i + 1, len(nums)): - if nums[i] + nums[j] not in lookup: - lookup[nums[i] + nums[j]] = [] is_duplicated = False for [x, y] in lookup[nums[i] + nums[j]]: if nums[x] == nums[i]: @@ -49,11 +47,9 @@ def fourSum(self, nums, target): class Solution2: # @return a list of lists of length 4, [[val1,val2,val3,val4]] def fourSum(self, nums, target): - nums, result, lookup = sorted(nums), [], {} + nums, result, lookup = sorted(nums), [], collections.defaultdict(list) for i in xrange(0, len(nums) - 1): for j in xrange(i + 1, len(nums)): - if nums[i] + nums[j] not in lookup: - lookup[nums[i] + nums[j]] = [] lookup[nums[i] + nums[j]].append([i, j]) for i in lookup.keys(): From 24a83ce302d1c4c369f3b19c277b1b813b9fc23e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:07:42 +0800 Subject: [PATCH 1041/1939] Update substring-with-concatenation-of-all-words.py --- .../substring-with-concatenation-of-all-words.py | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/Python/substring-with-concatenation-of-all-words.py b/Python/substring-with-concatenation-of-all-words.py index a6aeb0d27..03e5fa7f3 100644 --- a/Python/substring-with-concatenation-of-all-words.py +++ b/Python/substring-with-concatenation-of-all-words.py @@ -19,23 +19,18 @@ class Solution: # @param L, a list of string # @return a list of integer def findSubstring(self, S, L): - result, words, word_num, word_len = [], {}, len(L), len(L[0]) + result, word_num, word_len = [], len(L), len(L[0]) + words = collections.defaultdict(int) for i in L: - if i not in words: - words[i] = 1 - else: - words[i] += 1 + words[i] += 1 for i in xrange(len(S) + 1 - word_len * word_num): - cur, j = {}, 0 + cur, j = collections.defaultdict(int), 0 while j < word_num: word = S[i + j * word_len:i + j * word_len + word_len] if word not in words: break - if word not in cur: - cur[word] = 1 - else: - cur[word] += 1 + cur[word] += 1 if cur[word] > words[word]: break j += 1 From 0967bb8a0e8ccc6086c4e7d5835375645d8a0782 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:26:04 +0800 Subject: [PATCH 1042/1939] Update anagrams.py --- Python/anagrams.py | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/Python/anagrams.py b/Python/anagrams.py index 7930db78c..b1bd692b7 100644 --- a/Python/anagrams.py +++ b/Python/anagrams.py @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(nlogg) = O(n / g * glogg), g is max size of group # Space: O(n) # # Given an array of strings, return all groups of strings that are anagrams. @@ -6,22 +6,21 @@ # Note: All inputs will be in lower-case. # -class Solution: - # @param strs, a list of strings - # @return a list of strings - def anagrams(self, strs): - anagrams_map, result = {}, [] +class Solution(object): + def groupAnagrams(self, strs): + """ + :type strs: List[str] + :rtype: List[List[str]] + """ + anagrams_map, result = collections.defaultdict(list), [] for s in strs: sorted_str = ("").join(sorted(s)) - if sorted_str in anagrams_map: - anagrams_map[sorted_str].append(s) - else: - anagrams_map[sorted_str] = [s] + anagrams_map[sorted_str].append(s) for anagram in anagrams_map.values(): - if len(anagram) > 1: - result += anagram + anagram.sort() + result.append(anagram) return result if __name__ == "__main__": result = Solution().anagrams(["cat", "dog", "act", "mac"]) - print result \ No newline at end of file + print result From 9fa10265aaf0ddd7aef8bdb845ff4875fa3b32db Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:27:09 +0800 Subject: [PATCH 1043/1939] Update anagrams.py --- Python/anagrams.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/anagrams.py b/Python/anagrams.py index b1bd692b7..a9e815abe 100644 --- a/Python/anagrams.py +++ b/Python/anagrams.py @@ -1,4 +1,4 @@ -# Time: O(nlogg) = O(n / g * glogg), g is max size of group +# Time: O(nlogg) = O(n / g * glogg), g is max size of groups # Space: O(n) # # Given an array of strings, return all groups of strings that are anagrams. From 10ac9c1ff3e511f97031e7d8a74e207741724741 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:27:49 +0800 Subject: [PATCH 1044/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5abdea70c..d1a0f5e56 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,7 @@ Shell 18| [4 Sum](https://leetcode.com/problems/4sum/) |[Python](./Python/4sum.py) | _O(n^2 * p)_ | _O(n^2 * p)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || 36| [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [Python](./Python/valid-sudoku.py) | _O(n^2)_ | _O(n)_ | Easy || -49| [Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n)_ | _O(n)_ | Medium || +49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(nlogg)_ | _O(n)_ | Medium || 76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || 149| [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) | [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || 159| [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| From 037fbf39916ab9f71a6a379995e3506eafd8e10a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:29:50 +0800 Subject: [PATCH 1045/1939] Update max-points-on-a-line.py --- Python/max-points-on-a-line.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/Python/max-points-on-a-line.py b/Python/max-points-on-a-line.py index 58bfcf73c..67b31f245 100644 --- a/Python/max-points-on-a-line.py +++ b/Python/max-points-on-a-line.py @@ -10,13 +10,15 @@ def __init__(self, a=0, b=0): self.x = a self.y = b -class Solution: - # @param points, a list of Points - # @return an integer +class Solution(object): def maxPoints(self, points): + """ + :type points: List[Point] + :rtype: int + """ max_points = 0 for i, start in enumerate(points): - slope_count, same = {}, 1 + slope_count, same = collections.defaultdict(int), 1 for j in xrange(i + 1, len(points)): end = points[j] if start.x == end.x and start.y == end.y: @@ -25,10 +27,7 @@ def maxPoints(self, points): slope = float("inf") if start.x - end.x != 0: slope = (start.y - end.y) * 1.0 / (start.x - end.x) - if slope not in slope_count: - slope_count[slope] = 1 - else: - slope_count[slope] += 1 + slope_count[slope] += 1 current_max = same for slope in slope_count: From 75f36bd399b5d37530ffe7490bc3311a6342a82c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:32:18 +0800 Subject: [PATCH 1046/1939] Update two-sum-iii-data-structure-design.py --- Python/two-sum-iii-data-structure-design.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Python/two-sum-iii-data-structure-design.py b/Python/two-sum-iii-data-structure-design.py index 0bcaf917e..828b5db15 100644 --- a/Python/two-sum-iii-data-structure-design.py +++ b/Python/two-sum-iii-data-structure-design.py @@ -16,15 +16,13 @@ class TwoSum: # initialize your data structure here def __init__(self): - self.lookup = {} + self.lookup = collections.defaultdict(int) # @return nothing def add(self, number): - if number in self.lookup: - self.lookup[number] += 1 - else: - self.lookup[number] = 1 + self.lookup[number] += 1 + # @param value, an integer # @return a Boolean @@ -44,4 +42,4 @@ def find(self, value): for i in (4, 7): print Sol.find(i) - \ No newline at end of file + From cf20be8b4c51b4736f89b0d212ceb60d5862d26c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:38:25 +0800 Subject: [PATCH 1047/1939] Update repeated-dna-sequences.py --- Python/repeated-dna-sequences.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/Python/repeated-dna-sequences.py b/Python/repeated-dna-sequences.py index b3b926173..e2727b908 100644 --- a/Python/repeated-dna-sequences.py +++ b/Python/repeated-dna-sequences.py @@ -18,18 +18,15 @@ class Solution: # @param s, a string # @return a list of strings def findRepeatedDnaSequences(self, s): - dict = {} - rolling_hash = 0 - res = [] + dict, rolling_hash, res = {}, 0, [] for i in xrange(len(s)): rolling_hash = rolling_hash << 3 & 0x3fffffff | ord(s[i]) & 7 - if dict.get(rolling_hash) is None: + if rolling_hash not in dict: dict[rolling_hash] = True - else: - if dict[rolling_hash]: - res.append(s[i - 9: i + 1]) - dict[rolling_hash] = False + elif dict[rolling_hash]: + res.append(s[i - 9: i + 1]) + dict[rolling_hash] = False return res if __name__ == "__main__": From 2b41dee74affedc3026f9ae97c0fbdcf4cd57281 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:40:42 +0800 Subject: [PATCH 1048/1939] Update shortest-word-distance-ii.py --- Python/shortest-word-distance-ii.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Python/shortest-word-distance-ii.py b/Python/shortest-word-distance-ii.py index 494c9c682..fb76a188c 100644 --- a/Python/shortest-word-distance-ii.py +++ b/Python/shortest-word-distance-ii.py @@ -5,12 +5,9 @@ class WordDistance: # initialize your data structure here. # @param {string[]} words def __init__(self, words): - self.wordIndex = {} + self.wordIndex = collections.defaultdict(list) for i in xrange(len(words)): - if words[i] not in self.wordIndex: - self.wordIndex[words[i]] = [i] - else: - self.wordIndex[words[i]].append(i) + self.wordIndex[words[i]].append(i) # @param {string} word1 # @param {string} word2 @@ -29,3 +26,4 @@ def shortest(self, word1, word2): j += 1 return dist + From 4377d8f96e1f817585d2dbc8a2a1ff824da7bc88 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Oct 2015 20:42:38 +0800 Subject: [PATCH 1049/1939] Update group-shifted-strings.py --- Python/group-shifted-strings.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Python/group-shifted-strings.py b/Python/group-shifted-strings.py index c3aa782fb..53259c496 100644 --- a/Python/group-shifted-strings.py +++ b/Python/group-shifted-strings.py @@ -5,12 +5,9 @@ class Solution: # @param {string[]} strings # @return {string[][]} def groupStrings(self, strings): - groups = {}; + groups = collections.defaultdict(list) for s in strings: # Grouping. - if self.hashStr(s) not in groups: - groups[self.hashStr(s)] = [s] - else: - groups[self.hashStr(s)].append(s) + groups[self.hashStr(s)].append(s) result = [] for key, val in groups.iteritems(): From b7c76c93c3aa4b8d468fbff9256dcfeacab5a1ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 21:13:35 +0800 Subject: [PATCH 1050/1939] Create word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 43 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 C++/word-pattern-ii.cpp diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp new file mode 100644 index 000000000..f12a1ae0e --- /dev/null +++ b/C++/word-pattern-ii.cpp @@ -0,0 +1,43 @@ +// Time: O(C(n + p - 1, p - 1)), n is length of str, p is length of pattern +// Space: O(n + p) + +class Solution { +public: + bool wordPatternMatch(string pattern, string str) { + unordered_map w2p; + unordered_map p2w; + return match(pattern, str, 0, 0, &w2p, &p2w); + } + + bool match(const string &pattern, const string &str, + const int i, const int j, + unordered_map* w2p, + unordered_map* p2w) { + + if (i == pattern.size() && j == str.length()) { + return true; + } + + for (int k = j; k < str.length(); ++k) { + const char p = pattern[i]; + const string w = str.substr(j, k - j + 1); + bool build_mapping = false; + if (!w2p->count(w) && !p2w->count(p)) { + // Build mapping. Space: O(c) + (*w2p)[w] = p; + (*p2w)[p] = w; + build_mapping = true; + } else if (!w2p->count(w) || (*w2p)[w] != p) { + // Contradict mapping. + continue; + } + if (match(pattern, str, i + 1, k + 1, w2p, p2w)) { + return true; + } else if (build_mapping) { + w2p->erase(w); + p2w->erase(p); + } + } + return false; + } +}; From 3e66f9c10a3a2d45b91a85051da8f2e0c8696af3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 21:16:34 +0800 Subject: [PATCH 1051/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d1a0f5e56..27d9845e9 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,11 @@ ![Language](https://img.shields.io/badge/language-Python%20-orange.svg) ![License](https://img.shields.io/badge/license-MIT-blue.svg) -![Progress](https://img.shields.io/badge/progress-290%20%2F%20290%20-ff69b4.svg) +![Progress](https://img.shields.io/badge/progress-291%20%2F%20291%20-ff69b4.svg) -Up to date (2015-10-05), there are `273` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-10), there are `274` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `290` questions. +Here is the classification of all `291` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -399,6 +399,7 @@ Shell 254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| +291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(C(n + p - 1, p - 1))_ | _O(n + p)_ | Hard |📖|| --- From 5410864ced89c7b94f1183449643164d5cc1f248 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 21:17:38 +0800 Subject: [PATCH 1052/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index f12a1ae0e..770883a94 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -23,7 +23,7 @@ class Solution { const string w = str.substr(j, k - j + 1); bool build_mapping = false; if (!w2p->count(w) && !p2w->count(p)) { - // Build mapping. Space: O(c) + // Build mapping. Space: O(n + p) (*w2p)[w] = p; (*p2w)[p] = w; build_mapping = true; From 8c0ed2bbc3d655431fe6d208e5f4acb922550cd2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:05:38 +0800 Subject: [PATCH 1053/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 46 ++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index 770883a94..e4b11cf85 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -1,4 +1,4 @@ -// Time: O(C(n + p - 1, p - 1)), n is length of str, p is length of pattern +// Time: O(n * C(n + p - 1, p - 1)), n is length of str, p is length of pattern // Space: O(n + p) class Solution { @@ -13,31 +13,29 @@ class Solution { const int i, const int j, unordered_map* w2p, unordered_map* p2w) { - - if (i == pattern.size() && j == str.length()) { - return true; - } - - for (int k = j; k < str.length(); ++k) { + bool is_match = false; + if (i == pattern.length() && j == str.length()) { + is_match = true; + } else if (i < pattern.length() && j < str.length()) { const char p = pattern[i]; - const string w = str.substr(j, k - j + 1); - bool build_mapping = false; - if (!w2p->count(w) && !p2w->count(p)) { - // Build mapping. Space: O(n + p) - (*w2p)[w] = p; - (*p2w)[p] = w; - build_mapping = true; - } else if (!w2p->count(w) || (*w2p)[w] != p) { - // Contradict mapping. - continue; - } - if (match(pattern, str, i + 1, k + 1, w2p, p2w)) { - return true; - } else if (build_mapping) { - w2p->erase(w); - p2w->erase(p); + if (p2w->count(p)) { + if ((*p2w)[p] == str.substr(j, (*p2w)[p].length())) { // Match pattern. + return match(pattern, str, i + 1, j + (*p2w)[p].length(), w2p, p2w); + } // Else return false. + } else { + for (int k = j; k < str.length() && !is_match; ++k) { + const string w = str.substr(j, k - j + 1); + if (!w2p->count(w)) { + // Build mapping. Space: O(n + p) + (*w2p)[w] = p; + (*p2w)[p] = w; + is_match = match(pattern, str, i + 1, k + 1, w2p, p2w); + w2p->erase(w); + p2w->erase(p); + } // Else try longer word. + } } } - return false; + return is_match; } }; From a82fb2312110397b012c4ae48914bb2f64776af2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:07:24 +0800 Subject: [PATCH 1054/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index e4b11cf85..4efdfbd37 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -20,7 +20,7 @@ class Solution { const char p = pattern[i]; if (p2w->count(p)) { if ((*p2w)[p] == str.substr(j, (*p2w)[p].length())) { // Match pattern. - return match(pattern, str, i + 1, j + (*p2w)[p].length(), w2p, p2w); + is_match = match(pattern, str, i + 1, j + (*p2w)[p].length(), w2p, p2w); } // Else return false. } else { for (int k = j; k < str.length() && !is_match; ++k) { From f1bb6744e052ae0bd1aafa5d7e67fadc611e22fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:10:22 +0800 Subject: [PATCH 1055/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 27d9845e9..467a62cb8 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,7 @@ Shell 249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |📖|| 266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |📖|| 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| -290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || +290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(p)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || --- @@ -399,7 +399,7 @@ Shell 254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| -291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(C(n + p - 1, p - 1))_ | _O(n + p)_ | Hard |📖|| +291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n + p - 1, p - 1))_ | _O(n + p)_ | Hard |📖|| --- From 0f82804e24a9615a8d9e62d641f1f568646e917c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:11:26 +0800 Subject: [PATCH 1056/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 467a62cb8..86a0b5628 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,7 @@ Shell 249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |📖|| 266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |📖|| 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| -290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(p)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || +290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || --- @@ -399,7 +399,7 @@ Shell 254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| -291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n + p - 1, p - 1))_ | _O(n + p)_ | Hard |📖|| +291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n + c - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| --- From 8c60f0b2edf948ab2d3df053bdffd651e2beb87a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:12:15 +0800 Subject: [PATCH 1057/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index 4efdfbd37..da7c8111e 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -1,4 +1,4 @@ -// Time: O(n * C(n + p - 1, p - 1)), n is length of str, p is length of pattern +// Time: O(n * C(n + p - 1, p - 1)), n is length of str, c is unique count of pattern // Space: O(n + p) class Solution { @@ -26,7 +26,7 @@ class Solution { for (int k = j; k < str.length() && !is_match; ++k) { const string w = str.substr(j, k - j + 1); if (!w2p->count(w)) { - // Build mapping. Space: O(n + p) + // Build mapping. Space: O(n + c) (*w2p)[w] = p; (*p2w)[p] = w; is_match = match(pattern, str, i + 1, k + 1, w2p, p2w); From 8933455a7b965686efe42b20b445fb1e16ec81ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:17:51 +0800 Subject: [PATCH 1058/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index da7c8111e..be366c88a 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -1,5 +1,7 @@ -// Time: O(n * C(n + p - 1, p - 1)), n is length of str, c is unique count of pattern -// Space: O(n + p) +// Time: O(n * C(n + c - 1, c - 1)), n is length of str, c is unique count of pattern, +// there are C(n + c - 1, c - 1) possible splits of string, +// and each one costs O(n) to check if if matches the word pattern. +// Space: O(n + c) class Solution { public: From 59856983cc8c2b522f5a4a8d7bea89f842294390 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:19:55 +0800 Subject: [PATCH 1059/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index be366c88a..bc0ebaa20 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -29,11 +29,9 @@ class Solution { const string w = str.substr(j, k - j + 1); if (!w2p->count(w)) { // Build mapping. Space: O(n + c) - (*w2p)[w] = p; - (*p2w)[p] = w; + (*w2p)[w] = p, (*p2w)[p] = w; is_match = match(pattern, str, i + 1, k + 1, w2p, p2w); - w2p->erase(w); - p2w->erase(p); + w2p->erase(w), p2w->erase(p); } // Else try longer word. } } From a5557b957d19e5d70c6f089fcb04ba083a1a86e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:27:26 +0800 Subject: [PATCH 1060/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index bc0ebaa20..9192431fa 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -1,5 +1,5 @@ -// Time: O(n * C(n + c - 1, c - 1)), n is length of str, c is unique count of pattern, -// there are C(n + c - 1, c - 1) possible splits of string, +// Time: O(n * C(n - 1, c - 1)), n is length of str, c is unique count of pattern, +// there are H(n - c, c - 1) = C(n - 1, c - 1) possible splits of string, // and each one costs O(n) to check if if matches the word pattern. // Space: O(n + c) From a85720ea3b43b6c50ae1ae341614d22880cd7148 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:28:55 +0800 Subject: [PATCH 1061/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 86a0b5628..c938a9fb7 100644 --- a/README.md +++ b/README.md @@ -399,7 +399,7 @@ Shell 254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| -291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n + c - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| +291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| --- From 7cbeada5724534b8a99085a4db635801e459a8fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:29:38 +0800 Subject: [PATCH 1062/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index 9192431fa..5b58c1b41 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -1,6 +1,6 @@ // Time: O(n * C(n - 1, c - 1)), n is length of str, c is unique count of pattern, // there are H(n - c, c - 1) = C(n - 1, c - 1) possible splits of string, -// and each one costs O(n) to check if if matches the word pattern. +// and each one costs O(n) to check if it matches the word pattern. // Space: O(n + c) class Solution { From 47cada8927957e0ce5fd8eb588dbeabb4c33a6e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:29:57 +0800 Subject: [PATCH 1063/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index 5b58c1b41..f24ab4d11 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -1,6 +1,6 @@ // Time: O(n * C(n - 1, c - 1)), n is length of str, c is unique count of pattern, -// there are H(n - c, c - 1) = C(n - 1, c - 1) possible splits of string, -// and each one costs O(n) to check if it matches the word pattern. +// there are H(n - c, c - 1) = C(n - 1, c - 1) possible splits of string, +// and each one costs O(n) to check if it matches the word pattern. // Space: O(n + c) class Solution { From 7c9bce8255e04799fe4dd70764e8f37b38cd1a2d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:41:26 +0800 Subject: [PATCH 1064/1939] Create word-pattern-ii.py --- Python/word-pattern-ii.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/word-pattern-ii.py diff --git a/Python/word-pattern-ii.py b/Python/word-pattern-ii.py new file mode 100644 index 000000000..f534a712d --- /dev/null +++ b/Python/word-pattern-ii.py @@ -0,0 +1,39 @@ +# Time: O(n * C(n + c - 1, c - 1)), n is length of str, c is unique count of pattern, +# there are C(n + c - 1, c - 1) possible splits of string, +# and each one costs O(n) to check if if matches the word pattern. +# Space: O(n + c) + +class Solution(object): + def wordPatternMatch(self, pattern, str): + """ + :type pattern: str + :type str: str + :rtype: bool + """ + w2p, p2w = {}, {} + return self.match(pattern, str, 0, 0, w2p, p2w) + + + def match(self, pattern, str, i, j, w2p, p2w): + is_match = False + if i == len(pattern) and j == len(str): + is_match = True + elif i < len(pattern) and j < len(str): + p = pattern[i] + if p in p2w: + if p2w[p] == str[j:j+len(p2w[p])]: # Match pattern. + is_match = self.match(pattern, str, i + 1, j + len(p2w[p]), w2p, p2w) + # Else return false. + else: + for k in xrange(j, len(str)): + w = str[j:k+1] + if w not in w2p: + # Build mapping. Space: O(n + c) + w2p[w], p2w[p] = p, w; + is_match = self.match(pattern, str, i + 1, k + 1, w2p, p2w) + w2p.pop(w), p2w.pop(p); + if is_match: + break + # Else try longer word. + return is_match + From 3c51f9881670a031aa55ee7ad8dc797c46df5cd7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:44:58 +0800 Subject: [PATCH 1065/1939] Update word-pattern-ii.py --- Python/word-pattern-ii.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/word-pattern-ii.py b/Python/word-pattern-ii.py index f534a712d..8adcb5452 100644 --- a/Python/word-pattern-ii.py +++ b/Python/word-pattern-ii.py @@ -21,8 +21,9 @@ def match(self, pattern, str, i, j, w2p, p2w): elif i < len(pattern) and j < len(str): p = pattern[i] if p in p2w: - if p2w[p] == str[j:j+len(p2w[p])]: # Match pattern. - is_match = self.match(pattern, str, i + 1, j + len(p2w[p]), w2p, p2w) + w = p2w[p] + if w == str[j:j+len(w)]: # Match pattern. + is_match = self.match(pattern, str, i + 1, j + len(w), w2p, p2w) # Else return false. else: for k in xrange(j, len(str)): From ee95b20b147e5eda390a661183daa71983934c8d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:47:00 +0800 Subject: [PATCH 1066/1939] Update word-pattern-ii.py --- Python/word-pattern-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-pattern-ii.py b/Python/word-pattern-ii.py index 8adcb5452..6ad2f49b9 100644 --- a/Python/word-pattern-ii.py +++ b/Python/word-pattern-ii.py @@ -1,6 +1,6 @@ # Time: O(n * C(n + c - 1, c - 1)), n is length of str, c is unique count of pattern, # there are C(n + c - 1, c - 1) possible splits of string, -# and each one costs O(n) to check if if matches the word pattern. +# and each one costs O(n) to check if it matches the word pattern. # Space: O(n + c) class Solution(object): From d2e687248caefd131ef9dcb6a27f179e16771dae Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:47:34 +0800 Subject: [PATCH 1067/1939] Update word-pattern-ii.cpp --- C++/word-pattern-ii.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/C++/word-pattern-ii.cpp b/C++/word-pattern-ii.cpp index f24ab4d11..bf679e586 100644 --- a/C++/word-pattern-ii.cpp +++ b/C++/word-pattern-ii.cpp @@ -15,14 +15,16 @@ class Solution { const int i, const int j, unordered_map* w2p, unordered_map* p2w) { + bool is_match = false; if (i == pattern.length() && j == str.length()) { is_match = true; } else if (i < pattern.length() && j < str.length()) { const char p = pattern[i]; if (p2w->count(p)) { - if ((*p2w)[p] == str.substr(j, (*p2w)[p].length())) { // Match pattern. - is_match = match(pattern, str, i + 1, j + (*p2w)[p].length(), w2p, p2w); + const auto& w = (*p2w)[p]; + if (w == str.substr(j, w.length())) { // Match pattern. + is_match = match(pattern, str, i + 1, j + w.length(), w2p, p2w); } // Else return false. } else { for (int k = j; k < str.length() && !is_match; ++k) { From 8cf99de74590a65046a408e574ce684be69b4e4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Oct 2015 23:50:27 +0800 Subject: [PATCH 1068/1939] Update word-pattern-ii.py --- Python/word-pattern-ii.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/word-pattern-ii.py b/Python/word-pattern-ii.py index 6ad2f49b9..bd7121ccf 100644 --- a/Python/word-pattern-ii.py +++ b/Python/word-pattern-ii.py @@ -1,7 +1,7 @@ -# Time: O(n * C(n + c - 1, c - 1)), n is length of str, c is unique count of pattern, -# there are C(n + c - 1, c - 1) possible splits of string, -# and each one costs O(n) to check if it matches the word pattern. -# Space: O(n + c) +# Time: O(n * C(n - 1, c - 1)), n is length of str, c is unique count of pattern, +# there are H(n - c, c - 1) = C(n - 1, c - 1) possible splits of string, +# and each one costs O(n) to check if it matches the word pattern. +# Space: O(n + c) class Solution(object): def wordPatternMatch(self, pattern, str): From dd459f968199073d8cc03afd27416d19fda2296a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Oct 2015 01:16:30 +0800 Subject: [PATCH 1069/1939] Update word-pattern-ii.py --- Python/word-pattern-ii.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/word-pattern-ii.py b/Python/word-pattern-ii.py index bd7121ccf..2d12cd67c 100644 --- a/Python/word-pattern-ii.py +++ b/Python/word-pattern-ii.py @@ -26,7 +26,7 @@ def match(self, pattern, str, i, j, w2p, p2w): is_match = self.match(pattern, str, i + 1, j + len(w), w2p, p2w) # Else return false. else: - for k in xrange(j, len(str)): + for k in xrange(j, len(str)): # Try any possible word w = str[j:k+1] if w not in w2p: # Build mapping. Space: O(n + c) @@ -35,6 +35,5 @@ def match(self, pattern, str, i, j, w2p, p2w): w2p.pop(w), p2w.pop(p); if is_match: break - # Else try longer word. return is_match From 640d34983f42984dfc4cc1c409f5263f77380146 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Oct 2015 23:05:03 +0800 Subject: [PATCH 1070/1939] Create nim-game.py --- Python/nim-game.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Python/nim-game.py diff --git a/Python/nim-game.py b/Python/nim-game.py new file mode 100644 index 000000000..619248d22 --- /dev/null +++ b/Python/nim-game.py @@ -0,0 +1,25 @@ +# Time: O(1) +# Space: O(1) +# +# You are playing the following Nim Game with your friend: +# There is a heap of stones on the table, each time one of +# you take turns to remove 1 to 3 stones. +# The one who removes the last stone will be the winner. +# You will take the first turn to remove the stones. +# +# Both of you are very clever and have optimal strategies for +# the game. Write a function to determine whether you can win +# the game given the number of stones in the heap. +# +# For example, if there are 4 stones in the heap, then you will +# never win the game: no matter 1, 2, or 3 stones you remove, +# the last stone will always be removed by your friend. +# + +class Solution(object): + def canWinNim(self, n): + """ + :type n: int + :rtype: bool + """ + return n % 4 != 0 From 0a4374cdb4e8d26873af2b1acc075ee7e2dd4eb0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Oct 2015 23:06:36 +0800 Subject: [PATCH 1071/1939] Create nim-game.cpp --- C++/nim-game.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 C++/nim-game.cpp diff --git a/C++/nim-game.cpp b/C++/nim-game.cpp new file mode 100644 index 000000000..f0b3470bb --- /dev/null +++ b/C++/nim-game.cpp @@ -0,0 +1,9 @@ +// Time: O(1) +// Soace: O(1) + +class Solution { +public: + bool canWinNim(int n) { + return n % 4 != 0; + } +}; From 9fc86856a6f87e5010d78ca95a04fe7884d17a45 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Oct 2015 23:10:16 +0800 Subject: [PATCH 1072/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c938a9fb7..8cf4eb793 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,11 @@ ![Language](https://img.shields.io/badge/language-Python%20-orange.svg) ![License](https://img.shields.io/badge/license-MIT-blue.svg) -![Progress](https://img.shields.io/badge/progress-291%20%2F%20291%20-ff69b4.svg) +![Progress](https://img.shields.io/badge/progress-292%20%2F%20292%20-ff69b4.svg) -Up to date (2015-10-10), there are `274` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-11), there are `275` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `291` questions. +Here is the classification of all `292` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -255,6 +255,7 @@ Shell 248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard |📖|| 258| [Add Digits](https://leetcode.com/problems/add-digits/) | [C++](./C++/add-digits.cpp) [Python](./Python/add-digits.py) | _O(1)_ | _O(1)_ | Easy ||| 263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(logn)_ | _O(1)_ | Easy ||| +292| [Nim Game](https://leetcode.com/problems/nim-game/) | [C++](./C++/nim-game.cpp) [Python](./Python/nim-game.py) | _O(1)_ | _O(1)_ | Easy | LintCode || --- From 5522134fa23e04b585a91a4c658893045921f5d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Oct 2015 00:06:28 +0800 Subject: [PATCH 1073/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8cf4eb793..61ad5c1b2 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ![License](https://img.shields.io/badge/license-MIT-blue.svg) ![Progress](https://img.shields.io/badge/progress-292%20%2F%20292%20-ff69b4.svg) -Up to date (2015-10-11), there are `275` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-12), there are `275` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `292` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From adba5b784a2791f88ae71aa91b187bb4d072a5e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Oct 2015 09:42:18 +0800 Subject: [PATCH 1074/1939] Update implement-trie-prefix-tree.py --- Python/implement-trie-prefix-tree.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/implement-trie-prefix-tree.py b/Python/implement-trie-prefix-tree.py index c52003ae3..0301555ad 100644 --- a/Python/implement-trie-prefix-tree.py +++ b/Python/implement-trie-prefix-tree.py @@ -34,8 +34,8 @@ def insert(self, word): # @return {boolean} # Returns if the word is in the trie. def search(self, word): - res, node = self.childSearch(word) - if res: + node = self.childSearch(word) + if node: return node.is_string return False @@ -44,7 +44,7 @@ def search(self, word): # Returns if there is any word in the trie # that starts with the given prefix. def startsWith(self, prefix): - return self.childSearch(prefix)[0] + return self.childSearch(prefix) is not None def childSearch(self, word): cur = self.root @@ -52,8 +52,8 @@ def childSearch(self, word): if c in cur.leaves: cur = cur.leaves[c] else: - return False, None - return True, cur + return None + return cur # Your Trie object will be instantiated and called as such: # trie = Trie() From ac82178ab4c6a5627239e0246b4c3275596fa4c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Oct 2015 09:59:58 +0800 Subject: [PATCH 1075/1939] Update implement-trie-prefix-tree.py --- Python/implement-trie-prefix-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/implement-trie-prefix-tree.py b/Python/implement-trie-prefix-tree.py index 0301555ad..ffc2eddd8 100644 --- a/Python/implement-trie-prefix-tree.py +++ b/Python/implement-trie-prefix-tree.py @@ -44,7 +44,7 @@ def search(self, word): # Returns if there is any word in the trie # that starts with the given prefix. def startsWith(self, prefix): - return self.childSearch(prefix) is not None + return not self.childSearch(prefix) def childSearch(self, word): cur = self.root From 6d3a5874d5787435d555080f10dd9099d31a6828 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Oct 2015 10:01:33 +0800 Subject: [PATCH 1076/1939] Update implement-trie-prefix-tree.py --- Python/implement-trie-prefix-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/implement-trie-prefix-tree.py b/Python/implement-trie-prefix-tree.py index ffc2eddd8..0301555ad 100644 --- a/Python/implement-trie-prefix-tree.py +++ b/Python/implement-trie-prefix-tree.py @@ -44,7 +44,7 @@ def search(self, word): # Returns if there is any word in the trie # that starts with the given prefix. def startsWith(self, prefix): - return not self.childSearch(prefix) + return self.childSearch(prefix) is not None def childSearch(self, word): cur = self.root From 668a7dd690af9df48810067ee224ca8d0293baf3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Oct 2015 23:29:44 +0800 Subject: [PATCH 1077/1939] Create LICENSE.md --- LICENSE.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE.md diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..b0d82f1f5 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 https://github.com/kamyu104/LeetCode + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 4f8efbc3b070b2bba016fff749dae6ef09ae8577 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Oct 2015 23:38:03 +0800 Subject: [PATCH 1078/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 61ad5c1b2..1b9c79b0c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # LeetCode ![Language](https://img.shields.io/badge/language-Python%20-orange.svg) -![License](https://img.shields.io/badge/license-MIT-blue.svg) +[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/kamyu104/LeetCode/blob/master/LICENSE.md) ![Progress](https://img.shields.io/badge/progress-292%20%2F%20292%20-ff69b4.svg) Up to date (2015-10-12), there are `275` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). From f430b291da39a7092a8faf450d3aab31f684c938 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Oct 2015 23:40:09 +0800 Subject: [PATCH 1079/1939] Update README.md --- README.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/README.md b/README.md index 1b9c79b0c..a97be8d2c 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,4 @@ -# LeetCode - -![Language](https://img.shields.io/badge/language-Python%20-orange.svg) -[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/kamyu104/LeetCode/blob/master/LICENSE.md) -![Progress](https://img.shields.io/badge/progress-292%20%2F%20292%20-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/kamyu104/LeetCode/blob/master/LICENSE.md) ![Progress](https://img.shields.io/badge/progress-292%20%2F%20292%20-ff69b4.svg) Up to date (2015-10-12), there are `275` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. From 81a872c28191ea3e179bd3b91888e225b4b16bf6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 14 Oct 2015 00:09:36 +0800 Subject: [PATCH 1080/1939] Update README.md --- README.md | 107 ++++++++++++++---------------------------------------- 1 file changed, 27 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index a97be8d2c..a9e3ab809 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,7 @@ For more questions and solutions, you can see my [LintCode](https://github.com/k I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) ---- -Algorithms -=== +## Algorithms * [Bit Manipulation](https://github.com/kamyu104/LeetCode#bit-manipulation) * [Array](https://github.com/kamyu104/LeetCode#array) @@ -36,20 +34,16 @@ Algorithms * [Design](https://github.com/kamyu104/LeetCode#design) -Database -=== +## Database * [SQL](https://github.com/kamyu104/LeetCode#sql) -Shell -=== +## Shell * [Shell Script](https://github.com/kamyu104/LeetCode#shell-script) ---- - -##Bit Manipulation +## Bit Manipulation # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 136 | [Single Number](https://leetcode.com/problems/single-number/) | [C++](./C++/single-number.cpp) [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || @@ -61,10 +55,7 @@ Shell 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || 268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium | LintCode || ---- - -##Array - +## Array # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || @@ -100,9 +91,7 @@ Shell 277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |📖, EPI || 289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| ---- - -##String +## String # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` @@ -124,9 +113,7 @@ Shell 271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [C++](./C++/encode-and-decode-strings.cpp) [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 273| [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [C++](./C++/integer-to-english-words.cpp) [Python](./Python/integer-to-english-words.py) | _O(logn)_ | _O(1)_ | Medium | | ---- - -##Linked List +## Linked List # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || @@ -144,9 +131,7 @@ Shell 237| [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./C++/delete-node-in-a-linked-list.cpp) [Python](./Python/delete-node-in-a-linked-list.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 242| [Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./C++/valid-anagram.cpp) [Python](./Python/valid-anagram.py) | _O(n)_ | _O(1)_ | Easy | LintCode | ---- - -##Stack +## Stack # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || @@ -162,25 +147,19 @@ Shell 255| [Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/verify-preorder-sequence-in-binary-search-tree.cpp) [Python](./Python/verify-preorder-sequence-in-binary-search-tree.py) | _O(n)_| _O(1)_| Medium |📖|| 272| [Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(h)_| Hard |📖|| ---- - -##Queue +## Queue # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard | EPI, LintCode | 281| [Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator/)| [C++](./C++/zigzag-iterator.cpp) [Python](./Python/zigzag-iterator.py) | _O(n)_ | _O(k)_ | Medium |📖|| ---- - -##Heap +## Heap # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || 264| [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [C++](./C++/ugly-number-ii.cpp) [Python](./Python/ugly-number-ii.py) | _O(n)_ | _O(1)_ | Medium | CTCI, LintCode | BST, Heap | ---- - -##Tree +## Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | @@ -192,9 +171,7 @@ Shell 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || ---- - -##Hash Table +## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || @@ -220,18 +197,13 @@ Shell 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || - ---- - -##Data Structure +## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || 225| [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | [C++](./C++/implement-stack-using-queues.cpp) [Python](./Python/implement-stack-using-queues.py) | push: _O(n)_, pop: _O(1)_, top: _O(1)_ | _O(n)_ | Medium || ---- - -##Math +## Math # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || @@ -253,9 +225,7 @@ Shell 263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(logn)_ | _O(1)_ | Easy ||| 292| [Nim Game](https://leetcode.com/problems/nim-game/) | [C++](./C++/nim-game.cpp) [Python](./Python/nim-game.py) | _O(1)_ | _O(1)_ | Easy | LintCode || ---- - -##Sort +## Sort # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || @@ -273,9 +243,7 @@ Shell 274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Medium || Counting Sort | 280| [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) | [C++](./C++/wiggle-sort.cpp) [Python](./Python/wiggle-sort.py) | _O(n)_ | _O(1)_ | Medium |📖| | ---- - -##Two Pointers +## Two Pointers # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || @@ -288,9 +256,7 @@ Shell 283 | [Move Zeros](https://leetcode.com/problems/move-zeros/) | [C++](./C++/move-zeros.cpp) [Python](./Python/move-zeros.py) | _O(n)_ | _O(1)_ | Easy | | 287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Hard | | Binary Search, Two Pointers | ---- - -##Brute Force Search +## Brute Force Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || @@ -300,9 +266,7 @@ Shell 90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || 267| [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) | [C++](./C++/palindrome-permutation-ii.cpp) [Python](./Python/palindrome-permutation-ii.py) | _O(n * n!)_ | _O(n)_ | Medium |📖|| ---- - -##Divide and Conquer +## Divide and Conquer # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || @@ -322,9 +286,7 @@ Shell 156| [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| 241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n * 4^n / n^(3/2))_ | Medium || ---- - -##Binary Search +## Binary Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || @@ -342,8 +304,7 @@ Shell 275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | 278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy | LintCode || --- -##Binary Search Tree +## Binary Search Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) [Python](./Python/contains-duplicate-iii.py) | _O(nlogk)_ | _O(k)_ | medium || @@ -352,9 +313,7 @@ Shell 270| [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/)| [C++](./C++/closest-binary-search-tree-value.cpp) [Python](./Python/closest-binary-search-tree-value.py) | _O(h)_ | _O(1)_ | Easy | 📖 | 285| [Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/)| [C++](./C++/inorder-successor-in-bst.cpp) [Python](./Python/inorder-successor-in-bst.py) | _O(h)_ | _O(1)_ | Medium | 📖 | ---- - -##Breadth-First Search +## Breadth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 102| [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || @@ -370,9 +329,7 @@ Shell 269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Hard |📖| Topological Sort, BFS, DFS | 286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [C++](./C++/walls-and-gates.cpp) [Python](./Python/walls-and-gates.py) | _O(m * n)_ | _O(g)_ | Medium | 📖 | ---- - -##Depth-First Search +## Depth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || @@ -398,9 +355,7 @@ Shell 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| 291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| ---- - -##Dynamic Programming +## Dynamic Programming # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 10| [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || @@ -432,16 +387,12 @@ Shell 276| [Paint Fence](https://leetcode.com/problems/paint-fence/) | [C++](./C++/paint-fence.cpp) [Python](./Python/paint-fence.py) | _O(n)_| _O(1)_| Easy |📖|| 279| [Perfect Squares](https://leetcode.com/problems/perfect-squares/)| [C++](./C++/perfect-squares.cpp) [Python](./Python/perfect-squares.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium || Hash | ---- - -##Backtracking +## Backtracking # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || ---- - -##Greedy +## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || @@ -460,9 +411,7 @@ Shell -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 284| [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [C++](./C++/peeking-iterator.cpp) [Python](./Python/peeking-iterator.py) | _O(1)_ | _O(1)_ | Medium || ---- - -##SQL +## SQL # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 175| [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || @@ -479,9 +428,7 @@ Shell 197| [Rising Temperature](https://leetcode.com/problems/rising-temperature/) | [MySQL](./MySQL/rising-temperature.sql) | _O(n^2)_ | _O(n)_ | Easy || 262| [Trips and Users ](https://leetcode.com/problems/trips-and-users/) | [MySQL](./MySQL/trips-and-users.sql) | _O((t * u) + tlogt)_ | _O(t)_ | Hard || ---- - -##Shell Script +## Shell Script # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 192 | [Word Frequency](https://leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || From 252d20b6397c2f6ab1f59a37452fb06286d71c5c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 14 Oct 2015 00:41:27 +0800 Subject: [PATCH 1081/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a9e3ab809..7177ae80f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/kamyu104/LeetCode/blob/master/LICENSE.md) ![Progress](https://img.shields.io/badge/progress-292%20%2F%20292%20-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/kamyu104/LeetCode/blob/master/LICENSE.md) ![Progress](https://img.shields.io/badge/progress-292%20%2F%20292-ff69b4.svg) Up to date (2015-10-12), there are `275` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. From 510b05ccab1c339e26a62227d68bc9c1d85924da Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 14 Oct 2015 00:46:22 +0800 Subject: [PATCH 1082/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7177ae80f..139922670 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/kamyu104/LeetCode/blob/master/LICENSE.md) ![Progress](https://img.shields.io/badge/progress-292%20%2F%20292-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-292%20%2F%20292-ff69b4.svg) Up to date (2015-10-12), there are `275` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. From de1ea83d0d93af2691d1470aa40a6c67974a86cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 10:36:01 +0800 Subject: [PATCH 1083/1939] Create flip-game.cpp --- C++/flip-game.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/flip-game.cpp diff --git a/C++/flip-game.cpp b/C++/flip-game.cpp new file mode 100644 index 000000000..4eb7a1c3c --- /dev/null +++ b/C++/flip-game.cpp @@ -0,0 +1,20 @@ + // Time: O(n) + // Space: O(1) + + class Solution { + public: + vector generatePossibleNextMoves(string s) { + vector res; + int n = s.length(); + for (int i = 0; i < n - 1; ++i) { + if (s[i] == '+') { + for (;i < n - 1 && s[i + 1] == '+'; ++i) { + s[i] = s[i + 1] = '-'; + res.emplace_back(s); + s[i] = s[i + 1] = '+'; + } + } + } + return res; + } + }; From acf237d1af8aa6e59fb04b3a912e0fe91e98a3dd Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 10:37:16 +0800 Subject: [PATCH 1084/1939] Update flip-game.cpp --- C++/flip-game.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game.cpp b/C++/flip-game.cpp index 4eb7a1c3c..89face9e7 100644 --- a/C++/flip-game.cpp +++ b/C++/flip-game.cpp @@ -1,4 +1,4 @@ - // Time: O(n) + // Time: O(n^2) // Space: O(1) class Solution { From a9e400e429feee8652ecfcf61a67b366acff67f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 10:38:27 +0800 Subject: [PATCH 1085/1939] Update flip-game.cpp --- C++/flip-game.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/flip-game.cpp b/C++/flip-game.cpp index 89face9e7..f429a534f 100644 --- a/C++/flip-game.cpp +++ b/C++/flip-game.cpp @@ -6,11 +6,11 @@ vector generatePossibleNextMoves(string s) { vector res; int n = s.length(); - for (int i = 0; i < n - 1; ++i) { + for (int i = 0; i < n - 1; ++i) { // n times if (s[i] == '+') { for (;i < n - 1 && s[i + 1] == '+'; ++i) { s[i] = s[i + 1] = '-'; - res.emplace_back(s); + res.emplace_back(s); // O(n) to copy a string s[i] = s[i + 1] = '+'; } } From f1a00618e105f8ea0f1385295ce1d224f1ced6ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 10:40:47 +0800 Subject: [PATCH 1086/1939] Update flip-game.cpp --- C++/flip-game.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game.cpp b/C++/flip-game.cpp index f429a534f..14666965e 100644 --- a/C++/flip-game.cpp +++ b/C++/flip-game.cpp @@ -1,5 +1,5 @@ // Time: O(n^2) - // Space: O(1) + // Space: O(1), no extra space except that result requires at most O(n^2) space class Solution { public: From d4a1e1357448f37096e8fc28f6a711bc505333b4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 13:33:00 +0800 Subject: [PATCH 1087/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 139922670..f1921a64d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-292%20%2F%20292-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-293%20%2F%20293-ff69b4.svg) -Up to date (2015-10-12), there are `275` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-12), there are `276` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `292` questions. +Here is the classification of all `293` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -90,6 +90,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium |📖|| 277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |📖, EPI || 289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| +293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(c* n)_ | _O(1)_ | Easy |📖|| ## String # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 2ae0a3d79ac42b04093cff05aed50ae6864bf5da Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 13:33:54 +0800 Subject: [PATCH 1088/1939] Update flip-game.cpp --- C++/flip-game.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game.cpp b/C++/flip-game.cpp index 14666965e..c08e6ebe2 100644 --- a/C++/flip-game.cpp +++ b/C++/flip-game.cpp @@ -1,4 +1,4 @@ - // Time: O(n^2) + // Time: O(c * n), n is length of string, c is count of "++" // Space: O(1), no extra space except that result requires at most O(n^2) space class Solution { From de6c71480c0e47e4e1d293a99c401b1cfa34ed1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 13:36:56 +0800 Subject: [PATCH 1089/1939] Update flip-game.cpp --- C++/flip-game.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/flip-game.cpp b/C++/flip-game.cpp index c08e6ebe2..9617f3906 100644 --- a/C++/flip-game.cpp +++ b/C++/flip-game.cpp @@ -1,14 +1,14 @@ - // Time: O(c * n), n is length of string, c is count of "++" - // Space: O(1), no extra space except that result requires at most O(n^2) space + // Time: O(c * n + n), n is length of string, c is count of "++" + // Space: O(1), no extra space excluding that result requires at most O(n^2) space class Solution { public: vector generatePossibleNextMoves(string s) { vector res; int n = s.length(); - for (int i = 0; i < n - 1; ++i) { // n times + for (int i = 0; i < n - 1; ++i) { // O(n) times if (s[i] == '+') { - for (;i < n - 1 && s[i + 1] == '+'; ++i) { + for (;i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) times s[i] = s[i + 1] = '-'; res.emplace_back(s); // O(n) to copy a string s[i] = s[i + 1] = '+'; From 297693eed3e0540c4f005595720c6042a41b5858 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 13:55:47 +0800 Subject: [PATCH 1090/1939] Create flip-game.py --- Python/flip-game.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/flip-game.py diff --git a/Python/flip-game.py b/Python/flip-game.py new file mode 100644 index 000000000..5c4987706 --- /dev/null +++ b/Python/flip-game.py @@ -0,0 +1,32 @@ +# Time: O(c * n + n) +# Space: O(n) + +# This solution compares only O(1) times for the two consecutive "+" +class Solution(object): + def generatePossibleNextMoves(self, s): + """ + :type s: str + :rtype: List[str] + """ + res = [] + i, n = 0, len(s) - 1 + while i < n: # O(n) times + if s[i] == '+': + while i < n and s[i+1] == '+': # O(c) times + res.append(s[:i] + '--' + s[i+2:]) # O(n) time and space + i += 1 + i += 1 + return res + + +# Time: O(c * m * n + n) = O(c * n + n), where m = 2 in this question +# Space: O(n) +# This solution compares O(m) = O(2) times for two consecutive "+", where m is length of the pattern +class Solution2(object): + def generatePossibleNextMoves(self, s): + """ + :type s: str + :rtype: List[str] + """ + return [s[:i] + "--" + s[i+2:] for i in xrange(len(s) - 1) if s[i:i+2] == "++"] + From 2d228d1b0e3541b24b57f55b7fb55385441da7f7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 13:56:30 +0800 Subject: [PATCH 1091/1939] Update flip-game.py --- Python/flip-game.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/flip-game.py b/Python/flip-game.py index 5c4987706..5960ebde3 100644 --- a/Python/flip-game.py +++ b/Python/flip-game.py @@ -10,9 +10,9 @@ def generatePossibleNextMoves(self, s): """ res = [] i, n = 0, len(s) - 1 - while i < n: # O(n) times + while i < n: # O(n) time if s[i] == '+': - while i < n and s[i+1] == '+': # O(c) times + while i < n and s[i+1] == '+': # O(c) time res.append(s[:i] + '--' + s[i+2:]) # O(n) time and space i += 1 i += 1 From 9ee81f05070a5cdc6d9f2b242582803a908e5c23 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 13:57:28 +0800 Subject: [PATCH 1092/1939] Update flip-game.cpp --- C++/flip-game.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/flip-game.cpp b/C++/flip-game.cpp index 9617f3906..97df3f779 100644 --- a/C++/flip-game.cpp +++ b/C++/flip-game.cpp @@ -1,14 +1,14 @@ // Time: O(c * n + n), n is length of string, c is count of "++" - // Space: O(1), no extra space excluding that result requires at most O(n^2) space + // Space: O(1), no extra space excluding the result which requires at most O(n^2) space class Solution { public: vector generatePossibleNextMoves(string s) { vector res; int n = s.length(); - for (int i = 0; i < n - 1; ++i) { // O(n) times + for (int i = 0; i < n - 1; ++i) { // O(n) time if (s[i] == '+') { - for (;i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) times + for (;i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time s[i] = s[i + 1] = '-'; res.emplace_back(s); // O(n) to copy a string s[i] = s[i + 1] = '+'; From ba2006e7cb85100f2650d6f737880a851622149e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 13:59:05 +0800 Subject: [PATCH 1093/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f1921a64d..98d3c8fbc 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium |📖|| 277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |📖, EPI || 289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| -293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(c* n)_ | _O(1)_ | Easy |📖|| +293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(c * n + n)_ | _O(1)_ | Easy |📖|| ## String # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 04e329dc2e855db8231fa0ce3ee18c4ca3cef5bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Oct 2015 14:11:53 +0800 Subject: [PATCH 1094/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 98d3c8fbc..e89bbd203 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-293%20%2F%20293-ff69b4.svg) -Up to date (2015-10-12), there are `276` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-15), there are `276` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `293` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 74ae2c7107ed255bd35cda8afaf39b9b044c11ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 13:35:16 +0800 Subject: [PATCH 1095/1939] Create flip-game-ii.cpp --- C++/flip-game-ii.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/flip-game-ii.cpp diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp new file mode 100644 index 000000000..0992b778b --- /dev/null +++ b/C++/flip-game-ii.cpp @@ -0,0 +1,20 @@ +// Time: O(n^(c+1)), n is length of string, c is count of "++" +// Space: O(c) + +class Solution { +public: + bool canWin(string s) { + int n = s.length(); + bool other_win = true; + for (int i = 0; other_win && i < n - 1; ++i) { // O(n) time + if (s[i] == '+') { + for (; other_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time + s[i] = s[i + 1] = '-'; + other_win = canWin(s); // F(n, c) = n * F(n, c - 1) = ... = n^c * F(n, 0) = n^(c+1) + s[i] = s[i + 1] = '+'; + } + } + } + return !other_win; + } +}; From d5911d98f4ac2e93b21320211292fda26745b4b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 13:37:30 +0800 Subject: [PATCH 1096/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 0992b778b..71e5be866 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,5 +1,5 @@ // Time: O(n^(c+1)), n is length of string, c is count of "++" -// Space: O(c) +// Space: O(c), recursion would be called at most c in depth. class Solution { public: From 8b5164bd57ed2dc0a54855e1bc212397ef66d6cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 13:51:21 +0800 Subject: [PATCH 1097/1939] Create flip-game-ii.py --- Python/flip-game-ii.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/flip-game-ii.py diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py new file mode 100644 index 000000000..82a246869 --- /dev/null +++ b/Python/flip-game-ii.py @@ -0,0 +1,21 @@ +# Time: O(n^(c+2)), n is length of string, c is count of "++" +# Space: O(c * n), recursion would be called at most c in depth. Besides, +# it costs n space for modifying string at each depth. + +class Solution(object): + def canWin(self, s): + """ + :type s: str + :rtype: bool + """ + i, n = 0, len(s) - 1 + other_win = True + while other_win and i < n: # O(n) time + if s[i] == '+': + while other_win and i < n and s[i+1] == '+': # O(c) time + # F(n, c) = n * (F(n, c-1) + n) = ... = n^c * F(n, 0) + n^2 * (1 + n + ... + n^(c-1)) + # = n^(c+1) + n^2 * (n^c - 1) / (n - 1) = O(n^(c+2)) + other_win = self.canWin(s[:i] + '--' + s[i+2:]) # O(n) space + i += 1 + i += 1 + return not other_win From 716492e4d0ec38e128036643d6c6fed40074661d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 13:52:06 +0800 Subject: [PATCH 1098/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 82a246869..54cd9e2b0 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -1,6 +1,6 @@ # Time: O(n^(c+2)), n is length of string, c is count of "++" -# Space: O(c * n), recursion would be called at most c in depth. Besides, -# it costs n space for modifying string at each depth. +# Space: O(c * n), recursion would be called at most c in depth. +# Besides, it costs n space for modifying string at each depth. class Solution(object): def canWin(self, s): From 70dc76d1a48807c16950aa487339be10e3686009 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 13:54:21 +0800 Subject: [PATCH 1099/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e89bbd203..1ea1c0e38 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-293%20%2F%20293-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-294%20%2F%20294-ff69b4.svg) -Up to date (2015-10-15), there are `276` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-16), there are `277` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `293` questions. +Here is the classification of all `294` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -392,6 +392,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || +294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n^(c+1))_ | _O(c)_ | Medium |📖|| ## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note From fe5c27806a98fc2ab016decee2623a1880690d6f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 13:56:54 +0800 Subject: [PATCH 1100/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 54cd9e2b0..fe17b2e55 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -9,13 +9,13 @@ def canWin(self, s): :rtype: bool """ i, n = 0, len(s) - 1 - other_win = True - while other_win and i < n: # O(n) time + is_win = False + while not is_win and i < n: # O(n) time if s[i] == '+': - while other_win and i < n and s[i+1] == '+': # O(c) time + while not is_win and i < n and s[i+1] == '+': # O(c) time # F(n, c) = n * (F(n, c-1) + n) = ... = n^c * F(n, 0) + n^2 * (1 + n + ... + n^(c-1)) # = n^(c+1) + n^2 * (n^c - 1) / (n - 1) = O(n^(c+2)) - other_win = self.canWin(s[:i] + '--' + s[i+2:]) # O(n) space + is_win = not self.canWin(s[:i] + '--' + s[i+2:]) # O(n) space i += 1 i += 1 - return not other_win + return is_win From 16b7ba1d2d78709ab9d362520c338c1a096135d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 13:58:04 +0800 Subject: [PATCH 1101/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 71e5be866..26989ed79 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -5,16 +5,16 @@ class Solution { public: bool canWin(string s) { int n = s.length(); - bool other_win = true; - for (int i = 0; other_win && i < n - 1; ++i) { // O(n) time + bool is_win = false; + for (int i = 0; !is_win && i < n - 1; ++i) { // O(n) time if (s[i] == '+') { - for (; other_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time + for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time s[i] = s[i + 1] = '-'; - other_win = canWin(s); // F(n, c) = n * F(n, c - 1) = ... = n^c * F(n, 0) = n^(c+1) + is_win = !canWin(s); // F(n, c) = n * F(n, c - 1) = ... = n^c * F(n, 0) = n^(c+1) s[i] = s[i + 1] = '+'; } } } - return !other_win; + return is_win; } }; From 1696390e896883615ee49eae9211c4c01e94ec40 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 13:59:37 +0800 Subject: [PATCH 1102/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 26989ed79..14c1c981d 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,5 +1,6 @@ // Time: O(n^(c+1)), n is length of string, c is count of "++" // Space: O(c), recursion would be called at most c in depth. +// Besides, no extra space in each depth for the modified string. class Solution { public: From cd39d8157cc688f35eae00ec2e074d2af49bd546 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 14:01:22 +0800 Subject: [PATCH 1103/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 14c1c981d..6e32b2b5c 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -11,7 +11,7 @@ class Solution { if (s[i] == '+') { for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time s[i] = s[i + 1] = '-'; - is_win = !canWin(s); // F(n, c) = n * F(n, c - 1) = ... = n^c * F(n, 0) = n^(c+1) + is_win = !canWin(s); // t(n, c) = n * t(n, c - 1) = ... = n^c * t(n, 0) = n^(c+1) s[i] = s[i + 1] = '+'; } } From cbe69d3bbe1ceb27e6741bfcfc32e94a47c84916 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 14:01:57 +0800 Subject: [PATCH 1104/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index fe17b2e55..0af88ce56 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -13,8 +13,8 @@ def canWin(self, s): while not is_win and i < n: # O(n) time if s[i] == '+': while not is_win and i < n and s[i+1] == '+': # O(c) time - # F(n, c) = n * (F(n, c-1) + n) = ... = n^c * F(n, 0) + n^2 * (1 + n + ... + n^(c-1)) - # = n^(c+1) + n^2 * (n^c - 1) / (n - 1) = O(n^(c+2)) + # t(n, c) = n * (t(n, c-1) + n) = ... = n^c * t(n, 0) + n^2 * (1 + n + ... + n^(c-1)) + # = n^(c+1) + n^2 * (n^c - 1) / (n-1) = O(n^(c+2)) is_win = not self.canWin(s[:i] + '--' + s[i+2:]) # O(n) space i += 1 i += 1 From 71ff8bda2d05a045b1534394ac8a981a9bafaf79 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 14:15:19 +0800 Subject: [PATCH 1105/1939] Update flip-game.cpp --- C++/flip-game.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game.cpp b/C++/flip-game.cpp index 97df3f779..9d01c5804 100644 --- a/C++/flip-game.cpp +++ b/C++/flip-game.cpp @@ -1,4 +1,4 @@ - // Time: O(c * n + n), n is length of string, c is count of "++" + // Time: O(c * n + n) = O(n * (c+1)), n is length of string, c is count of "++" // Space: O(1), no extra space excluding the result which requires at most O(n^2) space class Solution { From fbf84aeff7f3680a2f10d1b995c1068fe0cffa1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 14:18:10 +0800 Subject: [PATCH 1106/1939] Update flip-game.py --- Python/flip-game.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/flip-game.py b/Python/flip-game.py index 5960ebde3..8c8760f43 100644 --- a/Python/flip-game.py +++ b/Python/flip-game.py @@ -1,4 +1,4 @@ -# Time: O(c * n + n) +# Time: O(c * n + n) = O(n * (c+1)) # Space: O(n) # This solution compares only O(1) times for the two consecutive "+" From 212b36cd83dbdba80715135c5ccb5741a03dab4e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 14:33:31 +0800 Subject: [PATCH 1107/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 6e32b2b5c..7618cf9f9 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,4 +1,4 @@ -// Time: O(n^(c+1)), n is length of string, c is count of "++" +// Time: O(n * c!), n is length of string, c is count of "++" // Space: O(c), recursion would be called at most c in depth. // Besides, no extra space in each depth for the modified string. @@ -11,7 +11,9 @@ class Solution { if (s[i] == '+') { for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time s[i] = s[i + 1] = '-'; - is_win = !canWin(s); // t(n, c) = n * t(n, c - 1) = ... = n^c * t(n, 0) = n^(c+1) + // t(n, c) = c * t(n, c - 1) + n = ... = c! * t(n, 0) + n * c! (1 + 1/2! + ... 1/c!) + // = n * c! + n * c! * O(e) = O(n * c!) + is_win = !canWin(s); s[i] = s[i + 1] = '+'; } } From 9ace9b32c3ff3aa6dd7dc661f57fc8cc2aaa358b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 14:34:50 +0800 Subject: [PATCH 1108/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1ea1c0e38..76234c7b6 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium |📖|| 277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |📖, EPI || 289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| -293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(c * n + n)_ | _O(1)_ | Easy |📖|| +293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(n * (c+1))_ | _O(1)_ | Easy |📖|| ## String # | Problem | Solution | Time | Space | Difficulty | Tag | Note @@ -392,7 +392,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || -294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n^(c+1))_ | _O(c)_ | Medium |📖|| +294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n * c!)_ | _O(c)_ | Medium |📖|| ## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note From ec853d758480eb1b6e0135408c7a48833deb06bf Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 14:58:43 +0800 Subject: [PATCH 1109/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 0af88ce56..d0e40209d 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -1,4 +1,4 @@ -# Time: O(n^(c+2)), n is length of string, c is count of "++" +# Time: O(c * n * c!), n is length of string, c is count of "++" # Space: O(c * n), recursion would be called at most c in depth. # Besides, it costs n space for modifying string at each depth. @@ -13,8 +13,9 @@ def canWin(self, s): while not is_win and i < n: # O(n) time if s[i] == '+': while not is_win and i < n and s[i+1] == '+': # O(c) time - # t(n, c) = n * (t(n, c-1) + n) = ... = n^c * t(n, 0) + n^2 * (1 + n + ... + n^(c-1)) - # = n^(c+1) + n^2 * (n^c - 1) / (n-1) = O(n^(c+2)) + # t(n, c) = c * (t(n, c-1) + n) + n = ... + # = c! * t(n, 0) + n * c! * (c + 1) (1/0! + 1/1! + ... 1/c!) + # = n * c! + n * c! * (c + 1) * O(e) = O(c * n * c!) is_win = not self.canWin(s[:i] + '--' + s[i+2:]) # O(n) space i += 1 i += 1 From 83d2e82e1cfc85119d3d184b855005c2dada37d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 14:58:59 +0800 Subject: [PATCH 1110/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index d0e40209d..3c0bcfc9b 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -14,7 +14,7 @@ def canWin(self, s): if s[i] == '+': while not is_win and i < n and s[i+1] == '+': # O(c) time # t(n, c) = c * (t(n, c-1) + n) + n = ... - # = c! * t(n, 0) + n * c! * (c + 1) (1/0! + 1/1! + ... 1/c!) + # = c! * t(n, 0) + n * c! * (c + 1) * (1/0! + 1/1! + ... 1/c!) # = n * c! + n * c! * (c + 1) * O(e) = O(c * n * c!) is_win = not self.canWin(s[:i] + '--' + s[i+2:]) # O(n) space i += 1 From 7fe51c42bbc92d89f555102208875243712cf063 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 14:59:34 +0800 Subject: [PATCH 1111/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 7618cf9f9..3593230b0 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -11,7 +11,7 @@ class Solution { if (s[i] == '+') { for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time s[i] = s[i + 1] = '-'; - // t(n, c) = c * t(n, c - 1) + n = ... = c! * t(n, 0) + n * c! (1 + 1/2! + ... 1/c!) + // t(n, c) = c * t(n, c - 1) + n = ... = c! * t(n, 0) + n * c! * (1/0! + 1/1! + ... 1/c!) // = n * c! + n * c! * O(e) = O(n * c!) is_win = !canWin(s); s[i] = s[i + 1] = '+'; From 202faf1f4b4b8489269a9609ce405a0734804680 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 23:20:11 +0800 Subject: [PATCH 1112/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 61 ++++++++++++++++++++++++++++++++------------ 1 file changed, 45 insertions(+), 16 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 3593230b0..401f28e4b 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,23 +1,52 @@ +// Time: O(n * 2^c) +// Space: O(n * 2^c) + +// hash solution. +class Solution { +public: + bool canWin(string s) { + if (!lookup_.count(s)) { + int n = s.length(); + bool is_win = false; + for (int i = 0; !is_win && i < n - 1; ++i) { // O(n) time + if (s[i] == '+') { + for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time + s[i] = s[i + 1] = '-'; + // t(n, c) = c * t(n, c - 1) + n = ... = c! * t(n, 0) + n * c! * (1/0! + 1/1! + ... 1/c!) + // = n * c! + n * c! * O(e) = O(n * c!) + is_win = !canWin(s); + s[i] = s[i + 1] = '+'; + lookup_[s] = is_win; + } + } + } + } + return lookup_[s]; + } +private: + unordered_map lookup_; +}; + + // Time: O(n * c!), n is length of string, c is count of "++" // Space: O(c), recursion would be called at most c in depth. // Besides, no extra space in each depth for the modified string. - -class Solution { +class Solution2 { public: bool canWin(string s) { - int n = s.length(); - bool is_win = false; - for (int i = 0; !is_win && i < n - 1; ++i) { // O(n) time - if (s[i] == '+') { - for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time - s[i] = s[i + 1] = '-'; - // t(n, c) = c * t(n, c - 1) + n = ... = c! * t(n, 0) + n * c! * (1/0! + 1/1! + ... 1/c!) - // = n * c! + n * c! * O(e) = O(n * c!) - is_win = !canWin(s); - s[i] = s[i + 1] = '+'; - } - } - } - return is_win; + int n = s.length(); + bool is_win = false; + for (int i = 0; !is_win && i < n - 1; ++i) { // O(n) time + if (s[i] == '+') { + for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time + s[i] = s[i + 1] = '-'; + // t(n, c) = c * t(n, c - 1) + n = ... = c! * t(n, 0) + n * c! * (1/0! + 1/1! + ... 1/c!) + // = n * c! + n * c! * O(e) = O(n * c!) + is_win = !canWin(s); + s[i] = s[i + 1] = '+'; + } + } + } + return is_win; } }; From c1eebcf97626e50de2258a05ec238d6a89be452b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 23:28:19 +0800 Subject: [PATCH 1113/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 401f28e4b..01d825443 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,5 +1,6 @@ -// Time: O(n * 2^c) -// Space: O(n * 2^c) +// Time: O(c * n * 2^c), try all the possible game strings, +// and each string would have c choices to become the next string +// Space: O(n * 2^c), keep all the possible game strings // hash solution. class Solution { @@ -8,12 +9,10 @@ class Solution { if (!lookup_.count(s)) { int n = s.length(); bool is_win = false; - for (int i = 0; !is_win && i < n - 1; ++i) { // O(n) time + for (int i = 0; !is_win && i < n - 1; ++i) { if (s[i] == '+') { - for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time + for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { s[i] = s[i + 1] = '-'; - // t(n, c) = c * t(n, c - 1) + n = ... = c! * t(n, 0) + n * c! * (1/0! + 1/1! + ... 1/c!) - // = n * c! + n * c! * O(e) = O(n * c!) is_win = !canWin(s); s[i] = s[i + 1] = '+'; lookup_[s] = is_win; From 6568343d3b30280b0a18d1524b6ecec57bb395ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 23:49:51 +0800 Subject: [PATCH 1114/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 3c0bcfc9b..1ef43d578 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -1,8 +1,36 @@ +# Time: O(n + c^3 * 2^c * logc) +# Space: O(c * 2^c) + +# hash solution. +class Solution(object): + def canWin(self, s): + """ + :type s: str + :rtype: bool + """ + lookup = {} + + def canWinHelper(consecutives): + consecutives = tuple(sorted(c for c in consecutives if c >= 2)) # O(clogc) + if consecutives not in lookup: + # We have total O(2^c) game strings, + # each one has O(c) choices to the next one, + # and each one would cost O(clogc) to sort, + # so we get O((c * clogc) * 2^c) = O(c^2 * 2^c * logc) time. + # To cache the results of all combinations, thus O(c * 2^c) space. + lookup[consecutives] = any(not canWinHelper(consecutives[:i] + (j, c-2-j) + consecutives[i+1:]) + for i, c in enumerate(consecutives) + for j in xrange(c - 1)) + return lookup[consecutives] + + # re.findall: O(n) time, canWinHelper: O(c) in depth + return canWinHelper(map(len, re.findall(r'\+\++', s))) + + # Time: O(c * n * c!), n is length of string, c is count of "++" # Space: O(c * n), recursion would be called at most c in depth. # Besides, it costs n space for modifying string at each depth. - -class Solution(object): +class Solution2(object): def canWin(self, s): """ :type s: str From 79b294c83fee3bde6b1ae1bc5f90d9bd85baf4ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Oct 2015 23:51:11 +0800 Subject: [PATCH 1115/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 01d825443..83167ac6b 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,5 +1,5 @@ -// Time: O(c * n * 2^c), try all the possible game strings, -// and each string would have c choices to become the next string +// Time: O(n + c * n * 2^c), try all the possible game strings, +// and each string would have c choices to become the next string // Space: O(n * 2^c), keep all the possible game strings // hash solution. From 594431242d1675885002817e12d857dbc4889d9f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 01:12:56 +0800 Subject: [PATCH 1116/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 83167ac6b..7ad3199e8 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -7,7 +7,7 @@ class Solution { public: bool canWin(string s) { if (!lookup_.count(s)) { - int n = s.length(); + const int n = s.length(); bool is_win = false; for (int i = 0; !is_win && i < n - 1; ++i) { if (s[i] == '+') { @@ -33,7 +33,7 @@ class Solution { class Solution2 { public: bool canWin(string s) { - int n = s.length(); + const int n = s.length(); bool is_win = false; for (int i = 0; !is_win && i < n - 1; ++i) { // O(n) time if (s[i] == '+') { From 8581c73681c437ce7f247feab793012f05527be2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 01:27:07 +0800 Subject: [PATCH 1117/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 68 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 3 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 7ad3199e8..241d7ccb7 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,9 +1,71 @@ +// Time: O(n + c^3 * 2^c * logc) +// Space: O(c * 2^c) + +// hash solution. +class Solution { +public: + struct multiset_hash { + std::size_t operator() (const multiset& set) const { + string set_string; + for (const auto& i : set) { + set_string.append(to_string(i) + " "); + } + return hash()(set_string); + } + }; + + bool canWin(string s) { + const int n = s.length(); + multiset consecutives; + for (int i = 0; i < n - 1; ++i) { // O(n) time + if (s[i] == '+') { + int c = 1; + for (; i < n - 1 && s[i + 1] == '+'; ++i, ++c); + if (c >= 2) { + consecutives.emplace(c); + } + } + } + return canWinHelper(consecutives); + } + +private: + bool canWinHelper(const multiset& consecutives) { + if (!lookup_.count(consecutives)) { + bool is_win = false; + for (auto it = consecutives.cbegin(); !is_win && it != consecutives.cend(); ++it) { + const int c = *it; + multiset next_consecutives(consecutives); + next_consecutives.erase(next_consecutives.find(c)); + for (int i = 0; !is_win && i < c - 1; ++i) { + if (i >= 2) { + next_consecutives.emplace(i); + } + if (c - 2 - i >= 2) { + next_consecutives.emplace(c - 2 - i); + } + is_win = !canWinHelper(next_consecutives); + if (i >= 2) { + next_consecutives.erase(next_consecutives.find(i)); + } + if (c - 2 - i >= 2) { + next_consecutives.erase(next_consecutives.find(c - 2 - i)); + } + lookup_[consecutives] = is_win; + } + } + } + return lookup_[consecutives]; + } + unordered_map, bool, multiset_hash> lookup_; +}; + + // Time: O(n + c * n * 2^c), try all the possible game strings, // and each string would have c choices to become the next string // Space: O(n * 2^c), keep all the possible game strings - // hash solution. -class Solution { +class Solution2 { public: bool canWin(string s) { if (!lookup_.count(s)) { @@ -30,7 +92,7 @@ class Solution { // Time: O(n * c!), n is length of string, c is count of "++" // Space: O(c), recursion would be called at most c in depth. // Besides, no extra space in each depth for the modified string. -class Solution2 { +class Solution3 { public: bool canWin(string s) { const int n = s.length(); From d0137a5d2c132d16118906feabf1bcca4066534b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 01:32:15 +0800 Subject: [PATCH 1118/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 1ef43d578..ad6538eb2 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -14,9 +14,10 @@ def canWinHelper(consecutives): consecutives = tuple(sorted(c for c in consecutives if c >= 2)) # O(clogc) if consecutives not in lookup: # We have total O(2^c) game strings, + # and each hash key in hash table would cost O(c), # each one has O(c) choices to the next one, # and each one would cost O(clogc) to sort, - # so we get O((c * clogc) * 2^c) = O(c^2 * 2^c * logc) time. + # so we get O((c * 2^c) * (c * clogc)) = O(c^3 * 2^c * logc) time. # To cache the results of all combinations, thus O(c * 2^c) space. lookup[consecutives] = any(not canWinHelper(consecutives[:i] + (j, c-2-j) + consecutives[i+1:]) for i, c in enumerate(consecutives) From 114c4296385f33d897fd1db280fe5f33dbe58682 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 01:41:15 +0800 Subject: [PATCH 1119/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 241d7ccb7..3aa2253d2 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -30,14 +30,14 @@ class Solution { } private: - bool canWinHelper(const multiset& consecutives) { + bool canWinHelper(const multiset& consecutives) { // O(2^c) time if (!lookup_.count(consecutives)) { bool is_win = false; - for (auto it = consecutives.cbegin(); !is_win && it != consecutives.cend(); ++it) { + for (auto it = consecutives.cbegin(); !is_win && it != consecutives.cend(); ++it) { // O(c) time const int c = *it; multiset next_consecutives(consecutives); next_consecutives.erase(next_consecutives.find(c)); - for (int i = 0; !is_win && i < c - 1; ++i) { + for (int i = 0; !is_win && i < c - 1; ++i) { // O(clogc) time if (i >= 2) { next_consecutives.emplace(i); } @@ -51,7 +51,7 @@ class Solution { if (c - 2 - i >= 2) { next_consecutives.erase(next_consecutives.find(c - 2 - i)); } - lookup_[consecutives] = is_win; + lookup_[consecutives] = is_win; // O(c) time } } } From 5e4f3e0fc2583502c029bbb668aa9c112d3ede7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 01:46:19 +0800 Subject: [PATCH 1120/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index ad6538eb2..539fe32ea 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -2,6 +2,12 @@ # Space: O(c * 2^c) # hash solution. +# We have total O(2^c) game strings, +# and each hash key in hash table would cost O(c), +# each one has O(c) choices to the next one, +# and each one would cost O(clogc) to sort, +# so we get O((c * 2^c) * (c * clogc)) = O(c^3 * 2^c * logc) time. +# To cache the results of all combinations, thus O(c * 2^c) space. class Solution(object): def canWin(self, s): """ @@ -10,19 +16,13 @@ def canWin(self, s): """ lookup = {} - def canWinHelper(consecutives): - consecutives = tuple(sorted(c for c in consecutives if c >= 2)) # O(clogc) + def canWinHelper(consecutives): # O(2^c) time + consecutives = tuple(sorted(c for c in consecutives if c >= 2)) # O(clogc) time if consecutives not in lookup: - # We have total O(2^c) game strings, - # and each hash key in hash table would cost O(c), - # each one has O(c) choices to the next one, - # and each one would cost O(clogc) to sort, - # so we get O((c * 2^c) * (c * clogc)) = O(c^3 * 2^c * logc) time. - # To cache the results of all combinations, thus O(c * 2^c) space. - lookup[consecutives] = any(not canWinHelper(consecutives[:i] + (j, c-2-j) + consecutives[i+1:]) - for i, c in enumerate(consecutives) - for j in xrange(c - 1)) - return lookup[consecutives] + lookup[consecutives] = any(not canWinHelper(consecutives[:i] + (j, c-2-j) + consecutives[i+1:]) # O(c) time + for i, c in enumerate(consecutives) # O(c) time + for j in xrange(c - 1)) # O(c) time + return lookup[consecutives] # O(c) time # re.findall: O(n) time, canWinHelper: O(c) in depth return canWinHelper(map(len, re.findall(r'\+\++', s))) From 336e1ffdc7b9b0488bfe8de48732946294733a2b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 01:48:37 +0800 Subject: [PATCH 1121/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 76234c7b6..a7c0edcfe 100644 --- a/README.md +++ b/README.md @@ -392,7 +392,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || -294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n * c!)_ | _O(c)_ | Medium |📖|| +294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n + c^3 * 2^c * logc)_ | _O(c * 2^c)_ | Medium |📖|| ## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 8dd0fc3c01767ce3b135c7d4a7920fc80ac81248 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 01:49:22 +0800 Subject: [PATCH 1122/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 539fe32ea..ad48e2b29 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -1,4 +1,4 @@ -# Time: O(n + c^3 * 2^c * logc) +# Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" # Space: O(c * 2^c) # hash solution. From 4802fcb9de94edc42213d8bc877255dfebc7e72d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 01:49:31 +0800 Subject: [PATCH 1123/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 3aa2253d2..9c814d61a 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,4 +1,4 @@ -// Time: O(n + c^3 * 2^c * logc) +// Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" // Space: O(c * 2^c) // hash solution. From b5e1849ccd854e98b3f27114d7ac56601ed48a67 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 02:22:12 +0800 Subject: [PATCH 1124/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 9c814d61a..867b724e8 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,6 +1,9 @@ // Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" // Space: O(c * 2^c) +// The best theory solution (DP, O(n^2) could be seen here: +// https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0ms + // hash solution. class Solution { public: From c5025c8839128ace67e05372b2ca6e26b14b2358 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 02:22:30 +0800 Subject: [PATCH 1125/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 867b724e8..531afcc4f 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,7 +1,7 @@ // Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" // Space: O(c * 2^c) -// The best theory solution (DP, O(n^2) could be seen here: +// The best theory solution (DP, O(n^2)) could be seen here: // https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0ms // hash solution. From 0c3b0a197707c3617833d405c6dbdc57779ce4a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 02:23:19 +0800 Subject: [PATCH 1126/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index ad48e2b29..c500674fe 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -1,3 +1,6 @@ +# The best theory solution (DP, O(n^2)) could be seen here: +# https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0m + # Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" # Space: O(c * 2^c) From 092970a35d0ad3a407cc39170effd7d20fa395af Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 02:23:40 +0800 Subject: [PATCH 1127/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 531afcc4f..d95c90b51 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,9 +1,8 @@ -// Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" -// Space: O(c * 2^c) - // The best theory solution (DP, O(n^2)) could be seen here: // https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0ms +// Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" +// Space: O(c * 2^c) // hash solution. class Solution { public: From 720e79644211b23ee9ed6cd5deff95aa68a6eb44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 02:23:52 +0800 Subject: [PATCH 1128/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index c500674fe..690cbca24 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -3,7 +3,6 @@ # Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" # Space: O(c * 2^c) - # hash solution. # We have total O(2^c) game strings, # and each hash key in hash table would cost O(c), From 970699456a4c96e876d40550fbaa83e08021ea13 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 03:10:06 +0800 Subject: [PATCH 1129/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index d95c90b51..272a393e1 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,10 +1,38 @@ +// Time: O(n^2) +// Space: O(n) + // The best theory solution (DP, O(n^2)) could be seen here: // https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0ms +class Solution { +public: + bool canWin(string s) { + replace(s.begin(), s.end(), '-', ' '); + istringstream in(s); + int g_final = 0; + vector g; // Sprague-Grundy function of 0 ~ maxlen, O(n) space + for (string t; in >> t; ) { // Split the string + int p = t.size(); + while (g.size() <= p) { // O(n) time + string x{t}; + int i = 0, j = g.size() - 2; + while (i <= j) { // // the S-G value of all subgame states, O(n) time + // Theorem 2: g[game] = g[subgame1]^g[subgame2]^g[subgame3]...; + x[g[i++] ^ g[j--]] = '-'; + } + // Find first missing number. + g.emplace_back(x.find('+')); + } + g_final ^= g[p]; // g[0], g[1] is always 0 + } + return g_final; // Theorem 1: First player must win iff g(current_state) != 0 + } +}; + // Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" // Space: O(c * 2^c) // hash solution. -class Solution { +class Solution2 { public: struct multiset_hash { std::size_t operator() (const multiset& set) const { @@ -67,7 +95,7 @@ class Solution { // and each string would have c choices to become the next string // Space: O(n * 2^c), keep all the possible game strings // hash solution. -class Solution2 { +class Solution3 { public: bool canWin(string s) { if (!lookup_.count(s)) { @@ -94,7 +122,7 @@ class Solution2 { // Time: O(n * c!), n is length of string, c is count of "++" // Space: O(c), recursion would be called at most c in depth. // Besides, no extra space in each depth for the modified string. -class Solution3 { +class Solution4 { public: bool canWin(string s) { const int n = s.length(); From 1b22654309a845ec36aeda39c661c315d1f045c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 03:11:08 +0800 Subject: [PATCH 1130/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a7c0edcfe..d807d05b7 100644 --- a/README.md +++ b/README.md @@ -392,7 +392,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || -294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n + c^3 * 2^c * logc)_ | _O(c * 2^c)_ | Medium |📖|| +294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n^2)_ | _O(n)_ | Medium |📖| DP, Hash | ## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 034580d97b54e7df9f77aa9b3416877bc322c8da Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 03:11:40 +0800 Subject: [PATCH 1131/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 272a393e1..73d307de8 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -15,7 +15,7 @@ class Solution { while (g.size() <= p) { // O(n) time string x{t}; int i = 0, j = g.size() - 2; - while (i <= j) { // // the S-G value of all subgame states, O(n) time + while (i <= j) { // The S-G value of all subgame states, O(n) time // Theorem 2: g[game] = g[subgame1]^g[subgame2]^g[subgame3]...; x[g[i++] ^ g[j--]] = '-'; } From da352672f47223028932aad3bb7bacd7ec043544 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 03:34:57 +0800 Subject: [PATCH 1132/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 690cbca24..89b050500 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -1,5 +1,19 @@ +# Time: O(n^2) +# Space: O(n) + # The best theory solution (DP, O(n^2)) could be seen here: # https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0m +class Solution(object): + def canWin(self, s): + g, g_final = [0], 0 + for p in map(len, re.split('-+', s)): + while len(g) <= p: + # Theorem 2: g[game] = g[subgame1]^g[subgame2]^g[subgame3]...; + # and find first missing number. + g += min(set(xrange(p)) - {x^y for x, y in itertools.izip(g[:len(g)/2], g[-2:-len(g)/2-2:-1])}), + g_final ^= g[p] + return g_final > 0 # Theorem 1: First player must win iff g(current_state) != 0 + # Time: O(n + c^3 * 2^c * logc), n is length of string, c is count of "++" # Space: O(c * 2^c) @@ -10,7 +24,7 @@ # and each one would cost O(clogc) to sort, # so we get O((c * 2^c) * (c * clogc)) = O(c^3 * 2^c * logc) time. # To cache the results of all combinations, thus O(c * 2^c) space. -class Solution(object): +class Solution2(object): def canWin(self, s): """ :type s: str @@ -33,7 +47,7 @@ def canWinHelper(consecutives): # O(2^c) # Time: O(c * n * c!), n is length of string, c is count of "++" # Space: O(c * n), recursion would be called at most c in depth. # Besides, it costs n space for modifying string at each depth. -class Solution2(object): +class Solution3(object): def canWin(self, s): """ :type s: str From 65f65e6df701f750a8221407f2fccc6c2d1eeac3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 03:36:59 +0800 Subject: [PATCH 1133/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 89b050500..4a7375ec5 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -6,7 +6,7 @@ class Solution(object): def canWin(self, s): g, g_final = [0], 0 - for p in map(len, re.split('-+', s)): + for p in itertools.imap(len, re.split('-+', s)): while len(g) <= p: # Theorem 2: g[game] = g[subgame1]^g[subgame2]^g[subgame3]...; # and find first missing number. From 6bbb65db91b8413e3597cc957c771f54e10f6e36 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 16:52:49 +0800 Subject: [PATCH 1134/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index 73d307de8..affb920ca 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -1,7 +1,7 @@ -// Time: O(n^2) -// Space: O(n) +// Time: O(n + c^2), c is max length of consecutive '+' +// Space: O(c) -// The best theory solution (DP, O(n^2)) could be seen here: +// The best theory solution (DP, O(n + c^2)) could be seen here: // https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0ms class Solution { public: @@ -12,10 +12,10 @@ class Solution { vector g; // Sprague-Grundy function of 0 ~ maxlen, O(n) space for (string t; in >> t; ) { // Split the string int p = t.size(); - while (g.size() <= p) { // O(n) time + while (g.size() <= p) { // O(c) time string x{t}; int i = 0, j = g.size() - 2; - while (i <= j) { // The S-G value of all subgame states, O(n) time + while (i <= j) { // The S-G value of all subgame states, O(c) time // Theorem 2: g[game] = g[subgame1]^g[subgame2]^g[subgame3]...; x[g[i++] ^ g[j--]] = '-'; } From 8ece11064637ce88940b6b1768d32a7e37f92ec2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 16:55:25 +0800 Subject: [PATCH 1135/1939] Update flip-game-ii.py --- Python/flip-game-ii.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 4a7375ec5..79cc4b979 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -1,7 +1,7 @@ -# Time: O(n^2) -# Space: O(n) +# Time: O(n + c^2) +# Space: O(c) -# The best theory solution (DP, O(n^2)) could be seen here: +# The best theory solution (DP, O(n + c^2)) could be seen here: # https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0m class Solution(object): def canWin(self, s): From ebed9ff7f8006447d2afa8cde0ca128982ffc6e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Oct 2015 17:08:46 +0800 Subject: [PATCH 1136/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d807d05b7..b4e40ef35 100644 --- a/README.md +++ b/README.md @@ -392,7 +392,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || -294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n^2)_ | _O(n)_ | Medium |📖| DP, Hash | +294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n + c^2)_ | _O(c)_ | Medium |📖| DP, Hash | ## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 7cc07ed6242dc3da9aab40fb2fc98bed5c417ff9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Oct 2015 14:05:56 +0800 Subject: [PATCH 1137/1939] Update flip-game-ii.cpp --- C++/flip-game-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flip-game-ii.cpp b/C++/flip-game-ii.cpp index affb920ca..4c0bc5f01 100644 --- a/C++/flip-game-ii.cpp +++ b/C++/flip-game-ii.cpp @@ -22,7 +22,7 @@ class Solution { // Find first missing number. g.emplace_back(x.find('+')); } - g_final ^= g[p]; // g[0], g[1] is always 0 + g_final ^= g[p]; } return g_final; // Theorem 1: First player must win iff g(current_state) != 0 } From 14305c6906791e2b72fc426053f0cca2a74c2845 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Oct 2015 16:23:53 +0800 Subject: [PATCH 1138/1939] Update intersection-of-two-linked-lists.py --- Python/intersection-of-two-linked-lists.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/intersection-of-two-linked-lists.py b/Python/intersection-of-two-linked-lists.py index d2d7af59f..4642fdcc5 100644 --- a/Python/intersection-of-two-linked-lists.py +++ b/Python/intersection-of-two-linked-lists.py @@ -33,11 +33,12 @@ class Solution: # @return the intersected ListNode def getIntersectionNode(self, headA, headB): curA, curB = headA, headB - tailA, tailB = None, None + begin, tailA, tailB = None, None, None while curA and curB: if curA == curB: - return curA + begin = curA + break if curA.next: curA = curA.next @@ -55,4 +56,4 @@ def getIntersectionNode(self, headA, headB): else: break - return None \ No newline at end of file + return begin From 96afea713e7067646c73124cb5248f9187d5279b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Oct 2015 15:40:09 +0800 Subject: [PATCH 1139/1939] Create find-median-from-data-stream.cpp --- C++/find-median-from-data-stream.cpp | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/find-median-from-data-stream.cpp diff --git a/C++/find-median-from-data-stream.cpp b/C++/find-median-from-data-stream.cpp new file mode 100644 index 000000000..bded76ee2 --- /dev/null +++ b/C++/find-median-from-data-stream.cpp @@ -0,0 +1,44 @@ +// Time: O(logn), per addition +// Space: O(n), total space + +class MedianFinder { +public: + + // Adds a number into the data structure. + void addNum(int num) { + // Balance smaller half and larger half. + if (max_bst_.empty() || num > *max_bst_.cbegin()) { + min_bst_.insert(num); + if (min_bst_.size() > max_bst_.size() + 1) { + max_bst_.insert(*min_bst_.cbegin()); + min_bst_.erase(min_bst_.cbegin()); + } + } else { + max_bst_.insert(num); + if (max_bst_.size() > min_bst_.size()) { + min_bst_.insert(*max_bst_.cbegin()); + max_bst_.erase(max_bst_.cbegin()); + } + } + } + + // Returns the median of current data stream + double findMedian() { + return min_bst_.size() == max_bst_.size() ? + (*max_bst_.cbegin() + *min_bst_.cbegin()) / 2.0 : + *min_bst_.cbegin(); + + } + +private: + // min_num_ stores the larger half seen so far. + multiset> min_bst_; + // max_bst_ stores the smaller half seen so far. + multiset> max_bst_; + +}; + +// Your MedianFinder object will be instantiated and called as such: +// MedianFinder mf; +// mf.addNum(1); +// mf.findMedian(); From 001f39f13dd19a6b19e93b151f5c79b39e0ba328 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Oct 2015 15:41:57 +0800 Subject: [PATCH 1140/1939] Update find-median-from-data-stream.cpp --- C++/find-median-from-data-stream.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-median-from-data-stream.cpp b/C++/find-median-from-data-stream.cpp index bded76ee2..ec8affa27 100644 --- a/C++/find-median-from-data-stream.cpp +++ b/C++/find-median-from-data-stream.cpp @@ -1,4 +1,4 @@ -// Time: O(logn), per addition +// Time: O(nlogn) for total n addNums, O(logn) per addNum, O(1) per findMedian. // Space: O(n), total space class MedianFinder { From c9a09591ff678680ddbf8daa71837502e45a3bda Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Oct 2015 15:42:21 +0800 Subject: [PATCH 1141/1939] Update find-median-from-data-stream.cpp --- C++/find-median-from-data-stream.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-median-from-data-stream.cpp b/C++/find-median-from-data-stream.cpp index ec8affa27..94e1666b0 100644 --- a/C++/find-median-from-data-stream.cpp +++ b/C++/find-median-from-data-stream.cpp @@ -31,7 +31,7 @@ class MedianFinder { } private: - // min_num_ stores the larger half seen so far. + // min_bst_ stores the larger half seen so far. multiset> min_bst_; // max_bst_ stores the smaller half seen so far. multiset> max_bst_; From c93c7868ed3e36448eeb2323435c9132f1382287 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Oct 2015 15:53:13 +0800 Subject: [PATCH 1142/1939] Update find-median-from-data-stream.cpp --- C++/find-median-from-data-stream.cpp | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/C++/find-median-from-data-stream.cpp b/C++/find-median-from-data-stream.cpp index 94e1666b0..6044272bf 100644 --- a/C++/find-median-from-data-stream.cpp +++ b/C++/find-median-from-data-stream.cpp @@ -1,7 +1,46 @@ // Time: O(nlogn) for total n addNums, O(logn) per addNum, O(1) per findMedian. // Space: O(n), total space +// Heap solution. class MedianFinder { +public: + + // Adds a number into the data structure. + void addNum(int num) { + // Balance smaller half and larger half. + if (max_heap_.empty() || num > max_heap_.top()) { + min_heap_.emplace(num); + if (min_heap_.size() > max_heap_.size() + 1) { + max_heap_.emplace(min_heap_.top()); + min_heap_.pop(); + } + } else { + max_heap_.emplace(num); + if (max_heap_.size() > min_heap_.size()) { + min_heap_.emplace(max_heap_.top()); + max_heap_.pop(); + } + } + } + + // Returns the median of current data stream + double findMedian() { + return min_heap_.size() == max_heap_.size() ? + (max_heap_.top() + min_heap_.top()) / 2.0 : + min_heap_.top(); + + } + +private: + // min_heap_ stores the larger half seen so far. + priority_queue, greater> min_heap_; + // max_heap_ stores the smaller half seen so far. + priority_queue, less> max_heap_; + +}; + +// BST solution. +class MedianFinder2 { public: // Adds a number into the data structure. From ed96e212e9feeeb5e565c412d92fcf95feb7f865 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Oct 2015 15:53:38 +0800 Subject: [PATCH 1143/1939] Update find-median-from-data-stream.cpp --- C++/find-median-from-data-stream.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/C++/find-median-from-data-stream.cpp b/C++/find-median-from-data-stream.cpp index 6044272bf..6dfec4602 100644 --- a/C++/find-median-from-data-stream.cpp +++ b/C++/find-median-from-data-stream.cpp @@ -36,7 +36,6 @@ class MedianFinder { priority_queue, greater> min_heap_; // max_heap_ stores the smaller half seen so far. priority_queue, less> max_heap_; - }; // BST solution. @@ -74,7 +73,6 @@ class MedianFinder2 { multiset> min_bst_; // max_bst_ stores the smaller half seen so far. multiset> max_bst_; - }; // Your MedianFinder object will be instantiated and called as such: From a1bdbfc998e2705688aa65ed53ecbc2af78b3bde Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Oct 2015 15:56:11 +0800 Subject: [PATCH 1144/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b4e40ef35..89e4baa1f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-294%20%2F%20294-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-295%20%2F%20295-ff69b4.svg) -Up to date (2015-10-16), there are `277` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-19), there are `278` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `294` questions. +Here is the classification of all `295` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -159,6 +159,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || 264| [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [C++](./C++/ugly-number-ii.cpp) [Python](./Python/ugly-number-ii.py) | _O(n)_ | _O(1)_ | Medium | CTCI, LintCode | BST, Heap | +295| [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | [C++](./C++/find-median-from-data-stream.cpp) [Python](./Python/find-median-from-data-stream.py) | _O(nlogn)_ | _O(n)_ | Hard | EPI, LintCode | BST, Heap | ## Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 4c12c130914118d2e75f96c86b4704fe1c6615d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Oct 2015 17:36:17 +0800 Subject: [PATCH 1145/1939] Create find-median-from-data-stream.py --- Python/find-median-from-data-stream.py | 64 ++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Python/find-median-from-data-stream.py diff --git a/Python/find-median-from-data-stream.py b/Python/find-median-from-data-stream.py new file mode 100644 index 000000000..3e3f968fb --- /dev/null +++ b/Python/find-median-from-data-stream.py @@ -0,0 +1,64 @@ +# Time: O(nlogn) for total n addNums, O(logn) per addNum, O(1) per findMedian. +# Space: O(n), total space + +# Median is the middle value in an ordered integer list. +# If the size of the list is even, there is no middle value. +# So the median is the mean of the two middle value. +# +# Examples: +# [2,3,4] , the median is 3 +# +# [2,3], the median is (2 + 3) / 2 = 2.5 +# +# Design a data structure that supports the following two operations: +# +# void addNum(int num) - Add a integer number from the data stream to the data structure. +# double findMedian() - Return the median of all elements so far. +# For example: +# +# add(1) +# add(2) +# findMedian() -> 1.5 +# add(3) +# findMedian() -> 2 + +# Heap solution. +from heapq import heappush, heappop + +class MedianFinder: + def __init__(self): + """ + Initialize your data structure here. + """ + self.__max_heap = [] + self.__min_heap = [] + + def addNum(self, num): + """ + Adds a num into the data structure. + :type num: int + :rtype: void + """ + # Balance smaller half and larger half. + if not self.__max_heap or num > -self.__max_heap[0]: + heappush(self.__min_heap, num) + if len(self.__min_heap) > len(self.__max_heap) + 1: + heappush(self.__max_heap, -heappop(self.__min_heap)) + else: + heappush(self.__max_heap, -num) + if len(self.__max_heap) > len(self.__min_heap): + heappush(self.__min_heap, -heappop(self.__max_heap)) + + def findMedian(self): + """ + Returns the median of current data stream + :rtype: float + """ + return (-self.__max_heap[0] + self.__min_heap[0]) / 2.0 \ + if len(self.__min_heap) == len(self.__max_heap) \ + else self.__min_heap[0] + +# Your MedianFinder object will be instantiated and called as such: +# mf = MedianFinder() +# mf.addNum(1) +# mf.findMedian() From 0b279a97352ad104572bca0719606db70197cbeb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Oct 2015 22:16:15 +0800 Subject: [PATCH 1146/1939] Update find-median-from-data-stream.cpp --- C++/find-median-from-data-stream.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/find-median-from-data-stream.cpp b/C++/find-median-from-data-stream.cpp index 6dfec4602..1735e3596 100644 --- a/C++/find-median-from-data-stream.cpp +++ b/C++/find-median-from-data-stream.cpp @@ -46,15 +46,15 @@ class MedianFinder2 { void addNum(int num) { // Balance smaller half and larger half. if (max_bst_.empty() || num > *max_bst_.cbegin()) { - min_bst_.insert(num); + min_bst_.emplace(num); if (min_bst_.size() > max_bst_.size() + 1) { - max_bst_.insert(*min_bst_.cbegin()); + max_bst_.emplace(*min_bst_.cbegin()); min_bst_.erase(min_bst_.cbegin()); } } else { - max_bst_.insert(num); + max_bst_.emplace(num); if (max_bst_.size() > min_bst_.size()) { - min_bst_.insert(*max_bst_.cbegin()); + min_bst_.emplace(*max_bst_.cbegin()); max_bst_.erase(max_bst_.cbegin()); } } From c109581fe0d197835ccc79841af68fd9f491d9d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Oct 2015 13:30:17 +0800 Subject: [PATCH 1147/1939] Create best-meeting-point.cpp --- C++/best-meeting-point.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/best-meeting-point.cpp diff --git a/C++/best-meeting-point.cpp b/C++/best-meeting-point.cpp new file mode 100644 index 000000000..9a6839fa4 --- /dev/null +++ b/C++/best-meeting-point.cpp @@ -0,0 +1,30 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int minTotalDistance(vector>& grid) { + vector x, y; + for (int i = 0; i < grid.size(); ++i) { + for (int j = 0; j < grid[0].size(); ++j) { + if (grid[i][j]) { + x.emplace_back(i); + y.emplace_back(j); + } + } + } + nth_element(x.begin(), x.begin() + x.size() / 2, x.end()); + nth_element(y.begin(), y.begin() + y.size() / 2, y.end()); + const int mid_x = x[x.size() / 2]; + const int mid_y = y[y.size() / 2]; + int sum = 0; + for (int i = 0; i < grid.size(); ++i) { + for (int j = 0; j < grid[0].size(); ++j) { + if (grid[i][j]) { + sum += abs(mid_x - i) + abs(mid_y - j); + } + } + } + return sum; + } +}; From 3e4136fe09fac004b3d18cab5130cedf5ac84dc9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Oct 2015 13:36:15 +0800 Subject: [PATCH 1148/1939] Create best-meeting-point.py --- Python/best-meeting-point.py | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/best-meeting-point.py diff --git a/Python/best-meeting-point.py b/Python/best-meeting-point.py new file mode 100644 index 000000000..f9232a3a0 --- /dev/null +++ b/Python/best-meeting-point.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(n) + +from random import randint + +class Solution(object): + def minTotalDistance(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + x = [i for i, row in enumerate(grid) for v in row if v == 1] + y = [j for row in grid for j, v in enumerate(row) if v == 1] + mid_x = self.findKthLargest(x, len(x) / 2 + 1) + mid_y = self.findKthLargest(y, len(y) / 2 + 1) + + return sum([abs(mid_x-i) + abs(mid_y-j) \ + for i, row in enumerate(grid) for j, v in enumerate(row) if v == 1]) + + def findKthLargest(self, nums, k): + left, right = 0, len(nums) - 1 + while left <= right: + pivot_idx = randint(left, right) + new_pivot_idx = self.PartitionAroundPivot(left, right, pivot_idx, nums) + if new_pivot_idx == k - 1: + return nums[new_pivot_idx] + elif new_pivot_idx > k - 1: + right = new_pivot_idx - 1 + else: # new_pivot_idx < k - 1. + left = new_pivot_idx + 1 + + def PartitionAroundPivot(self, left, right, pivot_idx, nums): + pivot_value = nums[pivot_idx] + new_pivot_idx = left + nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx] + for i in xrange(left, right): + if nums[i] > pivot_value: + nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] + new_pivot_idx += 1 + + nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right] + return new_pivot_idx From 5d33e564f5bbad06a9e46e2e650cf5e97a6fd68b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Oct 2015 13:39:11 +0800 Subject: [PATCH 1149/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 89e4baa1f..d8c3ece03 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-295%20%2F%20295-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-296%20%2F%20296-ff69b4.svg) -Up to date (2015-10-19), there are `278` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-22), there are `279` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `295` questions. +Here is the classification of all `296` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -91,6 +91,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |📖, EPI || 289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| 293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(n * (c+1))_ | _O(1)_ | Easy |📖|| +296| [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) | [C++](./C++/best-meeting-point.cpp) [Python](./Python/best-meeting-point.py) | _O(n)_ | _O(n)_ | Medium |📖|| ## String # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 40d0f678f564b79c2f14d1ca7ce4433aaeb34822 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Oct 2015 01:12:57 +0800 Subject: [PATCH 1150/1939] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 8360da215..66af2e6d7 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -1,4 +1,4 @@ -# Time: O(log(m + n)) +# Time: O(log(min(m, n))) # Space: O(1) # # There are two sorted arrays A and B of size m and n respectively. From 77a569bcea82803c4b7436f65b494c7884993be4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Oct 2015 01:13:26 +0800 Subject: [PATCH 1151/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d8c3ece03..34ab965e8 100644 --- a/README.md +++ b/README.md @@ -292,7 +292,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Binary Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(m + n))_ | _O(1)_ | Hard || +4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(min(m, n)))_ | _O(1)_ | Hard || 33| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || 34| [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || 35| [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || From a774b4a5491434d99201b58108a87ac32365a80e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Oct 2015 20:27:26 +0800 Subject: [PATCH 1152/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 933105f98..d8747151d 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -1,5 +1,5 @@ # Time: O(|V| + |E|) -# Space: O(|V| + |E|) +# Space: O(|V|) # BFS solution. class Solution: @@ -11,17 +11,18 @@ def validTree(self, n, edges): return False visited_from, neighbors = 0, 1 - nodes = {} # A dictionary to track each node's [visited_from, neighbors] - for i in xrange(n): # Space: O(|V|) + nodes = {} # A structure to track each node's [visited_from, neighbors] + for i in xrange(n): nodes[i] = [-1, []] - for edge in edges: # Space: O(|E|) + for edge in edges: nodes[edge[0]][neighbors].append(edge[1]) nodes[edge[1]][neighbors].append(edge[0]) - # BFS to check whether these edges make up a valid tree. + # BFS to check whether the graph is valid tree. visited = {} q = collections.deque() - q.append(0) + if edges: + q.append(edges[0][0]) while q: i = q.popleft() visited[i] = True From ae9c396acdd85e76cd3f32ef89af228d405fd086 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Oct 2015 20:32:16 +0800 Subject: [PATCH 1153/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index 9ed2ab7ab..332745ab5 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -10,6 +10,8 @@ class Solution { bool validTree(int n, vector>& edges) { if (edges.size() != n - 1) { return false; + } else if (n == 1) { + return true; } unordered_map nodes; @@ -23,17 +25,17 @@ class Solution { unordered_set visited; queue q; - q.emplace(0); + q.emplace(edges[0].first); while (!q.empty()) { int i = q.front(); q.pop(); - visited.insert(i); + visited.emplace(i); for (const auto& n : nodes[i].neighbors) { if (n != nodes[i].parent) { if (visited.find(n) != visited.end()) { return false; } else { - visited.insert(n); + visited.emplace(n); nodes[n].parent = i; q.emplace(n); } From 1500f0dba6c052e2d54494a6cfda78ac79c2e278 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Oct 2015 20:33:25 +0800 Subject: [PATCH 1154/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index d8747151d..7517ea783 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -9,6 +9,8 @@ class Solution: def validTree(self, n, edges): if len(edges) != n - 1: return False + elif n == 1: + return True visited_from, neighbors = 0, 1 nodes = {} # A structure to track each node's [visited_from, neighbors] @@ -21,8 +23,7 @@ def validTree(self, n, edges): # BFS to check whether the graph is valid tree. visited = {} q = collections.deque() - if edges: - q.append(edges[0][0]) + q.append(edges[0][0]) while q: i = q.popleft() visited[i] = True From aa3c7d9f0fe37f664239a359a7007683597c4c48 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Oct 2015 20:36:58 +0800 Subject: [PATCH 1155/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index 332745ab5..e1c325da1 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -27,7 +27,7 @@ class Solution { queue q; q.emplace(edges[0].first); while (!q.empty()) { - int i = q.front(); + const int i = q.front(); q.pop(); visited.emplace(i); for (const auto& n : nodes[i].neighbors) { From c6b16061458b3300d316d0fc096226e1ffcb42fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Oct 2015 20:37:33 +0800 Subject: [PATCH 1156/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 7517ea783..d0abbc729 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -1,5 +1,5 @@ # Time: O(|V| + |E|) -# Space: O(|V|) +# Space: O(|V| + |E|) # BFS solution. class Solution: From 00206aa0e1c835caa8d2ce591f6626094affda07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Oct 2015 20:40:10 +0800 Subject: [PATCH 1157/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index e1c325da1..29fc4fe29 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -7,6 +7,7 @@ class Solution { int parent; vectorneighbors; }; + bool validTree(int n, vector>& edges) { if (edges.size() != n - 1) { return false; From 8ec0968aa2efde4232e719fba243369a0fb86744 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Oct 2015 20:47:06 +0800 Subject: [PATCH 1158/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index 29fc4fe29..b2e40b2c7 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -20,13 +20,17 @@ class Solution { nodes[edge.first].neighbors.emplace_back(edge.second); nodes[edge.second].neighbors.emplace_back(edge.first); } + if (nodes.size() != n) { + return false; + } + for (int i = 0; i < n; ++i) { nodes[i].parent = -1; } unordered_set visited; queue q; - q.emplace(edges[0].first); + q.emplace(0); while (!q.empty()) { const int i = q.front(); q.pop(); From 8221d4bf6bcef77cc8af70a77c699e7ee2a28d90 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Oct 2015 20:57:13 +0800 Subject: [PATCH 1159/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index d0abbc729..6d22e0e9b 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -7,23 +7,26 @@ class Solution: # @param {integer[][]} edges # @return {boolean} def validTree(self, n, edges): - if len(edges) != n - 1: + if len(edges) != n - 1: # Check number of edges. return False elif n == 1: return True visited_from, neighbors = 0, 1 - nodes = {} # A structure to track each node's [visited_from, neighbors] - for i in xrange(n): - nodes[i] = [-1, []] + + # A structure to track each node's [visited_from, neighbors] + nodes = collections.defaultdict(lambda: [-1, []]) for edge in edges: nodes[edge[0]][neighbors].append(edge[1]) nodes[edge[1]][neighbors].append(edge[0]) + + if len(nodes) != n: # Check number of nodes. + return False # BFS to check whether the graph is valid tree. visited = {} q = collections.deque() - q.append(edges[0][0]) + q.append(0) while q: i = q.popleft() visited[i] = True From 2eb1d700edf9087ca65c1aa8eae22fe6d65eaeac Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Oct 2015 21:06:11 +0800 Subject: [PATCH 1160/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index b2e40b2c7..91708668c 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -1,10 +1,11 @@ + // Time: O(|V| + |E|) // Space: O(|V| + |E|) class Solution { public: struct node { - int parent; + int parent = -1; vectorneighbors; }; @@ -20,14 +21,11 @@ class Solution { nodes[edge.first].neighbors.emplace_back(edge.second); nodes[edge.second].neighbors.emplace_back(edge.first); } + if (nodes.size() != n) { return false; } - for (int i = 0; i < n; ++i) { - nodes[i].parent = -1; - } - unordered_set visited; queue q; q.emplace(0); From af916e24dfdecb2f8eef4e6dc267495285429792 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Oct 2015 12:11:50 +0800 Subject: [PATCH 1161/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index 91708668c..a42df4cad 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -1,4 +1,3 @@ - // Time: O(|V| + |E|) // Space: O(|V| + |E|) @@ -33,6 +32,7 @@ class Solution { const int i = q.front(); q.pop(); visited.emplace(i); + --n; for (const auto& n : nodes[i].neighbors) { if (n != nodes[i].parent) { if (visited.find(n) != visited.end()) { @@ -45,6 +45,6 @@ class Solution { } } } - return true; + return n == 0; } }; From 0f1606cf6b24e0d75311188a8c8fa44c09b33a25 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Oct 2015 12:14:49 +0800 Subject: [PATCH 1162/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 6d22e0e9b..40d662d5c 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -30,12 +30,13 @@ def validTree(self, n, edges): while q: i = q.popleft() visited[i] = True - for n in nodes[i][neighbors]: - if n != nodes[i][visited_from]: - if n in visited: + n -= 1 + for node in nodes[i][neighbors]: + if node != nodes[i][visited_from]: + if node in visited: return False else: - visited[n] = True - nodes[n][visited_from] = i - q.append(n) - return True + visited[node] = True + nodes[node][visited_from] = i + q.append(node) + return n == 0 From 1cb6918fa49a9e9ab9dcc3179a72d639fe1d08d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Oct 2015 12:16:03 +0800 Subject: [PATCH 1163/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index a42df4cad..be921dd2c 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -33,14 +33,14 @@ class Solution { q.pop(); visited.emplace(i); --n; - for (const auto& n : nodes[i].neighbors) { - if (n != nodes[i].parent) { - if (visited.find(n) != visited.end()) { + for (const auto& node : nodes[i].neighbors) { + if (node != nodes[i].parent) { + if (visited.find(node) != visited.end()) { return false; } else { - visited.emplace(n); - nodes[n].parent = i; - q.emplace(n); + visited.emplace(node); + nodes[node].parent = i; + q.emplace(node); } } } From c3c1e8880a8232ddbdb394ebb630d750fee99adf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Oct 2015 12:25:00 +0800 Subject: [PATCH 1164/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 40d662d5c..dd1b0d1ea 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -30,7 +30,6 @@ def validTree(self, n, edges): while q: i = q.popleft() visited[i] = True - n -= 1 for node in nodes[i][neighbors]: if node != nodes[i][visited_from]: if node in visited: @@ -39,4 +38,4 @@ def validTree(self, n, edges): visited[node] = True nodes[node][visited_from] = i q.append(node) - return n == 0 + return len(visited) == n From 170e7ef08090605c3e98285ba1a947f98b05b4d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Oct 2015 12:28:16 +0800 Subject: [PATCH 1165/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index be921dd2c..400d04bb3 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -32,7 +32,6 @@ class Solution { const int i = q.front(); q.pop(); visited.emplace(i); - --n; for (const auto& node : nodes[i].neighbors) { if (node != nodes[i].parent) { if (visited.find(node) != visited.end()) { @@ -45,6 +44,6 @@ class Solution { } } } - return n == 0; + return visited.size() == n; } }; From fe7ddfaab72ba6468d372fbac84f74871c1f7749 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Oct 2015 12:36:16 +0800 Subject: [PATCH 1166/1939] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index 400d04bb3..983f6ecfa 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -1,6 +1,7 @@ // Time: O(|V| + |E|) // Space: O(|V| + |E|) +// Same complexity, but faster version. class Solution { public: struct node { @@ -47,3 +48,42 @@ class Solution { return visited.size() == n; } }; + +// Time: O(|V| + |E|) +// Space: O(|V| + |E|) +class Solution2 { +public: + struct node { + int parent = -1; + vectorneighbors; + }; + + bool validTree(int n, vector>& edges) { + unordered_map nodes; + for (const auto& edge : edges) { + nodes[edge.first].neighbors.emplace_back(edge.second); + nodes[edge.second].neighbors.emplace_back(edge.first); + } + + unordered_set visited; + queue q; + q.emplace(0); + while (!q.empty()) { + const int i = q.front(); + q.pop(); + visited.emplace(i); + for (const auto& node : nodes[i].neighbors) { + if (node != nodes[i].parent) { + if (visited.find(node) != visited.end()) { + return false; + } else { + visited.emplace(node); + nodes[node].parent = i; + q.emplace(node); + } + } + } + } + return visited.size() == n; + } +}; From 956b03645089e5c16cb72c0af78c9311bad8fcfd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Oct 2015 12:38:48 +0800 Subject: [PATCH 1167/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index dd1b0d1ea..16dae9e70 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -1,7 +1,7 @@ # Time: O(|V| + |E|) # Space: O(|V| + |E|) -# BFS solution. +# BFS solution. Same complexity but faster version. class Solution: # @param {integer} n # @param {integer[][]} edges @@ -39,3 +39,37 @@ def validTree(self, n, edges): nodes[node][visited_from] = i q.append(node) return len(visited) == n + + +# Time: O(|V| + |E|) +# Space: O(|V| + |E|) +# BFS solution. +class Solution: + # @param {integer} n + # @param {integer[][]} edges + # @return {boolean} + def validTree(self, n, edges): + visited_from, neighbors = 0, 1 + + # A structure to track each node's [visited_from, neighbors] + nodes = collections.defaultdict(lambda: [-1, []]) + for edge in edges: + nodes[edge[0]][neighbors].append(edge[1]) + nodes[edge[1]][neighbors].append(edge[0]) + + # BFS to check whether the graph is valid tree. + visited = {} + q = collections.deque() + q.append(0) + while q: + i = q.popleft() + visited[i] = True + for node in nodes[i][neighbors]: + if node != nodes[i][visited_from]: + if node in visited: + return False + else: + visited[node] = True + nodes[node][visited_from] = i + q.append(node) + return len(visited) == n From 28b562b56f300675e436728fda741d71344d980b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Oct 2015 12:40:11 +0800 Subject: [PATCH 1168/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 16dae9e70..d1e0ffcb5 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -44,7 +44,7 @@ def validTree(self, n, edges): # Time: O(|V| + |E|) # Space: O(|V| + |E|) # BFS solution. -class Solution: +class Solution2: # @param {integer} n # @param {integer[][]} edges # @return {boolean} From ed83e903805941580e3bc58976892c3f330fb4d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Oct 2015 19:39:36 +0800 Subject: [PATCH 1169/1939] Create serialize-and-deserialize-binary-tree.cpp --- C++/serialize-and-deserialize-binary-tree.cpp | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 C++/serialize-and-deserialize-binary-tree.cpp diff --git a/C++/serialize-and-deserialize-binary-tree.cpp b/C++/serialize-and-deserialize-binary-tree.cpp new file mode 100644 index 000000000..ffd0e2b55 --- /dev/null +++ b/C++/serialize-and-deserialize-binary-tree.cpp @@ -0,0 +1,76 @@ +// Time: O(n) +// Space: O(h) + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + string output; + serializeHelper(root, &output); + return output; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + TreeNode *root = nullptr; + int start = 0; + deserializeHelper(data, &start, &root); + return root; + } + +private: + bool getNumber(const string &data, int *start, int *num) { + int sign = 1; + if (data[*start] == '#') { + *start += 2; // Skip "# ". + return false; + } else if (data[*start] == '-') { + sign = -1; + ++(*start); + } + + for (*num = 0; isdigit(data[*start]); ++(*start)) { + *num = *num * 10 + data[*start] - '0'; + } + *num *= sign; + ++(*start); // Skip " ". + + return true; + } + + void deserializeHelper(const string& data, + int *start, TreeNode **root) { + int num; + if (!getNumber(data, start, &num)) { + *root = nullptr; + } else { + *root = new TreeNode(num); + deserializeHelper(data, start, &((*root)->left)); + deserializeHelper(data, start, &((*root)->right)); + } + } + + void serializeHelper(const TreeNode *root, string *prev) { + if (!root) { + prev->append("# "); + } else { + prev->append(to_string(root->val).append(" ")); + serializeHelper(root->left, prev); + serializeHelper(root->right, prev); + } + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.deserialize(codec.serialize(root)); From c3cd578cd2b7677632d11c371eab475299b44c06 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Oct 2015 19:47:47 +0800 Subject: [PATCH 1170/1939] Update README.md --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 34ab965e8..d85793e60 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-296%20%2F%20296-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-297%20%2F%20297-ff69b4.svg) -Up to date (2015-10-22), there are `279` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-26), there are `280` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `296` questions. +Here is the classification of all `297` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -170,9 +170,10 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie -211 | [Add and Search Word - Data structure design ](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS +211 | [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || +297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 0e2408c5461769327d86a1af997a1fbf1bfa6884 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Oct 2015 20:51:53 +0800 Subject: [PATCH 1171/1939] Update serialize-and-deserialize-binary-tree.cpp --- C++/serialize-and-deserialize-binary-tree.cpp | 61 ++++++------------- 1 file changed, 20 insertions(+), 41 deletions(-) diff --git a/C++/serialize-and-deserialize-binary-tree.cpp b/C++/serialize-and-deserialize-binary-tree.cpp index ffd0e2b55..f588515bb 100644 --- a/C++/serialize-and-deserialize-binary-tree.cpp +++ b/C++/serialize-and-deserialize-binary-tree.cpp @@ -15,59 +15,38 @@ class Codec { // Encodes a tree to a single string. string serialize(TreeNode* root) { - string output; - serializeHelper(root, &output); - return output; + ostringstream out; + serializeHelper(root, out); + return out.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { - TreeNode *root = nullptr; - int start = 0; - deserializeHelper(data, &start, &root); - return root; + istringstream in(data); + return deserializeHelper(in); } private: - bool getNumber(const string &data, int *start, int *num) { - int sign = 1; - if (data[*start] == '#') { - *start += 2; // Skip "# ". - return false; - } else if (data[*start] == '-') { - sign = -1; - ++(*start); - } - - for (*num = 0; isdigit(data[*start]); ++(*start)) { - *num = *num * 10 + data[*start] - '0'; - } - *num *= sign; - ++(*start); // Skip " ". - - return true; - } - - void deserializeHelper(const string& data, - int *start, TreeNode **root) { - int num; - if (!getNumber(data, start, &num)) { - *root = nullptr; + void serializeHelper(const TreeNode *root, ostringstream& out) { + if (!root) { + out << "# "; } else { - *root = new TreeNode(num); - deserializeHelper(data, start, &((*root)->left)); - deserializeHelper(data, start, &((*root)->right)); + out << root->val << " "; + serializeHelper(root->left, out); + serializeHelper(root->right, out); } } - void serializeHelper(const TreeNode *root, string *prev) { - if (!root) { - prev->append("# "); - } else { - prev->append(to_string(root->val).append(" ")); - serializeHelper(root->left, prev); - serializeHelper(root->right, prev); + TreeNode *deserializeHelper(istringstream& in) { + string val; + in >> val; + if (val != "#") { + TreeNode* root = new TreeNode(stoi(val)); + root->left = deserializeHelper(in); + root->right = deserializeHelper(in); + return root; } + return nullptr; } }; From bdbb6c2bb331072c5a475ab9aa13af4e27c5bde0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Oct 2015 21:02:12 +0800 Subject: [PATCH 1172/1939] Update serialize-and-deserialize-binary-tree.cpp --- C++/serialize-and-deserialize-binary-tree.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/serialize-and-deserialize-binary-tree.cpp b/C++/serialize-and-deserialize-binary-tree.cpp index f588515bb..97da19e79 100644 --- a/C++/serialize-and-deserialize-binary-tree.cpp +++ b/C++/serialize-and-deserialize-binary-tree.cpp @@ -40,13 +40,14 @@ class Codec { TreeNode *deserializeHelper(istringstream& in) { string val; in >> val; - if (val != "#") { + if (val == "#") { + return nullptr; + } else { TreeNode* root = new TreeNode(stoi(val)); root->left = deserializeHelper(in); root->right = deserializeHelper(in); return root; } - return nullptr; } }; From bf1bdf2dcf303ad5ba0d26b5c5606e55dec2fbb8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Oct 2015 21:09:32 +0800 Subject: [PATCH 1173/1939] Update serialize-and-deserialize-binary-tree.cpp --- C++/serialize-and-deserialize-binary-tree.cpp | 66 ++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/C++/serialize-and-deserialize-binary-tree.cpp b/C++/serialize-and-deserialize-binary-tree.cpp index 97da19e79..6464813d7 100644 --- a/C++/serialize-and-deserialize-binary-tree.cpp +++ b/C++/serialize-and-deserialize-binary-tree.cpp @@ -11,6 +11,70 @@ * }; */ class Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + string output; + serializeHelper(root, &output); + return output; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + TreeNode *root = nullptr; + int start = 0; + deserializeHelper(data, &start, &root); + return root; + } + +private: + bool getNumber(const string &data, int *start, int *num) { + int sign = 1; + if (data[*start] == '#') { + *start += 2; // Skip "# ". + return false; + } else if (data[*start] == '-') { + sign = -1; + ++(*start); + } + + for (*num = 0; isdigit(data[*start]); ++(*start)) { + *num = *num * 10 + data[*start] - '0'; + } + *num *= sign; + ++(*start); // Skip " ". + + return true; + } + + void serializeHelper(const TreeNode *root, string *prev) { + if (!root) { + prev->append("# "); + } else { + prev->append(to_string(root->val).append(" ")); + serializeHelper(root->left, prev); + serializeHelper(root->right, prev); + } + } + + void deserializeHelper(const string& data, + int *start, TreeNode **root) { + int num; + if (!getNumber(data, start, &num)) { + *root = nullptr; + } else { + *root = new TreeNode(num); + deserializeHelper(data, start, &((*root)->left)); + deserializeHelper(data, start, &((*root)->right)); + } + } +}; + + +// Time: O(n) +// Space: O(n) +class Codec2 { public: // Encodes a tree to a single string. @@ -22,7 +86,7 @@ class Codec { // Decodes your encoded data to tree. TreeNode* deserialize(string data) { - istringstream in(data); + istringstream in(data); // Space: O(n) return deserializeHelper(in); } From 0b8f9a697283634caf9c325accbb5e0b84f28d1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Oct 2015 21:17:39 +0800 Subject: [PATCH 1174/1939] Create serialize-and-deserialize-binary-tree.py --- .../serialize-and-deserialize-binary-tree.py | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Python/serialize-and-deserialize-binary-tree.py diff --git a/Python/serialize-and-deserialize-binary-tree.py b/Python/serialize-and-deserialize-binary-tree.py new file mode 100644 index 000000000..2bcff9362 --- /dev/null +++ b/Python/serialize-and-deserialize-binary-tree.py @@ -0,0 +1,71 @@ +# Time: O(n) +# Space: O(n) + +# Serialization is the process of converting a data structure or +# object into a sequence of bits so that it can be stored in a file +# or memory buffer, or transmitted across a network connection link +# to be reconstructed later in the same or another computer environment. +# +# Design an algorithm to serialize and deserialize a binary tree. +# There is no restriction on how your serialization/deserialization +# algorithm should work. You just need to ensure that a binary tree can +# be serialized to a string and this string can be deserialized to the +# original tree structure. +# +# For example, you may serialize the following tree +# +# 1 +# / \ +# 2 3 +# / \ +# 4 5 +# as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes +# a binary tree. You do not necessarily need to follow this format, so +# please be creative and come up with different approaches yourself. +# Note: Do not use class member/global/static variables to store states. +# Your serialize and deserialize algorithms should be stateless. +# + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None +class Codec: + + def serialize(self, root): + """Encodes a tree to a single string. + + :type root: TreeNode + :rtype: str + """ + def serializeHelper(node): + if not node: + vals.append('#') + else: + vals.append(str(node.val)) + serializeHelper(node.left) + serializeHelper(node.right) + vals = [] + serializeHelper(root) + return ' '.join(vals) + + + def deserialize(self, data): + """Decodes your encoded data to tree. + + :type data: str + :rtype: TreeNode + """ + def deserializeHelper(): + val = next(vals) + if val == '#': + return None + else: + node = TreeNode(int(val)) + node.left = deserializeHelper() + node.right = deserializeHelper() + return node + vals = iter(data.split()) + return deserializeHelper() From 8d838e401cab806708a92f11b11dbce2fa8ebe04 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Oct 2015 21:25:22 +0800 Subject: [PATCH 1175/1939] Update serialize-and-deserialize-binary-tree.py --- .../serialize-and-deserialize-binary-tree.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Python/serialize-and-deserialize-binary-tree.py b/Python/serialize-and-deserialize-binary-tree.py index 2bcff9362..d69f43dd0 100644 --- a/Python/serialize-and-deserialize-binary-tree.py +++ b/Python/serialize-and-deserialize-binary-tree.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(n) +# Space: O(h) # Serialization is the process of converting a data structure or # object into a sequence of bits so that it can be stored in a file @@ -67,5 +67,19 @@ def deserializeHelper(): node.left = deserializeHelper() node.right = deserializeHelper() return node - vals = iter(data.split()) + def isplit(source, sep): + sepsize = len(sep) + start = 0 + while True: + idx = source.find(sep, start) + if idx == -1: + yield source[start:] + return + yield source[start:idx] + start = idx + sepsize + vals = iter(isplit(data, ' ')) return deserializeHelper() + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.deserialize(codec.serialize(root)) From a54b71b82624565a3cb4f3f6fa1381bef163b7be Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Oct 2015 21:54:20 +0800 Subject: [PATCH 1176/1939] Update serialize-and-deserialize-binary-tree.cpp --- C++/serialize-and-deserialize-binary-tree.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/C++/serialize-and-deserialize-binary-tree.cpp b/C++/serialize-and-deserialize-binary-tree.cpp index 6464813d7..baeb0076e 100644 --- a/C++/serialize-and-deserialize-binary-tree.cpp +++ b/C++/serialize-and-deserialize-binary-tree.cpp @@ -24,8 +24,7 @@ class Codec { TreeNode* deserialize(string data) { TreeNode *root = nullptr; int start = 0; - deserializeHelper(data, &start, &root); - return root; + return deserializeHelper(data, &start); } private: @@ -58,15 +57,15 @@ class Codec { } } - void deserializeHelper(const string& data, - int *start, TreeNode **root) { + TreeNode *deserializeHelper(const string& data, int *start) { int num; if (!getNumber(data, start, &num)) { - *root = nullptr; + return nullptr; } else { - *root = new TreeNode(num); - deserializeHelper(data, start, &((*root)->left)); - deserializeHelper(data, start, &((*root)->right)); + TreeNode *root = new TreeNode(num); + root->left = deserializeHelper(data, start); + root->right = deserializeHelper(data, start); + return root; } } }; From 05c489c1da9e54b7fbb3a48ae2f1735a21d7e3ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Oct 2015 14:03:21 +0800 Subject: [PATCH 1177/1939] Create binary-tree-longest-consecutive-sequence.cpp --- ...nary-tree-longest-consecutive-sequence.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/binary-tree-longest-consecutive-sequence.cpp diff --git a/C++/binary-tree-longest-consecutive-sequence.cpp b/C++/binary-tree-longest-consecutive-sequence.cpp new file mode 100644 index 000000000..75fc8356c --- /dev/null +++ b/C++/binary-tree-longest-consecutive-sequence.cpp @@ -0,0 +1,39 @@ +// Time: O(n) +// Space: O(h) + +/** + * 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: + int longestConsecutive(TreeNode* root) { + int max_len = 0; + longestConsecutiveHelper(root, &max_len); + return max_len; + } + + int longestConsecutiveHelper(TreeNode *root, int *max_len) { + if (!root) { + return 0; + } + + const int left_len = longestConsecutiveHelper(root->left, max_len); + const int right_len = longestConsecutiveHelper(root->right, max_len); + + int cur_len = 1; + if (root->left && root->left->val == root->val + 1) { + cur_len = max(cur_len, left_len + 1); + } + if (root->right && root->right->val == root->val + 1) { + cur_len = max(cur_len, right_len + 1); + } + *max_len = max(*max_len, max(cur_len, max(left_len, right_len))); + return cur_len; + } +}; From ee5d71d53785fc70c3c0a73e414c78d406e6a969 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Oct 2015 14:07:41 +0800 Subject: [PATCH 1178/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d85793e60..795d998c0 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-297%20%2F%20297-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-298%20%2F%20298-ff69b4.svg) -Up to date (2015-10-26), there are `280` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-28), there are `281` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `297` questions. +Here is the classification of all `298` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -289,6 +289,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 129| [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || 156| [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| 241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n * 4^n / n^(3/2))_ | Medium || +298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) | [Python](./Python/binary-tree-longest-consecutive-sequence.py) | _O(n)_ | _O(h)_ | Medium |📖| ## Binary Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 8781c337114144bb3eea3ba294e539693a4ba420 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Oct 2015 14:08:23 +0800 Subject: [PATCH 1179/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 795d998c0..55c609b36 100644 --- a/README.md +++ b/README.md @@ -289,7 +289,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 129| [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [Python](./Python/sum-root-to-leaf-numbers.py) | _O(n)_ | _O(h)_ | Medium || 156| [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| 241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n * 4^n / n^(3/2))_ | Medium || -298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) | [Python](./Python/binary-tree-longest-consecutive-sequence.py) | _O(n)_ | _O(h)_ | Medium |📖| +298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) | [C++](./C++/binary-tree-longest-consecutive-sequence.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence.py) | _O(n)_ | _O(h)_ | Medium |📖| ## Binary Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 16ff40adfcb25151ef9d632833f0f9c7e971136a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Oct 2015 14:23:51 +0800 Subject: [PATCH 1180/1939] Create binary-tree-longest-consecutive-sequence.py --- ...inary-tree-longest-consecutive-sequence.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/binary-tree-longest-consecutive-sequence.py diff --git a/Python/binary-tree-longest-consecutive-sequence.py b/Python/binary-tree-longest-consecutive-sequence.py new file mode 100644 index 000000000..3597dfb68 --- /dev/null +++ b/Python/binary-tree-longest-consecutive-sequence.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(h) + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def longestConsecutive(self, root): + """ + :type root: TreeNode + :rtype: int + """ + self.max_len = 0 + + def longestConsecutiveHelper(root): + if not root: + return 0 + + left_len = longestConsecutiveHelper(root.left) + right_len = longestConsecutiveHelper(root.right) + + cur_len = 1 + if root.left and root.left.val == root.val + 1: + cur_len = max(cur_len, left_len + 1); + if root.right and root.right.val == root.val + 1: + cur_len = max(cur_len, right_len + 1) + self.max_len = max(self.max_len, cur_len, left_len, right_len) + return cur_len + + longestConsecutiveHelper(root) + return self.max_len From 2c31abbd22137e64b8ed37f76a0d2a3060e55b6f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Oct 2015 14:25:11 +0800 Subject: [PATCH 1181/1939] Update binary-tree-longest-consecutive-sequence.py --- Python/binary-tree-longest-consecutive-sequence.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/binary-tree-longest-consecutive-sequence.py b/Python/binary-tree-longest-consecutive-sequence.py index 3597dfb68..769c417ee 100644 --- a/Python/binary-tree-longest-consecutive-sequence.py +++ b/Python/binary-tree-longest-consecutive-sequence.py @@ -28,7 +28,9 @@ def longestConsecutiveHelper(root): cur_len = max(cur_len, left_len + 1); if root.right and root.right.val == root.val + 1: cur_len = max(cur_len, right_len + 1) + self.max_len = max(self.max_len, cur_len, left_len, right_len) + return cur_len longestConsecutiveHelper(root) From 6f7104c306b04b2f63afe0fcfe7774c9caeb4f63 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:15:36 +0800 Subject: [PATCH 1182/1939] Create bulls-and-cow.py --- Python/bulls-and-cow.py | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/bulls-and-cow.py diff --git a/Python/bulls-and-cow.py b/Python/bulls-and-cow.py new file mode 100644 index 000000000..3a895a191 --- /dev/null +++ b/Python/bulls-and-cow.py @@ -0,0 +1,46 @@ +# Time: O(n) +# Space: O(10) = O(1) + + +# You are playing the following Bulls and Cows game with your friend: +# You write a 4-digit secret number and ask your friend to guess it, +# each time your friend guesses a number, you give a hint, the hint +# tells your friend how many digits are in the correct positions +# (called "bulls") and how many digits are in the wrong positions +# (called "cows"), your friend will use those hints to find out the +# secret number. +# +# For example: +# +# Secret number: 1807 +# Friend's guess: 7810 +# Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.) +# According to Wikipedia: "Bulls and Cows (also known as Cows and Bulls +# or Pigs and Bulls or Bulls and Cleots) is an old code-breaking mind or +# paper and pencil game for two or more players, predating the similar +# commercially marketed board game Mastermind. The numerical version of +# the game is usually played with 4 digits, but can also be played with +# 3 or any other number of digits." +# +# Write a function to return a hint according to the secret number and +# friend's guess, use A to indicate the bulls and B to indicate the cows, +# in the above example, your function should return 1A3B. +# +# You may assume that the secret number and your friend's guess only contain +# digits, and their lengths are always equal. +# + +from collections import Counter +from itertools import imap + +class Solution(object): + def getHint(self, secret, guess): + """ + :type secret: str + :type guess: str + :rtype: str + """ + A = sum(imap(operator.eq, secret, guess)) + B = sum((Counter(secret) & Counter(guess)).values()) - A + return "%dA%dB" % (A, B) + From 45094467d7731723c76f5c60605ac09219a2fbae Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:25:20 +0800 Subject: [PATCH 1183/1939] Create bulls-and-cow.cpp --- C++/bulls-and-cow.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/bulls-and-cow.cpp diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cow.cpp new file mode 100644 index 000000000..f3c6efa7b --- /dev/null +++ b/C++/bulls-and-cow.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +//OSpace: O(10) = O(1) + +class Solution { +public: + string getHint(string secret, string guess) { + unordered_map lookup; + int A = 0, B = 0; + for (const auto& s : secret) { + ++lookup[s]; + } + for (const auto& g : guess) { + if (lookup[g]) { + --lookup[g]; + ++B; + } + } + for (int i = 0; i < secret.length() && i < guess.length(); ++i) { + if (secret[i] == guess[i]) { + ++A, --B; + } + } + return to_string(A).append("A").append(to_string(B).append("B")); + } +}; From 0fe1440d7b4bbd8be267cf5fc815ab3d1806be9a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:25:54 +0800 Subject: [PATCH 1184/1939] Update bulls-and-cow.cpp --- C++/bulls-and-cow.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cow.cpp index f3c6efa7b..d03061198 100644 --- a/C++/bulls-and-cow.cpp +++ b/C++/bulls-and-cow.cpp @@ -1,6 +1,7 @@ // Time: O(n) -//OSpace: O(10) = O(1) +// Space: O(10) = O(1) +// Two pass solution. class Solution { public: string getHint(string secret, string guess) { From 9d89ae50b0e5b2562ff9e1c1c36a0c195e318845 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:29:20 +0800 Subject: [PATCH 1185/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 55c609b36..13cc37604 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-298%20%2F%20298-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-299%20%2F%20299-ff69b4.svg) -Up to date (2015-10-28), there are `281` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-31), there are `282` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `298` questions. +Here is the classification of all `299` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -200,6 +200,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |📖|| 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || +299| [Word Pattern](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 0036534a06f1b26b8a42263f3840e487ce429278 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:30:01 +0800 Subject: [PATCH 1186/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 13cc37604..6fa090f4f 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |📖|| 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || -299| [Word Pattern](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| +299| [Bulls and Cow](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 3036c1a8de5a890d5b361b063437c0ea89206391 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:40:53 +0800 Subject: [PATCH 1187/1939] Update bulls-and-cow.cpp --- C++/bulls-and-cow.cpp | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cow.cpp index d03061198..fefbfc28e 100644 --- a/C++/bulls-and-cow.cpp +++ b/C++/bulls-and-cow.cpp @@ -1,8 +1,35 @@ // Time: O(n) // Space: O(10) = O(1) -// Two pass solution. +// One pass solution. class Solution { +public: + string getHint(string secret, string guess) { + unordered_map lookup, lookup_B; + int A = 0, B = 0; + for (const auto& s : secret) { + ++lookup[s]; + } + for (int i = 0; i < secret.length() && i < guess.length(); ++i) { + if (lookup[guess[i]]) { + --lookup[guess[i]]; + if (secret[i] == guess[i]) { + ++A; + } else { + ++lookup_B[guess[i]]; + ++B; + } + } else if (lookup_B[guess[i]] && secret[i] == guess[i]) { + --lookup_B[guess[i]]; + --B, ++A; + } + } + return to_string(A).append("A").append(to_string(B).append("B")); + } +}; + +// Two pass solution. +class Solution2 { public: string getHint(string secret, string guess) { unordered_map lookup; From ff45ea86809992ae90ed66da2f00935d00ea181f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:42:21 +0800 Subject: [PATCH 1188/1939] Update bulls-and-cow.py --- Python/bulls-and-cow.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/bulls-and-cow.py b/Python/bulls-and-cow.py index 3a895a191..21250a483 100644 --- a/Python/bulls-and-cow.py +++ b/Python/bulls-and-cow.py @@ -30,6 +30,7 @@ # digits, and their lengths are always equal. # +# Two pass solution. from collections import Counter from itertools import imap From 58c0eea20448c90255bf5960943974b169dde561 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:45:20 +0800 Subject: [PATCH 1189/1939] Update bulls-and-cow.cpp --- C++/bulls-and-cow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cow.cpp index fefbfc28e..292e398b6 100644 --- a/C++/bulls-and-cow.cpp +++ b/C++/bulls-and-cow.cpp @@ -28,7 +28,7 @@ class Solution { } }; -// Two pass solution. +// Three pass solution. class Solution2 { public: string getHint(string secret, string guess) { From daa3471a84000f84c5dfcb163d54c8c2f21ff750 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:45:53 +0800 Subject: [PATCH 1190/1939] Update bulls-and-cow.cpp --- C++/bulls-and-cow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cow.cpp index 292e398b6..fefbfc28e 100644 --- a/C++/bulls-and-cow.cpp +++ b/C++/bulls-and-cow.cpp @@ -28,7 +28,7 @@ class Solution { } }; -// Three pass solution. +// Two pass solution. class Solution2 { public: string getHint(string secret, string guess) { From 33e31d28663e2b4154c64a66c2ea29c38de48fbc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:54:31 +0800 Subject: [PATCH 1191/1939] Update bulls-and-cow.cpp --- C++/bulls-and-cow.cpp | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cow.cpp index fefbfc28e..c87d65010 100644 --- a/C++/bulls-and-cow.cpp +++ b/C++/bulls-and-cow.cpp @@ -5,24 +5,18 @@ class Solution { public: string getHint(string secret, string guess) { - unordered_map lookup, lookup_B; + unordered_map s_map, g_map; int A = 0, B = 0; - for (const auto& s : secret) { - ++lookup[s]; - } - for (int i = 0; i < secret.length() && i < guess.length(); ++i) { - if (lookup[guess[i]]) { - --lookup[guess[i]]; - if (secret[i] == guess[i]) { - ++A; - } else { - ++lookup_B[guess[i]]; - ++B; - } - } else if (lookup_B[guess[i]] && secret[i] == guess[i]) { - --lookup_B[guess[i]]; - --B, ++A; - } + const int n = min(secret.length(), guess.length()); + for (int i = 0; i < n; ++i) { + const char s = secret[i]; + const char g = guess[i]; + if (s == g) { + ++A; + } else { + (s_map[g] > 0) ? --s_map[g], ++B : ++g_map[g]; + (g_map[s] > 0) ? --g_map[s], ++B : ++s_map[s]; + } } return to_string(A).append("A").append(to_string(B).append("B")); } @@ -43,7 +37,8 @@ class Solution2 { ++B; } } - for (int i = 0; i < secret.length() && i < guess.length(); ++i) { + const int n = min(secret.length(), guess.length()); + for (int i = 0; i < n; ++i) { if (secret[i] == guess[i]) { ++A, --B; } From 330af19280ccd8de5fe2d93bde63156de78f0442 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 09:57:47 +0800 Subject: [PATCH 1192/1939] Update bulls-and-cow.cpp --- C++/bulls-and-cow.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cow.cpp index c87d65010..3b7db1c7e 100644 --- a/C++/bulls-and-cow.cpp +++ b/C++/bulls-and-cow.cpp @@ -5,7 +5,7 @@ class Solution { public: string getHint(string secret, string guess) { - unordered_map s_map, g_map; + unordered_map s_lookup, g_lookup; int A = 0, B = 0; const int n = min(secret.length(), guess.length()); for (int i = 0; i < n; ++i) { @@ -14,8 +14,8 @@ class Solution { if (s == g) { ++A; } else { - (s_map[g] > 0) ? --s_map[g], ++B : ++g_map[g]; - (g_map[s] > 0) ? --g_map[s], ++B : ++s_map[s]; + (s_lookup[g] > 0) ? --s_lookup[g], ++B : ++g_lookup[g]; + (g_lookup[s] > 0) ? --g_lookup[s], ++B : ++s_lookup[s]; } } return to_string(A).append("A").append(to_string(B).append("B")); From 840af0cfd7349765f5fa0ffac3d4ce31481f5d6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 10:09:24 +0800 Subject: [PATCH 1193/1939] Update bulls-and-cow.py --- Python/bulls-and-cow.py | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/Python/bulls-and-cow.py b/Python/bulls-and-cow.py index 21250a483..2b3d091cf 100644 --- a/Python/bulls-and-cow.py +++ b/Python/bulls-and-cow.py @@ -30,11 +30,42 @@ # digits, and their lengths are always equal. # +# One pass solution. +from collections import defaultdict +from itertools import izip + +class Solution(object): + def getHint(self, secret, guess): + """ + :type secret: str + :type guess: str + :rtype: str + """ + A, B = 0, 0 + s_lookup, g_lookup = defaultdict(int), defaultdict(int) + for s, g in izip(secret, guess): + if s == g: + A += 1 + else: + if s_lookup[g]: + s_lookup[g] -= 1 + B += 1 + else: + g_lookup[g] += 1 + if g_lookup[s]: + g_lookup[s] -= 1 + B += 1 + else: + s_lookup[s] += 1 + + return "%dA%dB" % (A, B) + + # Two pass solution. from collections import Counter from itertools import imap -class Solution(object): +class Solution2(object): def getHint(self, secret, guess): """ :type secret: str From f4b718e313f282d3cf8c790e8e4729d19b67cba3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 10:22:23 +0800 Subject: [PATCH 1194/1939] Update bulls-and-cow.cpp --- C++/bulls-and-cow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cow.cpp index 3b7db1c7e..21a490532 100644 --- a/C++/bulls-and-cow.cpp +++ b/C++/bulls-and-cow.cpp @@ -18,7 +18,7 @@ class Solution { (g_lookup[s] > 0) ? --g_lookup[s], ++B : ++s_lookup[s]; } } - return to_string(A).append("A").append(to_string(B).append("B")); + return to_string(A) + "A" + to_string(B) + "B"; } }; @@ -43,6 +43,6 @@ class Solution2 { ++A, --B; } } - return to_string(A).append("A").append(to_string(B).append("B")); + return to_string(A) + "A" + to_string(B) + "B"; } }; From b81e973b726e172f142d496000a26aee8c081253 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 10:27:20 +0800 Subject: [PATCH 1195/1939] Update bulls-and-cow.cpp --- C++/bulls-and-cow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cow.cpp index 21a490532..373ec2c6d 100644 --- a/C++/bulls-and-cow.cpp +++ b/C++/bulls-and-cow.cpp @@ -18,7 +18,7 @@ class Solution { (g_lookup[s] > 0) ? --g_lookup[s], ++B : ++s_lookup[s]; } } - return to_string(A) + "A" + to_string(B) + "B"; + return to_string(A).append("A").append(to_string(B)).append("B"); } }; @@ -43,6 +43,6 @@ class Solution2 { ++A, --B; } } - return to_string(A) + "A" + to_string(B) + "B"; + return to_string(A).append("A").append(to_string(B)).append("B"); } }; From 5ca15ee23900bec577d72d12fd2308db862ec2a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 31 Oct 2015 10:46:28 +0800 Subject: [PATCH 1196/1939] Update bulls-and-cow.py --- Python/bulls-and-cow.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/bulls-and-cow.py b/Python/bulls-and-cow.py index 2b3d091cf..b0c8849f4 100644 --- a/Python/bulls-and-cow.py +++ b/Python/bulls-and-cow.py @@ -1,7 +1,6 @@ # Time: O(n) # Space: O(10) = O(1) - # You are playing the following Bulls and Cows game with your friend: # You write a 4-digit secret number and ask your friend to guess it, # each time your friend guesses a number, you give a hint, the hint From d0d2997a25d8868388952157c444d4ba486edc2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Nov 2015 23:27:12 +0800 Subject: [PATCH 1197/1939] Create longest-increasing-subsequence.cpp --- C++/longest-increasing-subsequence.cpp | 38 ++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/longest-increasing-subsequence.cpp diff --git a/C++/longest-increasing-subsequence.cpp b/C++/longest-increasing-subsequence.cpp new file mode 100644 index 000000000..0de6550e1 --- /dev/null +++ b/C++/longest-increasing-subsequence.cpp @@ -0,0 +1,38 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector LIS; + + for (const auto& i : nums) { + insert(LIS, i); + } + + return LIS.size(); + } + +private: + void insert(vector& LIS, int target) { + int left = 0, right = LIS.size() - 1; + auto comp = [](int x, int target) { return x >= target; }; + + // Find the first index "left" which satisfies LIS[left] >= target + while (left <= right) { + int mid = left + (right - left) / 2; + if (comp(LIS[mid], target)) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + // If not found, append the target. + if (left == LIS.size()) { + LIS.emplace_back(target); + } else { + LIS[left] = target; + } + } +}; From 7d0097ff55a341a955b698de6661856de647264a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Nov 2015 23:29:10 +0800 Subject: [PATCH 1198/1939] Update longest-increasing-subsequence.cpp --- C++/longest-increasing-subsequence.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/longest-increasing-subsequence.cpp b/C++/longest-increasing-subsequence.cpp index 0de6550e1..29d92b3d9 100644 --- a/C++/longest-increasing-subsequence.cpp +++ b/C++/longest-increasing-subsequence.cpp @@ -6,22 +6,22 @@ class Solution { int lengthOfLIS(vector& nums) { vector LIS; - for (const auto& i : nums) { - insert(LIS, i); + for (const auto& num : nums) { + insert(&LIS, num); } return LIS.size(); } private: - void insert(vector& LIS, int target) { - int left = 0, right = LIS.size() - 1; + void insert(vector *LIS, const int target) { + int left = 0, right = LIS->size() - 1; auto comp = [](int x, int target) { return x >= target; }; // Find the first index "left" which satisfies LIS[left] >= target while (left <= right) { int mid = left + (right - left) / 2; - if (comp(LIS[mid], target)) { + if (comp((*LIS)[mid], target)) { right = mid - 1; } else { left = mid + 1; @@ -29,10 +29,10 @@ class Solution { } // If not found, append the target. - if (left == LIS.size()) { - LIS.emplace_back(target); + if (left == LIS->size()) { + LIS->emplace_back(target); } else { - LIS[left] = target; + (*LIS)[left] = target; } } }; From cf6fa09ad7f23f9c5c5b4594fcc93b7410a5e153 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Nov 2015 23:31:44 +0800 Subject: [PATCH 1199/1939] Update longest-increasing-subsequence.cpp --- C++/longest-increasing-subsequence.cpp | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/C++/longest-increasing-subsequence.cpp b/C++/longest-increasing-subsequence.cpp index 29d92b3d9..79154eb87 100644 --- a/C++/longest-increasing-subsequence.cpp +++ b/C++/longest-increasing-subsequence.cpp @@ -1,6 +1,7 @@ // Time: O(nlogn) // Space: O(n) +// Binary search solution with STL. class Solution { public: int lengthOfLIS(vector& nums) { @@ -13,6 +14,33 @@ class Solution { return LIS.size(); } +private: + void insert(vector *LIS, const int target) { + // Find the first index "left" which satisfies LIS[left] >= target + auto it = lower_bound(LIS->begin(), LIS->end(), target); + + // If not found, append the target. + if (it != LIS->end()) { + *it = target; + } else { + LIS->emplace_back(target); + } + } +}; + +// Binary search solution. +class Solution2 { +public: + int lengthOfLIS(vector& nums) { + vector LIS; + + for (const auto& num : nums) { + insert(&LIS, num); + } + + return LIS.size(); + } + private: void insert(vector *LIS, const int target) { int left = 0, right = LIS->size() - 1; From 3c029069c2e36e97b6d563cf0c974a2bfd1bdc7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Nov 2015 23:34:16 +0800 Subject: [PATCH 1200/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6fa090f4f..b2f178a6d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-299%20%2F%20299-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-300%20%2F%20300-ff69b4.svg) -Up to date (2015-10-31), there are `282` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-10-31), there are `283` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `299` questions. +Here is the classification of all `300` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -309,6 +309,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./C++/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || 275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | 278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy | LintCode || +300| [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | [C++](./C++/longest-increasing-subsequence.cpp) [Python](./Python/longest-increasing-subsequence.py) | _O(nlogn)_ | _O(n)_ | Medium | CTCI, LintCode || ## Binary Search Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note From a55365c9e743007822d54a55fccbe3c8522846b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Nov 2015 23:43:13 +0800 Subject: [PATCH 1201/1939] Create longest-increasing-subsequence.py --- Python/longest-increasing-subsequence.py | 44 ++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/longest-increasing-subsequence.py diff --git a/Python/longest-increasing-subsequence.py b/Python/longest-increasing-subsequence.py new file mode 100644 index 000000000..314c110f3 --- /dev/null +++ b/Python/longest-increasing-subsequence.py @@ -0,0 +1,44 @@ +# Time: O(nlogn) +# Space: O(n) +# +# Given an unsorted array of integers, +# find the length of longest increasing subsequence. +# +# For example, +# Given [10, 9, 2, 5, 3, 7, 101, 18], +# The longest increasing subsequence is [2, 3, 7, 101], +# therefore the length is 4. Note that there may be more +# than one LIS combination, it is only necessary for you to return the length. +# +# Your algorithm should run in O(n2) complexity. +# +# Follow up: Could you improve it to O(n log n) time complexity? +# + +# Binary search solution. +class Solution(object): + def lengthOfLIS(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + LIS = [] + def insert(target): + left, right = 0, len(LIS) - 1 + # Find the first index "left" which satisfies LIS[left] >= target + while left <= right: + mid = left + (right - left) / 2; + if LIS[mid] >= target: + right = mid - 1 + else: + left = mid + 1 + # If not found, append the target. + if left == len(LIS): + LIS.append(target); + else: + LIS[left] = target + + for num in nums: + insert(num) + + return len(LIS) From e73072808f468942bd3fdd9b6722a226d468c865 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Nov 2015 23:51:13 +0800 Subject: [PATCH 1202/1939] Update longest-increasing-subsequence.cpp --- C++/longest-increasing-subsequence.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/C++/longest-increasing-subsequence.cpp b/C++/longest-increasing-subsequence.cpp index 79154eb87..27fb853d6 100644 --- a/C++/longest-increasing-subsequence.cpp +++ b/C++/longest-increasing-subsequence.cpp @@ -64,3 +64,24 @@ class Solution2 { } } }; + +// Time: O(n^2) +// Space: O(n) +// Traditional DP solution. +class Solution3 { +public: + int lengthOfLIS(vector& nums) { + const int n = nums.size(); + vector dp(n, 1); + int res = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + dp[i] = max(dp[i], dp[j] + 1); + } + } + res = max(res, dp[i]); + } + return res; + } +}; From 62689752a41afeb0db63b95bab2af80abf81ff19 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Nov 2015 23:54:19 +0800 Subject: [PATCH 1203/1939] Update longest-increasing-subsequence.cpp --- C++/longest-increasing-subsequence.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-increasing-subsequence.cpp b/C++/longest-increasing-subsequence.cpp index 27fb853d6..6a705e2a8 100644 --- a/C++/longest-increasing-subsequence.cpp +++ b/C++/longest-increasing-subsequence.cpp @@ -72,7 +72,7 @@ class Solution3 { public: int lengthOfLIS(vector& nums) { const int n = nums.size(); - vector dp(n, 1); + vector dp(n, 1); // dp[i]: the length of LIS ends with nums[i] int res = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { From a6a2f4b999214e65745cdf1fc64c53c05bc32626 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Nov 2015 23:58:55 +0800 Subject: [PATCH 1204/1939] Update longest-increasing-subsequence.py --- Python/longest-increasing-subsequence.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Python/longest-increasing-subsequence.py b/Python/longest-increasing-subsequence.py index 314c110f3..5061c8998 100644 --- a/Python/longest-increasing-subsequence.py +++ b/Python/longest-increasing-subsequence.py @@ -42,3 +42,20 @@ def insert(target): insert(num) return len(LIS) + +# Time: O(n^2) +# Space: O(n) +# Traditional DP solution. +class Solution2(object): + def lengthOfLIS(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + dp = [] + for i in xrange(len(nums)): + dp.append(1) + for j in xrange(i): + if nums[j] < nums[i]: + dp[i] = max(dp[i], dp[j] + 1) + return max(dp) if dp else 0 From d1679fe516b59518411a4b0d1d7bbe1d2b35316b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Nov 2015 00:00:30 +0800 Subject: [PATCH 1205/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b2f178a6d..38407b16d 100644 --- a/README.md +++ b/README.md @@ -309,7 +309,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 222| [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [C++](./C++/count-complete-tree-nodes.cpp) [Python](./Python/count-complete-tree-nodes.py) | _O((logn)^2)_ | _O(1)_ | Medium || 275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | 278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy | LintCode || -300| [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | [C++](./C++/longest-increasing-subsequence.cpp) [Python](./Python/longest-increasing-subsequence.py) | _O(nlogn)_ | _O(n)_ | Medium | CTCI, LintCode || +300| [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | [C++](./C++/longest-increasing-subsequence.cpp) [Python](./Python/longest-increasing-subsequence.py) | _O(nlogn)_ | _O(n)_ | Medium | CTCI, LintCode | Binary Search, DP| ## Binary Search Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note From ce77bb2a4822e976b5bf60069224949bc60544a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Nov 2015 00:01:23 +0800 Subject: [PATCH 1206/1939] Update longest-increasing-subsequence.py --- Python/longest-increasing-subsequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/longest-increasing-subsequence.py b/Python/longest-increasing-subsequence.py index 5061c8998..596fffaaf 100644 --- a/Python/longest-increasing-subsequence.py +++ b/Python/longest-increasing-subsequence.py @@ -52,7 +52,7 @@ def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int """ - dp = [] + dp = [] # dp[i]: the length of LIS ends with nums[i] for i in xrange(len(nums)): dp.append(1) for j in xrange(i): From 036f11a4a1ea98489740f439355c1913a685d9c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Nov 2015 00:05:10 +0800 Subject: [PATCH 1207/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 38407b16d..ece90b071 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-300%20%2F%20300-ff69b4.svg) -Up to date (2015-10-31), there are `283` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-03), there are `283` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `300` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From ba13f8850ccb12efbc196e45dbc31e6c45c54257 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Nov 2015 01:26:18 +0800 Subject: [PATCH 1208/1939] Update longest-increasing-subsequence.cpp --- C++/longest-increasing-subsequence.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/longest-increasing-subsequence.cpp b/C++/longest-increasing-subsequence.cpp index 6a705e2a8..aff8c30bf 100644 --- a/C++/longest-increasing-subsequence.cpp +++ b/C++/longest-increasing-subsequence.cpp @@ -20,10 +20,10 @@ class Solution { auto it = lower_bound(LIS->begin(), LIS->end(), target); // If not found, append the target. - if (it != LIS->end()) { - *it = target; - } else { + if (it == LIS->end()) { LIS->emplace_back(target); + } else { + *it = target; } } }; From 42a1cb2588a0e6096ac20c709d14f06f4b364d6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 09:10:14 +0800 Subject: [PATCH 1209/1939] Update longest-valid-parentheses.py --- Python/longest-valid-parentheses.py | 49 +++++++++++++---------------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/Python/longest-valid-parentheses.py b/Python/longest-valid-parentheses.py index 559ce3e30..dd0376eb8 100644 --- a/Python/longest-valid-parentheses.py +++ b/Python/longest-valid-parentheses.py @@ -9,35 +9,28 @@ # Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. # -class Solution: - # @param s, a string - # @return an integer +class Solution(object): def longestValidParentheses(self, s): - longest = 0 - - start, depth = -1, 0 - for i in xrange(len(s)): - if s[i] == "(": - depth += 1 - else: - depth -= 1 - if depth < 0: - start, depth = i, 0 - elif depth == 0: - longest = max(longest, i - start) - - start, depth = len(s), 0 - for i in reversed(xrange(len(s))): - if s[i] == ")": - depth += 1 - else: - depth -= 1 - if depth < 0: - start, depth = i, 0 - elif depth == 0: - longest = max(longest, start - i) - - return longest + """ + :type s: str + :rtype: int + """ + def length(it, start, c): + depth, longest = 0, 0 + for i in it: + if s[i] == c: + depth += 1 + else: + depth -= 1 + if depth < 0: + start, depth = i, 0 + elif depth == 0: + longest = max(longest, abs(i - start)) + return longest + + return max(length(xrange(len(s)), -1, '('), \ + length(reversed(xrange(len(s))), len(s), ')')) + # Time: O(n) # Space: O(n) From 0c72477e4c8066bf27234938c34ad819b68aabca Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 10:21:34 +0800 Subject: [PATCH 1210/1939] Create remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 68 ++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 C++/remove-invalid-parentheses.cpp diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp new file mode 100644 index 000000000..4b2c56e3a --- /dev/null +++ b/C++/remove-invalid-parentheses.cpp @@ -0,0 +1,68 @@ +// DFS solution. +class Solution { +public: + vector removeInvalidParentheses(string s) { + // Calculate the minimum left and right parantheses to remove + int left_removed = 0, right_removed = 0; + for (const auto& c : s) { + if (c == '(') { + ++left_removed; + } else if (c == ')') { + if (!left_removed) { + ++right_removed; + } else { + --left_removed; + } + } + } + vector res; + removeInvalidParentheses(s, 0, left_removed, right_removed, &res); + return res; + } + + + void removeInvalidParentheses(const string& s, int start, + int left_removed, int right_removed, vector *res) { + + if (left_removed == 0 && right_removed == 0) { + if (isValid(s)) { + res->emplace_back(s); + } + return; + } + + for (int i = start; i < s.size(); ++i) { + string tmp = s; + if (right_removed == 0 && left_removed > 0 && tmp[i] == '(') { + if (i == start || tmp[i] != tmp[i - 1]) { // Skip duplicated. + tmp.erase(i, 1); + removeInvalidParentheses(tmp, i, left_removed - 1, right_removed, res); + } + } + if (right_removed > 0 && tmp[i] == ')') { + if (i == start || tmp[i] != tmp[i - 1]) { // Skip duplicated. + tmp.erase(i, 1); + removeInvalidParentheses(tmp, i, left_removed, right_removed - 1, res); + } + } + + } + } + +private: + // Check whether s is valid or not. + bool isValid(string s) { + int sum = 0; + for (const auto &c : s) { + if (c == '(') { + ++sum; + } else if (c == ')') { + --sum; + } + if (sum < 0) { + return false; + } + } + return sum == 0; + } +}; From ef19bf318ff394bc0794206506bfc385c88e866d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 10:24:11 +0800 Subject: [PATCH 1211/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index 4b2c56e3a..a9f96eea5 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -1,3 +1,6 @@ +// Time: O(n * 2^n) +// Space: O(n^2) + // DFS solution. class Solution { public: From 862e7850dd8204023c88e590dcfd10d48323340f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 10:25:37 +0800 Subject: [PATCH 1212/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index a9f96eea5..7853a5be0 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -1,5 +1,5 @@ -// Time: O(n * 2^n) -// Space: O(n^2) +// Time: O(n * 2^n), try out all possible substrings +// Space: O(n^2), the depth is at most n, and it costs n at each depth // DFS solution. class Solution { From a9f86e9966334ae9a389db70992e6161f1bca185 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 10:28:05 +0800 Subject: [PATCH 1213/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ece90b071..850c47490 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-300%20%2F%20300-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-301%20%2F%20301-ff69b4.svg) -Up to date (2015-11-03), there are `283` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-05), there are `284` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `300` questions. +Here is the classification of all `301` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -361,6 +361,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| 291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| +301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(n * 2^n)_ | _O(n^2)_ | Medium ||| ## Dynamic Programming # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 10241379ae793a6791a489be5289fc3df89e9a67 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 10:54:06 +0800 Subject: [PATCH 1214/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 850c47490..94ec7f965 100644 --- a/README.md +++ b/README.md @@ -361,7 +361,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| 291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| -301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(n * 2^n)_ | _O(n^2)_ | Medium ||| +301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(C(n, c))_ | _O(c)_ | Medium ||| ## Dynamic Programming # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 5c2be688169a96e705a69a8e647ef24dab287cc2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 10:54:57 +0800 Subject: [PATCH 1215/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index 7853a5be0..7b5c1c296 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -1,4 +1,4 @@ -// Time: O(n * 2^n), try out all possible substrings +// Time: O(n * C(n, c)), try out all possible substrings with the minimum c deletion. // Space: O(n^2), the depth is at most n, and it costs n at each depth // DFS solution. From a672beea1e336db39d9687f7c4749c013b978e61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 11:11:20 +0800 Subject: [PATCH 1216/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index 7b5c1c296..8ce4a17f2 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -34,7 +34,7 @@ class Solution { return; } - for (int i = start; i < s.size(); ++i) { + for (int i = start; i < s.length(); ++i) { string tmp = s; if (right_removed == 0 && left_removed > 0 && tmp[i] == '(') { if (i == start || tmp[i] != tmp[i - 1]) { // Skip duplicated. From 11fca963f02b746bc67369cdece72110cf059a2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 11:17:38 +0800 Subject: [PATCH 1217/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index 8ce4a17f2..559c8af54 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -1,5 +1,5 @@ // Time: O(n * C(n, c)), try out all possible substrings with the minimum c deletion. -// Space: O(n^2), the depth is at most n, and it costs n at each depth +// Space: O(n * c), the depth is at most c, and it costs n at each depth // DFS solution. class Solution { From 4737c8639e6aee62d9f9e613ce46bbee86676e39 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 11:20:54 +0800 Subject: [PATCH 1218/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index 559c8af54..a5400f3fc 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -35,15 +35,16 @@ class Solution { } for (int i = start; i < s.length(); ++i) { - string tmp = s; - if (right_removed == 0 && left_removed > 0 && tmp[i] == '(') { - if (i == start || tmp[i] != tmp[i - 1]) { // Skip duplicated. + if (right_removed == 0 && left_removed > 0 && s[i] == '(') { + if (i == start || s[i] != s[i - 1]) { // Skip duplicated. + string tmp = s; tmp.erase(i, 1); removeInvalidParentheses(tmp, i, left_removed - 1, right_removed, res); } } - if (right_removed > 0 && tmp[i] == ')') { - if (i == start || tmp[i] != tmp[i - 1]) { // Skip duplicated. + if (right_removed > 0 && s[i] == ')') { + if (i == start || s[i] != s[i - 1]) { // Skip duplicated. + string tmp = s; tmp.erase(i, 1); removeInvalidParentheses(tmp, i, left_removed, right_removed - 1, res); } From 7ebce9ef8de5e8c97b58ffcf374be85e6ddc935a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 11:30:55 +0800 Subject: [PATCH 1219/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index a5400f3fc..b3966f866 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -41,8 +41,7 @@ class Solution { tmp.erase(i, 1); removeInvalidParentheses(tmp, i, left_removed - 1, right_removed, res); } - } - if (right_removed > 0 && s[i] == ')') { + } else if (right_removed > 0 && s[i] == ')') { if (i == start || s[i] != s[i - 1]) { // Skip duplicated. string tmp = s; tmp.erase(i, 1); From 08dcba7ec3dcb32aa37d1d6e1a5a2bce12ae9dd0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 11:37:22 +0800 Subject: [PATCH 1220/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 87 +++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 2 deletions(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index b3966f866..74001506a 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -1,8 +1,91 @@ -// Time: O(n * C(n, c)), try out all possible substrings with the minimum c deletion. -// Space: O(n * c), the depth is at most c, and it costs n at each depth +// Time: O(C(n, c)), try out all possible substrings with the minimum c deletion. +// Space: O(c), the depth is at most c, and it costs n at each depth // DFS solution. class Solution { +public: + vector removeInvalidParentheses(string s) { + // Calculate the minimum left and right parantheses to remove + int left_removed = 0, right_removed = 0; + for (const auto& c : s) { + if (c == '(') { + ++left_removed; + } else if (c == ')') { + if (!left_removed) { + ++right_removed; + } else { + --left_removed; + } + } + } + vector res; + vector removed; + removeInvalidParentheses(s, 0, left_removed, right_removed, &removed, &res); + return res; + } + + + void removeInvalidParentheses(const string& s, int start, + int left_removed, int right_removed, + vector *removed, vector *res) { + + if (left_removed == 0 && right_removed == 0) { + string tmp; + for (int i = 0, j = 0; i < s.length(); ++i) { + if (j < removed->size() && i == (*removed)[j]) { + ++j; + } else { + tmp.push_back(s[i]); + } + } + if (isValid(tmp)) { + res->emplace_back(tmp); + } + return; + } + + for (int i = start; i < s.length(); ++i) { + if (right_removed == 0 && left_removed > 0 && s[i] == '(') { + if (i == start || s[i] != s[i - 1]) { // Skip duplicated. + removed->emplace_back(i); + removeInvalidParentheses(s, i + 1, left_removed - 1, right_removed, + removed, res); + removed->pop_back(); + } + } else if (right_removed > 0 && s[i] == ')') { + if (i == start || s[i] != s[i - 1]) { // Skip duplicated. + removed->emplace_back(i); + removeInvalidParentheses(s, i + 1, left_removed, right_removed - 1, + removed, res); + removed->pop_back(); + } + } + + } + } + +private: + // Check whether s is valid or not. + bool isValid(string s) { + int sum = 0; + for (const auto &c : s) { + if (c == '(') { + ++sum; + } else if (c == ')') { + --sum; + } + if (sum < 0) { + return false; + } + } + return sum == 0; + } +}; + +// Time: O(n * C(n, c)), try out all possible substrings with the minimum c deletion. +// Space: O(n * c), the depth is at most c, and it costs n at each depth +// DFS solution. +class Solution2 { public: vector removeInvalidParentheses(string s) { // Calculate the minimum left and right parantheses to remove From 49157b50617b770acaac91653fc184b19fbf0471 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 11:38:25 +0800 Subject: [PATCH 1221/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index 74001506a..ec4cc4088 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -24,7 +24,6 @@ class Solution { return res; } - void removeInvalidParentheses(const string& s, int start, int left_removed, int right_removed, vector *removed, vector *res) { From 15ed06a151710d7a48831bf1e7f9ad1a55b20fb4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 11:46:37 +0800 Subject: [PATCH 1222/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index ec4cc4088..e89c36b3c 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -19,21 +19,19 @@ class Solution { } } vector res; - vector removed; + unordered_set removed; removeInvalidParentheses(s, 0, left_removed, right_removed, &removed, &res); return res; } void removeInvalidParentheses(const string& s, int start, int left_removed, int right_removed, - vector *removed, vector *res) { + unordered_set *removed, vector *res) { if (left_removed == 0 && right_removed == 0) { string tmp; for (int i = 0, j = 0; i < s.length(); ++i) { - if (j < removed->size() && i == (*removed)[j]) { - ++j; - } else { + if (!removed->count(i)) { tmp.push_back(s[i]); } } @@ -46,17 +44,17 @@ class Solution { for (int i = start; i < s.length(); ++i) { if (right_removed == 0 && left_removed > 0 && s[i] == '(') { if (i == start || s[i] != s[i - 1]) { // Skip duplicated. - removed->emplace_back(i); + removed->emplace(i); removeInvalidParentheses(s, i + 1, left_removed - 1, right_removed, removed, res); - removed->pop_back(); + removed->erase(i); } } else if (right_removed > 0 && s[i] == ')') { if (i == start || s[i] != s[i - 1]) { // Skip duplicated. - removed->emplace_back(i); + removed->emplace(i); removeInvalidParentheses(s, i + 1, left_removed, right_removed - 1, removed, res); - removed->pop_back(); + removed->erase(i); } } @@ -81,6 +79,7 @@ class Solution { } }; + // Time: O(n * C(n, c)), try out all possible substrings with the minimum c deletion. // Space: O(n * c), the depth is at most c, and it costs n at each depth // DFS solution. From 30201be078719c42cb050c3447520c25a3790bb5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 13:32:42 +0800 Subject: [PATCH 1223/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index e89c36b3c..0d18a96cd 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -30,7 +30,7 @@ class Solution { if (left_removed == 0 && right_removed == 0) { string tmp; - for (int i = 0, j = 0; i < s.length(); ++i) { + for (int i = 0; i < s.length(); ++i) { if (!removed->count(i)) { tmp.push_back(s[i]); } From 14cbe1eaef6d7aa029460e90933872d70c58ef3e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 13:39:16 +0800 Subject: [PATCH 1224/1939] Create remove-invalid-parentheses.py --- Python/remove-invalid-parentheses.py | 73 ++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Python/remove-invalid-parentheses.py diff --git a/Python/remove-invalid-parentheses.py b/Python/remove-invalid-parentheses.py new file mode 100644 index 000000000..35504e3ca --- /dev/null +++ b/Python/remove-invalid-parentheses.py @@ -0,0 +1,73 @@ +# Time: O(C(n, c)), try out all possible substrings with the minimum c deletion. +# Space: O(c), the depth is at most c, and it costs n at each depth +# +# Remove the minimum number of invalid parentheses in order to +# make the input string valid. Return all possible results. +# +# Note: The input string may contain letters other than the +# parentheses ( and ). +# +# Examples: +# "()())()" -> ["()()()", "(())()"] +# "(a)())()" -> ["(a)()()", "(a())()"] +# ")(" -> [""] +# + +# DFS solution. +class Solution(object): + def removeInvalidParentheses(self, s): + """ + :type s: str + :rtype: List[str] + """ + # Calculate the minimum left and right parantheses to remove + def findMinRemove(s): + left_removed, right_removed = 0, 0 + for c in s: + if c == '(': + left_removed += 1 + elif c == ')': + if not left_removed: + right_removed += 1 + else: + left_removed -= 1 + return (left_removed, right_removed) + + # Check whether s is valid or not. + def isValid(s): + sum = 0 + for c in s: + if c == '(': + sum += 1 + elif c == ')': + sum -= 1 + if sum < 0: + return False + return sum == 0 + + def removeInvalidParenthesesHelper(start, left_removed, right_removed): + if left_removed == 0 and right_removed == 0: + tmp = "" + for i, c in enumerate(s): + if i not in removed: + tmp += c + if isValid(tmp): + res.append(tmp) + return + + for i in xrange(start, len(s)): + if right_removed == 0 and left_removed > 0 and s[i] == '(': + if i == start or s[i] != s[i - 1]: # Skip duplicated. + removed[i] = True + removeInvalidParenthesesHelper(i + 1, left_removed - 1, right_removed) + del removed[i] + elif right_removed > 0 and s[i] == ')': + if i == start or s[i] != s[i - 1]: # Skip duplicated. + removed[i] = True + removeInvalidParenthesesHelper(i + 1, left_removed, right_removed - 1); + del removed[i] + + res, removed = [], {} + (left_removed, right_removed) = findMinRemove(s) + removeInvalidParenthesesHelper(0, left_removed, right_removed) + return res From 2a123946a444220977703b1873bd3a063453d2aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 13:40:23 +0800 Subject: [PATCH 1225/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index 0d18a96cd..2878e6280 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -20,11 +20,11 @@ class Solution { } vector res; unordered_set removed; - removeInvalidParentheses(s, 0, left_removed, right_removed, &removed, &res); + removeInvalidParenthesesHelper(s, 0, left_removed, right_removed, &removed, &res); return res; } - void removeInvalidParentheses(const string& s, int start, + void removeInvalidParenthesesHelper(const string& s, int start, int left_removed, int right_removed, unordered_set *removed, vector *res) { @@ -45,15 +45,15 @@ class Solution { if (right_removed == 0 && left_removed > 0 && s[i] == '(') { if (i == start || s[i] != s[i - 1]) { // Skip duplicated. removed->emplace(i); - removeInvalidParentheses(s, i + 1, left_removed - 1, right_removed, - removed, res); + removeInvalidParenthesesHelper(s, i + 1, left_removed - 1, right_removed, + removed, res); removed->erase(i); } } else if (right_removed > 0 && s[i] == ')') { if (i == start || s[i] != s[i - 1]) { // Skip duplicated. removed->emplace(i); - removeInvalidParentheses(s, i + 1, left_removed, right_removed - 1, - removed, res); + removeInvalidParenthesesHelper(s, i + 1, left_removed, right_removed - 1, + removed, res); removed->erase(i); } } @@ -100,12 +100,12 @@ class Solution2 { } } vector res; - removeInvalidParentheses(s, 0, left_removed, right_removed, &res); + removeInvalidParenthesesHelper(s, 0, left_removed, right_removed, &res); return res; } - void removeInvalidParentheses(const string& s, int start, + void removeInvalidParenthesesHelper(const string& s, int start, int left_removed, int right_removed, vector *res) { if (left_removed == 0 && right_removed == 0) { @@ -120,13 +120,13 @@ class Solution2 { if (i == start || s[i] != s[i - 1]) { // Skip duplicated. string tmp = s; tmp.erase(i, 1); - removeInvalidParentheses(tmp, i, left_removed - 1, right_removed, res); + removeInvalidParenthesesHelper(tmp, i, left_removed - 1, right_removed, res); } } else if (right_removed > 0 && s[i] == ')') { if (i == start || s[i] != s[i - 1]) { // Skip duplicated. string tmp = s; tmp.erase(i, 1); - removeInvalidParentheses(tmp, i, left_removed, right_removed - 1, res); + removeInvalidParenthesesHelper(tmp, i, left_removed, right_removed - 1, res); } } From 05e6df60101b88c0be97bc7beacde20df49963d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 13:44:32 +0800 Subject: [PATCH 1226/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 49 ++++++++++++++++++------------ 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index 2878e6280..e9b8c64b3 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -5,23 +5,29 @@ class Solution { public: vector removeInvalidParentheses(string s) { - // Calculate the minimum left and right parantheses to remove int left_removed = 0, right_removed = 0; + findMinRemove(s, &left_removed, &right_removed); + + vector res; + unordered_set removed; + removeInvalidParenthesesHelper(s, 0, left_removed, right_removed, &removed, &res); + return res; + } + +private: + void findMinRemove(const string& s, int *left_removed, int *right_removed) { + // Calculate the minimum left and right parantheses to remove. for (const auto& c : s) { if (c == '(') { - ++left_removed; + ++(*left_removed); } else if (c == ')') { - if (!left_removed) { - ++right_removed; + if (!(*left_removed)) { + ++(*right_removed); } else { - --left_removed; + --(*left_removed); } } } - vector res; - unordered_set removed; - removeInvalidParenthesesHelper(s, 0, left_removed, right_removed, &removed, &res); - return res; } void removeInvalidParenthesesHelper(const string& s, int start, @@ -61,7 +67,6 @@ class Solution { } } -private: // Check whether s is valid or not. bool isValid(string s) { int sum = 0; @@ -86,25 +91,30 @@ class Solution { class Solution2 { public: vector removeInvalidParentheses(string s) { - // Calculate the minimum left and right parantheses to remove int left_removed = 0, right_removed = 0; + findMinRemove(s, &left_removed, &right_removed); + + vector res; + removeInvalidParenthesesHelper(s, 0, left_removed, right_removed, &res); + return res; + } + + void findMinRemove(const string& s, int *left_removed, int *right_removed) { + // Calculate the minimum left and right parantheses to remove. for (const auto& c : s) { if (c == '(') { - ++left_removed; + ++(*left_removed); } else if (c == ')') { - if (!left_removed) { - ++right_removed; + if (!(*left_removed)) { + ++(*right_removed); } else { - --left_removed; + --(*left_removed); } } } - vector res; - removeInvalidParenthesesHelper(s, 0, left_removed, right_removed, &res); - return res; } - +private: void removeInvalidParenthesesHelper(const string& s, int start, int left_removed, int right_removed, vector *res) { @@ -133,7 +143,6 @@ class Solution2 { } } -private: // Check whether s is valid or not. bool isValid(string s) { int sum = 0; From 3ed20ca05b4d2139c202eab3d51b17f6028a738b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 13:51:47 +0800 Subject: [PATCH 1227/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 94 +++++++++++++++++++++++++++++- 1 file changed, 91 insertions(+), 3 deletions(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index e9b8c64b3..ea87c7cd4 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -1,13 +1,101 @@ // Time: O(C(n, c)), try out all possible substrings with the minimum c deletion. // Space: O(c), the depth is at most c, and it costs n at each depth -// DFS solution. +// DFS solution. (4ms) class Solution { public: vector removeInvalidParentheses(string s) { int left_removed = 0, right_removed = 0; findMinRemove(s, &left_removed, &right_removed); + vector res; + vector removed; + removeInvalidParenthesesHelper(s, 0, left_removed, right_removed, &removed, &res); + return res; + } + +private: + void findMinRemove(const string& s, int *left_removed, int *right_removed) { + // Calculate the minimum left and right parantheses to remove. + for (const auto& c : s) { + if (c == '(') { + ++(*left_removed); + } else if (c == ')') { + if (!(*left_removed)) { + ++(*right_removed); + } else { + --(*left_removed); + } + } + } + } + + void removeInvalidParenthesesHelper(const string& s, int start, + int left_removed, int right_removed, + vector *removed, vector *res) { + + if (left_removed == 0 && right_removed == 0) { + string tmp; + for (int i = 0, j = 0; i < s.length(); ++i) { + if (j < removed->size() && i == (*removed)[j]) { + ++j; + } else { + tmp.push_back(s[i]); + } + } + if (isValid(tmp)) { + res->emplace_back(tmp); + } + return; + } + + for (int i = start; i < s.length(); ++i) { + if (right_removed == 0 && left_removed > 0 && s[i] == '(') { + if (i == start || s[i] != s[i - 1]) { // Skip duplicated. + removed->emplace_back(i); + removeInvalidParenthesesHelper(s, i + 1, left_removed - 1, right_removed, + removed, res); + removed->pop_back(); + } + } else if (right_removed > 0 && s[i] == ')') { + if (i == start || s[i] != s[i - 1]) { // Skip duplicated. + removed->emplace_back(i); + removeInvalidParenthesesHelper(s, i + 1, left_removed, right_removed - 1, + removed, res); + removed->pop_back(); + } + } + + } + } + + // Check whether s is valid or not. + bool isValid(string s) { + int sum = 0; + for (const auto &c : s) { + if (c == '(') { + ++sum; + } else if (c == ')') { + --sum; + } + if (sum < 0) { + return false; + } + } + return sum == 0; + } +}; + +// Time: O(C(n, c)), try out all possible substrings with the minimum c deletion. +// Space: O(c), the depth is at most c, and it costs n at each depth + +// DFS solution. (8ms) +class Solution2 { +public: + vector removeInvalidParentheses(string s) { + int left_removed = 0, right_removed = 0; + findMinRemove(s, &left_removed, &right_removed); + vector res; unordered_set removed; removeInvalidParenthesesHelper(s, 0, left_removed, right_removed, &removed, &res); @@ -87,8 +175,8 @@ class Solution { // Time: O(n * C(n, c)), try out all possible substrings with the minimum c deletion. // Space: O(n * c), the depth is at most c, and it costs n at each depth -// DFS solution. -class Solution2 { +// DFS solution. (4ms) +class Solution3 { public: vector removeInvalidParentheses(string s) { int left_removed = 0, right_removed = 0; From 28f3689533cf0bad4aa66170db1afa55a79f174a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Nov 2015 13:52:47 +0800 Subject: [PATCH 1228/1939] Update remove-invalid-parentheses.cpp --- C++/remove-invalid-parentheses.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/remove-invalid-parentheses.cpp b/C++/remove-invalid-parentheses.cpp index ea87c7cd4..31242b26c 100644 --- a/C++/remove-invalid-parentheses.cpp +++ b/C++/remove-invalid-parentheses.cpp @@ -1,7 +1,7 @@ // Time: O(C(n, c)), try out all possible substrings with the minimum c deletion. // Space: O(c), the depth is at most c, and it costs n at each depth -// DFS solution. (4ms) +// DFS solution with removed array. (4ms) class Solution { public: vector removeInvalidParentheses(string s) { @@ -88,8 +88,7 @@ class Solution { // Time: O(C(n, c)), try out all possible substrings with the minimum c deletion. // Space: O(c), the depth is at most c, and it costs n at each depth - -// DFS solution. (8ms) +// DFS solution with removed hash. (8ms) class Solution2 { public: vector removeInvalidParentheses(string s) { From 7dde86ee8be5a757462facd9bfcfe52b915e37d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Nov 2015 22:56:50 +0800 Subject: [PATCH 1229/1939] Create smallest-rectangle-enclosing-black-pixels.py --- ...allest-rectangle-enclosing-black-pixels.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/smallest-rectangle-enclosing-black-pixels.py diff --git a/Python/smallest-rectangle-enclosing-black-pixels.py b/Python/smallest-rectangle-enclosing-black-pixels.py new file mode 100644 index 000000000..ec8cb98b6 --- /dev/null +++ b/Python/smallest-rectangle-enclosing-black-pixels.py @@ -0,0 +1,29 @@ +# Time: O(nlogn) +# Space: O(1) + +class Solution(object): + def minArea(self, image, x, y): + """ + :type image: List[List[str]] + :type x: int + :type y: int + :rtype: int + """ + def binarySearch(image, left, right, find, has_one): + while left <= right: # O(logn) times + mid = left + (right - left) / 2 + if find(mid, image, has_one): # Time: O(n) + right = mid - 1 + else: + left = mid + 1 + return left + + + searchColumns = lambda mid, image, has_one: any([int(row[mid]) for row in image]) == has_one + left = binarySearch(image, 0, y - 1, searchColumns, True) + right = binarySearch(image, y + 1, len(image[0]) - 1, searchColumns, False) + + searchRows = lambda mid, image, has_one: any(itertools.imap(int, image[mid])) == has_one + top = binarySearch(image, 0, x - 1, searchRows, True) + bottom = binarySearch(image, x + 1, len(image) - 1, searchRows, False) + return (right - left) * (bottom - top) From 857cbb26204ab10ca7e46c1b2466633d0ed811da Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Nov 2015 22:59:19 +0800 Subject: [PATCH 1230/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 94ec7f965..27872fbc9 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-301%20%2F%20301-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-302%20%2F%20302-ff69b4.svg) -Up to date (2015-11-05), there are `284` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-07), there are `285` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `301` questions. +Here is the classification of all `302` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -310,6 +310,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 275| [H-Index II](https://leetcode.com/problems/h-index-ii/) | [C++](./C++/h-index-ii.cpp) [Python](./Python/h-index-ii.py) | _O(logn)_ | _O(1)_ | Medium || Binary Search | 278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | [C++](./C++/first-bad-version.cpp) [Python](./Python/first-bad-version.py) | _O(logn)_ | _O(1)_ | Easy | LintCode || 300| [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | [C++](./C++/longest-increasing-subsequence.cpp) [Python](./Python/longest-increasing-subsequence.py) | _O(nlogn)_ | _O(n)_ | Medium | CTCI, LintCode | Binary Search, DP| +302| [Smallest Rectangle Enclosing Black Pixels](https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/)| [C++](./C++/smallest-rectangle-enclosing-black-pixels.cpp) [Python](./Python/smallest-rectangle-enclosing-black-pixels.py) | _O(nlogn)_ | _O(1)_ | Medium | 📖 | ## Binary Search Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 299d50b97636fb640d2992f75de10b8f8bb01ff5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Nov 2015 23:25:00 +0800 Subject: [PATCH 1231/1939] Create smallest-rectangle-enclosing-black-pixels.cpp --- ...llest-rectangle-enclosing-black-pixels.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 C++/smallest-rectangle-enclosing-black-pixels.cpp diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp new file mode 100644 index 000000000..42f6d3551 --- /dev/null +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -0,0 +1,52 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + int minArea(vector>& image, int x, int y) { + const auto searchColumns = + [](const int mid, const vector>& image, bool has_one) { + auto it = image.cbegin(); + for (; it < image.cend(); ++it) { + if ((*it)[mid] == '1') { + break; + } + } + return (it < image.cend()) == has_one; + }; + const int left = binarySearch(image, 0, y - 1, searchColumns, true); + const int right = binarySearch(image, y + 1, int(image[0].size()) - 1, searchColumns, false); + + const auto searchRows = + [](const int mid, const vector>& image, bool has_one) { + auto it = image[mid].cbegin(); + for (; it < image[mid].cend(); ++it) { + if (*it == '1') { + break; + } + } + return (it < image[mid].cend()) == has_one; + }; + const int top = binarySearch(image, 0, x - 1, searchRows, true); + const int bottom = binarySearch(image, x + 1, int(image.size()) - 1, searchRows, false); + + return (right - left) * (bottom - top); + } + + private: + int binarySearch(const vector>& image, int left, int right, + const function>& image, + bool has_one)>& find, + bool has_one) { + while (left <= right) { + const int mid = left + (right - left) / 2; + if (find(mid, image, has_one)) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } +}; From 06dc26868f4ee2ffec31eb0abf40d15acb433241 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Nov 2015 23:39:45 +0800 Subject: [PATCH 1232/1939] Update smallest-rectangle-enclosing-black-pixels.cpp --- ...allest-rectangle-enclosing-black-pixels.cpp | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp index 42f6d3551..97274f6c2 100644 --- a/C++/smallest-rectangle-enclosing-black-pixels.cpp +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -6,26 +6,16 @@ class Solution { int minArea(vector>& image, int x, int y) { const auto searchColumns = [](const int mid, const vector>& image, bool has_one) { - auto it = image.cbegin(); - for (; it < image.cend(); ++it) { - if ((*it)[mid] == '1') { - break; - } - } - return (it < image.cend()) == has_one; + return has_one == any_of(image.cbegin(), image.cend(), + [=](const vector& row) { return row[mid] == '1'; }); }; const int left = binarySearch(image, 0, y - 1, searchColumns, true); const int right = binarySearch(image, y + 1, int(image[0].size()) - 1, searchColumns, false); const auto searchRows = [](const int mid, const vector>& image, bool has_one) { - auto it = image[mid].cbegin(); - for (; it < image[mid].cend(); ++it) { - if (*it == '1') { - break; - } - } - return (it < image[mid].cend()) == has_one; + return has_one == any_of(image[mid].cbegin(), image[mid].cend(), + [](const char& col) { return col == '1'; }); }; const int top = binarySearch(image, 0, x - 1, searchRows, true); const int bottom = binarySearch(image, x + 1, int(image.size()) - 1, searchRows, false); From 6936c363c39fac040802bdfdd7a173d3ee56b7d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Nov 2015 23:42:43 +0800 Subject: [PATCH 1233/1939] Update smallest-rectangle-enclosing-black-pixels.cpp --- C++/smallest-rectangle-enclosing-black-pixels.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp index 97274f6c2..532c8054d 100644 --- a/C++/smallest-rectangle-enclosing-black-pixels.cpp +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -23,7 +23,7 @@ class Solution { return (right - left) * (bottom - top); } - private: +private: int binarySearch(const vector>& image, int left, int right, const function>& image, From 59ad80704401a800bfe7758ab259b8f235a01b34 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Nov 2015 00:08:42 +0800 Subject: [PATCH 1234/1939] Update smallest-rectangle-enclosing-black-pixels.cpp --- C++/smallest-rectangle-enclosing-black-pixels.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp index 532c8054d..8963ddd3d 100644 --- a/C++/smallest-rectangle-enclosing-black-pixels.cpp +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -25,9 +25,7 @@ class Solution { private: int binarySearch(const vector>& image, int left, int right, - const function>& image, - bool has_one)>& find, + const function>&, bool)>& find, bool has_one) { while (left <= right) { const int mid = left + (right - left) / 2; From a491f397a74c177887faebe7b688c4c3653c45a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Nov 2015 00:17:01 +0800 Subject: [PATCH 1235/1939] Update smallest-rectangle-enclosing-black-pixels.cpp --- ...llest-rectangle-enclosing-black-pixels.cpp | 49 ++++++++++++++++++- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp index 8963ddd3d..48f381bf1 100644 --- a/C++/smallest-rectangle-enclosing-black-pixels.cpp +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -2,6 +2,51 @@ // Space: O(1) class Solution { +public: + int minArea(vector>& image, int x, int y) { + using namespace std::placeholders; // for _1, _2, _3... + + const auto searchColumns = + [](const vector>& image, bool has_one, const int mid) { + return has_one == any_of(image.cbegin(), image.cend(), + [=](const vector& row) { return row[mid] == '1'; }); + }; + const auto searchRows = + [](const vector>& image, bool has_one, const int mid) { + return has_one == any_of(image[mid].cbegin(), image[mid].cend(), + [](const char& col) { return col == '1'; }); + }; + + function findLeft = bind(searchColumns, image, true, _1); + const int left = binarySearch(0, y - 1, findLeft); + + function findRight = bind(searchColumns, image, false, _1); + const int right = binarySearch(y + 1, image[0].size() - 1, findRight); + + function findTop = bind(searchRows, image, true, _1); + const int top = binarySearch(0, x - 1, findTop); + + function findBottom = bind(searchRows, image, false, _1); + const int bottom = binarySearch(x + 1, image.size() - 1, findBottom); + + return (right - left) * (bottom - top); + } + +private: + int binarySearch(int left, int right, function& find) { + while (left <= right) { + const int mid = left + (right - left) / 2; + if (find(mid)) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } +}; + +class Solution2 { public: int minArea(vector>& image, int x, int y) { const auto searchColumns = @@ -10,7 +55,7 @@ class Solution { [=](const vector& row) { return row[mid] == '1'; }); }; const int left = binarySearch(image, 0, y - 1, searchColumns, true); - const int right = binarySearch(image, y + 1, int(image[0].size()) - 1, searchColumns, false); + const int right = binarySearch(image, y + 1, image[0].size() - 1, searchColumns, false); const auto searchRows = [](const int mid, const vector>& image, bool has_one) { @@ -18,7 +63,7 @@ class Solution { [](const char& col) { return col == '1'; }); }; const int top = binarySearch(image, 0, x - 1, searchRows, true); - const int bottom = binarySearch(image, x + 1, int(image.size()) - 1, searchRows, false); + const int bottom = binarySearch(image, x + 1, image.size() - 1, searchRows, false); return (right - left) * (bottom - top); } From 4a12a04c3f56165db1e68a0d467d8e9ac5c90e1e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Nov 2015 00:21:21 +0800 Subject: [PATCH 1236/1939] Update smallest-rectangle-enclosing-black-pixels.cpp --- C++/smallest-rectangle-enclosing-black-pixels.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp index 48f381bf1..71b278426 100644 --- a/C++/smallest-rectangle-enclosing-black-pixels.cpp +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -50,7 +50,7 @@ class Solution2 { public: int minArea(vector>& image, int x, int y) { const auto searchColumns = - [](const int mid, const vector>& image, bool has_one) { + [](const vector>& image, bool has_one, const int mid) { return has_one == any_of(image.cbegin(), image.cend(), [=](const vector& row) { return row[mid] == '1'; }); }; @@ -58,7 +58,7 @@ class Solution2 { const int right = binarySearch(image, y + 1, image[0].size() - 1, searchColumns, false); const auto searchRows = - [](const int mid, const vector>& image, bool has_one) { + [](const vector>& image, bool has_one, const int mid) { return has_one == any_of(image[mid].cbegin(), image[mid].cend(), [](const char& col) { return col == '1'; }); }; @@ -70,11 +70,11 @@ class Solution2 { private: int binarySearch(const vector>& image, int left, int right, - const function>&, bool)>& find, + const function>&, bool, const int)>& find, bool has_one) { while (left <= right) { const int mid = left + (right - left) / 2; - if (find(mid, image, has_one)) { + if (find(image, has_one, mid)) { right = mid - 1; } else { left = mid + 1; From 4ea1a569481df31206fda08b2d158aff5dfc4e9b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Nov 2015 00:23:15 +0800 Subject: [PATCH 1237/1939] Update smallest-rectangle-enclosing-black-pixels.cpp --- C++/smallest-rectangle-enclosing-black-pixels.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp index 71b278426..e04a65f8d 100644 --- a/C++/smallest-rectangle-enclosing-black-pixels.cpp +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -54,23 +54,24 @@ class Solution2 { return has_one == any_of(image.cbegin(), image.cend(), [=](const vector& row) { return row[mid] == '1'; }); }; - const int left = binarySearch(image, 0, y - 1, searchColumns, true); - const int right = binarySearch(image, y + 1, image[0].size() - 1, searchColumns, false); + const int left = binarySearch(0, y - 1, searchColumns, image, true); + const int right = binarySearch(y + 1, image[0].size() - 1, searchColumns, image, false); const auto searchRows = [](const vector>& image, bool has_one, const int mid) { return has_one == any_of(image[mid].cbegin(), image[mid].cend(), [](const char& col) { return col == '1'; }); }; - const int top = binarySearch(image, 0, x - 1, searchRows, true); - const int bottom = binarySearch(image, x + 1, image.size() - 1, searchRows, false); + const int top = binarySearch(0, x - 1, searchRows, image, true); + const int bottom = binarySearch(x + 1, image.size() - 1, searchRows, image, false); return (right - left) * (bottom - top); } private: - int binarySearch(const vector>& image, int left, int right, + int binarySearch(int left, int right, const function>&, bool, const int)>& find, + const vector>& image, bool has_one) { while (left <= right) { const int mid = left + (right - left) / 2; From 4caa0be67194dbd8846422c5aba2bb06c05eac5d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Nov 2015 00:24:01 +0800 Subject: [PATCH 1238/1939] Update smallest-rectangle-enclosing-black-pixels.cpp --- C++/smallest-rectangle-enclosing-black-pixels.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp index e04a65f8d..2b30f00aa 100644 --- a/C++/smallest-rectangle-enclosing-black-pixels.cpp +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -54,14 +54,14 @@ class Solution2 { return has_one == any_of(image.cbegin(), image.cend(), [=](const vector& row) { return row[mid] == '1'; }); }; - const int left = binarySearch(0, y - 1, searchColumns, image, true); - const int right = binarySearch(y + 1, image[0].size() - 1, searchColumns, image, false); - const auto searchRows = [](const vector>& image, bool has_one, const int mid) { return has_one == any_of(image[mid].cbegin(), image[mid].cend(), [](const char& col) { return col == '1'; }); }; + + const int left = binarySearch(0, y - 1, searchColumns, image, true); + const int right = binarySearch(y + 1, image[0].size() - 1, searchColumns, image, false); const int top = binarySearch(0, x - 1, searchRows, image, true); const int bottom = binarySearch(x + 1, image.size() - 1, searchRows, image, false); From 3ae8b011fc2fba936c020055bdb4ade80a78e696 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Nov 2015 00:25:20 +0800 Subject: [PATCH 1239/1939] Update smallest-rectangle-enclosing-black-pixels.cpp --- C++/smallest-rectangle-enclosing-black-pixels.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp index 2b30f00aa..f59d24e0d 100644 --- a/C++/smallest-rectangle-enclosing-black-pixels.cpp +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -33,7 +33,7 @@ class Solution { } private: - int binarySearch(int left, int right, function& find) { + int binarySearch(int left, int right, function& find) { while (left <= right) { const int mid = left + (right - left) / 2; if (find(mid)) { @@ -46,6 +46,7 @@ class Solution { } }; + class Solution2 { public: int minArea(vector>& image, int x, int y) { From 37971ed529b8478460b34cbdfcab1c8c9f8beca3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Nov 2015 00:28:46 +0800 Subject: [PATCH 1240/1939] Update smallest-rectangle-enclosing-black-pixels.py --- .../smallest-rectangle-enclosing-black-pixels.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Python/smallest-rectangle-enclosing-black-pixels.py b/Python/smallest-rectangle-enclosing-black-pixels.py index ec8cb98b6..7237fbf85 100644 --- a/Python/smallest-rectangle-enclosing-black-pixels.py +++ b/Python/smallest-rectangle-enclosing-black-pixels.py @@ -9,21 +9,21 @@ def minArea(self, image, x, y): :type y: int :rtype: int """ - def binarySearch(image, left, right, find, has_one): + def binarySearch(left, right, find, image, has_one): while left <= right: # O(logn) times mid = left + (right - left) / 2 - if find(mid, image, has_one): # Time: O(n) + if find(image, has_one, mid): # Time: O(n) right = mid - 1 else: left = mid + 1 return left - searchColumns = lambda mid, image, has_one: any([int(row[mid]) for row in image]) == has_one - left = binarySearch(image, 0, y - 1, searchColumns, True) - right = binarySearch(image, y + 1, len(image[0]) - 1, searchColumns, False) + searchColumns = lambda image, has_one, mid: any([int(row[mid]) for row in image]) == has_one + left = binarySearch(0, y - 1, searchColumns, image, True) + right = binarySearch(y + 1, len(image[0]) - 1, searchColumns, image, False) - searchRows = lambda mid, image, has_one: any(itertools.imap(int, image[mid])) == has_one - top = binarySearch(image, 0, x - 1, searchRows, True) - bottom = binarySearch(image, x + 1, len(image) - 1, searchRows, False) + searchRows = lambda image, has_one, mid: any(itertools.imap(int, image[mid])) == has_one + top = binarySearch(0, x - 1, searchRows, image, True) + bottom = binarySearch(x + 1, len(image) - 1, searchRows, image, False) return (right - left) * (bottom - top) From 7c65803649c798f9dae7ed1c3fe83f640b2989c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Nov 2015 00:29:22 +0800 Subject: [PATCH 1241/1939] Update smallest-rectangle-enclosing-black-pixels.py --- Python/smallest-rectangle-enclosing-black-pixels.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/smallest-rectangle-enclosing-black-pixels.py b/Python/smallest-rectangle-enclosing-black-pixels.py index 7237fbf85..a410c374f 100644 --- a/Python/smallest-rectangle-enclosing-black-pixels.py +++ b/Python/smallest-rectangle-enclosing-black-pixels.py @@ -22,8 +22,9 @@ def binarySearch(left, right, find, image, has_one): searchColumns = lambda image, has_one, mid: any([int(row[mid]) for row in image]) == has_one left = binarySearch(0, y - 1, searchColumns, image, True) right = binarySearch(y + 1, len(image[0]) - 1, searchColumns, image, False) - + searchRows = lambda image, has_one, mid: any(itertools.imap(int, image[mid])) == has_one top = binarySearch(0, x - 1, searchRows, image, True) bottom = binarySearch(x + 1, len(image) - 1, searchRows, image, False) + return (right - left) * (bottom - top) From da5d1eb7dfa17910da717cac0409782dc94337ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Nov 2015 10:51:57 +0800 Subject: [PATCH 1242/1939] Update smallest-rectangle-enclosing-black-pixels.cpp --- ...llest-rectangle-enclosing-black-pixels.cpp | 45 ++++++++++++++++++- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/C++/smallest-rectangle-enclosing-black-pixels.cpp b/C++/smallest-rectangle-enclosing-black-pixels.cpp index f59d24e0d..9f96b1eee 100644 --- a/C++/smallest-rectangle-enclosing-black-pixels.cpp +++ b/C++/smallest-rectangle-enclosing-black-pixels.cpp @@ -1,11 +1,52 @@ // Time: O(nlogn) // Space: O(1) +// Using template. class Solution { public: int minArea(vector>& image, int x, int y) { using namespace std::placeholders; // for _1, _2, _3... + const auto searchColumns = + [](const vector>& image, bool has_one, const int mid) { + return has_one == any_of(image.cbegin(), image.cend(), + [=](const vector& row) { return row[mid] == '1'; }); + }; + const auto searchRows = + [](const vector>& image, bool has_one, const int mid) { + return has_one == any_of(image[mid].cbegin(), image[mid].cend(), + [](const char& col) { return col == '1'; }); + }; + + const int left = binarySearch(0, y - 1, bind(searchColumns, image, true, _1)); + const int right = binarySearch(y + 1, image[0].size() - 1, bind(searchColumns, image, false, _1)); + const int top = binarySearch(0, x - 1, bind(searchRows, image, true, _1)); + const int bottom = binarySearch(x + 1, image.size() - 1, bind(searchRows, image, false, _1)); + + return (right - left) * (bottom - top); + } + +private: + template + int binarySearch(int left, int right, const T& find) { + while (left <= right) { + const int mid = left + (right - left) / 2; + if (find(mid)) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } +}; + +// Using std::bind(). +class Solution2 { +public: + int minArea(vector>& image, int x, int y) { + using namespace std::placeholders; // for _1, _2, _3... + const auto searchColumns = [](const vector>& image, bool has_one, const int mid) { return has_one == any_of(image.cbegin(), image.cend(), @@ -46,8 +87,8 @@ class Solution { } }; - -class Solution2 { +// Using lambda. +class Solution3 { public: int minArea(vector>& image, int x, int y) { const auto searchColumns = From 1164389bbcd3cd4744c7b762b9770b4246f8bbc4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 00:11:57 +0800 Subject: [PATCH 1243/1939] Update add-and-search-word-data-structure-design.cpp --- C++/add-and-search-word-data-structure-design.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/add-and-search-word-data-structure-design.cpp b/C++/add-and-search-word-data-structure-design.cpp index 053516acd..1f721bc21 100644 --- a/C++/add-and-search-word-data-structure-design.cpp +++ b/C++/add-and-search-word-data-structure-design.cpp @@ -4,7 +4,6 @@ class WordDictionary { public: struct TrieNode{ - public: bool isString = false; unordered_map leaves; }; @@ -47,6 +46,7 @@ class WordDictionary { } return false; } + private: TrieNode *root_; }; From c4efc9991cbfec9e691d2ad501701f2ee8e19972 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 00:13:26 +0800 Subject: [PATCH 1244/1939] Update add-and-search-word-data-structure-design.cpp --- C++/add-and-search-word-data-structure-design.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/C++/add-and-search-word-data-structure-design.cpp b/C++/add-and-search-word-data-structure-design.cpp index 1f721bc21..861c59e9f 100644 --- a/C++/add-and-search-word-data-structure-design.cpp +++ b/C++/add-and-search-word-data-structure-design.cpp @@ -3,16 +3,16 @@ class WordDictionary { public: - struct TrieNode{ + struct TrieNode { bool isString = false; unordered_map leaves; }; - WordDictionary(){ + WordDictionary() { root_ = new TrieNode(); root_->isString = true; } - + // Adds a word into the data structure. void addWord(string word) { auto* p = root_; @@ -35,9 +35,10 @@ class WordDictionary { if (s == word.length()) { return node->isString; } - if (node->leaves.find(word[s]) != node->leaves.end()){ // Match the char. + // Match the char. + if (node->leaves.find(word[s]) != node->leaves.end()) { return searchWord(word, node->leaves[word[s]], s + 1); - } else if (word[s] == '.') { // Skip the char. + } else if (word[s] == '.') { // Skip the char. for (const auto& i : node->leaves) { if (searchWord(word, i.second, s + 1)) { return true; @@ -51,6 +52,7 @@ class WordDictionary { TrieNode *root_; }; + // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); From 3e1516fcd2a3f8b3d58a19aa55801071de1e355b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 00:23:01 +0800 Subject: [PATCH 1245/1939] Update add-and-search-word-data-structure-design.cpp --- C++/add-and-search-word-data-structure-design.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/add-and-search-word-data-structure-design.cpp b/C++/add-and-search-word-data-structure-design.cpp index 861c59e9f..1aed5b015 100644 --- a/C++/add-and-search-word-data-structure-design.cpp +++ b/C++/add-and-search-word-data-structure-design.cpp @@ -31,7 +31,7 @@ class WordDictionary { return searchWord(word, root_, 0); } - bool searchWord(string word, TrieNode* node, int s) { + bool searchWord(string word, TrieNode *node, int s) { if (s == word.length()) { return node->isString; } From 05276b0401cab9766a584e1da2910bd9d4480abc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 00:23:46 +0800 Subject: [PATCH 1246/1939] Update add-and-search-word-data-structure-design.cpp --- C++/add-and-search-word-data-structure-design.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/add-and-search-word-data-structure-design.cpp b/C++/add-and-search-word-data-structure-design.cpp index 1aed5b015..1968871e1 100644 --- a/C++/add-and-search-word-data-structure-design.cpp +++ b/C++/add-and-search-word-data-structure-design.cpp @@ -52,7 +52,6 @@ class WordDictionary { TrieNode *root_; }; - // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); From 66858645517506599341c793508ec6e6b0afb86c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 10:14:00 +0800 Subject: [PATCH 1247/1939] Update unique-binary-search-trees.py --- Python/unique-binary-search-trees.py | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/Python/unique-binary-search-trees.py b/Python/unique-binary-search-trees.py index cac4cb41d..e5debe1eb 100644 --- a/Python/unique-binary-search-trees.py +++ b/Python/unique-binary-search-trees.py @@ -1,5 +1,5 @@ -# Time: O(n^2) -# Space: O(n) +# Time: O(n) +# Space: O(1) # # Given n, how many structurally unique BST's (binary search trees) that store values 1...n? # @@ -13,7 +13,29 @@ # 2 1 2 3 # -class Solution: +# Math solution. +class Solution(object): + def numTrees(self, n): + """ + :type n: int + :rtype: int + """ + if n == 0: + return 1 + + def combination(n, k): + count = 1 + # C(n, k) = (n) / 1 * (n - 1) / 2 ... * (n - k + 1) / k + for i in xrange(1, k + 1): + count = count * (n - i + 1) / i; + return count + + return combination(2 * n, n) - combination(2 * n, n - 1) + +# Time: O(n^2) +# Space: O(n) +# DP solution. +class Solution2: # @return an integer def numTrees(self, n): counts = [1, 1] From 03b745521dd5fcd230c5853398901208a85356b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 10:14:53 +0800 Subject: [PATCH 1248/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 27872fbc9..277d7a8d4 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 85| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)|[Python](./Python/maximal-rectangle.py)| _O(n^2)_ | _O(n)_ | Hard || 87| [Scramble String](https://leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || 91| [Decode Ways](https://leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || -96| [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n^2)_ | _O(n)_ | Medium || +96| [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n)_ | _O(1)_ | Medium | Math | 97| [Interleaving String](https://leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || 115| [Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || 120| [Triangle](https://leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || From 332695be9d62fa7cdc30b4bc1417d9272974c3f8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 10:16:13 +0800 Subject: [PATCH 1249/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 277d7a8d4..e1a313148 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 85| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)|[Python](./Python/maximal-rectangle.py)| _O(n^2)_ | _O(n)_ | Hard || 87| [Scramble String](https://leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || 91| [Decode Ways](https://leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || -96| [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n)_ | _O(1)_ | Medium | Math | +96| [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n)_ | _O(1)_ | Medium || Math 97| [Interleaving String](https://leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || 115| [Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || 120| [Triangle](https://leetcode.com/problems/triangle/) | [Python](./Python/triangle.py) | _O(m * n)_ | _O(n)_ | Medium || From 13ac063af9f5a1d634bc513a07f7c9d81df8e0c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 16:07:11 +0800 Subject: [PATCH 1250/1939] Create range-sum-query-immutable.cpp --- C++/range-sum-query-immutable.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/range-sum-query-immutable.cpp diff --git a/C++/range-sum-query-immutable.cpp b/C++/range-sum-query-immutable.cpp new file mode 100644 index 000000000..ba3b86f24 --- /dev/null +++ b/C++/range-sum-query-immutable.cpp @@ -0,0 +1,26 @@ +// Time: ctor: O(n), +// lookup: O(1) +// Space: O(n) + +class NumArray { +public: + NumArray(vector &nums) { + accu.emplace_back(0); + for (const auto& num : nums) { + accu.emplace_back(accu.back() + num); + } + } + + int sumRange(int i, int j) { + return accu[j + 1] - accu[i]; + } + +private: + vector accu; +}; + + +// Your NumArray object will be instantiated and called as such: +// NumArray numArray(nums); +// numArray.sumRange(0, 1); +// numArray.sumRange(1, 2); From cf3e83cc135c031aa47bc1796fdbfc87ee2c6922 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 16:09:39 +0800 Subject: [PATCH 1251/1939] Create range-sum-query-immutable.py --- Python/range-sum-query-immutable.py | 41 +++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/range-sum-query-immutable.py diff --git a/Python/range-sum-query-immutable.py b/Python/range-sum-query-immutable.py new file mode 100644 index 000000000..2e6755a71 --- /dev/null +++ b/Python/range-sum-query-immutable.py @@ -0,0 +1,41 @@ +# Time: ctor: O(n), +# lookup: O(1) +# Space: O(n) +# +#Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. +# +# Example: +# Given nums = [-2, 0, 3, -5, 2, -1] +# +# sumRange(0, 2) -> 1 +# sumRange(2, 5) -> -1 +# sumRange(0, 5) -> -3 +# Note: +# You may assume that the array does not change. +# There are many calls to sumRange function. +# + +class NumArray(object): + def __init__(self, nums): + """ + initialize your data structure here. + :type nums: List[int] + """ + self.accu = [0] + for num in nums: + self.accu += self.accu[-1] + num, + + def sumRange(self, i, j): + """ + sum of elements nums[i..j], inclusive. + :type i: int + :type j: int + :rtype: int + """ + return self.accu[j + 1] - self.accu[i] + + +# Your NumArray object will be instantiated and called as such: +# numArray = NumArray(nums) +# numArray.sumRange(0, 1) +# numArray.sumRange(1, 2) From 21aef2a1e494d898ab2a9d27a5da5ce46c722908 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 16:18:33 +0800 Subject: [PATCH 1252/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e1a313148..802feccf3 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-302%20%2F%20302-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-303%20%2F%20303-ff69b4.svg) -Up to date (2015-11-07), there are `285` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-10), there are `286` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `302` questions. +Here is the classification of all `303` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -395,6 +395,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 265| [Paint House II](https://leetcode.com/problems/paint-house-ii/) | [C++](./C++/paint-house-ii.cpp) [Python](./Python/paint-house-ii.py) | _O(n * k)_| _O(k)_| Hard |📖|| 276| [Paint Fence](https://leetcode.com/problems/paint-fence/) | [C++](./C++/paint-fence.cpp) [Python](./Python/paint-fence.py) | _O(n)_| _O(1)_| Easy |📖|| 279| [Perfect Squares](https://leetcode.com/problems/perfect-squares/)| [C++](./C++/perfect-squares.cpp) [Python](./Python/perfect-squares.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium || Hash | +303| [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)| [C++](./C++/range-sum-query-immutable.cpp) [Python](./Python/range-sum-query-immutable.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(n)_ | Easy || ## Backtracking # | Problem | Solution | Time | Space | Difficulty | Tag | Note From eca07e6b94c923d521340306c82ddfae0bf53acb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 16:18:53 +0800 Subject: [PATCH 1253/1939] Update range-sum-query-immutable.cpp --- C++/range-sum-query-immutable.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/range-sum-query-immutable.cpp b/C++/range-sum-query-immutable.cpp index ba3b86f24..0a8c7e7b9 100644 --- a/C++/range-sum-query-immutable.cpp +++ b/C++/range-sum-query-immutable.cpp @@ -1,4 +1,4 @@ -// Time: ctor: O(n), +// Time: ctor: O(n), // lookup: O(1) // Space: O(n) From 5b6dd3dc6dcf4913f66a8740bdd803d02f004227 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Nov 2015 16:24:50 +0800 Subject: [PATCH 1254/1939] Update range-sum-query-immutable.py --- Python/range-sum-query-immutable.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/range-sum-query-immutable.py b/Python/range-sum-query-immutable.py index 2e6755a71..a5c6d7775 100644 --- a/Python/range-sum-query-immutable.py +++ b/Python/range-sum-query-immutable.py @@ -23,7 +23,7 @@ def __init__(self, nums): """ self.accu = [0] for num in nums: - self.accu += self.accu[-1] + num, + self.accu.append(self.accu[-1] + num), def sumRange(self, i, j): """ From eb03fcfef08fe5af27200802b6e9f575bf390ffe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 14:57:32 +0800 Subject: [PATCH 1255/1939] Create range-sum-query-2d-immutable.py --- Python/range-sum-query-2d-immutable.py | 66 ++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Python/range-sum-query-2d-immutable.py diff --git a/Python/range-sum-query-2d-immutable.py b/Python/range-sum-query-2d-immutable.py new file mode 100644 index 000000000..925d77b20 --- /dev/null +++ b/Python/range-sum-query-2d-immutable.py @@ -0,0 +1,66 @@ +# Time: ctor: O(m * n) +# lookup: O(1) +# Space: O(m * n) +# +# Given a 2D matrix matrix, find the sum of the elements inside +# the rectangle defined by its upper left corner (row1, col1) +# and lower right corner (row2, col2). +# +# Range Sum Query 2D +# The above rectangle (with the red border) is defined by +# (row1, col1) = (2, 1) and (row2, col2) = (4, 3), +# which contains sum = 8. +# +# Example: +# Given matrix = [ +# [3, 0, 1, 4, 2], +# [5, 6, 3, 2, 1], +# [1, 2, 0, 1, 5], +# [4, 1, 0, 1, 7], +# [1, 0, 3, 0, 5] +# ] +# +# sumRegion(2, 1, 4, 3) -> 8 +# sumRegion(1, 1, 2, 2) -> 11 +# sumRegion(1, 2, 2, 4) -> 12 +# Note: +# You may assume that the matrix does not change. +# There are many calls to sumRegion function. +# You may assume that row1 ≤ row2 and col1 ≤ col2. + +class NumMatrix(object): + def __init__(self, matrix): + """ + initialize your data structure here. + :type matrix: List[List[int]] + """ + if matrix is None or not matrix: + return + m, n = len(matrix), len(matrix[0]) + self.sums = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)] + for i in xrange(1, m+1): + for j in xrange(1, n+1): + self.sums[i][j] = matrix[i-1][j-1] + self.sums[i][j] += self.sums[i][j-1] + for j in xrange(1, n+1): + for i in xrange(1, m+1): + self.sums[i][j] += self.sums[i-1][j] + + def sumRegion(self, row1, col1, row2, col2): + """ + sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. + :type row1: int + :type col1: int + :type row2: int + :type col2: int + :rtype: int + """ + return self.sums[row2+1][col2+1] - self.sums[row2+1][col1] - \ + self.sums[row1][col2+1] + self.sums[row1][col1] + + + +# Your NumMatrix object will be instantiated and called as such: +# numMatrix = NumMatrix(matrix) +# numMatrix.sumRegion(0, 1, 2, 3) +# numMatrix.sumRegion(1, 2, 3, 4) From d7d0f8f6859e3f0fe6f6c7ff355c26bd49a7a07e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 14:59:24 +0800 Subject: [PATCH 1256/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 802feccf3..ac45a1623 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-303%20%2F%20303-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-304%20%2F%20304-ff69b4.svg) -Up to date (2015-11-10), there are `286` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-12), there are `287` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `303` questions. +Here is the classification of all `304` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -396,6 +396,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 276| [Paint Fence](https://leetcode.com/problems/paint-fence/) | [C++](./C++/paint-fence.cpp) [Python](./Python/paint-fence.py) | _O(n)_| _O(1)_| Easy |📖|| 279| [Perfect Squares](https://leetcode.com/problems/perfect-squares/)| [C++](./C++/perfect-squares.cpp) [Python](./Python/perfect-squares.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium || Hash | 303| [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)| [C++](./C++/range-sum-query-immutable.cpp) [Python](./Python/range-sum-query-immutable.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(n)_ | Easy || +304| [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/)| [C++](./C++/range-sum-query-2d-immutable.cpp) [Python](./Python/range-sum-query-2d-immutable.py) | ctor: _O(m * n)_, lookup: _O(1)_ | _O(m * n)_ | Medium || ## Backtracking # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 65f098af35f91dfabf60cc2b8d5aa2281e16d514 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 15:00:31 +0800 Subject: [PATCH 1257/1939] Update range-sum-query-2d-immutable.py --- Python/range-sum-query-2d-immutable.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/range-sum-query-2d-immutable.py b/Python/range-sum-query-2d-immutable.py index 925d77b20..a77564651 100644 --- a/Python/range-sum-query-2d-immutable.py +++ b/Python/range-sum-query-2d-immutable.py @@ -26,7 +26,7 @@ # Note: # You may assume that the matrix does not change. # There are many calls to sumRegion function. -# You may assume that row1 ≤ row2 and col1 ≤ col2. +# You may assume that row1 <= row2 and col1 <= col2. class NumMatrix(object): def __init__(self, matrix): From b6e2f1ba7494cf12a4b57b00e4906d17813f2429 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 15:02:11 +0800 Subject: [PATCH 1258/1939] Update range-sum-query-2d-immutable.py --- Python/range-sum-query-2d-immutable.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/range-sum-query-2d-immutable.py b/Python/range-sum-query-2d-immutable.py index a77564651..1d69068fb 100644 --- a/Python/range-sum-query-2d-immutable.py +++ b/Python/range-sum-query-2d-immutable.py @@ -34,7 +34,7 @@ def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]] """ - if matrix is None or not matrix: + if not matrix: return m, n = len(matrix), len(matrix[0]) self.sums = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)] @@ -59,7 +59,6 @@ def sumRegion(self, row1, col1, row2, col2): self.sums[row1][col2+1] + self.sums[row1][col1] - # Your NumMatrix object will be instantiated and called as such: # numMatrix = NumMatrix(matrix) # numMatrix.sumRegion(0, 1, 2, 3) From ae17005643b6ce708f8bb9704311130e7e5261f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 15:09:33 +0800 Subject: [PATCH 1259/1939] Create range-sum-query-2d-immutable.cpp --- C++/range-sum-query-2d-immutable.cpp | 42 ++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/range-sum-query-2d-immutable.cpp diff --git a/C++/range-sum-query-2d-immutable.cpp b/C++/range-sum-query-2d-immutable.cpp new file mode 100644 index 000000000..4159959a2 --- /dev/null +++ b/C++/range-sum-query-2d-immutable.cpp @@ -0,0 +1,42 @@ +// Time: ctor: O(m * n) +// lookup: O(1) +// Space: O(m * n) + +class NumMatrix { +public: + NumMatrix(vector> &matrix) { + if (matrix.empty()) { + return; + } + const auto m = matrix.size(), n = matrix[0].size(); + for (int i = 0; i <= m; ++i) { + sums.emplace_back(n + 1, 0); + } + + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + sums[i][j] = matrix[i - 1][j - 1]; + sums[i][j] += sums[i][j - 1]; + } + } + for (int j = 0; j <= n; ++j) { + for (int i = 1; i <= m; ++i) { + sums[i][j] += sums[i - 1][j]; + } + } + } + + int sumRegion(int row1, int col1, int row2, int col2) { + return sums[row2+1][col2+1] - sums[row2+1][col1] - + sums[row1][col2+1] + sums[row1][col1]; + } + +private: + vector> sums; +}; + + +// Your NumMatrix object will be instantiated and called as such: +// NumMatrix numMatrix(matrix); +// numMatrix.sumRegion(0, 1, 2, 3); +// numMatrix.sumRegion(1, 2, 3, 4); From 456068f1a176a7d0d9b41e56ad861175bc16c77e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 15:10:20 +0800 Subject: [PATCH 1260/1939] Update range-sum-query-2d-immutable.cpp --- C++/range-sum-query-2d-immutable.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/range-sum-query-2d-immutable.cpp b/C++/range-sum-query-2d-immutable.cpp index 4159959a2..19b8062b0 100644 --- a/C++/range-sum-query-2d-immutable.cpp +++ b/C++/range-sum-query-2d-immutable.cpp @@ -8,11 +8,11 @@ class NumMatrix { if (matrix.empty()) { return; } + const auto m = matrix.size(), n = matrix[0].size(); for (int i = 0; i <= m; ++i) { sums.emplace_back(n + 1, 0); } - for (int i = 1; i <= m; ++i) { for (int j = 0; j <= n; ++j) { sums[i][j] = matrix[i - 1][j - 1]; From bc08499fd803278ea502bafdf845dec438f951f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 15:10:52 +0800 Subject: [PATCH 1261/1939] Update range-sum-query-2d-immutable.py --- Python/range-sum-query-2d-immutable.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/range-sum-query-2d-immutable.py b/Python/range-sum-query-2d-immutable.py index 1d69068fb..85a0095fc 100644 --- a/Python/range-sum-query-2d-immutable.py +++ b/Python/range-sum-query-2d-immutable.py @@ -36,6 +36,7 @@ def __init__(self, matrix): """ if not matrix: return + m, n = len(matrix), len(matrix[0]) self.sums = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)] for i in xrange(1, m+1): From 89044bacd3ff7d1c3964ee66ea3c37a1dded0808 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 15:15:35 +0800 Subject: [PATCH 1262/1939] Update range-sum-query-2d-immutable.cpp --- C++/range-sum-query-2d-immutable.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/range-sum-query-2d-immutable.cpp b/C++/range-sum-query-2d-immutable.cpp index 19b8062b0..164ff8b8a 100644 --- a/C++/range-sum-query-2d-immutable.cpp +++ b/C++/range-sum-query-2d-immutable.cpp @@ -15,8 +15,7 @@ class NumMatrix { } for (int i = 1; i <= m; ++i) { for (int j = 0; j <= n; ++j) { - sums[i][j] = matrix[i - 1][j - 1]; - sums[i][j] += sums[i][j - 1]; + sums[i][j] = sums[i][j - 1] + matrix[i - 1][j - 1] ; } } for (int j = 0; j <= n; ++j) { From 4edc8d207a62eb7238d19f737ebcd6d1c94377e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 15:15:45 +0800 Subject: [PATCH 1263/1939] Update range-sum-query-2d-immutable.cpp --- C++/range-sum-query-2d-immutable.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/range-sum-query-2d-immutable.cpp b/C++/range-sum-query-2d-immutable.cpp index 164ff8b8a..e511d400c 100644 --- a/C++/range-sum-query-2d-immutable.cpp +++ b/C++/range-sum-query-2d-immutable.cpp @@ -15,7 +15,7 @@ class NumMatrix { } for (int i = 1; i <= m; ++i) { for (int j = 0; j <= n; ++j) { - sums[i][j] = sums[i][j - 1] + matrix[i - 1][j - 1] ; + sums[i][j] = sums[i][j - 1] + matrix[i - 1][j - 1]; } } for (int j = 0; j <= n; ++j) { From 97f1b102cf3c8cea6f739e0449f53faeb5fa792e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 15:16:16 +0800 Subject: [PATCH 1264/1939] Update range-sum-query-2d-immutable.py --- Python/range-sum-query-2d-immutable.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/range-sum-query-2d-immutable.py b/Python/range-sum-query-2d-immutable.py index 85a0095fc..464fa3169 100644 --- a/Python/range-sum-query-2d-immutable.py +++ b/Python/range-sum-query-2d-immutable.py @@ -41,8 +41,7 @@ def __init__(self, matrix): self.sums = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)] for i in xrange(1, m+1): for j in xrange(1, n+1): - self.sums[i][j] = matrix[i-1][j-1] - self.sums[i][j] += self.sums[i][j-1] + self.sums[i][j] = self.sums[i][j-1] + matrix[i-1][j-1] for j in xrange(1, n+1): for i in xrange(1, m+1): self.sums[i][j] += self.sums[i-1][j] From 25f30ef413168000ef63cbb76d6635203f6ac0cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Nov 2015 15:18:41 +0800 Subject: [PATCH 1265/1939] Update range-sum-query-2d-immutable.cpp --- C++/range-sum-query-2d-immutable.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/range-sum-query-2d-immutable.cpp b/C++/range-sum-query-2d-immutable.cpp index e511d400c..2414f6bfc 100644 --- a/C++/range-sum-query-2d-immutable.cpp +++ b/C++/range-sum-query-2d-immutable.cpp @@ -26,8 +26,8 @@ class NumMatrix { } int sumRegion(int row1, int col1, int row2, int col2) { - return sums[row2+1][col2+1] - sums[row2+1][col1] - - sums[row1][col2+1] + sums[row1][col1]; + return sums[row2 + 1][col2 + 1] - sums[row2 + 1][col1] - + sums[row1][col2 + 1] + sums[row1][col1]; } private: From 858d95fef44df3744d17ddf7adcfc8217afe8113 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 10:14:05 +0800 Subject: [PATCH 1266/1939] Create number-of-islands-ii.cpp --- C++/number-of-islands-ii.cpp | 57 ++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 C++/number-of-islands-ii.cpp diff --git a/C++/number-of-islands-ii.cpp b/C++/number-of-islands-ii.cpp new file mode 100644 index 000000000..1e1203b34 --- /dev/null +++ b/C++/number-of-islands-ii.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + vector numIslands2(int m, int n, vector>& positions) { + vector numbers; + int number = 0; + const vector> directions{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; + unordered_map set; + for (const auto& position : positions) { + const auto& node = make_pair(position.first, position.second); + set[node_id(node, n)] = node_id(node, n); + + // For each direction, count distinct islands. + unordered_set neighbors; + for (const auto& d : directions) { + const auto& neighbor = make_pair(position.first + d.first, + position.second + d.second); + if (neighbor.first >= 0 && neighbor.first < m && + neighbor.second >= 0 && neighbor.second < n && + set.find(node_id(neighbor, n)) != set.end()) { + neighbors.emplace(find_set(node_id(neighbor, n), &set)); + } + } + + // For each direction, find and union. + for (const auto& d : directions) { + const auto& neighbor = make_pair(position.first + d.first, + position.second + d.second); + if (neighbor.first >= 0 && neighbor.first < m && + neighbor.second >= 0 && neighbor.second < n && + set.find(node_id(neighbor, n)) != set.end()) { + union_set(&set, node_id(node, n), node_id(neighbor, n)); + } + } + + number += 1 - neighbors.size(); + numbers.emplace_back(number); + } + return numbers; + } + + int node_id(const pair& node, const int n) { + return node.first * n + node.second; + } + + int find_set(int x, unordered_map *set) { + if ((*set)[x] != x) { + (*set)[x] = find_set((*set)[x], set); // path compression. + } + return (*set)[x]; + } + + void union_set(unordered_map *set, const int x, const int y) { + int x_root = find_set(x, set), y_root = find_set(y, set); + (*set)[min(x_root, y_root)] = max(x_root, y_root); + } +}; From e874e7b35d7e5de31e409ee17edae5f594d58d8a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 10:17:22 +0800 Subject: [PATCH 1267/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ac45a1623..639183fac 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-304%20%2F%20304-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-305%20%2F%20305-ff69b4.svg) -Up to date (2015-11-12), there are `287` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-14), there are `288` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `304` questions. +Here is the classification of all `305` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -201,6 +201,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || 299| [Bulls and Cow](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| +305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./Python/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(p)_ | _O(p)_| Hard | LintCode | Union Find ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 49d8597ba0305fc9f2cf15894fe99c4baab4df6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 10:18:13 +0800 Subject: [PATCH 1268/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 639183fac..80bd77a5f 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || 299| [Bulls and Cow](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| -305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./Python/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(p)_ | _O(p)_| Hard | LintCode | Union Find +305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(p)_ | _O(p)_| Hard | LintCode | Union Find ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 9bc5c2edd26f442a8116a311af579bc377e6d5bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 10:43:20 +0800 Subject: [PATCH 1269/1939] Create next-permutation-ii.py --- Python/next-permutation-ii.py | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/next-permutation-ii.py diff --git a/Python/next-permutation-ii.py b/Python/next-permutation-ii.py new file mode 100644 index 000000000..877683d6c --- /dev/null +++ b/Python/next-permutation-ii.py @@ -0,0 +1,50 @@ +# Time: O(p), p is number of positions +# Space: O(p) + +class Solution(object): + def numIslands2(self, m, n, positions): + """ + :type m: int + :type n: int + :type positions: List[List[int]] + :rtype: List[int] + """ + def node_id(node, n): + return node[0] * n + node[1] + + def find_set(x): + if set[x] != x: + set[x] = find_set(set[x]) # path compression. + return set[x] + + def union_set(x, y): + x_root, y_root = find_set(x), find_set(y) + set[min(x_root, y_root)] = max(x_root, y_root) + + numbers = [] + number = 0 + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + set = {} + for position in positions: + node = (position[0], position[1]) + set[node_id(node, n)] = node_id(node, n) + + # For each direction, count distinct islands. + neighbors = {} + for d in directions: + neighbor = (position[0] + d[0], position[1] + d[1]) + if 0 <= neighbor[0] < m and 0 <= neighbor[1] < n and \ + node_id(neighbor, n) in set: + neighbors[find_set(node_id(neighbor, n))] = True + + # For each direction, find and union. + for d in directions: + neighbor = (position[0] + d[0], position[1] + d[1]) + if 0 <= neighbor[0] < m and 0 <= neighbor[1] < n and \ + node_id(neighbor, n) in set: + union_set(node_id(node, n), node_id(neighbor, n)) + + number += 1 - len(neighbors) + numbers.append(number) + + return numbers From 13fc16a4ec159c8e4d7aea8036f0a8137b3932b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 10:44:52 +0800 Subject: [PATCH 1270/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 80bd77a5f..10a0e1413 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || 299| [Bulls and Cow](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| -305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(p)_ | _O(p)_| Hard | LintCode | Union Find +305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(p)_ | _O(p)_| Hard | LintCode, 📖 | Union Find ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 2e5dd38d2258f9fa9be2bbbcf3af4e4f18974223 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 10:47:36 +0800 Subject: [PATCH 1271/1939] Rename next-permutation-ii.py to number-of-islands-ii.py --- Python/{next-permutation-ii.py => number-of-islands-ii.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{next-permutation-ii.py => number-of-islands-ii.py} (100%) diff --git a/Python/next-permutation-ii.py b/Python/number-of-islands-ii.py similarity index 100% rename from Python/next-permutation-ii.py rename to Python/number-of-islands-ii.py From 152f3e210545ed4242f5f72cb77a3e48fa6da783 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 10:55:21 +0800 Subject: [PATCH 1272/1939] Update number-of-islands-ii.py --- Python/number-of-islands-ii.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/number-of-islands-ii.py b/Python/number-of-islands-ii.py index 877683d6c..d7581d2eb 100644 --- a/Python/number-of-islands-ii.py +++ b/Python/number-of-islands-ii.py @@ -37,6 +37,9 @@ def union_set(x, y): node_id(neighbor, n) in set: neighbors[find_set(node_id(neighbor, n))] = True + number += 1 - len(neighbors) # Merge neighbors into one island. + numbers.append(number) + # For each direction, find and union. for d in directions: neighbor = (position[0] + d[0], position[1] + d[1]) @@ -44,7 +47,4 @@ def union_set(x, y): node_id(neighbor, n) in set: union_set(node_id(node, n), node_id(neighbor, n)) - number += 1 - len(neighbors) - numbers.append(number) - return numbers From fe52dd795f9c1b7cd4760f8e9be66c175d2c20e4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 10:58:03 +0800 Subject: [PATCH 1273/1939] Update number-of-islands-ii.cpp --- C++/number-of-islands-ii.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/number-of-islands-ii.cpp b/C++/number-of-islands-ii.cpp index 1e1203b34..665a1bda2 100644 --- a/C++/number-of-islands-ii.cpp +++ b/C++/number-of-islands-ii.cpp @@ -22,6 +22,9 @@ class Solution { } } + number += 1 - neighbors.size(); // Merge neighbors into one island. + numbers.emplace_back(number); + // For each direction, find and union. for (const auto& d : directions) { const auto& neighbor = make_pair(position.first + d.first, @@ -32,9 +35,6 @@ class Solution { union_set(&set, node_id(node, n), node_id(neighbor, n)); } } - - number += 1 - neighbors.size(); - numbers.emplace_back(number); } return numbers; } From 8aad3e2479f0f53846337d49ee7b3edcc0926b68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 19:31:31 +0800 Subject: [PATCH 1274/1939] Update number-of-islands-ii.py --- Python/number-of-islands-ii.py | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/Python/number-of-islands-ii.py b/Python/number-of-islands-ii.py index d7581d2eb..b436b3ae7 100644 --- a/Python/number-of-islands-ii.py +++ b/Python/number-of-islands-ii.py @@ -28,23 +28,16 @@ def union_set(x, y): for position in positions: node = (position[0], position[1]) set[node_id(node, n)] = node_id(node, n) + number += 1 - # For each direction, count distinct islands. - neighbors = {} for d in directions: neighbor = (position[0] + d[0], position[1] + d[1]) if 0 <= neighbor[0] < m and 0 <= neighbor[1] < n and \ node_id(neighbor, n) in set: - neighbors[find_set(node_id(neighbor, n))] = True - - number += 1 - len(neighbors) # Merge neighbors into one island. + if find_set(node_id(node, n)) != find_set(node_id(neighbor, n)): + # Merge different islands. + union_set(node_id(node, n), node_id(neighbor, n)) + number -= 1 numbers.append(number) - # For each direction, find and union. - for d in directions: - neighbor = (position[0] + d[0], position[1] + d[1]) - if 0 <= neighbor[0] < m and 0 <= neighbor[1] < n and \ - node_id(neighbor, n) in set: - union_set(node_id(node, n), node_id(neighbor, n)) - return numbers From 3dfed6dbc3c3bd7e07fbd2118c6a1658ca451489 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 19:39:30 +0800 Subject: [PATCH 1275/1939] Update number-of-islands-ii.cpp --- C++/number-of-islands-ii.cpp | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/C++/number-of-islands-ii.cpp b/C++/number-of-islands-ii.cpp index 665a1bda2..694875e66 100644 --- a/C++/number-of-islands-ii.cpp +++ b/C++/number-of-islands-ii.cpp @@ -9,33 +9,25 @@ class Solution { for (const auto& position : positions) { const auto& node = make_pair(position.first, position.second); set[node_id(node, n)] = node_id(node, n); + ++number; - // For each direction, count distinct islands. - unordered_set neighbors; for (const auto& d : directions) { const auto& neighbor = make_pair(position.first + d.first, position.second + d.second); if (neighbor.first >= 0 && neighbor.first < m && neighbor.second >= 0 && neighbor.second < n && set.find(node_id(neighbor, n)) != set.end()) { - neighbors.emplace(find_set(node_id(neighbor, n), &set)); + if (find_set(node_id(node, n), &set) != + find_set(node_id(neighbor, n), &set)) { + // Merge different islands. + union_set(&set, node_id(node, n), node_id(neighbor, n)); + --number; + } } } - - number += 1 - neighbors.size(); // Merge neighbors into one island. numbers.emplace_back(number); - - // For each direction, find and union. - for (const auto& d : directions) { - const auto& neighbor = make_pair(position.first + d.first, - position.second + d.second); - if (neighbor.first >= 0 && neighbor.first < m && - neighbor.second >= 0 && neighbor.second < n && - set.find(node_id(neighbor, n)) != set.end()) { - union_set(&set, node_id(node, n), node_id(neighbor, n)); - } - } } + return numbers; } From 7350a8a311699fda83162c70df80bdcc9151574d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 19:41:19 +0800 Subject: [PATCH 1276/1939] Update number-of-islands-ii.cpp --- C++/number-of-islands-ii.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/number-of-islands-ii.cpp b/C++/number-of-islands-ii.cpp index 694875e66..32878a04c 100644 --- a/C++/number-of-islands-ii.cpp +++ b/C++/number-of-islands-ii.cpp @@ -1,3 +1,6 @@ +// Time: O(p), p is number of positions +// Space: O(p) + class Solution { public: vector numIslands2(int m, int n, vector>& positions) { From 3512f4154bd81cd2c1daedacc078b8dc603401fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Nov 2015 20:17:23 +0800 Subject: [PATCH 1277/1939] Update number-of-islands-ii.cpp --- C++/number-of-islands-ii.cpp | 67 ++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/C++/number-of-islands-ii.cpp b/C++/number-of-islands-ii.cpp index 32878a04c..d4e5a067f 100644 --- a/C++/number-of-islands-ii.cpp +++ b/C++/number-of-islands-ii.cpp @@ -1,6 +1,7 @@ // Time: O(p), p is number of positions // Space: O(p) +// Using unordered_map. class Solution { public: vector numIslands2(int m, int n, vector>& positions) { @@ -50,3 +51,69 @@ class Solution { (*set)[min(x_root, y_root)] = max(x_root, y_root); } }; + + +// Time: O(p), p is number of positions +// Space: O(m * n) +// Using vector. +class Solution2 { +public: + /** + * @param n an integer + * @param m an integer + * @param operators an array of point + * @return an integer array + */ + vector numIslands2(int m, int n, vector>& positions) { + vector numbers; + int number = 0; + const vector> directions{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; + vector set(m * n, -1); + for (const auto& position : positions) { + const auto& node = make_pair(position.first, position.second); + set[node_id(node, n)] = node_id(node, n); + ++number; + + for (const auto& d : directions) { + const auto& neighbor = make_pair(position.first + d.first, + position.second + d.second); + if (neighbor.first >= 0 && neighbor.first < m && + neighbor.second >= 0 && neighbor.second < n && + set[node_id(neighbor, n)] != -1) { + if (find_set(node_id(node, n), &set) != + find_set(node_id(neighbor, n), &set)) { + // Merge different islands. + union_set(&set, node_id(node, n), node_id(neighbor, n)); + --number; + } + } + } + numbers.emplace_back(number); + } + + return numbers; + } + + int node_id(const pair& node, const int m) { + return node.first * m + node.second; + } + + int find_set(int x, vector *set) { + int parent = x; + while ((*set)[parent] != parent) { + parent = (*set)[parent]; + } + while ((*set)[x] != x) { + int tmp = (*set)[x]; + (*set)[x] = parent; + x = tmp; + } + return parent; + } + + void union_set(vector *set, const int x, const int y) { + int x_root = find_set(x, set), y_root = find_set(y, set); + (*set)[min(x_root, y_root)] = max(x_root, y_root); + } +}; From 1f18dbac7f612eab7fe9fb75a540c7596b357bf1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Nov 2015 12:08:20 +0800 Subject: [PATCH 1278/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 10a0e1413..b2041b498 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || 299| [Bulls and Cow](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| -305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(p)_ | _O(p)_| Hard | LintCode, 📖 | Union Find +305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k * log(m * n)_ | _O(k)_| Hard | LintCode, 📖 | Union Find ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From cb40bb59b033676a1b788cc9e3cd2e63a751b026 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Nov 2015 12:09:35 +0800 Subject: [PATCH 1279/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b2041b498..0452c5861 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || 299| [Bulls and Cow](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| -305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k * log(m * n)_ | _O(k)_| Hard | LintCode, 📖 | Union Find +305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k * log(m * n))_ | _O(k)_| Hard | LintCode, 📖 | Union Find ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From cbda7aa5e5277e0b3fc250adce54a813dfaacaef Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Nov 2015 12:11:31 +0800 Subject: [PATCH 1280/1939] Update number-of-islands-ii.cpp --- C++/number-of-islands-ii.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/number-of-islands-ii.cpp b/C++/number-of-islands-ii.cpp index d4e5a067f..f013adc65 100644 --- a/C++/number-of-islands-ii.cpp +++ b/C++/number-of-islands-ii.cpp @@ -1,5 +1,5 @@ -// Time: O(p), p is number of positions -// Space: O(p) +// Time: O(k * log(m * n)), k is the length of the positions +// Space: O(k) // Using unordered_map. class Solution { @@ -53,7 +53,7 @@ class Solution { }; -// Time: O(p), p is number of positions +// Time: O(k * log(m * n)), k is the length of the positions // Space: O(m * n) // Using vector. class Solution2 { From 4e5e68394c69fb48ff98b5eb8ed66a10e60220a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Nov 2015 12:12:50 +0800 Subject: [PATCH 1281/1939] Update number-of-islands-ii.py --- Python/number-of-islands-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/number-of-islands-ii.py b/Python/number-of-islands-ii.py index b436b3ae7..7d1943976 100644 --- a/Python/number-of-islands-ii.py +++ b/Python/number-of-islands-ii.py @@ -1,5 +1,5 @@ -# Time: O(p), p is number of positions -# Space: O(p) +# Time: O(k * log(m * n)), k is the length of the positions +# Space: O(k) class Solution(object): def numIslands2(self, m, n, positions): From 80de738601d01a7ae8918a6e2191932d501fb22c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Nov 2015 17:09:00 +0800 Subject: [PATCH 1282/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0452c5861..47d715ed9 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |📖|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || 299| [Bulls and Cow](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| -305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k * log(m * n))_ | _O(k)_| Hard | LintCode, 📖 | Union Find +305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k)_ | _O(k)_| Hard | LintCode, 📖 | Union Find ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 9fd24d287cbacdf0cdbd9a889ab6dfc65e8807fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Nov 2015 17:09:39 +0800 Subject: [PATCH 1283/1939] Update number-of-islands-ii.cpp --- C++/number-of-islands-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/number-of-islands-ii.cpp b/C++/number-of-islands-ii.cpp index f013adc65..c597ede52 100644 --- a/C++/number-of-islands-ii.cpp +++ b/C++/number-of-islands-ii.cpp @@ -1,4 +1,4 @@ -// Time: O(k * log(m * n)), k is the length of the positions +// Time: O(k), k is the length of the positions // Space: O(k) // Using unordered_map. @@ -53,7 +53,7 @@ class Solution { }; -// Time: O(k * log(m * n)), k is the length of the positions +// Time: O(k), k is the length of the positions // Space: O(m * n) // Using vector. class Solution2 { From 408cb96a43040b9c7c5b9498bb974a0d563427a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Nov 2015 17:10:21 +0800 Subject: [PATCH 1284/1939] Update number-of-islands-ii.py --- Python/number-of-islands-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/number-of-islands-ii.py b/Python/number-of-islands-ii.py index 7d1943976..360a40f22 100644 --- a/Python/number-of-islands-ii.py +++ b/Python/number-of-islands-ii.py @@ -1,4 +1,4 @@ -# Time: O(k * log(m * n)), k is the length of the positions +# Time: O(k), k is the length of the positions # Space: O(k) class Solution(object): From 163ed5b0a2c3c523e20868f5c05d782ef96fa32f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Nov 2015 21:03:41 +0800 Subject: [PATCH 1285/1939] Update number-of-islands-ii.cpp --- C++/number-of-islands-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/number-of-islands-ii.cpp b/C++/number-of-islands-ii.cpp index c597ede52..a64a6138e 100644 --- a/C++/number-of-islands-ii.cpp +++ b/C++/number-of-islands-ii.cpp @@ -1,4 +1,4 @@ -// Time: O(k), k is the length of the positions +// Time: O(klog*k) ~= O(k), k is the length of the positions // Space: O(k) // Using unordered_map. @@ -53,7 +53,7 @@ class Solution { }; -// Time: O(k), k is the length of the positions +// Time: O(klog*k) ~= O(k), k is the length of the positions // Space: O(m * n) // Using vector. class Solution2 { From 59574b86f6cad19f22283c222529a9866af7c717 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Nov 2015 21:04:21 +0800 Subject: [PATCH 1286/1939] Update number-of-islands-ii.py --- Python/number-of-islands-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/number-of-islands-ii.py b/Python/number-of-islands-ii.py index 360a40f22..40be19f7b 100644 --- a/Python/number-of-islands-ii.py +++ b/Python/number-of-islands-ii.py @@ -1,4 +1,4 @@ -# Time: O(k), k is the length of the positions +# Time: O(klog*k) ~= O(k), k is the length of the positions # Space: O(k) class Solution(object): From cb638585737731647b07a6424cc48e5b0bc61ab1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Nov 2015 21:57:41 +0800 Subject: [PATCH 1287/1939] Update number-of-islands-ii.py --- Python/number-of-islands-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/number-of-islands-ii.py b/Python/number-of-islands-ii.py index 40be19f7b..3c36a265e 100644 --- a/Python/number-of-islands-ii.py +++ b/Python/number-of-islands-ii.py @@ -35,7 +35,7 @@ def union_set(x, y): if 0 <= neighbor[0] < m and 0 <= neighbor[1] < n and \ node_id(neighbor, n) in set: if find_set(node_id(node, n)) != find_set(node_id(neighbor, n)): - # Merge different islands. + # Merge different islands, amortised time: O(log*k) ~= O(1) union_set(node_id(node, n), node_id(neighbor, n)) number -= 1 numbers.append(number) From 15d2ad6585705d7469ac30e14209a70102a880d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Nov 2015 21:59:00 +0800 Subject: [PATCH 1288/1939] Update number-of-islands-ii.cpp --- C++/number-of-islands-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/number-of-islands-ii.cpp b/C++/number-of-islands-ii.cpp index a64a6138e..cc234784d 100644 --- a/C++/number-of-islands-ii.cpp +++ b/C++/number-of-islands-ii.cpp @@ -23,7 +23,7 @@ class Solution { set.find(node_id(neighbor, n)) != set.end()) { if (find_set(node_id(node, n), &set) != find_set(node_id(neighbor, n), &set)) { - // Merge different islands. + // Merge different islands, amortised time: O(log*k) ~= O(1) union_set(&set, node_id(node, n), node_id(neighbor, n)); --number; } @@ -83,7 +83,7 @@ class Solution2 { set[node_id(neighbor, n)] != -1) { if (find_set(node_id(node, n), &set) != find_set(node_id(neighbor, n), &set)) { - // Merge different islands. + // Merge different islands, amortised time: O(log*k) ~= O(1) union_set(&set, node_id(node, n), node_id(neighbor, n)); --number; } From 05148b2f91270ec2c4f26175b9ba2e7d9e64a0f7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Nov 2015 13:37:27 +0800 Subject: [PATCH 1289/1939] Create additive-number.cpp --- C++/additive-number.cpp | 52 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 C++/additive-number.cpp diff --git a/C++/additive-number.cpp b/C++/additive-number.cpp new file mode 100644 index 000000000..4be80dd35 --- /dev/null +++ b/C++/additive-number.cpp @@ -0,0 +1,52 @@ +// Time: O(n^3) +// Space: O(n) + +class Solution { +public: + bool isAdditiveNumber(string num) { + for (int i = 1; i < num.length(); ++i) { + for (int j = i + 1; j < num.length(); ++j) { + string s1 = num.substr(0, i), s2 = num.substr(i, j - i); + if ((s1.length() > 1 && s1[0] == '0') || + (s2.length() > 1 && s2[0] == '0')) { + continue; + } + + string next = add(s1, s2); + string cur = s1 + s2 + next; + while (cur.length() < num.length()) { + s1 = s2; + s2 = next; + next = add(s1, s2); + cur += next; + } + if (cur == num) { + return true; + } + } + } + return false; + } + +private: + string add(const string& m, const string& n) { + string res; + int res_length = max(m.length(), n.length()) ; + + int carry = 0; + for (int i = 0; i < res_length; ++i) { + int m_digit_i = i < m.length() ? m[m.length() - 1 - i] - '0' : 0; + int n_digit_i = i < n.length() ? n[n.length() - 1 - i] - '0' : 0; + int sum = carry + m_digit_i + n_digit_i; + carry = sum / 10; + sum %= 10; + res.push_back('0' + sum); + } + if (carry) { + res.push_back('0' + carry); + } + reverse(res.begin(), res.end()); + + return res; + } +}; From b7e7b5482a456d298168af6e8a64e8926a8c2dc1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Nov 2015 13:40:44 +0800 Subject: [PATCH 1290/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 47d715ed9..8d1ca046a 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-305%20%2F%20305-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-306%20%2F%20306-ff69b4.svg) -Up to date (2015-11-14), there are `288` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-18), there are `289` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `305` questions. +Here is the classification of all `306` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -114,6 +114,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` 271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [C++](./C++/encode-and-decode-strings.cpp) [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 273| [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [C++](./C++/integer-to-english-words.cpp) [Python](./Python/integer-to-english-words.py) | _O(logn)_ | _O(1)_ | Medium | | +306| [Addictive Number](https://leetcode.com/problems/additive-number/) | [C++](./C++/additive-number.cpp) [Python](./Python/additive-number.py) | _O(n^3)_ | _O(n)_ | Medium | | ## Linked List # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 1615031580c007d46ba660563bb9a3c0f4eb227f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Nov 2015 14:00:15 +0800 Subject: [PATCH 1291/1939] Create additive-number.py --- Python/additive-number.py | 64 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Python/additive-number.py diff --git a/Python/additive-number.py b/Python/additive-number.py new file mode 100644 index 000000000..d879520ef --- /dev/null +++ b/Python/additive-number.py @@ -0,0 +1,64 @@ +# Time: O(n^3) +# Space: O(n) +# +# Additive number is a positive integer whose digits can form additive sequence. +# +# A valid additive sequence should contain at least three numbers. +# Except for the first two numbers, each subsequent number in the sequence +# must be the sum of the preceding two. +# +# For example: +# "112358" is an additive number because the digits can form an additive sequence: +# 1, 1, 2, 3, 5, 8. +# +# 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 +# "199100199" is also an additive number, the additive sequence is: +# 1, 99, 100, 199. +# +# 1 + 99 = 100, 99 + 100 = 199 +# Note: Numbers in the additive sequence cannot have leading zeros, +# so sequence 1, 2, 03 or 1, 02, 3 is invalid. +# +# Given a string represents an integer, write a function to determine +# if it's an additive number. +# +# Follow up: +# How would you handle overflow for very large input integers? +# + +class Solution(object): + def isAdditiveNumber(self, num): + """ + :type num: str + :rtype: bool + """ + def add(a, b): + res, carry, val = "", 0, 0 + for i in xrange(max(len(a), len(b))): + val = carry + if i < len(a): + val += int(a[-(i + 1)]) + if i < len(b): + val += int(b[-(i + 1)]) + carry, val = val / 10, val % 10 + res += str(val) + if carry: + res += str(carry) + return res[::-1] + + + for i in xrange(1, len(num) - 1): + for j in xrange(i + 1, len(num)): + s1, s2 = num[0:i], num[i:j] + if (len(s1) > 1 and s1[0] == '0') or \ + (len(s2) > 1 and s2[0] == '0'): + continue + + expected = add(s1, s2) + cur = s1 + s2 + expected + while len(cur) < len(num): + s1, s2, expected = s2, expected, add(s2, expected) + cur += expected + if cur == num: + return True + return False From f165c7aba5cb51d6ca8851103291398f75f2fd96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Nov 2015 14:01:22 +0800 Subject: [PATCH 1292/1939] Update additive-number.cpp --- C++/additive-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/additive-number.cpp b/C++/additive-number.cpp index 4be80dd35..e6dff5cd2 100644 --- a/C++/additive-number.cpp +++ b/C++/additive-number.cpp @@ -4,7 +4,7 @@ class Solution { public: bool isAdditiveNumber(string num) { - for (int i = 1; i < num.length(); ++i) { + for (int i = 1; i < num.length() - 1; ++i) { for (int j = i + 1; j < num.length(); ++j) { string s1 = num.substr(0, i), s2 = num.substr(i, j - i); if ((s1.length() > 1 && s1[0] == '0') || From d4b86d401e77ce26b9595170a22be10fb2fea6e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Nov 2015 14:03:19 +0800 Subject: [PATCH 1293/1939] Update additive-number.cpp --- C++/additive-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/additive-number.cpp b/C++/additive-number.cpp index e6dff5cd2..4be80dd35 100644 --- a/C++/additive-number.cpp +++ b/C++/additive-number.cpp @@ -4,7 +4,7 @@ class Solution { public: bool isAdditiveNumber(string num) { - for (int i = 1; i < num.length() - 1; ++i) { + for (int i = 1; i < num.length(); ++i) { for (int j = i + 1; j < num.length(); ++j) { string s1 = num.substr(0, i), s2 = num.substr(i, j - i); if ((s1.length() > 1 && s1[0] == '0') || From 2d7e37917ef386f8a4649ccc2d88d048508a4177 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Nov 2015 14:03:45 +0800 Subject: [PATCH 1294/1939] Update additive-number.py --- Python/additive-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/additive-number.py b/Python/additive-number.py index d879520ef..edde1bc02 100644 --- a/Python/additive-number.py +++ b/Python/additive-number.py @@ -47,7 +47,7 @@ def add(a, b): return res[::-1] - for i in xrange(1, len(num) - 1): + for i in xrange(1, len(num)): for j in xrange(i + 1, len(num)): s1, s2 = num[0:i], num[i:j] if (len(s1) > 1 and s1[0] == '0') or \ From 9aa1db54125a16d941d53276b665464dfdcfb43d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 19 Nov 2015 02:57:26 +0800 Subject: [PATCH 1295/1939] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8d1ca046a..a5c99a753 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-306%20%2F%20306-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-306%20%2F%20307-ff69b4.svg) -Up to date (2015-11-18), there are `289` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-19), there are `290` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `306` questions. +Here is the classification of all `307` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From 4ecf71a2425138d782550270412bbb51e77475a9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 Nov 2015 09:21:27 +0900 Subject: [PATCH 1296/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a5c99a753..b6c5a2692 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS +307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(h)_, query: _O(h)_ | _O(h)_ | Medium | LintCode | DFS ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 19a99960b1d7e5082df06d1c43a26edf8624a0e4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 Nov 2015 17:08:31 +0900 Subject: [PATCH 1297/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b6c5a2692..db78a196d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-306%20%2F%20307-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-307%20%2F%20307-ff69b4.svg) Up to date (2015-11-19), there are `290` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. From 81bad53af64add799c391617698a0756aec1231b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Nov 2015 18:02:39 +0900 Subject: [PATCH 1298/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db78a196d..e5aa3e30e 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS -307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(h)_, query: _O(h)_ | _O(h)_ | Medium | LintCode | DFS +307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(h)_, query: _O(h)_ | _O(h)_ | Medium | LintCode | DFS, Segment Tree ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 3efb314f2c72a6ce77968a2a068a4c2bca50b1de Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 Nov 2015 09:56:40 +0900 Subject: [PATCH 1299/1939] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e5aa3e30e..05ecf59c1 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-307%20%2F%20307-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-307%20%2F%20308-ff69b4.svg) -Up to date (2015-11-19), there are `290` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-23), there are `291` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `307` questions. +Here is the classification of all `308` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From 1b82ad2006998ebf48f46b5d7ff5127641e1beef Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 Nov 2015 23:52:19 +0800 Subject: [PATCH 1300/1939] Create range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 102 ++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 C++/range-sum-query-mutable.cpp diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp new file mode 100644 index 000000000..55f650852 --- /dev/null +++ b/C++/range-sum-query-mutable.cpp @@ -0,0 +1,102 @@ +// Time: ctor: O(n), +// update: O(h), +// query: O(h) +// Space: O(h), used by DFS + +class NumArray { +public: + class SegmentTreeNode { + public: + int start, end; + int sum; + SegmentTreeNode *left, *right; + SegmentTreeNode(int i, int j, int s) : + start(i), end(j), sum(s), + left(nullptr), right(nullptr) { + } + }; + + NumArray(vector &nums) { + root_ = buildHelper(nums, 0, nums.size() - 1); + } + + void update(int i, int val) { + updateHelper(root_, i, val); + } + + int sumRange(int i, int j) { + return sumRangeHelper(root_, i, j); + } + +private: + SegmentTreeNode *root_; + + // Build segment tree. + SegmentTreeNode *buildHelper(vector &A, int start, int end) { + if (start > end) { + return nullptr; + } + + // The root's start and end is given by build method. + SegmentTreeNode *root = new SegmentTreeNode(start, end, 0); + + // If start equals to end, there will be no children for this node. + if (start == end) { + root->sum = A[start]; + return root; + } + + // Left child: start=A.left, end=(A.left + A.right) / 2. + root->left = buildHelper(A, start, (start + end) / 2); + + // Right child: start=(A.left + A.right) / 2 + 1, end=A.right. + root->right = buildHelper(A, (start + end) / 2 + 1, end); + + // Update sum. + root->sum = (root->left != nullptr ? root->left->sum : 0) + + (root->right != nullptr ? root->right->sum : 0); + return root; + } + + void updateHelper(SegmentTreeNode *root, int i, int val) { + // Out of range. + if (root == nullptr || root->start > i || root->end < i) { + return; + } + + // Change the node's value with [i] to the new given value. + if (root->start == i && root->end == i) { + root->sum = val; + return; + } + + updateHelper(root->left, i, val); + updateHelper(root->right, i, val); + + // Update sum. + root->sum = (root->left != nullptr ? root->left->sum : 0) + + (root->right != nullptr ? root->right->sum : 0); + } + + int sumRangeHelper(SegmentTreeNode *root, int start, int end) { + // Out of range. + if (root == nullptr || root->start > end || root->end < start) { + return 0; + } + + // Current segment is totally within range [start, end] + if (root->start >= start && root->end <= end) { + return root->sum; + } + + return sumRangeHelper(root->left, start, end) + + sumRangeHelper(root->right, start, end); + } +}; + + +// Your NumArray object will be instantiated and called as such: +// NumArray numArray(nums); +// numArray.sumRange(0, 1); +// numArray.update(1, 10); +// numArray.sumRange(1, 2); From 5ed53c7f07dc49cfb20a85aadc00c093cc4749f4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 Nov 2015 23:54:05 +0800 Subject: [PATCH 1301/1939] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index 55f650852..e2ce9e939 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -5,17 +5,6 @@ class NumArray { public: - class SegmentTreeNode { - public: - int start, end; - int sum; - SegmentTreeNode *left, *right; - SegmentTreeNode(int i, int j, int s) : - start(i), end(j), sum(s), - left(nullptr), right(nullptr) { - } - }; - NumArray(vector &nums) { root_ = buildHelper(nums, 0, nums.size() - 1); } @@ -29,6 +18,17 @@ class NumArray { } private: + class SegmentTreeNode { + public: + int start, end; + int sum; + SegmentTreeNode *left, *right; + SegmentTreeNode(int i, int j, int s) : + start(i), end(j), sum(s), + left(nullptr), right(nullptr) { + } + }; + SegmentTreeNode *root_; // Build segment tree. From 29725f17ce4bb164208234434685db1f95030362 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 00:08:35 +0800 Subject: [PATCH 1302/1939] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index e2ce9e939..867d2b488 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -32,7 +32,7 @@ class NumArray { SegmentTreeNode *root_; // Build segment tree. - SegmentTreeNode *buildHelper(vector &A, int start, int end) { + SegmentTreeNode *buildHelper(const vector& nums, int start, int end) { if (start > end) { return nullptr; } @@ -42,15 +42,15 @@ class NumArray { // If start equals to end, there will be no children for this node. if (start == end) { - root->sum = A[start]; + root->sum = nums[start]; return root; } - // Left child: start=A.left, end=(A.left + A.right) / 2. - root->left = buildHelper(A, start, (start + end) / 2); + // Left child: start=numsleft, end=(numsleft + numsright) / 2. + root->left = buildHelper(nums, start, (start + end) / 2); - // Right child: start=(A.left + A.right) / 2 + 1, end=A.right. - root->right = buildHelper(A, (start + end) / 2 + 1, end); + // Right child: start=(numsleft + numsright) / 2 + 1, end=numsright. + root->right = buildHelper(nums, (start + end) / 2 + 1, end); // Update sum. root->sum = (root->left != nullptr ? root->left->sum : 0) + From 5650a5cfa377e74d29f683da9b8d7f6103a4b871 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 00:20:20 +0800 Subject: [PATCH 1303/1939] Create range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 108 ++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Python/range-sum-query-mutable.py diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py new file mode 100644 index 000000000..67bf8875f --- /dev/null +++ b/Python/range-sum-query-mutable.py @@ -0,0 +1,108 @@ +# Time: ctor: O(n), +# update: O(h), +# query: O(h) +# Space: O(h), used by DFS +# +# Given an integer array nums, find the sum of +# the elements between indices i and j (i <= j), inclusive. +# +# The update(i, val) function modifies nums by +# updating the element at index i to val. +# Example: +# Given nums = [1, 3, 5] +# +# sumRange(0, 2) -> 9 +# update(1, 2) +# sumRange(0, 2) -> 8 +# Note: +# The array is only modifiable by the update function. +# You may assume the number of calls to update +# and sumRange function is distributed evenly. +# + +class NumArray(object): + def __init__(self, nums): + """ + initialize your data structure here. + :type nums: List[int] + """ + # Build segment tree. + def buildHelper(nums, start, end): + if start > end: + return None + + # The root's start and end is given by build method. + root = self._SegmentTreeNode(start, end, 0) + + # If start equals to end, there will be no children for this node. + if start == end: + root.sum = nums[start] + return root + + # Left child: start=nums.left, end=(nums.left + nums.right) / 2. + root.left = buildHelper(nums, start, (start + end) / 2) + + # Right child: start=(nums.left + nums.right) / 2 + 1, end=nums.right. + root.right = buildHelper(nums, (start + end) / 2 + 1, end) + + # Update sum. + root.sum = (root.left.sum if root.left else 0) + \ + (root.right.sum if root.right else 0); + return root + + self.__root = buildHelper(nums, 0, len(nums) - 1) + + def update(self, i, val): + """ + :type i: int + :type val: int + :rtype: int + """ + def updateHelper(root, i, val): + # Out of range. + if not root or root.start > i or root.end < i: + return + + # Change the node's value with [i] to the new given value. + if root.start == i and root.end == i: + root.sum = val + return + + updateHelper(root.left, i, val) + updateHelper(root.right, i, val) + + # Update sum. + root.sum = (root.left.sum if root.left else 0) + \ + (root.right.sum if root.right else 0) + + return updateHelper(self.__root, i, val) + + def sumRange(self, i, j): + """ + sum of elements nums[i..j], inclusive. + :type i: int + :type j: int + :rtype: int + """ + def sumRangeHelper(root, start, end): + # Out of range. + if not root or root.start > end or root.end < start: + return 0 + # Current segment is totally within range [start, end] + if root.start >= start and root.end <= end: + return root.sum + return sumRangeHelper(root.left, start, end) + \ + sumRangeHelper(root.right, start, end) + + return sumRangeHelper(self.__root, i, j) + + class _SegmentTreeNode: + def __init__(self, i, j,s): + self.start, self.end, self.sum = i, j, s + + +# Your NumArray object will be instantiated and called as such: +# numArray = NumArray(nums) +# numArray.sumRange(0, 1) +# numArray.update(1, 10) +# numArray.sumRange(1, 2) From 4a9cef876f1819000047cdcfb9dc937ec504c376 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 00:27:31 +0800 Subject: [PATCH 1304/1939] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index 67bf8875f..29181fa27 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -97,7 +97,7 @@ def sumRangeHelper(root, start, end): return sumRangeHelper(self.__root, i, j) class _SegmentTreeNode: - def __init__(self, i, j,s): + def __init__(self, i, j, s): self.start, self.end, self.sum = i, j, s From 5729a7df13d3c8705702b243f0d6f39db13e361c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 00:33:49 +0800 Subject: [PATCH 1305/1939] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index 29181fa27..70b269991 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -47,7 +47,7 @@ def buildHelper(nums, start, end): # Update sum. root.sum = (root.left.sum if root.left else 0) + \ - (root.right.sum if root.right else 0); + (root.right.sum if root.right else 0) return root self.__root = buildHelper(nums, 0, len(nums) - 1) From ee9d1b39de28765e22fc119c25c859fe51a5d167 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 02:25:53 +0800 Subject: [PATCH 1306/1939] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index 867d2b488..5a4612d49 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -5,12 +5,15 @@ class NumArray { public: - NumArray(vector &nums) { + NumArray(vector &nums) : nums_ref_(nums) { root_ = buildHelper(nums, 0, nums.size() - 1); } void update(int i, int val) { - updateHelper(root_, i, val); + if (nums_ref_[i] != val) { + nums_ref_[i] = val; + updateHelper(root_, i, val); + } } int sumRange(int i, int j) { @@ -30,6 +33,7 @@ class NumArray { }; SegmentTreeNode *root_; + vector& nums_ref_; // Build segment tree. SegmentTreeNode *buildHelper(const vector& nums, int start, int end) { From a238f4303f5ae934253b0de15c0d853b37a8b8c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 02:27:32 +0800 Subject: [PATCH 1307/1939] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index 5a4612d49..076183020 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -21,6 +21,8 @@ class NumArray { } private: + vector& nums_ref_; + class SegmentTreeNode { public: int start, end; @@ -33,7 +35,6 @@ class NumArray { }; SegmentTreeNode *root_; - vector& nums_ref_; // Build segment tree. SegmentTreeNode *buildHelper(const vector& nums, int start, int end) { From 2b72374732c4b66f5521e6ae94bd8b8a505a7419 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 02:29:36 +0800 Subject: [PATCH 1308/1939] Create range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 130 +++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 C++/range-sum-query-2d-mutable.cpp diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp new file mode 100644 index 000000000..95de21d96 --- /dev/null +++ b/C++/range-sum-query-2d-mutable.cpp @@ -0,0 +1,130 @@ +// Time: ctor: O(m * n), +// update: O(logm + logn), +// query: O(logm + logn) +// Space: O(logm + logn), used by DFS + +class NumMatrix { +public: + NumMatrix(vector> &matrix) : matrix_ref_(matrix) { + if (!matrix.empty() && !matrix[0].empty()) { + const int m = matrix.size(); + const int n = matrix[0].size(); + root_ = buildHelper(matrix, + make_pair(0, 0), + make_pair(m - 1, n - 1)); + } + } + + void update(int row, int col, int val) { + if (matrix_ref_[row][col] != val) { + matrix_ref_[row][col] = val; + updateHelper(root_, make_pair(row, col), val); + } + } + + int sumRegion(int row1, int col1, int row2, int col2) { + return sumRangeHelper(root_, make_pair(row1, col1), make_pair(row2, col2)); + } + +private: + vector>& matrix_ref_; + + class SegmentTreeNode { + public: + pair start, end; + int sum; + vector neighbor; + SegmentTreeNode(const pair& i, const pair& j, int s) : + start(i), end(j), sum(s), + neighbor(4) { + } + }; + + SegmentTreeNode *root_; + + // Build segment tree. + SegmentTreeNode *buildHelper(const vector>& matrix, + const pair& start, + const pair& end) { + if (start.first > end.first || start.second > end.second) { + return nullptr; + } + + // The root's start and end is given by build method. + SegmentTreeNode *root = new SegmentTreeNode(start, end, 0); + + // If start equals to end, there will be no children for this node. + if (start == end) { + root->sum = matrix[start.first][start.second]; + return root; + } + + int mid_x = (start.first + end.first) / 2; + int mid_y = (start.second + end.second) / 2; + root->neighbor[0] = buildHelper(matrix, start, make_pair(mid_x, mid_y)); + root->neighbor[1] = buildHelper(matrix, make_pair(start.first, mid_y + 1), make_pair(mid_x, end.second)); + root->neighbor[2] = buildHelper(matrix, make_pair(mid_x + 1, start.second), make_pair(end.first, mid_y)); + root->neighbor[3] = buildHelper(matrix, make_pair(mid_x + 1, mid_y + 1), end); + for (auto& node : root->neighbor) { + if (node) { + root->sum += node->sum; + } + } + return root; + } + + void updateHelper(SegmentTreeNode *root, const pair& i, int val) { + // Out of range. + if (root == nullptr || + (root->start.first > i.first || root->start.second > i.second) || + (root->end.first < i.first || root->end.second < i.second)) { + return; + } + + // Change the node's value with [i] to the new given value. + if ((root->start.first == i.first && root->start.second == i.second) && + (root->end.first == i.first && root->end.second == i.second)) { + root->sum = val; + return; + } + for (auto& node : root->neighbor) { + updateHelper(node, i, val); + } + + root->sum = 0; + for (auto& node : root->neighbor) { + if (node) { + root->sum += node->sum; + } + } + } + + int sumRangeHelper(SegmentTreeNode *root, const pair& start, const pair& end) { + // Out of range. + if (root == nullptr || + (root->start.first > end.first || root->start.second > end.second) || + (root->end.first < start.first || root->end.second < start.second)) { + return 0; + } + + // Current segment is totally within range [start, end] + if ((root->start.first >= start.first && root->start.second >= start.second) && + (root->end.first <= end.first && root->end.second <= end.second)) { + return root->sum; + } + int sum = 0; + for (auto& node : root->neighbor) { + if (node) { + sum += sumRangeHelper(node, start, end); + } + } + return sum; + } +}; + + +// Your NumMatrix object will be instantiated and called as such: +// NumMatrix numMatrix(matrix); +// numMatrix.sumRegion(0, 1, 2, 3); +// numMatrix.update(1, 1, 10); +// numMatrix.sumRegion(1, 2, 3, 4); From b8ee4d2deac9e78acfbb7ae56bace677459e0d84 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 02:36:06 +0800 Subject: [PATCH 1309/1939] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index 70b269991..74f21773f 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -27,6 +27,7 @@ def __init__(self, nums): :type nums: List[int] """ # Build segment tree. + self.__nums = nums def buildHelper(nums, start, end): if start > end: return None @@ -74,8 +75,9 @@ def updateHelper(root, i, val): # Update sum. root.sum = (root.left.sum if root.left else 0) + \ (root.right.sum if root.right else 0) - - return updateHelper(self.__root, i, val) + if self.__nums[i] != val: + self.__nums[i] = val + updateHelper(self.__root, i, val) def sumRange(self, i, j): """ From 00e953783803781129e3d8c39de4ca455fa9ba41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 02:46:07 +0800 Subject: [PATCH 1310/1939] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 05ecf59c1..2dd0868cb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-307%20%2F%20308-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-308%20%2F%20308-ff69b4.svg) Up to date (2015-11-23), there are `291` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. @@ -176,6 +176,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(h)_, query: _O(h)_ | _O(h)_ | Medium | LintCode | DFS, Segment Tree +308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(logm + logn)_ | Hard | 📖 | DFS, Segment Tree ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 9cf18232a36f2b800cc6450608aa50657caf7ae0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 02:46:35 +0800 Subject: [PATCH 1311/1939] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index 95de21d96..3df613e87 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -1,6 +1,6 @@ -// Time: ctor: O(m * n), +// Time: ctor: O(m * n), // update: O(logm + logn), -// query: O(logm + logn) +// query: O(logm + logn) // Space: O(logm + logn), used by DFS class NumMatrix { From 87f02ed8a8e1a062b669375b0cc90be28118f0af Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 02:46:57 +0800 Subject: [PATCH 1312/1939] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index 076183020..bb2a3038e 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -1,6 +1,6 @@ -// Time: ctor: O(n), +// Time: ctor: O(n), // update: O(h), -// query: O(h) +// query: O(h) // Space: O(h), used by DFS class NumArray { From e46e93d489e89e4cbfd542d81ebec13278732e63 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 02:47:14 +0800 Subject: [PATCH 1313/1939] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index 74f21773f..0036f3e18 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -1,6 +1,6 @@ -# Time: ctor: O(n), +# Time: ctor: O(n), # update: O(h), -# query: O(h) +# query: O(h) # Space: O(h), used by DFS # # Given an integer array nums, find the sum of From dfd052ee417699c95b8343fb967a0b525ec9fb5e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 02:53:56 +0800 Subject: [PATCH 1314/1939] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index 3df613e87..82916c2b2 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -35,8 +35,7 @@ class NumMatrix { int sum; vector neighbor; SegmentTreeNode(const pair& i, const pair& j, int s) : - start(i), end(j), sum(s), - neighbor(4) { + start(i), end(j), sum(s) { } }; @@ -61,10 +60,10 @@ class NumMatrix { int mid_x = (start.first + end.first) / 2; int mid_y = (start.second + end.second) / 2; - root->neighbor[0] = buildHelper(matrix, start, make_pair(mid_x, mid_y)); - root->neighbor[1] = buildHelper(matrix, make_pair(start.first, mid_y + 1), make_pair(mid_x, end.second)); - root->neighbor[2] = buildHelper(matrix, make_pair(mid_x + 1, start.second), make_pair(end.first, mid_y)); - root->neighbor[3] = buildHelper(matrix, make_pair(mid_x + 1, mid_y + 1), end); + root->neighbor.emplace_back(buildHelper(matrix, start, make_pair(mid_x, mid_y))); + root->neighbor.emplace_back(buildHelper(matrix, make_pair(start.first, mid_y + 1), make_pair(mid_x, end.second))); + root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, start.second), make_pair(end.first, mid_y))); + root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, mid_y + 1), end)); for (auto& node : root->neighbor) { if (node) { root->sum += node->sum; From 479ae9e66f640c3e229e94a70add1360db7a027d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 13:59:39 +0800 Subject: [PATCH 1315/1939] Create best-time-to-buy-and-sell-stock-with-cooldown.cpp --- ...me-to-buy-and-sell-stock-with-cooldown.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp diff --git a/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp b/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp new file mode 100644 index 000000000..875f13f1c --- /dev/null +++ b/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp @@ -0,0 +1,44 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maxProfit(vector& prices) { + if (prices.empty()) { + return 0; + } + vector buy(2), coolDown(2), sell(2); + buy[0] = -prices[0]; + for (int i = 1; i < prices.size(); ++i) { + // Bought before or buy today. + buy[i % 2] = max(buy[(i - 1) % 2], coolDown[(i - 1) % 2] - prices[i]); + // Sell today. + sell[i % 2] = buy[(i - 1) % 2] + prices[i]; + // Sold before yesterday or sold yesterday. + coolDown[i % 2] = max(coolDown[(i - 1) % 2], sell[(i - 1) % 2]); + } + return max(coolDown[(prices.size() - 1) % 2], sell[(prices.size() - 1) % 2]); + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { +public: + int maxProfit(vector& prices) { + if (prices.empty()) { + return 0; + } + vector buy(prices.size()), coolDown(prices.size()), sell(prices.size()); + buy[0] = -prices[0]; + for (int i = 1; i < prices.size(); ++i) { + // Bought before or buy today. + buy[i] = max(buy[i - 1], coolDown[i - 1] - prices[i]); + // Sell today. + sell[i] = buy[i - 1] + prices[i]; + // Sold before yesterday or sold yesterday. + coolDown[i] = max(coolDown[i - 1], sell[i - 1]); + } + return max(coolDown[prices.size() - 1], sell[prices.size() - 1]); + } +}; From 7274f43c8950be110f8fe3b1aa65825d782455e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 14:04:03 +0800 Subject: [PATCH 1316/1939] Update best-time-to-buy-and-sell-stock-with-cooldown.cpp --- C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp b/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp index 875f13f1c..c55b0f321 100644 --- a/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp +++ b/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp @@ -7,7 +7,7 @@ class Solution { if (prices.empty()) { return 0; } - vector buy(2), coolDown(2), sell(2); + vector buy(2), sell(2), coolDown(2); buy[0] = -prices[0]; for (int i = 1; i < prices.size(); ++i) { // Bought before or buy today. @@ -29,7 +29,7 @@ class Solution2 { if (prices.empty()) { return 0; } - vector buy(prices.size()), coolDown(prices.size()), sell(prices.size()); + vector buy(prices.size()), sell(prices.size()), coolDown(prices.size()); buy[0] = -prices[0]; for (int i = 1; i < prices.size(); ++i) { // Bought before or buy today. From 4bc599ec811c6da455ec92e680b43afe7e431386 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 14:06:25 +0800 Subject: [PATCH 1317/1939] Create best-time-to-buy-and-sell-stock-with-cooldown.py --- ...ime-to-buy-and-sell-stock-with-cooldown.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/best-time-to-buy-and-sell-stock-with-cooldown.py diff --git a/Python/best-time-to-buy-and-sell-stock-with-cooldown.py b/Python/best-time-to-buy-and-sell-stock-with-cooldown.py new file mode 100644 index 000000000..2e95e742b --- /dev/null +++ b/Python/best-time-to-buy-and-sell-stock-with-cooldown.py @@ -0,0 +1,38 @@ +# Time: O(n) +# Space: O(1) + +# Say you have an array for which the ith element is the price of a given stock on day i. +# +# Design an algorithm to find the maximum profit. You may complete as +# many transactions as you like (ie, buy one and sell one share of the +# stock multiple times) with the following restrictions: +# +# You may not engage in multiple transactions at the same time +# (ie, you must sell the stock before you buy again). +# After you sell your stock, you cannot buy stock on next day. +# (ie, cooldown 1 day) +# Example: +# +# prices = [1, 2, 3, 0, 2] +# maxProfit = 3 +# transactions = [buy, sell, cooldown, buy, sell] +# + +class Solution(object): + def maxProfit(self, prices): + """ + :type prices: List[int] + :rtype: int + """ + if not prices: + return 0 + buy, sell, coolDown = [0] * 2, [0] * 2, [0] * 2 + buy[0] = -prices[0] + for i in xrange(1, len(prices)): + # Bought before or buy today. + buy[i % 2] = max(buy[(i - 1) % 2], coolDown[(i - 1) % 2] - prices[i]) + # Sell today. + sell[i % 2] = buy[(i - 1) % 2] + prices[i] + # Sold before yesterday or sold yesterday. + coolDown[i % 2] = max(coolDown[(i - 1) % 2], sell[(i - 1) % 2]) + return max(coolDown[(len(prices) - 1) % 2], sell[(len(prices) - 1) % 2]) From e2b0aebc2e32057c15d6d23c7ffa80e7193ef768 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 14:07:17 +0800 Subject: [PATCH 1318/1939] Update best-time-to-buy-and-sell-stock-with-cooldown.cpp --- C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp b/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp index c55b0f321..b68cc89bb 100644 --- a/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp +++ b/C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp @@ -13,9 +13,9 @@ class Solution { // Bought before or buy today. buy[i % 2] = max(buy[(i - 1) % 2], coolDown[(i - 1) % 2] - prices[i]); // Sell today. - sell[i % 2] = buy[(i - 1) % 2] + prices[i]; + sell[i % 2] = buy[(i - 1) % 2] + prices[i]; // Sold before yesterday or sold yesterday. - coolDown[i % 2] = max(coolDown[(i - 1) % 2], sell[(i - 1) % 2]); + coolDown[i % 2] = max(coolDown[(i - 1) % 2], sell[(i - 1) % 2]); } return max(coolDown[(prices.size() - 1) % 2], sell[(prices.size() - 1) % 2]); } @@ -35,9 +35,9 @@ class Solution2 { // Bought before or buy today. buy[i] = max(buy[i - 1], coolDown[i - 1] - prices[i]); // Sell today. - sell[i] = buy[i - 1] + prices[i]; + sell[i] = buy[i - 1] + prices[i]; // Sold before yesterday or sold yesterday. - coolDown[i] = max(coolDown[i - 1], sell[i - 1]); + coolDown[i] = max(coolDown[i - 1], sell[i - 1]); } return max(coolDown[prices.size() - 1], sell[prices.size() - 1]); } From 5504fabc984ccda330e8afee2adbfb32c6d963e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 14:10:18 +0800 Subject: [PATCH 1319/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2dd0868cb..f377e529f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-308%20%2F%20308-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-309%20%2F%20309-ff69b4.svg) -Up to date (2015-11-23), there are `291` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-24), there are `292` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `308` questions. +Here is the classification of all `309` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -401,6 +401,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 279| [Perfect Squares](https://leetcode.com/problems/perfect-squares/)| [C++](./C++/perfect-squares.cpp) [Python](./Python/perfect-squares.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium || Hash | 303| [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)| [C++](./C++/range-sum-query-immutable.cpp) [Python](./Python/range-sum-query-immutable.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(n)_ | Easy || 304| [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/)| [C++](./C++/range-sum-query-2d-immutable.cpp) [Python](./Python/range-sum-query-2d-immutable.py) | ctor: _O(m * n)_, lookup: _O(1)_ | _O(m * n)_ | Medium || +309| [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-cooldown.py) | _O(n)_ | _O(1)_ | Medium || ## Backtracking # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 97431ae1ece90ded0261facc0e5511f728ea93de Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 23:05:57 +0800 Subject: [PATCH 1320/1939] Create range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 78 ++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Python/range-sum-query-2d-mutable.py diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py new file mode 100644 index 000000000..2bcab018f --- /dev/null +++ b/Python/range-sum-query-2d-mutable.py @@ -0,0 +1,78 @@ +# Time: ctor: O(mlogm * nlogn) +# update: O(logm * logn) +# query: O(logm * logn) +# Space: O(m * n) + +# Binary Indexed Tree (BIT) solution. +class NumMatrix(object): + def __init__(self, matrix): + """ + initialize your data structure here. + :type matrix: List[List[int]] + """ + if not matrix: + return + self.__matrix = matrix + self.__m = len(matrix) + self.__n = len(matrix[0]) + self.__bit = [[0] * (self.__n + 1) for _ in xrange(self.__m + 1)] + for i in xrange(self.__m): + for j in xrange(self.__n): + self.add(i, j, matrix[i][j]) + + + def add(self, row, col, val): + row += 1 + col += 1 + i = row + while i <= self.__m: + j = col + while j <= self.__n: + self.__bit[i][j] += val + j += (j & -j) + i += (i & -i) + + + def update(self, row, col, val): + """ + update the element at matrix[row,col] to val. + :type row: int + :type col: int + :type val: int + :rtype: void + """ + if val - self.__matrix[row][col]: + self.add(row, col, val - self.__matrix[row][col]) + self.__matrix[row][col] = val + + + def sumRegion(self, row1, col1, row2, col2): + """ + sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. + :type row1: int + :type col1: int + :type row2: int + :type col2: int + :rtype: int + """ + def sumRegion_bit(row, col): + row += 1 + col += 1 + ret = 0 + i = row + while i > 0: + j = col + while j > 0: + ret += self.__bit[i][j] + j -= (j & -j) + i -= (i & -i) + return ret + + ret = sumRegion_bit(row2, col2) + if row1 > 0 and col1 > 0: + ret += sumRegion_bit(row1 - 1, col1 - 1) + if col1 > 0: + ret -= sumRegion_bit(row2, col1 - 1) + if row1 > 0: + ret -= sumRegion_bit(row1 - 1, col2) + return ret From 8e04a054800eff057adb0a08833a1ac3ad888dae Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 23:14:53 +0800 Subject: [PATCH 1321/1939] Update range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py index 2bcab018f..71b785b5a 100644 --- a/Python/range-sum-query-2d-mutable.py +++ b/Python/range-sum-query-2d-mutable.py @@ -76,3 +76,10 @@ def sumRegion_bit(row, col): if row1 > 0: ret -= sumRegion_bit(row1 - 1, col2) return ret + + +# Your NumMatrix object will be instantiated and called as such: +# numMatrix = NumMatrix(matrix) +# numMatrix.sumRegion(0, 1, 2, 3) +# numMatrix.update(1, 1, 10) +# numMatrix.sumRegion(1, 2, 3, 4) From 40c220ff4f3447a7331c377a10b69abef2050e1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 23:20:07 +0800 Subject: [PATCH 1322/1939] Update range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py index 71b785b5a..c2217fcc4 100644 --- a/Python/range-sum-query-2d-mutable.py +++ b/Python/range-sum-query-2d-mutable.py @@ -18,20 +18,7 @@ def __init__(self, matrix): self.__bit = [[0] * (self.__n + 1) for _ in xrange(self.__m + 1)] for i in xrange(self.__m): for j in xrange(self.__n): - self.add(i, j, matrix[i][j]) - - - def add(self, row, col, val): - row += 1 - col += 1 - i = row - while i <= self.__m: - j = col - while j <= self.__n: - self.__bit[i][j] += val - j += (j & -j) - i += (i & -i) - + self.__add(i, j, matrix[i][j]) def update(self, row, col, val): """ @@ -42,7 +29,7 @@ def update(self, row, col, val): :rtype: void """ if val - self.__matrix[row][col]: - self.add(row, col, val - self.__matrix[row][col]) + self.__add(row, col, val - self.__matrix[row][col]) self.__matrix[row][col] = val @@ -77,6 +64,17 @@ def sumRegion_bit(row, col): ret -= sumRegion_bit(row1 - 1, col2) return ret + def __add(self, row, col, val): + row += 1 + col += 1 + i = row + while i <= self.__m: + j = col + while j <= self.__n: + self.__bit[i][j] += val + j += (j & -j) + i += (i & -i) + # Your NumMatrix object will be instantiated and called as such: # numMatrix = NumMatrix(matrix) From fef67c2264af17115c16b2d78b127f2053f1fb1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 23:33:11 +0800 Subject: [PATCH 1323/1939] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 62 +++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index 0036f3e18..cb459b677 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -1,7 +1,7 @@ # Time: ctor: O(n), -# update: O(h), -# query: O(h) -# Space: O(h), used by DFS +# update: O(logn), +# query: O(logn) +# Space: O(n), used by DFS # # Given an integer array nums, find the sum of # the elements between indices i and j (i <= j), inclusive. @@ -20,6 +20,7 @@ # and sumRange function is distributed evenly. # +# Segment Tree solutoin. class NumArray(object): def __init__(self, nums): """ @@ -102,6 +103,61 @@ class _SegmentTreeNode: def __init__(self, i, j, s): self.start, self.end, self.sum = i, j, s +# Time: ctor: O(nlogn), +# update: O(logn), +# query: O(logn) +# Space: O(n) +# Binary Indexed Tree (BIT) solution. +class NumArray2(object): + def __init__(self, nums): + """ + initialize your data structure here. + :type nums: List[int] + """ + # Build segment tree. + if not nums: + return + self.__nums = nums + self.__n = len(nums) + self.__bit = [0] * (self.__n + 1) + for i in xrange(self.__n): + self.__add(i, nums[i]) + + def update(self, i, val): + """ + :type i: int + :type val: int + :rtype: int + """ + if val - self.__nums[i]: + self.__add(i, val - self.__nums[i]) + self.__nums[i] = val + + def sumRange(self, i, j): + """ + sum of elements nums[i..j], inclusive. + :type i: int + :type j: int + :rtype: int + """ + def sumRegion_bit(i): + i += 1 + ret = 0 + while i > 0: + ret += self.__bit[i] + i -= (i & -i) + return ret + + ret = sumRegion_bit(j) + if i > 0: + ret -= sumRegion_bit(i - 1) + return ret + + def __add(self, i, val): + i += 1 + while i <= self.__n: + self.__bit[i] += val + i += (i & -i) # Your NumArray object will be instantiated and called as such: # numArray = NumArray(nums) From 138cbdb6ae7b7cd0f16c2cc16a11ff8a5a74a738 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 23:34:42 +0800 Subject: [PATCH 1324/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f377e529f..292f04eec 100644 --- a/README.md +++ b/README.md @@ -175,8 +175,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS -307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(h)_, query: _O(h)_ | _O(h)_ | Medium | LintCode | DFS, Segment Tree -308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(logm + logn)_ | Hard | 📖 | DFS, Segment Tree +307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT +308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(logm + logn)_ | Hard | 📖 | DFS, Segment Tree, BIT ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 6a842322cd3fbc69bcb07ad9921085f5693e600e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 23:35:17 +0800 Subject: [PATCH 1325/1939] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index bb2a3038e..e62087419 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -1,7 +1,7 @@ // Time: ctor: O(n), -// update: O(h), -// query: O(h) -// Space: O(h), used by DFS +// update: O(logn), +// query: O(logn) +// Space: O(n) class NumArray { public: From 430a41fb04ba7724d42dc0a7d994aafc58a051e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 23:35:39 +0800 Subject: [PATCH 1326/1939] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index cb459b677..910cd4ce5 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -1,7 +1,7 @@ # Time: ctor: O(n), # update: O(logn), # query: O(logn) -# Space: O(n), used by DFS +# Space: O(n) # # Given an integer array nums, find the sum of # the elements between indices i and j (i <= j), inclusive. From 075bf612b61d84b51e3bb54807764a6978b79cef Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 23:41:46 +0800 Subject: [PATCH 1327/1939] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index 82916c2b2..2dac82bed 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -1,7 +1,7 @@ // Time: ctor: O(m * n), // update: O(logm + logn), // query: O(logm + logn) -// Space: O(logm + logn), used by DFS +// Space: O(m * n) class NumMatrix { public: From a1d27bd58cf6e8cdd053a4f99debd1ca21d6be85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Nov 2015 23:42:34 +0800 Subject: [PATCH 1328/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 292f04eec..01b5aba83 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Up to date (2015-11-24), there are `292` Algorithms / `13` Database / `4` Shell The number of questions is increasing recently. Here is the classification of all `309` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. -I'll keep updating for full summary and better solutions. Stay tuned for updates. +I'll keep updating for full summary3 and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) ## Algorithms @@ -176,7 +176,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT -308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(logm + logn)_ | Hard | 📖 | DFS, Segment Tree, BIT +308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From bc4f535e4385b6dcb891958edbe9bce0a6202cc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 00:01:51 +0800 Subject: [PATCH 1329/1939] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 71 ++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index 2dac82bed..dfa2a517c 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -121,6 +121,77 @@ class NumMatrix { } }; +// Time: ctor: O(mlogm * nlogn) +// update: O(logm * logn) +// query: O(logm * logn) +// Space: O(m * n) +class NumMatrix2 { +public: + NumMatrix(vector> &matrix) : + matrix_(matrix), m_(matrix.size()) { + + if (m_) { + n_ = matrix_[0].size(); + bit_ = vector>(m_ + 1, vector(n_ + 1)); + for (int i = 0; i < m_; ++i) { + for (int j = 0; j < n_; ++j) { + add(i, j, matrix_[i][j]); + } + } + } + } + + void update(int row, int col, int val) { + if (val - matrix_[row][col]) { + add(row, col, val - matrix_[row][col]); + matrix_[row][col] = val; + } + } + + int sumRegion(int row1, int col1, int row2, int col2) { + int sum = sumRegion_bit(row2, col2); + if (row1 > 0 && col1 > 0) { + sum += sumRegion_bit(row1 - 1, col1 - 1); + } + if (col1 > 0) { + sum -= sumRegion_bit(row2, col1 - 1); + } + if (row1 > 0) { + sum -= sumRegion_bit(row1 - 1, col2); + } + return sum; + } + +private: + vector> &matrix_; + vector> bit_; + int m_, n_; + + int sumRegion_bit(int row, int col) { + ++row, ++col; + int sum = 0; + for (int i = row; i > 0; i -= lower_bit(i)) { + for (int j = col; j > 0; j -= lower_bit(j)) { + sum += bit_[i][j]; + } + } + return sum; + } + + void add(int row, int col, int val) { + ++row, ++col; + for (int i = row; i <= m_; i += lower_bit(i)) { + for (int j = col; j <= n_; j += lower_bit(j)) { + bit_[i][j] += val; + } + } + } + + int lower_bit(int i) { + return i & -i; + } +}; + // Your NumMatrix object will be instantiated and called as such: // NumMatrix numMatrix(matrix); From f4fd3fdcc8d17892a774f57ec1e534b2b2f4dfca Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 00:02:37 +0800 Subject: [PATCH 1330/1939] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index dfa2a517c..b10424d7f 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -3,6 +3,7 @@ // query: O(logm + logn) // Space: O(m * n) +// Segment Tree solution. class NumMatrix { public: NumMatrix(vector> &matrix) : matrix_ref_(matrix) { @@ -125,6 +126,7 @@ class NumMatrix { // update: O(logm * logn) // query: O(logm * logn) // Space: O(m * n) +// Binary Indexed Tree (BIT) solution. class NumMatrix2 { public: NumMatrix(vector> &matrix) : From 315981ce912d66c29305b27724f66193621be9ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 00:11:39 +0800 Subject: [PATCH 1331/1939] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 58 +++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index e62087419..ca55070ef 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -3,6 +3,7 @@ // query: O(logn) // Space: O(n) +// Segment Tree solution. class NumArray { public: NumArray(vector &nums) : nums_ref_(nums) { @@ -99,6 +100,63 @@ class NumArray { } }; +// Time: ctor: O(nlogn), +// update: O(logn), +// query: O(logn) +// Space: O(n) +// Binary Indexed Tree (BIT) solution. +class NumArray2 { +public: + NumArray(vector &nums) : + nums_(nums), n_(nums.size()) { + + bit_ = vector(n_ + 1); + for (int i = 0; i < n_; ++i) { + add(i, nums_[i]); + } + } + + void update(int i, int val) { + if (val - nums_[i]) { + add(i, val - nums_[i]); + nums_[i] = val; + } + } + + int sumRange(int i, int j) { + int sum = sumRegion_bit(j); + if (i > 0) { + sum -= sumRegion_bit(i - 1); + } + return sum; + } + +private: + vector &nums_; + vector bit_; + int n_; + + int sumRegion_bit(int i) { + ++i; + int sum = 0; + for (; i > 0; i -= lower_bit(i)) { + sum += bit_[i]; + } + return sum; + } + + void add(int i, int val) { + ++i; + for (; i <= n_; i += lower_bit(i)) { + bit_[i] += val; + } + } + + int lower_bit(int i) { + return i & -i; + } +}; + // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); From 4bad371e53d178946ee8f1f8b23c7e1a9253647d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 00:16:09 +0800 Subject: [PATCH 1332/1939] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index b10424d7f..e57bcc0d6 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -6,7 +6,7 @@ // Segment Tree solution. class NumMatrix { public: - NumMatrix(vector> &matrix) : matrix_ref_(matrix) { + NumMatrix(vector> &matrix) : matrix_(matrix) { if (!matrix.empty() && !matrix[0].empty()) { const int m = matrix.size(); const int n = matrix[0].size(); @@ -17,8 +17,8 @@ class NumMatrix { } void update(int row, int col, int val) { - if (matrix_ref_[row][col] != val) { - matrix_ref_[row][col] = val; + if (matrix_[row][col] != val) { + matrix_[row][col] = val; updateHelper(root_, make_pair(row, col), val); } } @@ -28,7 +28,7 @@ class NumMatrix { } private: - vector>& matrix_ref_; + vector>& matrix_; class SegmentTreeNode { public: From de4995afb96a99415d871ac743df215f2c711392 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 00:16:30 +0800 Subject: [PATCH 1333/1939] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index ca55070ef..ff7f2eace 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -6,13 +6,13 @@ // Segment Tree solution. class NumArray { public: - NumArray(vector &nums) : nums_ref_(nums) { + NumArray(vector &nums) : nums_(nums) { root_ = buildHelper(nums, 0, nums.size() - 1); } void update(int i, int val) { - if (nums_ref_[i] != val) { - nums_ref_[i] = val; + if (nums_[i] != val) { + nums_[i] = val; updateHelper(root_, i, val); } } @@ -22,7 +22,7 @@ class NumArray { } private: - vector& nums_ref_; + vector& nums_; class SegmentTreeNode { public: From 2884576c314c2eb950968725fb9c2e7dddd34619 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 00:19:52 +0800 Subject: [PATCH 1334/1939] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index ff7f2eace..e67971f04 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -107,11 +107,9 @@ class NumArray { // Binary Indexed Tree (BIT) solution. class NumArray2 { public: - NumArray(vector &nums) : - nums_(nums), n_(nums.size()) { - - bit_ = vector(n_ + 1); - for (int i = 0; i < n_; ++i) { + NumArray(vector &nums) : nums_(nums) { + bit_ = vector(nums_.size() + 1); + for (int i = 0; i < nums_.size(); ++i) { add(i, nums_[i]); } } @@ -134,7 +132,6 @@ class NumArray2 { private: vector &nums_; vector bit_; - int n_; int sumRegion_bit(int i) { ++i; @@ -147,7 +144,7 @@ class NumArray2 { void add(int i, int val) { ++i; - for (; i <= n_; i += lower_bit(i)) { + for (; i <= nums_.size(); i += lower_bit(i)) { bit_[i] += val; } } From 991f5ff459b132f663011a9b5a77f1fe70d450fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 00:22:06 +0800 Subject: [PATCH 1335/1939] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index e57bcc0d6..17e9afefa 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -129,14 +129,13 @@ class NumMatrix { // Binary Indexed Tree (BIT) solution. class NumMatrix2 { public: - NumMatrix(vector> &matrix) : - matrix_(matrix), m_(matrix.size()) { - - if (m_) { - n_ = matrix_[0].size(); - bit_ = vector>(m_ + 1, vector(n_ + 1)); - for (int i = 0; i < m_; ++i) { - for (int j = 0; j < n_; ++j) { + NumMatrix(vector> &matrix) : matrix_(matrix) { + + if (!matrix_.empty()) { + bit_ = vector>(matrix_.size() + 1, + vector(matrix_[0].size() + 1)); + for (int i = 0; i < matrix_.size(); ++i) { + for (int j = 0; j < matrix_[0].size(); ++j) { add(i, j, matrix_[i][j]); } } @@ -167,7 +166,6 @@ class NumMatrix2 { private: vector> &matrix_; vector> bit_; - int m_, n_; int sumRegion_bit(int row, int col) { ++row, ++col; @@ -182,8 +180,8 @@ class NumMatrix2 { void add(int row, int col, int val) { ++row, ++col; - for (int i = row; i <= m_; i += lower_bit(i)) { - for (int j = col; j <= n_; j += lower_bit(j)) { + for (int i = row; i <= matrix_.size(); i += lower_bit(i)) { + for (int j = col; j <= matrix_[0].size(); j += lower_bit(j)) { bit_[i][j] += val; } } From e73e6bc14c2a9571694340c51f691b7d5e1aef1f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 00:24:29 +0800 Subject: [PATCH 1336/1939] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index 910cd4ce5..dbd1b079e 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -118,10 +118,9 @@ def __init__(self, nums): if not nums: return self.__nums = nums - self.__n = len(nums) - self.__bit = [0] * (self.__n + 1) - for i in xrange(self.__n): - self.__add(i, nums[i]) + self.__bit = [0] * (len(self.__nums) + 1) + for i, num in enumerate(self.__nums): + self.__add(i, num) def update(self, i, val): """ @@ -155,7 +154,7 @@ def sumRegion_bit(i): def __add(self, i, val): i += 1 - while i <= self.__n: + while i <= len(self.__nums): self.__bit[i] += val i += (i & -i) From f71e5693517d00264014823bff2e88306b49c9ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 00:27:43 +0800 Subject: [PATCH 1337/1939] Update range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py index c2217fcc4..74b2cf71c 100644 --- a/Python/range-sum-query-2d-mutable.py +++ b/Python/range-sum-query-2d-mutable.py @@ -13,11 +13,10 @@ def __init__(self, matrix): if not matrix: return self.__matrix = matrix - self.__m = len(matrix) - self.__n = len(matrix[0]) - self.__bit = [[0] * (self.__n + 1) for _ in xrange(self.__m + 1)] - for i in xrange(self.__m): - for j in xrange(self.__n): + self.__bit = [[0] * (len(self.__matrix[0]) + 1) \ + for _ in xrange(len(self.__matrix) + 1)] + for i in xrange(len(self.__matrix)): + for j in xrange(len(self.__matrix[0])): self.__add(i, j, matrix[i][j]) def update(self, row, col, val): @@ -68,9 +67,9 @@ def __add(self, row, col, val): row += 1 col += 1 i = row - while i <= self.__m: + while i <= len(self.__matrix): j = col - while j <= self.__n: + while j <= len(self.__matrix[0]): self.__bit[i][j] += val j += (j & -j) i += (i & -i) From 0eb188db8b8b515f7a6bae9c276aae3f9894cdce Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 18:39:57 +0800 Subject: [PATCH 1338/1939] Update range-sum-query-2d-immutable.cpp --- C++/range-sum-query-2d-immutable.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/C++/range-sum-query-2d-immutable.cpp b/C++/range-sum-query-2d-immutable.cpp index 2414f6bfc..b38183c27 100644 --- a/C++/range-sum-query-2d-immutable.cpp +++ b/C++/range-sum-query-2d-immutable.cpp @@ -1,4 +1,4 @@ -// Time: ctor: O(m * n) +// Time: ctor: O(m * n), // lookup: O(1) // Space: O(m * n) @@ -11,27 +11,27 @@ class NumMatrix { const auto m = matrix.size(), n = matrix[0].size(); for (int i = 0; i <= m; ++i) { - sums.emplace_back(n + 1, 0); + sums_.emplace_back(n + 1, 0); } for (int i = 1; i <= m; ++i) { for (int j = 0; j <= n; ++j) { - sums[i][j] = sums[i][j - 1] + matrix[i - 1][j - 1]; + sums_[i][j] = sums_[i][j - 1] + matrix[i - 1][j - 1]; } } for (int j = 0; j <= n; ++j) { for (int i = 1; i <= m; ++i) { - sums[i][j] += sums[i - 1][j]; + sums_[i][j] += sums_[i - 1][j]; } } } int sumRegion(int row1, int col1, int row2, int col2) { - return sums[row2 + 1][col2 + 1] - sums[row2 + 1][col1] - - sums[row1][col2 + 1] + sums[row1][col1]; + return sums_[row2 + 1][col2 + 1] - sums_[row2 + 1][col1] - + sums_[row1][col2 + 1] + sums_[row1][col1]; } private: - vector> sums; + vector> sums_; }; From 17e9217ede4edc415eac96d9d73127a201ce5a4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 18:41:02 +0800 Subject: [PATCH 1339/1939] Update range-sum-query-2d-immutable.py --- Python/range-sum-query-2d-immutable.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/range-sum-query-2d-immutable.py b/Python/range-sum-query-2d-immutable.py index 464fa3169..786f74939 100644 --- a/Python/range-sum-query-2d-immutable.py +++ b/Python/range-sum-query-2d-immutable.py @@ -1,4 +1,4 @@ -# Time: ctor: O(m * n) +# Time: ctor: O(m * n), # lookup: O(1) # Space: O(m * n) # @@ -38,13 +38,13 @@ def __init__(self, matrix): return m, n = len(matrix), len(matrix[0]) - self.sums = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)] + self.__sums = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)] for i in xrange(1, m+1): for j in xrange(1, n+1): - self.sums[i][j] = self.sums[i][j-1] + matrix[i-1][j-1] + self.__sums[i][j] = self.__sums[i][j-1] + matrix[i-1][j-1] for j in xrange(1, n+1): for i in xrange(1, m+1): - self.sums[i][j] += self.sums[i-1][j] + self.__sums[i][j] += self.__sums[i-1][j] def sumRegion(self, row1, col1, row2, col2): """ @@ -55,8 +55,8 @@ def sumRegion(self, row1, col1, row2, col2): :type col2: int :rtype: int """ - return self.sums[row2+1][col2+1] - self.sums[row2+1][col1] - \ - self.sums[row1][col2+1] + self.sums[row1][col1] + return self.__sums[row2+1][col2+1] - self.__sums[row2+1][col1] - \ + self.__sums[row1][col2+1] + self.__sums[row1][col1] # Your NumMatrix object will be instantiated and called as such: From 675cab3920f3cc4f33dda91b00d134efa1db3c09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 22:04:50 +0800 Subject: [PATCH 1340/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 01b5aba83..f11e03f93 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Up to date (2015-11-24), there are `292` Algorithms / `13` Database / `4` Shell The number of questions is increasing recently. Here is the classification of all `309` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. -I'll keep updating for full summary3 and better solutions. Stay tuned for updates. +I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) ## Algorithms From a0433211d1b3ec64366f7b544f2a72fe440713a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 23:55:20 +0800 Subject: [PATCH 1341/1939] Update surrounded-regions.py --- Python/surrounded-regions.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Python/surrounded-regions.py b/Python/surrounded-regions.py index a0badb16c..527c590c9 100644 --- a/Python/surrounded-regions.py +++ b/Python/surrounded-regions.py @@ -25,27 +25,27 @@ class Solution: def solve(self, board): if not board: return - current = [] + q = collections.deque([]) for i in xrange(len(board)): - current.append((i, 0)) - current.append((i, len(board[0]) - 1)) + q.append((i, 0)) + q.append((i, len(board[0]) - 1)) for i in xrange(len(board[0])): - current.append((0, i)) - current.append((len(board) - 1, i)) + q.append((0, i)) + q.append((len(board) - 1, i)) - while current: - i, j = current.pop() + while q: + i, j = q.popleft() if board[i][j] in ['O', 'V']: board[i][j] = 'V' for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: if 0 <= x < len(board) and 0 <= y < len(board[0]) and board[x][y] == 'O': board[x][y] = 'V' - current.append((x, y)) + q.append((x, y)) for i in xrange(len(board)): - for j in range(len(board[0])): + for j in xrange(len(board[0])): if board[i][j] != 'V': board[i][j] = 'X' else: From 94f1d54ab06d8422e0a3e1e0acbe7b00d93ae523 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 23:55:53 +0800 Subject: [PATCH 1342/1939] Update surrounded-regions.py --- Python/surrounded-regions.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/surrounded-regions.py b/Python/surrounded-regions.py index 527c590c9..5c541aaa3 100644 --- a/Python/surrounded-regions.py +++ b/Python/surrounded-regions.py @@ -40,7 +40,8 @@ def solve(self, board): if board[i][j] in ['O', 'V']: board[i][j] = 'V' for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: - if 0 <= x < len(board) and 0 <= y < len(board[0]) and board[x][y] == 'O': + if 0 <= x < len(board) and 0 <= y < len(board[0]) and \ + board[x][y] == 'O': board[x][y] = 'V' q.append((x, y)) From 9465b0a6ff220b8c2707331a79b62f108770c98f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Nov 2015 23:57:02 +0800 Subject: [PATCH 1343/1939] Update surrounded-regions.py --- Python/surrounded-regions.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/surrounded-regions.py b/Python/surrounded-regions.py index 5c541aaa3..98e7a65ad 100644 --- a/Python/surrounded-regions.py +++ b/Python/surrounded-regions.py @@ -31,9 +31,9 @@ def solve(self, board): q.append((i, 0)) q.append((i, len(board[0]) - 1)) - for i in xrange(len(board[0])): - q.append((0, i)) - q.append((len(board) - 1, i)) + for j in xrange(len(board[0])): + q.append((0, j)) + q.append((len(board) - 1, j)) while q: i, j = q.popleft() From 9eb27235b777255dd41f3c0ef5918ef7439f855f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 00:01:40 +0800 Subject: [PATCH 1344/1939] Create surrounded-regions.cpp --- C++/surrounded-regions.cpp | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 C++/surrounded-regions.cpp diff --git a/C++/surrounded-regions.cpp b/C++/surrounded-regions.cpp new file mode 100644 index 000000000..d7bfb0756 --- /dev/null +++ b/C++/surrounded-regions.cpp @@ -0,0 +1,51 @@ +// Time: O(m * n) +// Space: O(m + n) + +class Solution { +public: + void solve(vector>& board) { + if (board.empty()) { + return; + } + + queue> q; + for (int i = 0; i < board.size(); ++i) { + q.emplace(make_pair(i, 0)); + q.emplace(make_pair(i, board[0].size() - 1)); + } + + for (int j = 0; j < board[0].size(); ++j) { + q.emplace(make_pair(0, j)); + q.emplace(make_pair(board.size() - 1, j)); + } + while (!q.empty()) { + int i, j; + tie(i, j) = q.front(); + q.pop(); + if (board[i][j] == 'O' || board[i][j] == 'V') { + board[i][j] = 'V'; + const vector> directions{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; + for (const auto& d : directions) { + const int x = i + d.first, y = j + d.second; + if (0 <= x && x < board.size() && + 0 <= y && y < board[0].size() && + board[x][y] == 'O') { + board[x][y] = 'V'; + q.emplace(make_pair(x, y)); + } + } + } + } + + for (int i = 0; i < board.size(); ++i) { + for (int j = 0; j < board[0].size(); ++j) { + if (board[i][j] != 'V') { + board[i][j] = 'X'; + } else { + board[i][j] = 'O'; + } + } + } + } +}; From c70d3b3770b8614343a33e3fa66b3a4b4b515b07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 00:02:28 +0800 Subject: [PATCH 1345/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f11e03f93..c9f1023a9 100644 --- a/README.md +++ b/README.md @@ -333,7 +333,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 103| [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Python](./Python/binary-tree-zigzag-level-order-traversal.py) | _O(n)_| _O(n)_| Medium || 117| [Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)|[Python](./Python/populating-next-right-pointers-in-each-node-ii.py)| _O(n)_ | _O(1)_ | Hard || 127| [Word Ladder](https://leetcode.com/problems/word-ladder/)|[Python](./Python/word-ladder.py) | _O(n * d)_ | _O(d)_ | Medium || -130| [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)|[Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || +130| [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)|[C++](./C++/surrounded-regions.cpp) [Python](./Python/surrounded-regions.py)| _O(m * n)_ | _O(m + n)_ | Medium || 133| [Clone Graph](https://leetcode.com/problems/clone-graph/)| [Python](./Python/clone-graph.py) | _O(n)_ | _O(n)_ | Medium || 207| [Course Schedule](https://leetcode.com/problems/course-schedule/)| [Python](./Python/course-schedule.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | 210| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Python](./Python/course-schedule-ii.py) | _O(\|V\| + \|E\|)_ | _O(\|E\|)_ | Medium || Topological Sort | From 80af4a0683560cd02e175a3119d1c04f256f2667 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 00:03:51 +0800 Subject: [PATCH 1346/1939] Update binary-tree-paths.cpp --- C++/binary-tree-paths.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/binary-tree-paths.cpp b/C++/binary-tree-paths.cpp index 6d51e934f..44dd1a57f 100644 --- a/C++/binary-tree-paths.cpp +++ b/C++/binary-tree-paths.cpp @@ -20,11 +20,11 @@ class Solution { } void binaryTreePathsRecu(TreeNode *node, vector *path, vector *result) { - if (node == nullptr) { + if (!node) { return; } - if (node->left == nullptr && node->right == nullptr) { + if (!node->left && !node->right) { string ans = ""; for (const auto& n : *path) { ans.append(to_string(n->val).append("->")); @@ -32,13 +32,13 @@ class Solution { result->emplace_back(move(ans.append(to_string(node->val)))); } - if (node->left != nullptr) { + if (node->left) { path->emplace_back(node); binaryTreePathsRecu(node->left, path, result); path->pop_back(); } - if (node->right != nullptr) { + if (node->right) { path->emplace_back(node); binaryTreePathsRecu(node->right, path, result); path->pop_back(); From fef269abbb26aed062c82647f4c1fd740deaa2de Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 00:17:11 +0800 Subject: [PATCH 1347/1939] Update word-search-ii.cpp --- C++/word-search-ii.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/C++/word-search-ii.cpp b/C++/word-search-ii.cpp index 768f0264d..d650c6882 100644 --- a/C++/word-search-ii.cpp +++ b/C++/word-search-ii.cpp @@ -90,10 +90,11 @@ class Solution { visited[i][j] = true; // Try each direction. - vector> direction{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; - for (int k = 0; k < 4; ++k) { + const vector> direction{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; + for (const auto& d : directions) { findWordsDFS(grid, visited, nextNode, - i + direction[k].first, j + direction[k].second, curr, ret); + i + d.first, j + d.second, curr, ret); } visited[i][j] = false; From 4852f5fdba2a04b107b94d813531fd0413766c4c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 00:18:03 +0800 Subject: [PATCH 1348/1939] Update word-search-ii.cpp --- C++/word-search-ii.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/word-search-ii.cpp b/C++/word-search-ii.cpp index d650c6882..7d668ef79 100644 --- a/C++/word-search-ii.cpp +++ b/C++/word-search-ii.cpp @@ -43,7 +43,7 @@ class Solution { vector findWords(vector>& board, vector& words) { unordered_set ret; vector> visited(board.size(), vector(board[0].size(), false)); - string curr; + string cur; TrieNode trie; for (const auto& word : words) { trie.Insert(word); @@ -51,7 +51,7 @@ class Solution { for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[0].size(); ++j) { - findWordsDFS(board, visited, &trie, i, j, curr, ret); + findWordsDFS(board, visited, &trie, i, j, cur, ret); } } @@ -63,7 +63,7 @@ class Solution { TrieNode *trie, int i, int j, - string curr, + string cur, unordered_set &ret) { // Invalid state. if (!trie || i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size()) { @@ -79,11 +79,11 @@ class Solution { TrieNode *nextNode = trie->leaves[grid[i][j]]; // Update current string. - curr.push_back(grid[i][j]); + cur.push_back(grid[i][j]); // Find the string, add to the answers. if (nextNode->isString) { - ret.insert(curr); + ret.insert(cur); } // Marked as visited. @@ -94,7 +94,7 @@ class Solution { {-1, 0}, {1, 0}}; for (const auto& d : directions) { findWordsDFS(grid, visited, nextNode, - i + d.first, j + d.second, curr, ret); + i + d.first, j + d.second, cur, ret); } visited[i][j] = false; From 5129877e25e56f3c24ab046bb66c5d1d2d43b8fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 00:18:21 +0800 Subject: [PATCH 1349/1939] Update word-search-ii.cpp --- C++/word-search-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/word-search-ii.cpp b/C++/word-search-ii.cpp index 7d668ef79..6a6c761cd 100644 --- a/C++/word-search-ii.cpp +++ b/C++/word-search-ii.cpp @@ -94,7 +94,7 @@ class Solution { {-1, 0}, {1, 0}}; for (const auto& d : directions) { findWordsDFS(grid, visited, nextNode, - i + d.first, j + d.second, cur, ret); + i + d.first, j + d.second, cur, ret); } visited[i][j] = false; From a968933d024f606c8e4e0668eddbdfad8a564a12 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 14:09:29 +0800 Subject: [PATCH 1350/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index d1e0ffcb5..66f47faa9 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -16,9 +16,9 @@ def validTree(self, n, edges): # A structure to track each node's [visited_from, neighbors] nodes = collections.defaultdict(lambda: [-1, []]) - for edge in edges: - nodes[edge[0]][neighbors].append(edge[1]) - nodes[edge[1]][neighbors].append(edge[0]) + for u, v in edges: + nodes[u][neighbors].append(v) + nodes[v][neighbors].append(u) if len(nodes) != n: # Check number of nodes. return False From 81a1017ffa546ca88c447f921b1621e933154a5f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 14:11:44 +0800 Subject: [PATCH 1351/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 66f47faa9..cc2f20d55 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -25,8 +25,7 @@ def validTree(self, n, edges): # BFS to check whether the graph is valid tree. visited = {} - q = collections.deque() - q.append(0) + q = collections.deque([0]) while q: i = q.popleft() visited[i] = True @@ -53,14 +52,13 @@ def validTree(self, n, edges): # A structure to track each node's [visited_from, neighbors] nodes = collections.defaultdict(lambda: [-1, []]) - for edge in edges: - nodes[edge[0]][neighbors].append(edge[1]) - nodes[edge[1]][neighbors].append(edge[0]) + for u, v in edges: + nodes[u]][neighbors].append(v) + nodes[v][neighbors].append(u) # BFS to check whether the graph is valid tree. visited = {} - q = collections.deque() - q.append(0) + q = collections.deque([0]) while q: i = q.popleft() visited[i] = True From 58c8befaa5384d6bd8a4315bba24bda8e01cd29a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 14:15:59 +0800 Subject: [PATCH 1352/1939] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index cc2f20d55..54408e956 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -12,15 +12,14 @@ def validTree(self, n, edges): elif n == 1: return True - visited_from, neighbors = 0, 1 - # A structure to track each node's [visited_from, neighbors] - nodes = collections.defaultdict(lambda: [-1, []]) + visited_from = [-1] * n + neighbors = collections.defaultdict(list) for u, v in edges: - nodes[u][neighbors].append(v) - nodes[v][neighbors].append(u) + neighbors[u].append(v) + neighbors[v].append(u) - if len(nodes) != n: # Check number of nodes. + if len(neighbors) != n: # Check number of nodes. return False # BFS to check whether the graph is valid tree. @@ -29,13 +28,13 @@ def validTree(self, n, edges): while q: i = q.popleft() visited[i] = True - for node in nodes[i][neighbors]: - if node != nodes[i][visited_from]: + for node in neighbors[i]: + if node != visited_from[i]: if node in visited: return False else: visited[node] = True - nodes[node][visited_from] = i + visited_from[node] = i q.append(node) return len(visited) == n @@ -48,13 +47,12 @@ class Solution2: # @param {integer[][]} edges # @return {boolean} def validTree(self, n, edges): - visited_from, neighbors = 0, 1 - # A structure to track each node's [visited_from, neighbors] - nodes = collections.defaultdict(lambda: [-1, []]) + visited_from = [-1] * n + neighbors = collections.defaultdict(list) for u, v in edges: - nodes[u]][neighbors].append(v) - nodes[v][neighbors].append(u) + neighbors[u].append(v) + neighbors[v].append(u) # BFS to check whether the graph is valid tree. visited = {} @@ -62,12 +60,12 @@ def validTree(self, n, edges): while q: i = q.popleft() visited[i] = True - for node in nodes[i][neighbors]: - if node != nodes[i][visited_from]: + for node in neighbors[i]: + if node != visited_from[i]: if node in visited: return False else: visited[node] = True - nodes[node][visited_from] = i + visited_from[node] = i q.append(node) return len(visited) == n From 18eff194bfaa14ec9400efcb4ceeb3c0faae053c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 14:54:37 +0800 Subject: [PATCH 1353/1939] Create minimum-height-trees.py --- Python/minimum-height-trees.py | 93 ++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Python/minimum-height-trees.py diff --git a/Python/minimum-height-trees.py b/Python/minimum-height-trees.py new file mode 100644 index 000000000..d46e1a3cd --- /dev/null +++ b/Python/minimum-height-trees.py @@ -0,0 +1,93 @@ +# Time: O(n) +# Space: O(n) + +# 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] +# +# Hint: +# +# How many MHTs can a graph have at most? +# Note: +# +# (1) According to the definition of tree on Wikipedia: +# "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. + +class Solution(object): + def findMinHeightTrees(self, n, edges): + """ + :type n: int + :type edges: List[List[int]] + :rtype: List[int] + """ + if n == 1: + return [0] + neighbors = collections.defaultdict(list) + degrees = collections.defaultdict(int) + for u, v in edges: + neighbors[u].append(v) + neighbors[v].append(u) + degrees[u] += 1 + degrees[v] += 1 + + pre_level, unvisited = [], set(xrange(n)) + for i in xrange(n): + if degrees[i] == 1: # A leaf. + pre_level.append(i) + + # A graph can have 2 MHTs at most. + # BFS from the leaves until the number + # of the unvisited nodes is less than 3. + while len(unvisited) > 2: + this_level = [] + for u in pre_level: + unvisited.remove(u) + for v in neighbors[u]: + if v in unvisited: + degrees[v] -= 1 + if degrees[v] == 1: + this_level += [v] + pre_level = this_level + + return list(unvisited) From 488d565aa7eb8f990c1921578517d687b01546cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 14:59:17 +0800 Subject: [PATCH 1354/1939] Update minimum-height-trees.py --- Python/minimum-height-trees.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Python/minimum-height-trees.py b/Python/minimum-height-trees.py index d46e1a3cd..826c99f91 100644 --- a/Python/minimum-height-trees.py +++ b/Python/minimum-height-trees.py @@ -63,17 +63,15 @@ def findMinHeightTrees(self, n, edges): """ if n == 1: return [0] - neighbors = collections.defaultdict(list) - degrees = collections.defaultdict(int) + + neighbors = collections.defaultdict(set) for u, v in edges: - neighbors[u].append(v) - neighbors[v].append(u) - degrees[u] += 1 - degrees[v] += 1 + neighbors[u].add(v) + neighbors[v].add(u) pre_level, unvisited = [], set(xrange(n)) for i in xrange(n): - if degrees[i] == 1: # A leaf. + if len(neighbors[i]) == 1: # A leaf. pre_level.append(i) # A graph can have 2 MHTs at most. @@ -85,8 +83,8 @@ def findMinHeightTrees(self, n, edges): unvisited.remove(u) for v in neighbors[u]: if v in unvisited: - degrees[v] -= 1 - if degrees[v] == 1: + neighbors[v].remove(u) + if len(neighbors[v]) == 1: this_level += [v] pre_level = this_level From 259ba972bc8542e87bf61ed0976f84fd82c22b8e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 15:20:15 +0800 Subject: [PATCH 1355/1939] Create minimum-height-trees.cpp --- C++/minimum-height-trees.cpp | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 C++/minimum-height-trees.cpp diff --git a/C++/minimum-height-trees.cpp b/C++/minimum-height-trees.cpp new file mode 100644 index 000000000..f848e90b1 --- /dev/null +++ b/C++/minimum-height-trees.cpp @@ -0,0 +1,49 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector findMinHeightTrees(int n, vector>& edges) { + if (n == 1) { + return {0}; + } + + unordered_map> neighbors; + for (const auto& e : edges) { + int u, v; + tie(u, v) = e; + neighbors[u].emplace(v); + neighbors[v].emplace(u); + } + + vector pre_level, cur_level; + unordered_set unvisited; + for (int i = 0; i < n; ++i) { + if (neighbors[i].size() == 1) { // A leaf. + pre_level.emplace_back(i); + } + unvisited.emplace(i); + } + + // A graph can have 2 MHTs at most. + // BFS from the leaves until the number + // of the unvisited nodes is less than 3. + while (unvisited.size() > 2) { + cur_level.clear(); + for (const auto& u : pre_level) { + unvisited.erase(u); + for (const auto& v : neighbors[u]) { + if (unvisited.count(v)) { + neighbors[v].erase(u); + if (neighbors[v].size() == 1) { + cur_level.emplace_back(v); + } + } + } + } + swap(pre_level, cur_level); + } + vector res(unvisited.begin(), unvisited.end()); + return res; + } +}; From 762f2343a1e410d3f9d608241ea535d5c5d4ad60 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 15:21:56 +0800 Subject: [PATCH 1356/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c9f1023a9..f9acd5e04 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-309%20%2F%20309-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-310%20%2F%20310-ff69b4.svg) -Up to date (2015-11-24), there are `292` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-26), there are `293` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `309` questions. +Here is the classification of all `310` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -340,6 +340,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 261| [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [C++](./C++/graph-valid-tree.cpp) [Python](./Python/graph-valid-tree.py) | _O(\|V\| + \|E\|)_ | _O(\|V\| + \|E\|)_ | Medium | 📖 | 269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Hard |📖| Topological Sort, BFS, DFS | 286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [C++](./C++/walls-and-gates.cpp) [Python](./Python/walls-and-gates.py) | _O(m * n)_ | _O(g)_ | Medium | 📖 | +310| [Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/)| [C++](./C++/minimum-height-trees.cpp) [Python](./Python/minimum-height-trees.py) | _O(n)_ | _O(n)_ | Medium || ## Depth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 1ae4a13fb1abb9355c1ea76343aa71be4dfc74c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 15:23:30 +0800 Subject: [PATCH 1357/1939] Update minimum-height-trees.py --- Python/minimum-height-trees.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Python/minimum-height-trees.py b/Python/minimum-height-trees.py index 826c99f91..fc91bd893 100644 --- a/Python/minimum-height-trees.py +++ b/Python/minimum-height-trees.py @@ -69,23 +69,24 @@ def findMinHeightTrees(self, n, edges): neighbors[u].add(v) neighbors[v].add(u) - pre_level, unvisited = [], set(xrange(n)) + pre_level, unvisited = [], set() for i in xrange(n): if len(neighbors[i]) == 1: # A leaf. pre_level.append(i) + unvisited.add(i) # A graph can have 2 MHTs at most. # BFS from the leaves until the number # of the unvisited nodes is less than 3. while len(unvisited) > 2: - this_level = [] + cur_level = [] for u in pre_level: unvisited.remove(u) for v in neighbors[u]: if v in unvisited: neighbors[v].remove(u) if len(neighbors[v]) == 1: - this_level += [v] - pre_level = this_level + cur_level += [v] + pre_level = cur_level return list(unvisited) From 3b43e774686f3eaf6f88068ebad69de85ca7ff18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 15:24:49 +0800 Subject: [PATCH 1358/1939] Update minimum-height-trees.cpp --- C++/minimum-height-trees.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/minimum-height-trees.cpp b/C++/minimum-height-trees.cpp index f848e90b1..feba813fc 100644 --- a/C++/minimum-height-trees.cpp +++ b/C++/minimum-height-trees.cpp @@ -43,6 +43,7 @@ class Solution { } swap(pre_level, cur_level); } + vector res(unvisited.begin(), unvisited.end()); return res; } From 008a6d5595b96b2818fd5e8da0a8b0e3c235bd49 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Nov 2015 19:06:22 +0800 Subject: [PATCH 1359/1939] Update minimum-height-trees.py --- Python/minimum-height-trees.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/minimum-height-trees.py b/Python/minimum-height-trees.py index fc91bd893..dbd7df905 100644 --- a/Python/minimum-height-trees.py +++ b/Python/minimum-height-trees.py @@ -86,7 +86,7 @@ def findMinHeightTrees(self, n, edges): if v in unvisited: neighbors[v].remove(u) if len(neighbors[v]) == 1: - cur_level += [v] + cur_level.append(v) pre_level = cur_level return list(unvisited) From a69175315949a783181556d69282c70d2ab01780 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 11:54:42 +0800 Subject: [PATCH 1360/1939] Update spiral-matrix-ii.py --- Python/spiral-matrix-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/spiral-matrix-ii.py b/Python/spiral-matrix-ii.py index ddfabca49..d0b870bd5 100644 --- a/Python/spiral-matrix-ii.py +++ b/Python/spiral-matrix-ii.py @@ -17,7 +17,7 @@ class Solution: # @return a list of lists of integer def generateMatrix(self, n): - matrix = [[0 for i in xrange(n)] for i in xrange(n)] + matrix = [[0 for _ in xrange(n)] for _ in xrange(n)] left, right, top, bottom, num = 0, n - 1, 0, n - 1, 1 From e52c24645f319621bc8be8765e370c774a8b493f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 12:21:38 +0800 Subject: [PATCH 1361/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f9acd5e04..4ddf5aa62 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || -59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(m * n)_ | _O(1)_ | Medium || +59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || From 89ab349d6aed3bb517d7c735b058bf9e5db1c471 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 14:50:58 +0800 Subject: [PATCH 1362/1939] Create sparse-matrix-multiplication.cpp --- C++/sparse-matrix-multiplication.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/sparse-matrix-multiplication.cpp diff --git a/C++/sparse-matrix-multiplication.cpp b/C++/sparse-matrix-multiplication.cpp new file mode 100644 index 000000000..5cb69247b --- /dev/null +++ b/C++/sparse-matrix-multiplication.cpp @@ -0,0 +1,20 @@ +// Time: O(m * n * l), A is m x n matrix, B is n x l matrix +// Space: O(m * l) + +class Solution { +public: + vector> multiply(vector>& A, vector>& B) { + const int m = A.size(), n = A[0].size(), l = B[0].size(); + vector> res(m, vector(l)); + for (int i = 0; i < m; ++i) { + for (int k = 0; k < n; ++k) { + if (A[i][k] != 0) { + for (int j = 0; j < l; ++j) { + res[i][j] += A[i][k] * B[k][j]; + } + } + } + } + return res; + } +}; From 8c9455b823b4be173bc51b10247f87f8f6070796 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 15:05:08 +0800 Subject: [PATCH 1363/1939] Create sparse-matrix-multiplication.py --- Python/sparse-matrix-multiplication.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Python/sparse-matrix-multiplication.py diff --git a/Python/sparse-matrix-multiplication.py b/Python/sparse-matrix-multiplication.py new file mode 100644 index 000000000..30dc340eb --- /dev/null +++ b/Python/sparse-matrix-multiplication.py @@ -0,0 +1,18 @@ +# Time: O(m * n * l), A is m x n matrix, B is n x l matrix +# Space: O(m * l) + +class Solution(object): + def multiply(self, A, B): + """ + :type A: List[List[int]] + :type B: List[List[int]] + :rtype: List[List[int]] + """ + m, n, l = len(A), len(A[0]), len(B[0]) + res = [[0 for _ in xrange(l)] for _ in xrange(m)] + for i in xrange(m): + for k in xrange(n): + if A[i][k]: + for j in xrange(l): + res[i][j] += A[i][k] * B[k][j] + return res From 889acaa30328c1de77e333cba7b0b6e281b392e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 15:05:39 +0800 Subject: [PATCH 1364/1939] Update sparse-matrix-multiplication.cpp --- C++/sparse-matrix-multiplication.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/sparse-matrix-multiplication.cpp b/C++/sparse-matrix-multiplication.cpp index 5cb69247b..3910db4fe 100644 --- a/C++/sparse-matrix-multiplication.cpp +++ b/C++/sparse-matrix-multiplication.cpp @@ -8,7 +8,7 @@ class Solution { vector> res(m, vector(l)); for (int i = 0; i < m; ++i) { for (int k = 0; k < n; ++k) { - if (A[i][k] != 0) { + if (A[i][k]) { for (int j = 0; j < l; ++j) { res[i][j] += A[i][k] * B[k][j]; } From b47a7442b66033b22eb90ea5fb7d23a40956259c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 15:07:57 +0800 Subject: [PATCH 1365/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4ddf5aa62..1de0a833d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-310%20%2F%20310-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-311%20%2F%20311-ff69b4.svg) -Up to date (2015-11-26), there are `293` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-28), there are `294` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `310` questions. +Here is the classification of all `311` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -92,6 +92,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| 293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(n * (c+1))_ | _O(1)_ | Easy |📖|| 296| [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) | [C++](./C++/best-meeting-point.cpp) [Python](./Python/best-meeting-point.py) | _O(n)_ | _O(n)_ | Medium |📖|| +311| [Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/) | [C++](./C++/sparse-matrix-multiplication.cpp) [Python](./Python/sparse-matrix-multiplication.py) | _O(m * n * l)_ | _O(m * l)_ | Medium |📖|| ## String # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 14e563e839d59fc77b18f24bb35b551148e9dfef Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 15:25:11 +0800 Subject: [PATCH 1366/1939] Update and rename spiralOrder.cpp to spiral-matrix.cpp --- C++/spiral-matrix.cpp | 89 +++++++++++++++++++++++++++++++++++++++++++ C++/spiralOrder.cpp | 40 ------------------- 2 files changed, 89 insertions(+), 40 deletions(-) create mode 100644 C++/spiral-matrix.cpp delete mode 100644 C++/spiralOrder.cpp diff --git a/C++/spiral-matrix.cpp b/C++/spiral-matrix.cpp new file mode 100644 index 000000000..122fde62b --- /dev/null +++ b/C++/spiral-matrix.cpp @@ -0,0 +1,89 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + vector spiralOrder(vector>& matrix) { + vector result; + if (matrix.empty()) { + return result; + } + + for (int left = 0, right = matrix[0].size() - 1, + top = 0, bottom = matrix.size() - 1; + left <= right && top <= bottom; + ++left, --right, ++top, --bottom) { + + for (int j = left; j <= right; ++j) { + result.emplace_back(matrix[top][j]); + } + for (int i = top + 1; i < bottom; ++i) { + result.emplace_back(matrix[i][right]); + } + for (int j = right; top < bottom && j >= left; --j) { + result.emplace_back(matrix[bottom][j]); + } + for (int i = bottom - 1; left < right && i > top; --i) { + result.emplace_back(matrix[i][left]); + } + } + + return result; + } +}; + +// Time: O(m * n) +// Space: O(1) +class Solution2 { +public: + vector spiralOrder(vector>& matrix) { + const int m = matrix.size(); + vector ans; + if (m == 0) { + return ans; + } + + const int n = matrix.front().size(); + enum Action {RIGHT, DOWN, LEFT, UP}; + Action action = RIGHT; + for (int i = 0, j = 0, begini = 0, beginj = 0, endi = m, + endj = n, cnt = 0, total = m * n; cnt < total; ++cnt) { + + ans.emplace_back(matrix[i][j]); + + switch (action) { + case RIGHT: + if (j + 1 < endj) { + ++j; + } else { + action = DOWN, ++begini, ++i; + } + break; + case DOWN: + if (i + 1 < endi) { + ++i; + } else { + action = LEFT, --endj, --j; + } + break; + case LEFT: + if (j - 1 >= beginj) { + --j; + } else { + action = UP, --endi, --i; + } + break; + case UP: + if (i - 1 >= begini) { + --i; + } else { + action = RIGHT, ++beginj, ++j; + } + break; + default: + break; + } + } + return ans; + } +}; diff --git a/C++/spiralOrder.cpp b/C++/spiralOrder.cpp deleted file mode 100644 index 21e2b96cd..000000000 --- a/C++/spiralOrder.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - vector spiralOrder(vector > &matrix) { - const int m = matrix.size(); - vector ans; - if(m == 0) return ans; - - const int n = matrix.front().size(); - enum Action {RIGHT, DOWN, LEFT, UP}; - Action action = RIGHT; - for(int i = 0, j = 0, begini = 0, beginj = 0, endi = m, endj = n, cnt = 0, total = m * n; cnt < total; ++cnt) { - ans.push_back(matrix[i][j]); - - switch(action) { - case RIGHT: - if(j + 1 < endj) ++j; - else action = DOWN, ++begini, ++i; - break; - case DOWN: - if(i + 1 < endi) ++i; - else action = LEFT, --endj, --j; - break; - case LEFT: - if(j - 1 >= beginj) --j; - else action = UP, --endi, --i; - break; - case UP: - if(i - 1 >= begini) --i; - else action = RIGHT, ++beginj, ++j; - break; - default: - break; - } - } - return ans; - } -}; From 8071af5d42922a44d721366ea31b3b32c929fbb2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 15:26:24 +0800 Subject: [PATCH 1367/1939] Update spiral-matrix.cpp --- C++/spiral-matrix.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/C++/spiral-matrix.cpp b/C++/spiral-matrix.cpp index 122fde62b..61d6fc9ba 100644 --- a/C++/spiral-matrix.cpp +++ b/C++/spiral-matrix.cpp @@ -4,9 +4,9 @@ class Solution { public: vector spiralOrder(vector>& matrix) { - vector result; + vector res; if (matrix.empty()) { - return result; + return res; } for (int left = 0, right = matrix[0].size() - 1, @@ -15,20 +15,20 @@ class Solution { ++left, --right, ++top, --bottom) { for (int j = left; j <= right; ++j) { - result.emplace_back(matrix[top][j]); + res.emplace_back(matrix[top][j]); } for (int i = top + 1; i < bottom; ++i) { - result.emplace_back(matrix[i][right]); + res.emplace_back(matrix[i][right]); } for (int j = right; top < bottom && j >= left; --j) { - result.emplace_back(matrix[bottom][j]); + res.emplace_back(matrix[bottom][j]); } for (int i = bottom - 1; left < right && i > top; --i) { - result.emplace_back(matrix[i][left]); + res.emplace_back(matrix[i][left]); } } - return result; + return res; } }; @@ -38,9 +38,9 @@ class Solution2 { public: vector spiralOrder(vector>& matrix) { const int m = matrix.size(); - vector ans; + vector res; if (m == 0) { - return ans; + return res; } const int n = matrix.front().size(); @@ -49,7 +49,7 @@ class Solution2 { for (int i = 0, j = 0, begini = 0, beginj = 0, endi = m, endj = n, cnt = 0, total = m * n; cnt < total; ++cnt) { - ans.emplace_back(matrix[i][j]); + res.emplace_back(matrix[i][j]); switch (action) { case RIGHT: @@ -84,6 +84,6 @@ class Solution2 { break; } } - return ans; + return res; } }; From 6f62755b2d8998bce06180d3fd75aa38208a6fc7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 15:31:57 +0800 Subject: [PATCH 1368/1939] Update and rename generateMatrix.cpp to spiral-matrix-ii.cpp --- C++/generateMatrix.cpp | 36 ------------------ C++/spiral-matrix-ii.cpp | 81 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 36 deletions(-) delete mode 100644 C++/generateMatrix.cpp create mode 100644 C++/spiral-matrix-ii.cpp diff --git a/C++/generateMatrix.cpp b/C++/generateMatrix.cpp deleted file mode 100644 index 9ef1713f0..000000000 --- a/C++/generateMatrix.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(n^2) - -class Solution { - public: - vector > generateMatrix(int n) { - vector > v(n, vector(n, 0)); - enum Action {RIGHT, DOWN, LEFT, UP}; - Action action = RIGHT; - for(int i = 0, j = 0, cnt = 0, total = n * n; cnt < total;) { - v[i][j] = ++cnt; - - switch(action) { - case RIGHT: - if(j + 1 < n && v[i][j + 1] == 0) ++j; - else action = DOWN, ++i; - break; - case DOWN: - if(i + 1 < n && v[i + 1][j] == 0) ++i; - else action = LEFT, --j; - break; - case LEFT: - if(j - 1 >= 0 && v[i][j - 1] == 0) --j; - else action = UP, --i; - break; - case UP: - if(i - 1 >= 0 && v[i - 1][j] == 0) --i; - else action = RIGHT, ++j; - break; - default: - break; - } - } - return v; - } -}; diff --git a/C++/spiral-matrix-ii.cpp b/C++/spiral-matrix-ii.cpp new file mode 100644 index 000000000..ed689f7f5 --- /dev/null +++ b/C++/spiral-matrix-ii.cpp @@ -0,0 +1,81 @@ +// Time: O(n^2) +// Space: O(1) + +class Solution { +public: + /** + * @param n an integer + * @return a square matrix + */ + vector> generateMatrix(int n) { + vector> matrix(n, vector(n)); + + for (int num = 0, left = 0, right = n - 1, top = 0, bottom = n - 1; + left <= right && top <= bottom; + ++left, --right, ++top, --bottom) { + + for (int j = left; j <= right; ++j) { + matrix[top][j] = ++num; + } + for (int i = top + 1; i < bottom; ++i) { + matrix[i][right] = ++num; + } + for (int j = right; top < bottom && j >= left; --j) { + matrix[bottom][j] = ++num; + } + for (int i = bottom - 1; left < right && i >= top + 1; --i) { + matrix[i][left] = ++num; + } + } + + return matrix; + } +}; + +// Time: O(n^2) +// Space: O(1) +class Solution2 { + public: + vector > generateMatrix(int n) { + vector > matrix(n, vector(n)); + enum Action {RIGHT, DOWN, LEFT, UP}; + Action action = RIGHT; + for (int i = 0, j = 0, cnt = 0, total = n * n; cnt < total;) { + matrix[i][j] = ++cnt; + + switch (action) { + case RIGHT: + if (j + 1 < n && matrix[i][j + 1] == 0) { + ++j; + } else { + action = DOWN, ++i; + } + break; + case DOWN: + if (i + 1 < n && matrix[i + 1][j] == 0) { + ++i; + } else { + action = LEFT, --j; + } + break; + case LEFT: + if (j - 1 >= 0 && matrix[i][j - 1] == 0) { + --j; + } else { + action = UP, --i; + } + break; + case UP: + if (i - 1 >= 0 && matrix[i - 1][j] == 0) { + --i; + } else { + action = RIGHT, ++j; + } + break; + default: + break; + } + } + return matrix; + } +}; From 84c6b65e543dbc02c58084a51495cba7d7e1e574 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 15:33:02 +0800 Subject: [PATCH 1369/1939] Update spiral-matrix-ii.cpp --- C++/spiral-matrix-ii.cpp | 80 ++++++++++++++++++++-------------------- 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/C++/spiral-matrix-ii.cpp b/C++/spiral-matrix-ii.cpp index ed689f7f5..52d40d6ca 100644 --- a/C++/spiral-matrix-ii.cpp +++ b/C++/spiral-matrix-ii.cpp @@ -35,47 +35,47 @@ class Solution { // Time: O(n^2) // Space: O(1) class Solution2 { - public: - vector > generateMatrix(int n) { - vector > matrix(n, vector(n)); - enum Action {RIGHT, DOWN, LEFT, UP}; - Action action = RIGHT; - for (int i = 0, j = 0, cnt = 0, total = n * n; cnt < total;) { - matrix[i][j] = ++cnt; +public: + vector > generateMatrix(int n) { + vector > matrix(n, vector(n)); + enum Action {RIGHT, DOWN, LEFT, UP}; + Action action = RIGHT; + for (int i = 0, j = 0, cnt = 0, total = n * n; cnt < total;) { + matrix[i][j] = ++cnt; - switch (action) { - case RIGHT: - if (j + 1 < n && matrix[i][j + 1] == 0) { - ++j; - } else { - action = DOWN, ++i; - } - break; - case DOWN: - if (i + 1 < n && matrix[i + 1][j] == 0) { - ++i; - } else { - action = LEFT, --j; - } - break; - case LEFT: - if (j - 1 >= 0 && matrix[i][j - 1] == 0) { - --j; - } else { - action = UP, --i; - } - break; - case UP: - if (i - 1 >= 0 && matrix[i - 1][j] == 0) { - --i; - } else { - action = RIGHT, ++j; - } - break; - default: - break; - } + switch (action) { + case RIGHT: + if (j + 1 < n && matrix[i][j + 1] == 0) { + ++j; + } else { + action = DOWN, ++i; + } + break; + case DOWN: + if (i + 1 < n && matrix[i + 1][j] == 0) { + ++i; + } else { + action = LEFT, --j; + } + break; + case LEFT: + if (j - 1 >= 0 && matrix[i][j - 1] == 0) { + --j; + } else { + action = UP, --i; + } + break; + case UP: + if (i - 1 >= 0 && matrix[i - 1][j] == 0) { + --i; + } else { + action = RIGHT, ++j; + } + break; + default: + break; } - return matrix; } + return matrix; + } }; From a53372ab979d08af488ff145a020c751925bc9ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Nov 2015 15:38:45 +0800 Subject: [PATCH 1370/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1de0a833d..009d58459 100644 --- a/README.md +++ b/README.md @@ -65,8 +65,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || -54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || -59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || +54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || +59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [C++](./C++/spiral-matrix-ii.cpp) [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || From 0ff86d24dadef8542b4df2b22cdb7b8fc0191789 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Nov 2015 20:38:18 +0800 Subject: [PATCH 1371/1939] Update sudoku-solver.py --- Python/sudoku-solver.py | 67 +++++++++++++++++------------------------ 1 file changed, 27 insertions(+), 40 deletions(-) diff --git a/Python/sudoku-solver.py b/Python/sudoku-solver.py index ed997c11f..fff654616 100644 --- a/Python/sudoku-solver.py +++ b/Python/sudoku-solver.py @@ -13,46 +13,33 @@ class Solution: # Solve the Sudoku by modifying the input board in-place. # Do not return any value. def solveSudoku(self, board): - for i in xrange(len(board)): - for j in xrange(len(board[0])): - if(board[i][j] == '.'): - for k in xrange(9): - board[i][j] = chr(ord('1') + k) - if self.isValid(board, i, j) and self.solveSudoku(board): - return True - board[i][j] = '.' + def isValid(board, x, y): + for i in xrange(9): + if i != x and board[i][y] == board[x][y]: return False - return True - - def isValid(self, board, x, y): - for i in xrange(9): - if i != x and board[i][y] == board[x][y]: - return False - - for j in xrange(9): - if j != y and board[x][j] == board[x][y]: - return False - - i = 3 * (x / 3) - while i < 3 * (x / 3 + 1): - j = 3 * (y / 3) - while j < 3 * (y / 3 + 1): - if (i != x or j != y) and board[i][j] == board[x][y]: + for j in xrange(9): + if j != y and board[x][j] == board[x][y]: return False - j += 1 - i += 1 - - return True + i = 3 * (x / 3) + while i < 3 * (x / 3 + 1): + j = 3 * (y / 3) + while j < 3 * (y / 3 + 1): + if (i != x or j != y) and board[i][j] == board[x][y]: + return False + j += 1 + i += 1 + return True + + def solver(board): + for i in xrange(len(board)): + for j in xrange(len(board[0])): + if(board[i][j] == '.'): + for k in xrange(9): + board[i][j] = chr(ord('1') + k) + if isValid(board, i, j) and solver(board): + return True + board[i][j] = '.' + return False + return True - -if __name__ == "__main__": - board = [['5', '3', '.', '.', '7', '.', '.', '.', '.'], - ['6', '.', '.', '1', '9', '5', '.', '.', '.'], - ['.', '9', '8', '.', '.', '.', '.', '6', '.'], - ['8', '.', '.', '.', '6', '.', '.', '.', '3'], - ['4', '.', '.', '8', '.', '3', '.', '.', '1'], - ['7', '.', '.', '.', '2', '.', '.', '.', '6'], - ['.', '6', '.', '.', '.', '.', '2', '8', '.'], - ['.', '.', '.', '4', '1', '9', '.', '.', '5'], - ['.', '.', '.', '.', '8', '.', '.', '7', '9']] - print Solution().solveSudoku(board) + solver(board) From 63e003325010d873fdb711d708739da08ccdc243 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Nov 2015 21:56:18 +0800 Subject: [PATCH 1372/1939] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 009d58459..c3c154b72 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-311%20%2F%20311-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-312%20%2F%20312-ff69b4.svg) -Up to date (2015-11-28), there are `294` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-11-30), there are `295` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `311` questions. +Here is the classification of all `312` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From 7d65e7f3ca4342a4cc653cc2b94c9951ecaa86aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Nov 2015 22:07:05 +0800 Subject: [PATCH 1373/1939] Create burst-balloons.cpp --- C++/burst-balloons.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/burst-balloons.cpp diff --git a/C++/burst-balloons.cpp b/C++/burst-balloons.cpp new file mode 100644 index 000000000..035544c69 --- /dev/null +++ b/C++/burst-balloons.cpp @@ -0,0 +1,30 @@ +// Time: O(n^3) +// Space: O(n^2) + +class Solution { +public: + int maxCoins(vector& nums) { + vector coins; + coins.emplace_back(1); + for (const auto& n : nums) { + if (n > 0) { + coins.emplace_back(n); + } + } + coins.emplace_back(1); + + vector> max_coins(coins.size(), vector(coins.size())); + for (int k = 2; k < coins.size(); ++k) { + for (int left = 0; left < coins.size() - k; ++left) { + const int right = left + k; + for (int i = left + 1; i < right; ++i) { + max_coins[left][right] = max(max_coins[left][right], + coins[left] * coins[i] * coins[right] + + max_coins[left][i] + max_coins[i][right]); + } + } + } + + return max_coins[0][coins.size() - 1]; + } +}; From 5f3d1bcea1f9fa72004f20d6d1d77592be8cf15f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Nov 2015 22:08:47 +0800 Subject: [PATCH 1374/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c3c154b72..986d82a51 100644 --- a/README.md +++ b/README.md @@ -404,6 +404,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 303| [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)| [C++](./C++/range-sum-query-immutable.cpp) [Python](./Python/range-sum-query-immutable.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(n)_ | Easy || 304| [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/)| [C++](./C++/range-sum-query-2d-immutable.cpp) [Python](./Python/range-sum-query-2d-immutable.py) | ctor: _O(m * n)_, lookup: _O(1)_ | _O(m * n)_ | Medium || 309| [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-cooldown.py) | _O(n)_ | _O(1)_ | Medium || +312| [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./C++/burst-balloons.cpp) [Python](./Python/burst-balloons.py) | _O(n^3)_ | _O(n^2)_ | Medium || ## Backtracking # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 9630088f247523de790179a3c97176ccb664e23e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Nov 2015 22:12:04 +0800 Subject: [PATCH 1375/1939] Update burst-balloons.cpp --- C++/burst-balloons.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/burst-balloons.cpp b/C++/burst-balloons.cpp index 035544c69..91f5e5dde 100644 --- a/C++/burst-balloons.cpp +++ b/C++/burst-balloons.cpp @@ -16,8 +16,7 @@ class Solution { vector> max_coins(coins.size(), vector(coins.size())); for (int k = 2; k < coins.size(); ++k) { for (int left = 0; left < coins.size() - k; ++left) { - const int right = left + k; - for (int i = left + 1; i < right; ++i) { + for (int i = left + 1, right = left + k; i < right; ++i) { max_coins[left][right] = max(max_coins[left][right], coins[left] * coins[i] * coins[right] + max_coins[left][i] + max_coins[i][right]); From 701fb63359e00b13d91ac3ec152c6f96bdfbc889 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Dec 2015 00:29:47 +0800 Subject: [PATCH 1376/1939] Create burst-balloons.py --- Python/burst-balloons.py | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/burst-balloons.py diff --git a/Python/burst-balloons.py b/Python/burst-balloons.py new file mode 100644 index 000000000..8f7774316 --- /dev/null +++ b/Python/burst-balloons.py @@ -0,0 +1,52 @@ +# Time: O(n^3) +# Space: O(n^2) + +# 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 +# + +# TLE, although it could pass in C++. +class Solution(object): + def maxCoins(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + coins = [1] + [i for i in nums if i > 0] + [1] + n = len(coins) + max_coins = [[0 for _ in xrange(n)] for _ in xrange(n)] + + for k in xrange(2, n): + for left in xrange(n - k): + right = left + k + for i in xrange(left + 1, right): + max_coins[left][right] = max(max_coins[left][right], \ + coins[left] * coins[i] * coins[right] + \ + max_coins[left][i] + max_coins[i][right]) + + return max_coins[0][-1] + From f012ab916f50882245ae074b4d9ebb898d9e9e9a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Dec 2015 18:38:53 +0800 Subject: [PATCH 1377/1939] Update burst-balloons.py --- Python/burst-balloons.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/burst-balloons.py b/Python/burst-balloons.py index 8f7774316..acdd5c15e 100644 --- a/Python/burst-balloons.py +++ b/Python/burst-balloons.py @@ -29,7 +29,6 @@ # coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 # -# TLE, although it could pass in C++. class Solution(object): def maxCoins(self, nums): """ From 49fbb194414fe7366f026c5856631c3c10736db9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Dec 2015 21:23:15 +0800 Subject: [PATCH 1378/1939] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 986d82a51..5476eb729 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-312%20%2F%20312-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-313%20%2F%20313-ff69b4.svg) -Up to date (2015-11-30), there are `295` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-03), there are `296` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `312` questions. +Here is the classification of all `313` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From bfdf99834bb7af84c49946718507529618f69e44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 00:40:08 +0800 Subject: [PATCH 1379/1939] Update ugly-number-ii.cpp --- C++/ugly-number-ii.cpp | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/C++/ugly-number-ii.cpp b/C++/ugly-number-ii.cpp index 910a209eb..57503e2a1 100644 --- a/C++/ugly-number-ii.cpp +++ b/C++/ugly-number-ii.cpp @@ -1,8 +1,38 @@ // Time: O(n) -// Space: O(1) +// Space: O(n) -// Heap solution. +// DP solution. (20ms) class Solution { +public: + int nthUglyNumber(int n) { + vector uglies{1}; + + int f2 = 2, f3 = 3, f5 = 5; + int idx2 = 0, idx3 = 0, idx5 = 0; + + while (uglies.size() < n) { + int min_val = min(min(f2, f3), f5); + uglies.emplace_back(min_val); + + if (min_val == f2) { + f2 = 2 * uglies[++idx2]; + } + if (min_val == f3) { + f3 = 3 * uglies[++idx3]; + } + if (min_val == f5) { + f5 = 5 * uglies[++idx5]; + } + } + + return uglies[n - 1]; + } +}; + +// Time: O(n) +// Space: O(1) +// Heap solution. (148ms) +class Solution2 { public: int nthUglyNumber(int n) { long long ugly_number = 0; @@ -28,7 +58,7 @@ class Solution { }; // BST solution. -class Solution2 { +class Solution3 { public: int nthUglyNumber(int n) { long long ugly_number = 0; From f5383f4420c99bd4ca4abc7a927f73c3015bb14a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 00:56:38 +0800 Subject: [PATCH 1380/1939] Create super-ugly-number.cpp --- C++/super-ugly-number.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/super-ugly-number.cpp diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp new file mode 100644 index 000000000..cbb4e57e4 --- /dev/null +++ b/C++/super-ugly-number.cpp @@ -0,0 +1,21 @@ +// Time: O(n * k) +// Space: O(n + k) + +// DP solution. +class Solution { +public: + int nthSuperUglyNumber(int n, vector& primes) { + vector uglies{1}, ugly_by_prime(primes), idx(primes.size()); + while (uglies.size() < n) { + int min_val = *min_element(ugly_by_prime.begin(), ugly_by_prime.end()); + uglies.emplace_back(min_val); + for (int i = 0; i < primes.size(); ++i) { + if (min_val == ugly_by_prime[i]) { + ugly_by_prime[i] = primes[i] * uglies[++idx[i]]; + } + } + } + + return uglies[n - 1]; + } +}; From 049de215e3cdbde8c8f5b39bdd351cf5a3357bfe Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 00:58:13 +0800 Subject: [PATCH 1381/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index cbb4e57e4..08053dda6 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -9,9 +9,9 @@ class Solution { while (uglies.size() < n) { int min_val = *min_element(ugly_by_prime.begin(), ugly_by_prime.end()); uglies.emplace_back(min_val); - for (int i = 0; i < primes.size(); ++i) { - if (min_val == ugly_by_prime[i]) { - ugly_by_prime[i] = primes[i] * uglies[++idx[i]]; + for (int k = 0; k < primes.size(); ++k) { + if (min_val == ugly_by_prime[k]) { + ugly_by_prime[k] = primes[k] * uglies[++idx[k]]; } } } From d37d799c2db9907d0dedce26a01e7a5886228a7e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 01:01:55 +0800 Subject: [PATCH 1382/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 08053dda6..338583ef6 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -1,14 +1,16 @@ // Time: O(n * k) // Space: O(n + k) -// DP solution. +// DP solution. (596ms) class Solution { public: int nthSuperUglyNumber(int n, vector& primes) { - vector uglies{1}, ugly_by_prime(primes), idx(primes.size()); - while (uglies.size() < n) { + vector uglies(n), ugly_by_prime(primes), idx(primes.size()); + uglies[0] = 1; + + for (int i = 1; i < n; ++i) { int min_val = *min_element(ugly_by_prime.begin(), ugly_by_prime.end()); - uglies.emplace_back(min_val); + uglies[i] = min_val; for (int k = 0; k < primes.size(); ++k) { if (min_val == ugly_by_prime[k]) { ugly_by_prime[k] = primes[k] * uglies[++idx[k]]; From 18be62038e1df619a1b0799e8d7845bb676515a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 01:02:34 +0800 Subject: [PATCH 1383/1939] Update ugly-number-ii.cpp --- C++/ugly-number-ii.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/C++/ugly-number-ii.cpp b/C++/ugly-number-ii.cpp index 57503e2a1..00c79a9f5 100644 --- a/C++/ugly-number-ii.cpp +++ b/C++/ugly-number-ii.cpp @@ -1,18 +1,19 @@ // Time: O(n) // Space: O(n) -// DP solution. (20ms) +// DP solution. (12ms) class Solution { public: int nthUglyNumber(int n) { - vector uglies{1}; + vector uglies(n); + uglies[0] = 1; int f2 = 2, f3 = 3, f5 = 5; int idx2 = 0, idx3 = 0, idx5 = 0; - while (uglies.size() < n) { + for (int i = 1; i < n; ++i) { int min_val = min(min(f2, f3), f5); - uglies.emplace_back(min_val); + uglies[i] = min_val; if (min_val == f2) { f2 = 2 * uglies[++idx2]; From c685069525ea39519f32c330fa64c1fbc24675f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 01:23:41 +0800 Subject: [PATCH 1384/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 338583ef6..777c67173 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -1,8 +1,7 @@ // Time: O(n * k) // Space: O(n + k) - // DP solution. (596ms) -class Solution { +class Solution2 { public: int nthSuperUglyNumber(int n, vector& primes) { vector uglies(n), ugly_by_prime(primes), idx(primes.size()); @@ -21,3 +20,33 @@ class Solution { return uglies[n - 1]; } }; + +// Time: O(n * klogk) +// Space: O(n + k) +// Heap solution. (1184ms) +class Solution2 { +public: + int nthSuperUglyNumber(int n, vector& primes) { + priority_queue, vector>, greater>> ugly_by_prime; + vector uglies(n), idx(primes.size()); + uglies[0] = 1; + + for (int k = 0; k < primes.size(); ++k) { + ugly_by_prime.push({primes[k], k}); + } + + for (int i = 1; i < n; ++i) { + int min, k; + tie(min, k) = ugly_by_prime.top(); + uglies[i] = min; + + while (ugly_by_prime.top().first == min) { // worst time: O(klogk) + tie(min, k) = ugly_by_prime.top(); + ugly_by_prime.pop(); + ugly_by_prime.push({primes[k] * uglies[++idx[k]], k}); + } + } + + return uglies[n - 1]; + } +}; From a26a2712cfe531236543cc07107d0c045b3e8bb0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 01:23:55 +0800 Subject: [PATCH 1385/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 777c67173..14a62ecc3 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -1,5 +1,6 @@ // Time: O(n * k) // Space: O(n + k) + // DP solution. (596ms) class Solution2 { public: @@ -40,7 +41,7 @@ class Solution2 { tie(min, k) = ugly_by_prime.top(); uglies[i] = min; - while (ugly_by_prime.top().first == min) { // worst time: O(klogk) + while (ugly_by_prime.top().first == min) { // worst time: O(klogk) tie(min, k) = ugly_by_prime.top(); ugly_by_prime.pop(); ugly_by_prime.push({primes[k] * uglies[++idx[k]], k}); From 8832bad5f9ac0b1c92078a981ae7dfa6fe4bcd24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 02:12:42 +0800 Subject: [PATCH 1386/1939] Create super-ugly-number.py --- Python/super-ugly-number.py | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/super-ugly-number.py diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py new file mode 100644 index 000000000..12be40339 --- /dev/null +++ b/Python/super-ugly-number.py @@ -0,0 +1,38 @@ +# Time: O(n * klogk) +# Space: O(n + k) + +# 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] < 1000. + +class Solution(object): + def nthSuperUglyNumber(self, n, primes): + """ + :type n: int + :type primes: List[int] + :rtype: int + """ + uglies, idx, ugly_by_prime = [1], [0] * len(primes), [] + for k, p in enumerate(primes): + heapq.heappush(ugly_by_prime, (p, k)) + + for i in xrange(1, n): + min_val, k = ugly_by_prime[0] + uglies += [min_val] + + while ugly_by_prime[0][0] == min_val: # worst time: O(klogk) + min_val, k = heapq.heappop(ugly_by_prime) + idx[k] += 1 + heapq.heappush(ugly_by_prime, (primes[k] * uglies[idx[k]], k)) + + return uglies[-1] + From 433177cb7cabf137d16b28c51d3871a02f49894c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 02:20:49 +0800 Subject: [PATCH 1387/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index 12be40339..61ea52a16 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -1,4 +1,4 @@ -# Time: O(n * klogk) +# Time: O(n * logk) ~ O(n * klogk) # Space: O(n + k) # Write a program to find the nth super ugly number. From b2d01b0be030fc7a0d57c828a075f4f3d6b8e586 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 02:21:38 +0800 Subject: [PATCH 1388/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 14a62ecc3..a994aebe4 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -22,7 +22,7 @@ class Solution2 { } }; -// Time: O(n * klogk) +// Time: O(n * logk) ~ O(n * klogk) // Space: O(n + k) // Heap solution. (1184ms) class Solution2 { From 4968163b6f8a1646e993054560e427f67df771e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 02:23:39 +0800 Subject: [PATCH 1389/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5476eb729..68c611b28 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || 264| [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [C++](./C++/ugly-number-ii.cpp) [Python](./Python/ugly-number-ii.py) | _O(n)_ | _O(1)_ | Medium | CTCI, LintCode | BST, Heap | 295| [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | [C++](./C++/find-median-from-data-stream.cpp) [Python](./Python/find-median-from-data-stream.py) | _O(nlogn)_ | _O(n)_ | Hard | EPI, LintCode | BST, Heap | +313| [Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | [C++](./C++/super-ugly-number.cpp) [Python](./Python/super-ugly-number.py) | _O(n * k)_ | _O(n + k)_ | Medium || BST, Heap | ## Tree # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 6105b39d279c392c360369efa7995873d0aad21a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 03:11:55 +0800 Subject: [PATCH 1390/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index a994aebe4..90d609c05 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -22,10 +22,43 @@ class Solution2 { } }; +// Time: O(n * logk) ~ O(n * klogk) +// Space: O(k^2) +// Heap solution. +class Solution2 { +public: + int nthSuperUglyNumber(int n, vector& primes) { + long long ugly_number = 0; + priority_queue, greater> heap; + + heap.emplace(1); + for (int i = 0; i < n; ++i) { + ugly_number = heap.top(); + heap.pop(); + int j = 0; + for (; j < primes.size() - 1; ++j) { + if (ugly_number % primes[j] == 0) { + for (int k = 0; k <= j; ++k) { + heap.emplace(ugly_number * primes[k]); // worst space: O(k^2) + } + break; + } + } + if (j == primes.size() - 1) { // worst time: O(klogk) + for (const auto& p: primes) { + heap.emplace(ugly_number * p); + } + } + } + + return ugly_number; + } +}; + // Time: O(n * logk) ~ O(n * klogk) // Space: O(n + k) // Heap solution. (1184ms) -class Solution2 { +class Solution3 { public: int nthSuperUglyNumber(int n, vector& primes) { priority_queue, vector>, greater>> ugly_by_prime; From 8800d8659590672832816568fe9701b756e66510 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 03:12:20 +0800 Subject: [PATCH 1391/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 90d609c05..2aca1ae49 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -24,7 +24,7 @@ class Solution2 { // Time: O(n * logk) ~ O(n * klogk) // Space: O(k^2) -// Heap solution. +// Heap solution. (620ms) class Solution2 { public: int nthSuperUglyNumber(int n, vector& primes) { From 71a5ed64e5dabb96243d37b63331d0ce711372c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 03:15:10 +0800 Subject: [PATCH 1392/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 2aca1ae49..9ed54d5eb 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -24,7 +24,7 @@ class Solution2 { // Time: O(n * logk) ~ O(n * klogk) // Space: O(k^2) -// Heap solution. (620ms) +// Heap solution. (612ms) class Solution2 { public: int nthSuperUglyNumber(int n, vector& primes) { @@ -36,7 +36,7 @@ class Solution2 { ugly_number = heap.top(); heap.pop(); int j = 0; - for (; j < primes.size() - 1; ++j) { + for (; j < primes.size(); ++j) { if (ugly_number % primes[j] == 0) { for (int k = 0; k <= j; ++k) { heap.emplace(ugly_number * primes[k]); // worst space: O(k^2) @@ -44,7 +44,7 @@ class Solution2 { break; } } - if (j == primes.size() - 1) { // worst time: O(klogk) + if (j == primes.size()) { // worst time: O(klogk) for (const auto& p: primes) { heap.emplace(ugly_number * p); } From aac9362467fe14bb8db198f009aee10e6252c357 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 03:28:07 +0800 Subject: [PATCH 1393/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 9ed54d5eb..5652dd76f 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -32,6 +32,9 @@ class Solution2 { priority_queue, greater> heap; heap.emplace(1); + for (const auto& p: primes) { + heap.emplace(p); + } for (int i = 0; i < n; ++i) { ugly_number = heap.top(); heap.pop(); @@ -39,16 +42,13 @@ class Solution2 { for (; j < primes.size(); ++j) { if (ugly_number % primes[j] == 0) { for (int k = 0; k <= j; ++k) { - heap.emplace(ugly_number * primes[k]); // worst space: O(k^2) + // worst time: O(klogk) + // worst space: O(k^2) + heap.emplace(ugly_number * primes[k]); } break; } } - if (j == primes.size()) { // worst time: O(klogk) - for (const auto& p: primes) { - heap.emplace(ugly_number * p); - } - } } return ugly_number; From 41299f1304c85d53445850e0a3b7775a3f96233d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 04:01:29 +0800 Subject: [PATCH 1394/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index 61ea52a16..7d7a98e30 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -1,4 +1,4 @@ -# Time: O(n * logk) ~ O(n * klogk) +# Time: O(n * k) # Space: O(n + k) # Write a program to find the nth super ugly number. @@ -15,6 +15,31 @@ # (3) 0 < k <= 100, 0 < n <= 106, 0 < primes[i] < 1000. class Solution(object): + def nthSuperUglyNumber(self, n, primes): + """ + :type n: int + :type primes: List[int] + :rtype: int + """ + uglies, idx, ugly_by_prime, ugly_set = [0] * n, [0] * len(primes), [], set([1]) + uglies[0] = 1 + + for k, p in enumerate(primes): + heapq.heappush(ugly_by_prime, (p, k)) + ugly_set.add(p) + + for i in xrange(1, n): + min_val, k = heapq.heappop(ugly_by_prime) + uglies[i] = min_val + while (primes[k] * uglies[idx[k]]) in ugly_set: + idx[k] += 1 + heapq.heappush(ugly_by_prime, (primes[k] * uglies[idx[k]], k)) + ugly_set.add(primes[k] * uglies[idx[k]]) + + return uglies[-1] + + +class Solution2(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int From 844878b85bde1a4037c68693d7c3eede95ffef7d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 04:02:49 +0800 Subject: [PATCH 1395/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 5652dd76f..d80a8ad64 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -2,7 +2,7 @@ // Space: O(n + k) // DP solution. (596ms) -class Solution2 { +class Solution { public: int nthSuperUglyNumber(int n, vector& primes) { vector uglies(n), ugly_by_prime(primes), idx(primes.size()); From d576f50d5eb2255ec844441371400fdd5663fe9e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 04:04:24 +0800 Subject: [PATCH 1396/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index 7d7a98e30..74942c3ea 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -14,6 +14,7 @@ # (2) The given numbers in primes are in ascending order. # (3) 0 < k <= 100, 0 < n <= 106, 0 < primes[i] < 1000. +# Hash solution. (932ms) class Solution(object): def nthSuperUglyNumber(self, n, primes): """ From fc3073d797632763de934bb21e1db0ab53c88cd4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 04:06:00 +0800 Subject: [PATCH 1397/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index 74942c3ea..88aa567e6 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -39,7 +39,8 @@ def nthSuperUglyNumber(self, n, primes): return uglies[-1] - +# Time: O(n * logk) ~ O(n * klogk) +# Space: O(n + k) class Solution2(object): def nthSuperUglyNumber(self, n, primes): """ From c745c30154519987f9e7b9f9103511b70cccdff8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 04:12:28 +0800 Subject: [PATCH 1398/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index d80a8ad64..890764304 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -55,10 +55,42 @@ class Solution2 { } }; +// Time: O(n * k) +// Space: O(n + k) +// Hash solution. (804ms) +class Solution3 { +public: + int nthSuperUglyNumber(int n, vector& primes) { + priority_queue, vector>, greater>> ugly_by_prime; + unordered_set ugly_set{1}; + vector uglies(n), idx(primes.size()); + uglies[0] = 1; + + for (int k = 0; k < primes.size(); ++k) { + ugly_by_prime.push({primes[k], k}); + ugly_set.emplace(primes[k]); + } + + for (int i = 1; i < n; ++i) { + int min, k; + tie(min, k) = ugly_by_prime.top(); + ugly_by_prime.pop(); + uglies[i] = min; + while (ugly_set.count(primes[k] * uglies[idx[k]])) { + ++idx[k]; + } + ugly_by_prime.push({primes[k] * uglies[idx[k]], k}); + ugly_set.emplace(primes[k] * uglies[idx[k]]); + } + + return uglies[n - 1]; + } +}; + // Time: O(n * logk) ~ O(n * klogk) // Space: O(n + k) // Heap solution. (1184ms) -class Solution3 { +class Solution4 { public: int nthSuperUglyNumber(int n, vector& primes) { priority_queue, vector>, greater>> ugly_by_prime; From ef9fe5f03a55d18869e0105e0f830dc0027d288f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 04:19:22 +0800 Subject: [PATCH 1399/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index 88aa567e6..66c7ebb6d 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -63,3 +63,28 @@ def nthSuperUglyNumber(self, n, primes): return uglies[-1] +# Time: O(n * k) +# Space: O(n + k) +# TLE, but it passess and performs very well in C++. +class Solution3(object): + def nthSuperUglyNumber(self, n, primes): + """ + :type n: int + :type primes: List[int] + :rtype: int + """ + ugly_number = 0 + + heap = [] + heapq.heappush(heap, 1) + for p in primes: + heapq.heappush(heap, p) + for _ in xrange(n): + ugly_number = heapq.heappop(heap) + for i in xrange(len(primes)): + if ugly_number % primes[i] == 0: + for j in xrange(i + 1): + heapq.heappush(heap, ugly_number * primes[j]) + break + + return ugly_number From eae659d1c95cbfa016185e8688fd53fa6034e2ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 04:20:13 +0800 Subject: [PATCH 1400/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index 66c7ebb6d..4c14e7daf 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -64,7 +64,7 @@ def nthSuperUglyNumber(self, n, primes): return uglies[-1] # Time: O(n * k) -# Space: O(n + k) +# Space: O(k^2) # TLE, but it passess and performs very well in C++. class Solution3(object): def nthSuperUglyNumber(self, n, primes): From 1a803878104c1f2fc7ade4ef3100f140befe1bcd Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 04:21:32 +0800 Subject: [PATCH 1401/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index 4c14e7daf..ad44c4fbb 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -63,9 +63,9 @@ def nthSuperUglyNumber(self, n, primes): return uglies[-1] -# Time: O(n * k) +# Time: O(n * logk) ~ O(n * klogk) # Space: O(k^2) -# TLE, but it passess and performs very well in C++. +# TLE, but it passess and performs well in C++. class Solution3(object): def nthSuperUglyNumber(self, n, primes): """ From e2a0500b8079bea46050a07e9289217dbf6abe18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 04:28:36 +0800 Subject: [PATCH 1402/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index ad44c4fbb..bc272f880 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -62,11 +62,36 @@ def nthSuperUglyNumber(self, n, primes): heapq.heappush(ugly_by_prime, (primes[k] * uglies[idx[k]], k)) return uglies[-1] - + +# Time: O(n * k) +# Space: O(n + k) +# TLE due to the last test case, but it passess and performs the best in C++. +class Solution3(object): + def nthSuperUglyNumber(self, n, primes): + """ + :type n: int + :type primes: List[int] + :rtype: int + """ + uglies = [0] * n + uglies[0] = 1 + ugly_by_prime = list(primes) + idx = [0] * len(primes) + + for i in xrange(1, n): + min_val = min(ugly_by_prime) + uglies[i] = min_val + for k in xrange(len(primes)): + if min_val == ugly_by_prime[k]: + idx[k] += 1 + ugly_by_prime[k] = primes[k] * uglies[idx[k]] + + return uglies[-1] + # Time: O(n * logk) ~ O(n * klogk) # Space: O(k^2) -# TLE, but it passess and performs well in C++. -class Solution3(object): +# TLE due to the last test case, but it passess and performs well in C++. +class Solution4(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int From 0949753a975496e107e91bfc6027bc833ed2a96b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 21:26:23 +0800 Subject: [PATCH 1403/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 890764304..07985c29a 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -67,19 +67,19 @@ class Solution3 { uglies[0] = 1; for (int k = 0; k < primes.size(); ++k) { - ugly_by_prime.push({primes[k], k}); + heap.push({primes[k], k}); ugly_set.emplace(primes[k]); } for (int i = 1; i < n; ++i) { int min, k; - tie(min, k) = ugly_by_prime.top(); - ugly_by_prime.pop(); + tie(min, k) = heap.top(); + heap.pop(); uglies[i] = min; while (ugly_set.count(primes[k] * uglies[idx[k]])) { ++idx[k]; } - ugly_by_prime.push({primes[k] * uglies[idx[k]], k}); + heap.push({primes[k] * uglies[idx[k]], k}); ugly_set.emplace(primes[k] * uglies[idx[k]]); } @@ -93,23 +93,23 @@ class Solution3 { class Solution4 { public: int nthSuperUglyNumber(int n, vector& primes) { - priority_queue, vector>, greater>> ugly_by_prime; + priority_queue, vector>, greater>> heap; vector uglies(n), idx(primes.size()); uglies[0] = 1; for (int k = 0; k < primes.size(); ++k) { - ugly_by_prime.push({primes[k], k}); + heap.push({primes[k], k}); } for (int i = 1; i < n; ++i) { int min, k; - tie(min, k) = ugly_by_prime.top(); + tie(min, k) = heap.top(); uglies[i] = min; - while (ugly_by_prime.top().first == min) { // worst time: O(klogk) - tie(min, k) = ugly_by_prime.top(); - ugly_by_prime.pop(); - ugly_by_prime.push({primes[k] * uglies[++idx[k]], k}); + while (heap.top().first == min) { // worst time: O(klogk) + tie(min, k) = heap.top(); + heap.pop(); + heap.push({primes[k] * uglies[++idx[k]], k}); } } From 6e5bc223a091ca363599da6e8b1522919a6cc940 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 21:34:28 +0800 Subject: [PATCH 1404/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 07985c29a..2f936c098 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -72,10 +72,9 @@ class Solution3 { } for (int i = 1; i < n; ++i) { - int min, k; - tie(min, k) = heap.top(); + int k; + tie(uglies[i]) = heap.top(); heap.pop(); - uglies[i] = min; while (ugly_set.count(primes[k] * uglies[idx[k]])) { ++idx[k]; } @@ -102,12 +101,11 @@ class Solution4 { } for (int i = 1; i < n; ++i) { - int min, k; - tie(min, k) = heap.top(); - uglies[i] = min; + int k; + tie(uglies[i], k) = heap.top(); - while (heap.top().first == min) { // worst time: O(klogk) - tie(min, k) = heap.top(); + while (heap.top().first == uglies[i]) { // worst time: O(klogk) + tie(uglies[i], k) = heap.top(); heap.pop(); heap.push({primes[k] * uglies[++idx[k]], k}); } From b1f2341d3aa6b5172c22b6bce91513323d88e58f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 21:38:34 +0800 Subject: [PATCH 1405/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 2f936c098..23a773e66 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -1,8 +1,33 @@ // Time: O(n * k) // Space: O(n + k) -// DP solution. (596ms) +// Heap solution. (308ms) class Solution { +public: + int nthSuperUglyNumber(int n, vector& primes) { + priority_queue, vector>, greater>> heap; + vector uglies(n), idx(primes.size()), ugly_by_prime(n); + uglies[0] = 1; + + for (int i = 0; i < primes.size(); ++i) { + heap.push({primes[i], i}); + } + for (int i = 1; i < n; ++i) { + int k; + tie(uglies[i], k) = heap.top(); + heap.pop(); + ugly_by_prime[i] = k; + while (ugly_by_prime[++idx[k]] > k); + heap.push({uglies[idx[k]] * primes[k], k}); + } + return uglies[n - 1]; + } +}; + +// Time: O(n * k) +// Space: O(n + k) +// DP solution. (596ms) +class Solution2 { public: int nthSuperUglyNumber(int n, vector& primes) { vector uglies(n), ugly_by_prime(primes), idx(primes.size()); @@ -25,7 +50,7 @@ class Solution { // Time: O(n * logk) ~ O(n * klogk) // Space: O(k^2) // Heap solution. (612ms) -class Solution2 { +class Solution3 { public: int nthSuperUglyNumber(int n, vector& primes) { long long ugly_number = 0; @@ -58,7 +83,7 @@ class Solution2 { // Time: O(n * k) // Space: O(n + k) // Hash solution. (804ms) -class Solution3 { +class Solution4 { public: int nthSuperUglyNumber(int n, vector& primes) { priority_queue, vector>, greater>> ugly_by_prime; @@ -89,7 +114,7 @@ class Solution3 { // Time: O(n * logk) ~ O(n * klogk) // Space: O(n + k) // Heap solution. (1184ms) -class Solution4 { +class Solution5 { public: int nthSuperUglyNumber(int n, vector& primes) { priority_queue, vector>, greater>> heap; From 6510e06ce82eccff01289fca82789f67a9455eb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 21:48:26 +0800 Subject: [PATCH 1406/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 54 ++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index bc272f880..e834317ef 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -14,8 +14,34 @@ # (2) The given numbers in primes are in ascending order. # (3) 0 < k <= 100, 0 < n <= 106, 0 < primes[i] < 1000. -# Hash solution. (932ms) +# Heap solution. (620ms) class Solution(object): + def nthSuperUglyNumber(self, n, primes): + """ + :type n: int + :type primes: List[int] + :rtype: int + """ + heap, uglies, idx, ugly_by_prime = [], [0] * n, [0] * len(primes), [0] * n + uglies[0] = 1 + + for k, p in enumerate(primes): + heapq.heappush(heap, (p, k)) + + for i in xrange(1, n): + uglies[i], k = heapq.heappop(heap) + ugly_by_prime[i] = k + idx[k] += 1 + while ugly_by_prime[idx[k]] > k: + idx[k] += 1 + heapq.heappush(heap, (primes[k] * uglies[idx[k]], k)) + + return uglies[-1] + +# Time: O(n * k) +# Space: O(n + k) +# Hash solution. (932ms) +class Solution2(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int @@ -30,8 +56,7 @@ def nthSuperUglyNumber(self, n, primes): ugly_set.add(p) for i in xrange(1, n): - min_val, k = heapq.heappop(ugly_by_prime) - uglies[i] = min_val + uglies[i], k = heapq.heappop(ugly_by_prime) while (primes[k] * uglies[idx[k]]) in ugly_set: idx[k] += 1 heapq.heappush(ugly_by_prime, (primes[k] * uglies[idx[k]], k)) @@ -41,32 +66,32 @@ def nthSuperUglyNumber(self, n, primes): # Time: O(n * logk) ~ O(n * klogk) # Space: O(n + k) -class Solution2(object): +class Solution3(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int :type primes: List[int] :rtype: int """ - uglies, idx, ugly_by_prime = [1], [0] * len(primes), [] + uglies, idx, heap = [1], [0] * len(primes), [] for k, p in enumerate(primes): - heapq.heappush(ugly_by_prime, (p, k)) + heapq.heappush(heap, (p, k)) for i in xrange(1, n): - min_val, k = ugly_by_prime[0] + min_val, k = heap[0] uglies += [min_val] - while ugly_by_prime[0][0] == min_val: # worst time: O(klogk) - min_val, k = heapq.heappop(ugly_by_prime) + while heap[0][0] == min_val: # worst time: O(klogk) + min_val, k = heapq.heappop(heap) idx[k] += 1 - heapq.heappush(ugly_by_prime, (primes[k] * uglies[idx[k]], k)) + heapq.heappush(heap, (primes[k] * uglies[idx[k]], k)) return uglies[-1] # Time: O(n * k) # Space: O(n + k) # TLE due to the last test case, but it passess and performs the best in C++. -class Solution3(object): +class Solution4(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int @@ -79,10 +104,9 @@ def nthSuperUglyNumber(self, n, primes): idx = [0] * len(primes) for i in xrange(1, n): - min_val = min(ugly_by_prime) - uglies[i] = min_val + uglies[i] = min(ugly_by_prime) for k in xrange(len(primes)): - if min_val == ugly_by_prime[k]: + if uglies[i] == ugly_by_prime[k]: idx[k] += 1 ugly_by_prime[k] = primes[k] * uglies[idx[k]] @@ -91,7 +115,7 @@ def nthSuperUglyNumber(self, n, primes): # Time: O(n * logk) ~ O(n * klogk) # Space: O(k^2) # TLE due to the last test case, but it passess and performs well in C++. -class Solution4(object): +class Solution5(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int From d16ab60f6c3f8a3537e090620eb4166aaf6974b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 21:55:48 +0800 Subject: [PATCH 1407/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index e834317ef..3775efbb3 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -22,7 +22,7 @@ def nthSuperUglyNumber(self, n, primes): :type primes: List[int] :rtype: int """ - heap, uglies, idx, ugly_by_prime = [], [0] * n, [0] * len(primes), [0] * n + heap, uglies, idx, ugly_by_last_prime = [], [0] * n, [0] * len(primes), [0] * n uglies[0] = 1 for k, p in enumerate(primes): @@ -30,9 +30,9 @@ def nthSuperUglyNumber(self, n, primes): for i in xrange(1, n): uglies[i], k = heapq.heappop(heap) - ugly_by_prime[i] = k + ugly_by_last_prime[i] = k idx[k] += 1 - while ugly_by_prime[idx[k]] > k: + while ugly_by_last_prime[idx[k]] > k: idx[k] += 1 heapq.heappush(heap, (primes[k] * uglies[idx[k]], k)) @@ -48,18 +48,18 @@ def nthSuperUglyNumber(self, n, primes): :type primes: List[int] :rtype: int """ - uglies, idx, ugly_by_prime, ugly_set = [0] * n, [0] * len(primes), [], set([1]) + uglies, idx, heap, ugly_set = [0] * n, [0] * len(primes), [], set([1]) uglies[0] = 1 for k, p in enumerate(primes): - heapq.heappush(ugly_by_prime, (p, k)) + heapq.heappush(heap, (p, k)) ugly_set.add(p) for i in xrange(1, n): - uglies[i], k = heapq.heappop(ugly_by_prime) + uglies[i], k = heapq.heappop(heap) while (primes[k] * uglies[idx[k]]) in ugly_set: idx[k] += 1 - heapq.heappush(ugly_by_prime, (primes[k] * uglies[idx[k]], k)) + heapq.heappush(heap, (primes[k] * uglies[idx[k]], k)) ugly_set.add(primes[k] * uglies[idx[k]]) return uglies[-1] From 60e02af4da246b49cc56b7ae94715b63db7d35e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 21:57:30 +0800 Subject: [PATCH 1408/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 23a773e66..4b24300ed 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -6,7 +6,7 @@ class Solution { public: int nthSuperUglyNumber(int n, vector& primes) { priority_queue, vector>, greater>> heap; - vector uglies(n), idx(primes.size()), ugly_by_prime(n); + vector uglies(n), idx(primes.size()), ugly_by_last_prime(n); uglies[0] = 1; for (int i = 0; i < primes.size(); ++i) { @@ -16,8 +16,8 @@ class Solution { int k; tie(uglies[i], k) = heap.top(); heap.pop(); - ugly_by_prime[i] = k; - while (ugly_by_prime[++idx[k]] > k); + ugly_by_last_prime[i] = k; + while (ugly_by_last_prime[++idx[k]] > k); heap.push({uglies[idx[k]] * primes[k], k}); } return uglies[n - 1]; @@ -86,7 +86,7 @@ class Solution3 { class Solution4 { public: int nthSuperUglyNumber(int n, vector& primes) { - priority_queue, vector>, greater>> ugly_by_prime; + priority_queue, vector>, greater>> heap; unordered_set ugly_set{1}; vector uglies(n), idx(primes.size()); uglies[0] = 1; From eb99ee2cf66b0a792e33c57790e60bb9ffc1a6a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 22:25:17 +0800 Subject: [PATCH 1409/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 4b24300ed..aa21003a5 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -1,4 +1,4 @@ -// Time: O(n * k) +// Time: O(n * logk) ~ O(n * k) // Space: O(n + k) // Heap solution. (308ms) From 97cc3ba11be2e7b2bacc3f68e9588244ad0cce95 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Dec 2015 22:26:06 +0800 Subject: [PATCH 1410/1939] Update super-ugly-number.py --- Python/super-ugly-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index 3775efbb3..993afd326 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -1,4 +1,4 @@ -# Time: O(n * k) +# Time: O(n * logk) ~ O(n * k) # Space: O(n + k) # Write a program to find the nth super ugly number. From 743c585dfaced102f4726bf6842153295defd2e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Dec 2015 09:44:20 +0800 Subject: [PATCH 1411/1939] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index aa21003a5..bb20c20d7 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -17,7 +17,7 @@ class Solution { tie(uglies[i], k) = heap.top(); heap.pop(); ugly_by_last_prime[i] = k; - while (ugly_by_last_prime[++idx[k]] > k); + while (ugly_by_last_prime[++idx[k]] > k); // worst time: O(k) heap.push({uglies[idx[k]] * primes[k], k}); } return uglies[n - 1]; From deb6a4199fb751f1831f74a97da33be230f1c265 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Dec 2015 16:30:26 +0800 Subject: [PATCH 1412/1939] Create binary-tree-vertical-order-traversal.py --- .../binary-tree-vertical-order-traversal.py | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/binary-tree-vertical-order-traversal.py diff --git a/Python/binary-tree-vertical-order-traversal.py b/Python/binary-tree-vertical-order-traversal.py new file mode 100644 index 000000000..455bb3710 --- /dev/null +++ b/Python/binary-tree-vertical-order-traversal.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(n) + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +# BFS + hash solution. +class Solution(object): + def verticalOrder(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + if not root: + return [] + + lookup = collections.defaultdict(list) + min_idx = float("inf") + max_idx = float("-inf") + + pre_level = [(root, 0)] + while pre_level: + cur_level = [] + for n, i in pre_level: + min_idx, max_idx = min(min_idx, i), max(max_idx, i) + lookup[i] += [n.val] + if n.left: + cur_level.append((n.left, i - 1)) + if n.right: + cur_level.append((n.right, i + 1)) + pre_level = cur_level + + res = [] + for i in xrange(min_idx, max_idx + 1): + if lookup[i]: + res.append(lookup[i]) + return res + From ea2590c62e9b26dd6ea321574141af4aa56a43b9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Dec 2015 16:31:33 +0800 Subject: [PATCH 1413/1939] Update binary-tree-vertical-order-traversal.py --- Python/binary-tree-vertical-order-traversal.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/binary-tree-vertical-order-traversal.py b/Python/binary-tree-vertical-order-traversal.py index 455bb3710..cff0052b6 100644 --- a/Python/binary-tree-vertical-order-traversal.py +++ b/Python/binary-tree-vertical-order-traversal.py @@ -36,7 +36,7 @@ def verticalOrder(self, root): res = [] for i in xrange(min_idx, max_idx + 1): - if lookup[i]: - res.append(lookup[i]) + res.append(lookup[i]) + return res From 65f62377943f90103832e5ad2b0e8b278226ebf7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Dec 2015 16:32:02 +0800 Subject: [PATCH 1414/1939] Update binary-tree-vertical-order-traversal.py --- Python/binary-tree-vertical-order-traversal.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/binary-tree-vertical-order-traversal.py b/Python/binary-tree-vertical-order-traversal.py index cff0052b6..73f500554 100644 --- a/Python/binary-tree-vertical-order-traversal.py +++ b/Python/binary-tree-vertical-order-traversal.py @@ -39,4 +39,3 @@ def verticalOrder(self, root): res.append(lookup[i]) return res - From b316c95d582854d177e53c36ff9d6eb09fbd26cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Dec 2015 16:34:58 +0800 Subject: [PATCH 1415/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 68c611b28..c0f1dc90f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-313%20%2F%20313-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-314%20%2F%20314-ff69b4.svg) -Up to date (2015-12-03), there are `296` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-05), there are `297` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `313` questions. +Here is the classification of all `314` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -207,6 +207,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || 299| [Bulls and Cow](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| 305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k)_ | _O(k)_| Hard | LintCode, 📖 | Union Find +314| [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) | [C++](./C++/binary-tree-vertical-order-traversal.cpp) [Python](./Python/binary-tree-vertical-order-traversal.py) | _O(n)_ | _O(n)_| Medium | 📖 | BFS ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 812d05e2391bd4e8e2d6b5290f4e198acb62dae3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Dec 2015 16:38:22 +0800 Subject: [PATCH 1416/1939] Update binary-tree-vertical-order-traversal.py --- Python/binary-tree-vertical-order-traversal.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/binary-tree-vertical-order-traversal.py b/Python/binary-tree-vertical-order-traversal.py index 73f500554..3f52c9ce7 100644 --- a/Python/binary-tree-vertical-order-traversal.py +++ b/Python/binary-tree-vertical-order-traversal.py @@ -19,8 +19,7 @@ def verticalOrder(self, root): return [] lookup = collections.defaultdict(list) - min_idx = float("inf") - max_idx = float("-inf") + min_idx, max_idx = float("inf"), float("-inf") pre_level = [(root, 0)] while pre_level: From 05c0cc3a263d4522ab89e87d3ea2aab82b96b5c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 09:57:19 +0800 Subject: [PATCH 1417/1939] Update binary-tree-vertical-order-traversal.py --- .../binary-tree-vertical-order-traversal.py | 32 ++++++------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/Python/binary-tree-vertical-order-traversal.py b/Python/binary-tree-vertical-order-traversal.py index 3f52c9ce7..8dd332ee4 100644 --- a/Python/binary-tree-vertical-order-traversal.py +++ b/Python/binary-tree-vertical-order-traversal.py @@ -15,26 +15,12 @@ def verticalOrder(self, root): :type root: TreeNode :rtype: List[List[int]] """ - if not root: - return [] - - lookup = collections.defaultdict(list) - min_idx, max_idx = float("inf"), float("-inf") - - pre_level = [(root, 0)] - while pre_level: - cur_level = [] - for n, i in pre_level: - min_idx, max_idx = min(min_idx, i), max(max_idx, i) - lookup[i] += [n.val] - if n.left: - cur_level.append((n.left, i - 1)) - if n.right: - cur_level.append((n.right, i + 1)) - pre_level = cur_level - - res = [] - for i in xrange(min_idx, max_idx + 1): - res.append(lookup[i]) - - return res + """ + cols = collections.defaultdict(list) + queue = [(root, 0)] + for node, i in queue: + if node: + cols[i].append(node.val) + queue += (node.left, i - 1), (node.right, i + 1) + return [cols[i] for i in xrange(min(cols.keys()), max(cols.keys()) + 1)] \ + if cols else [] From 2d5d39b945a28d345d9a785eaa49d1d527e8e37e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 10:18:45 +0800 Subject: [PATCH 1418/1939] Create binary-tree-vertical-order-traversal.cpp --- C++/binary-tree-vertical-order-traversal.cpp | 40 ++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/binary-tree-vertical-order-traversal.cpp diff --git a/C++/binary-tree-vertical-order-traversal.cpp b/C++/binary-tree-vertical-order-traversal.cpp new file mode 100644 index 000000000..80c0bf88d --- /dev/null +++ b/C++/binary-tree-vertical-order-traversal.cpp @@ -0,0 +1,40 @@ +// Time: O(n) +// Space: O(n) + +/** + * 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: + vector> verticalOrder(TreeNode* root) { + unordered_map> cols; + vector> queue{{root, 0}}; + for (int i = 0; i < queue.size(); ++i) { + TreeNode *node; + int j; + tie(node, j) = queue[i]; + if (node) { + cols[j].emplace_back(node->val); + queue.push_back({node->left, j - 1}); + queue.push_back({node->right, j + 1}); + } + } + int min_idx = numeric_limits::max(), + max_idx = numeric_limits::min(); + for (const auto& kvp : cols) { + min_idx = min(min_idx, kvp.first); + max_idx = max(max_idx, kvp.first); + } + vector> res; + for (int i = min_idx; !cols.empty() && i <= max_idx; ++i) { + res.emplace_back(cols[i]); + } + return res; + } +}; From 8f62b6ba54efebd9c1dc6d6365588917d2d6c0d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 11:40:16 +0800 Subject: [PATCH 1419/1939] Update binary-tree-vertical-order-traversal.cpp --- C++/binary-tree-vertical-order-traversal.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/binary-tree-vertical-order-traversal.cpp b/C++/binary-tree-vertical-order-traversal.cpp index 80c0bf88d..2d7036587 100644 --- a/C++/binary-tree-vertical-order-traversal.cpp +++ b/C++/binary-tree-vertical-order-traversal.cpp @@ -33,7 +33,7 @@ class Solution { } vector> res; for (int i = min_idx; !cols.empty() && i <= max_idx; ++i) { - res.emplace_back(cols[i]); + res.emplace_back(move(cols[i])); } return res; } From dad79ced72ce2d81011904f6f0c50dcce2e43030 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 13:39:29 +0800 Subject: [PATCH 1420/1939] Create count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 40 +++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/count-of-smaller-numbers-after-self.cpp diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp new file mode 100644 index 000000000..5151bf1d2 --- /dev/null +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -0,0 +1,40 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + vector countSmaller(vector& nums) { + vector sorted_nums(nums), orderings(nums.size()); + sort(sorted_nums.begin(), sorted_nums.end()); + for (int i = 0; i < nums.size(); ++i) { + orderings[i] = + lower_bound(sorted_nums.begin(), sorted_nums.end(), nums[i]) - + sorted_nums.begin(); + } + vector bit(nums.size() + 1), ans(nums.size()); + for (int i = orderings.size() - 1; i >= 0; --i) { + ans[i] = query(bit, orderings[i]); + add(bit, orderings[i] + 1, 1); + } + return ans; + } + +private: + void add(vector& bit, int i, int val) { + for (; i < bit.size(); i += lower_bit(i)) { + bit[i] += val; + } + } + + int query(const vector& bit, int i) { + int sum = 0; + for (; i > 0; i -= lower_bit(i)) { + sum += bit[i]; + } + return sum; + } + + int lower_bit(int i) { + return i & -i; + } +}; From 0da1f035aad07faf38829c1f613458c26cce9793 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 13:40:31 +0800 Subject: [PATCH 1421/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c0f1dc90f..4a85c7566 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-314%20%2F%20314-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-315%20%2F%20315-ff69b4.svg) -Up to date (2015-12-05), there are `297` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-05), there are `298` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `314` questions. +Here is the classification of all `316` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -179,6 +179,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT +|316|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BIT, BST | ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 38e34bc21900eafbfed090c5a9702d83ecd08c78 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 13:41:10 +0800 Subject: [PATCH 1422/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index 5151bf1d2..74c1cd6ab 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -1,6 +1,7 @@ // Time: O(nlogn) // Space: O(n) +// BIT solution. class Solution { public: vector countSmaller(vector& nums) { From 5526712c696f55aa8aaedb9de2d3edd05318513d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 13:43:57 +0800 Subject: [PATCH 1423/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4a85c7566..0734b927a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-315%20%2F%20315-ff69b4.svg) -Up to date (2015-12-05), there are `298` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-06), there are `298` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `316` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From e0860e11cb349ecb62e0a457c4cee9db89af40a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 13:45:08 +0800 Subject: [PATCH 1424/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0734b927a..1c2503f8a 100644 --- a/README.md +++ b/README.md @@ -179,7 +179,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT -|316|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BIT, BST | +315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BIT, BST | ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 31a8d1202b77bdbf5560e72398e571de765991e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 13:45:27 +0800 Subject: [PATCH 1425/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1c2503f8a..9a41f8f73 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Up to date (2015-12-06), there are `298` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `316` questions. +Here is the classification of all `315` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From 31fd505d641c9f414874c0a24827a3d871880afe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 13:52:14 +0800 Subject: [PATCH 1426/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9a41f8f73..ffcab91a9 100644 --- a/README.md +++ b/README.md @@ -179,7 +179,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT -315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BIT, BST | +315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BIT | ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 9a104854c14aa9e6ad999dffb1d2b634f3b2b386 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 14:26:45 +0800 Subject: [PATCH 1427/1939] Create count-of-smaller-numbers-after-self.py --- Python/count-of-smaller-numbers-after-self.py | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/count-of-smaller-numbers-after-self.py diff --git a/Python/count-of-smaller-numbers-after-self.py b/Python/count-of-smaller-numbers-after-self.py new file mode 100644 index 000000000..ef3839b26 --- /dev/null +++ b/Python/count-of-smaller-numbers-after-self.py @@ -0,0 +1,60 @@ +# Time: O(nlogn) +# Space: O(n) + +# You are given an integer array nums and you have to +# return a new counts array. The counts array has the +# property where counts[i] is the number of smaller +# elements to the right of nums[i]. +# +# Example: +# +# Given nums = [5, 2, 6, 1] +# +# To the right of 5 there are 2 smaller elements (2 and 1). +# To the right of 2 there is only 1 smaller element (1). +# To the right of 6 there is 1 smaller element (1). +# To the right of 1 there is 0 smaller element. +# Return the array [2, 1, 1, 0]. + +class Solution(object): + def countSmaller(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + def binarySearch(A, target, compare): + start, end = 0, len(A) - 1 + while start <= end: + mid = start + (end - start) / 2 + if compare(target, A[mid]): + end = mid - 1 + else: + start = mid + 1 + return start + + class BIT(object): + def __init__(self, n): + self.__bit = [0] * n + + def add(self, i, val): + while i < len(self.__bit): + self.__bit[i] += val + i += (i & -i) + + def query(self, i): + ret = 0 + while i > 0: + ret += self.__bit[i] + i -= (i & -i) + return ret + + sorted_nums, nth_smallest = sorted(nums), [0] * len(nums) + for i, num in enumerate(nums): + nth_smallest[i] = binarySearch(sorted_nums, num, lambda x, y: x <= y) + + ans, bit= [0] * len(nums), BIT(len(nums) + 1) + for i in reversed(xrange(len(nums))): + ans[i] = bit.query(nth_smallest[i]) + bit.add(nth_smallest[i] + 1, 1) + return ans + From 6779cc0f200f731ac59f299d05637e98d93e5597 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 14:27:08 +0800 Subject: [PATCH 1428/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index 74c1cd6ab..23d609b98 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -5,17 +5,17 @@ class Solution { public: vector countSmaller(vector& nums) { - vector sorted_nums(nums), orderings(nums.size()); + vector sorted_nums(nums), nth_smallest(nums.size()); sort(sorted_nums.begin(), sorted_nums.end()); for (int i = 0; i < nums.size(); ++i) { - orderings[i] = + nth_smallest[i] = lower_bound(sorted_nums.begin(), sorted_nums.end(), nums[i]) - sorted_nums.begin(); } vector bit(nums.size() + 1), ans(nums.size()); - for (int i = orderings.size() - 1; i >= 0; --i) { - ans[i] = query(bit, orderings[i]); - add(bit, orderings[i] + 1, 1); + for (int i = nth_smallest.size() - 1; i >= 0; --i) { + ans[i] = query(bit, nth_smallest[i]); + add(bit, nth_smallest[i] + 1, 1); } return ans; } From 5e4ae4a5fb992ba2ff157314be23702096384b3b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 14:30:03 +0800 Subject: [PATCH 1429/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index 23d609b98..ca10595f1 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -5,17 +5,17 @@ class Solution { public: vector countSmaller(vector& nums) { - vector sorted_nums(nums), nth_smallest(nums.size()); + vector sorted_nums(nums), orderings(nums.size()); sort(sorted_nums.begin(), sorted_nums.end()); for (int i = 0; i < nums.size(); ++i) { - nth_smallest[i] = + orderings[i] = lower_bound(sorted_nums.begin(), sorted_nums.end(), nums[i]) - sorted_nums.begin(); } vector bit(nums.size() + 1), ans(nums.size()); - for (int i = nth_smallest.size() - 1; i >= 0; --i) { - ans[i] = query(bit, nth_smallest[i]); - add(bit, nth_smallest[i] + 1, 1); + for (int i = nums.size() - 1; i >= 0; --i) { + ans[i] = query(bit, orderings[i]); + add(bit, orderings[i] + 1, 1); } return ans; } From a6f00eafbc313709cd13bd683a875bb5e917f375 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 14:30:31 +0800 Subject: [PATCH 1430/1939] Update count-of-smaller-numbers-after-self.py --- Python/count-of-smaller-numbers-after-self.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/count-of-smaller-numbers-after-self.py b/Python/count-of-smaller-numbers-after-self.py index ef3839b26..38f89542d 100644 --- a/Python/count-of-smaller-numbers-after-self.py +++ b/Python/count-of-smaller-numbers-after-self.py @@ -48,13 +48,13 @@ def query(self, i): i -= (i & -i) return ret - sorted_nums, nth_smallest = sorted(nums), [0] * len(nums) + sorted_nums, orderings = sorted(nums), [0] * len(nums) for i, num in enumerate(nums): - nth_smallest[i] = binarySearch(sorted_nums, num, lambda x, y: x <= y) + orderings[i] = binarySearch(sorted_nums, num, lambda x, y: x <= y) ans, bit= [0] * len(nums), BIT(len(nums) + 1) for i in reversed(xrange(len(nums))): - ans[i] = bit.query(nth_smallest[i]) - bit.add(nth_smallest[i] + 1, 1) + ans[i] = bit.query(orderings[i]) + bit.add(orderings[i] + 1, 1) return ans From 77f5c8b832889e26af7cb5f43685cd17756c54bd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 14:38:55 +0800 Subject: [PATCH 1431/1939] Update count-of-smaller-numbers-after-self.py --- Python/count-of-smaller-numbers-after-self.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Python/count-of-smaller-numbers-after-self.py b/Python/count-of-smaller-numbers-after-self.py index 38f89542d..8c67ec862 100644 --- a/Python/count-of-smaller-numbers-after-self.py +++ b/Python/count-of-smaller-numbers-after-self.py @@ -47,14 +47,16 @@ def query(self, i): ret += self.__bit[i] i -= (i & -i) return ret - - sorted_nums, orderings = sorted(nums), [0] * len(nums) + + # Get the place (position in the ascending order) of each number. + sorted_nums, places = sorted(nums), [0] * len(nums) for i, num in enumerate(nums): - orderings[i] = binarySearch(sorted_nums, num, lambda x, y: x <= y) + places[i] = binarySearch(sorted_nums, num, lambda x, y: x <= y) + # Count the smaller elements after the number. ans, bit= [0] * len(nums), BIT(len(nums) + 1) for i in reversed(xrange(len(nums))): - ans[i] = bit.query(orderings[i]) - bit.add(orderings[i] + 1, 1) + ans[i] = bit.query(places[i]) + bit.add(places[i] + 1, 1) return ans From abc222940c7bd573871579731f3352996d43639b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Dec 2015 14:40:25 +0800 Subject: [PATCH 1432/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index ca10595f1..bd4349198 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -5,17 +5,19 @@ class Solution { public: vector countSmaller(vector& nums) { - vector sorted_nums(nums), orderings(nums.size()); + // Get the place (position in the ascending order) of each number. + vector sorted_nums(nums), places(nums.size()); sort(sorted_nums.begin(), sorted_nums.end()); for (int i = 0; i < nums.size(); ++i) { - orderings[i] = + places[i] = lower_bound(sorted_nums.begin(), sorted_nums.end(), nums[i]) - sorted_nums.begin(); } + // Count the smaller elements after the number. vector bit(nums.size() + 1), ans(nums.size()); for (int i = nums.size() - 1; i >= 0; --i) { - ans[i] = query(bit, orderings[i]); - add(bit, orderings[i] + 1, 1); + ans[i] = query(bit, places[i]); + add(bit, places[i] + 1, 1); } return ans; } From 9d956fc3b33935298311f552ce1cf4e5fe9ac84d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Dec 2015 09:14:48 +0800 Subject: [PATCH 1433/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 85 ++++++++++++++++++++- 1 file changed, 84 insertions(+), 1 deletion(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index bd4349198..f34579e8e 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -1,8 +1,91 @@ // Time: O(nlogn) // Space: O(n) -// BIT solution. +// BST solution. (40ms) class Solution { +public: +public: + class BSTreeNode { + public: + int val, count; + BSTreeNode *left, *right; + BSTreeNode(int val, int count) { + this->val = val; + this->count = count; + this->left = this->right = nullptr; + } + }; + vector countSmaller(vector& nums) { + vector res(nums.size()); + + BSTreeNode *root = nullptr; + + // Insert into BST and get left count. + for (int i = nums.size() - 1; i >= 0; --i) { + int count = 0; + BSTreeNode *node = new BSTreeNode(nums[i], 0); + root = insertNode(root, node); + count = query(root, nums[i]); + res[i] = count; + } + + return res; + } + + // Insert node into BST. + BSTreeNode* insertNode(BSTreeNode* root, BSTreeNode* node) { + if (root == nullptr) { + return node; + } + BSTreeNode* curr = root; + while (curr) { + // Insert left if smaller. + if (node->val < curr->val) { + ++curr->count; // Increase the number of left children. + if (curr->left != nullptr) { + curr = curr->left; + } else { + curr->left = node; + break; + } + } else { // Insert right if larger or equal. + if (curr->right != nullptr) { + curr = curr->right; + } else { + curr->right = node; + break; + } + } + } + return root; + } + + // Query the smaller count of the value. + int query(BSTreeNode* root, int val) { + if (root == nullptr) { + return 0; + } + int count = 0; + BSTreeNode* curr = root; + while (curr) { + // Insert left. + if (val < curr->val) { + curr = curr->left; + } else if (val > curr->val) { + count += 1 + curr->count; // Count the number of the smaller nodes. + curr = curr->right; + } else { // Equal. + return count + curr->count; + } + } + return 0; + } +}; + +// Time: O(nlogn) +// Space: O(n) +// BIT solution. (56ms) +class Solution2 { public: vector countSmaller(vector& nums) { // Get the place (position in the ascending order) of each number. From 70475da2fa05590994aff24e7467e45dd4c73c8f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Dec 2015 09:15:09 +0800 Subject: [PATCH 1434/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ffcab91a9..8067ecd5b 100644 --- a/README.md +++ b/README.md @@ -179,7 +179,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT -315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BIT | +315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT | ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From e715b261ab6878e28a1609500fd92098bccaef8d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Dec 2015 09:17:14 +0800 Subject: [PATCH 1435/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index f34579e8e..52a66ad7e 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -3,7 +3,6 @@ // BST solution. (40ms) class Solution { -public: public: class BSTreeNode { public: @@ -15,6 +14,7 @@ class Solution { this->left = this->right = nullptr; } }; + vector countSmaller(vector& nums) { vector res(nums.size()); From 61f9c25bff9d1c9dc67a3c260e4fac68cacd86dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Dec 2015 00:11:05 +0800 Subject: [PATCH 1436/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index 52a66ad7e..5e3bf5d5e 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -22,11 +22,9 @@ class Solution { // Insert into BST and get left count. for (int i = nums.size() - 1; i >= 0; --i) { - int count = 0; BSTreeNode *node = new BSTreeNode(nums[i], 0); root = insertNode(root, node); - count = query(root, nums[i]); - res[i] = count; + res[i] = query(root, nums[i]); } return res; From 7f87a7f4dad229300264b6f7e82d082c2ae9804b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Dec 2015 00:15:06 +0800 Subject: [PATCH 1437/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index 5e3bf5d5e..eeb69111c 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -20,7 +20,7 @@ class Solution { BSTreeNode *root = nullptr; - // Insert into BST and get left count. + // Insert into BST and get right count. for (int i = nums.size() - 1; i >= 0; --i) { BSTreeNode *node = new BSTreeNode(nums[i], 0); root = insertNode(root, node); From 29db38be59227ea98aeac3d09deec4e3619a61c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Dec 2015 00:17:56 +0800 Subject: [PATCH 1438/1939] Update count-of-smaller-numbers-after-self.py --- Python/count-of-smaller-numbers-after-self.py | 68 ++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/Python/count-of-smaller-numbers-after-self.py b/Python/count-of-smaller-numbers-after-self.py index 8c67ec862..350491785 100644 --- a/Python/count-of-smaller-numbers-after-self.py +++ b/Python/count-of-smaller-numbers-after-self.py @@ -16,6 +16,7 @@ # To the right of 1 there is 0 smaller element. # Return the array [2, 1, 1, 0]. +# BIT solution. class Solution(object): def countSmaller(self, nums): """ @@ -59,4 +60,69 @@ def query(self, i): ans[i] = bit.query(places[i]) bit.add(places[i] + 1, 1) return ans - + +# Time: O(nlogn) +# Space: O(n) +# BST solution. +class Solution2(object): + def countSmaller(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + res = [0] * len(nums) + bst = self.BST() + # Insert into BST and get right count. + for i in reversed(xrange(len(nums))): + bst.insertNode(nums[i]) + res[i] = bst.query(nums[i]) + + return res + + class BST(object): + class BSTreeNode(object): + def __init__(self, val): + self.val = val + self.count = 0 + self.left = self.right = None + + def __init__(self): + self.root = None + + # Insert node into BST. + def insertNode(self, val): + node = self.BSTreeNode(val) + if not self.root: + self.root = node + return + curr = self.root + while curr: + # Insert left if smaller. + if node.val < curr.val: + curr.count += 1 # Increase the number of left children. + if curr.left: + curr = curr.left; + else: + curr.left = node; + break + else: # Insert right if larger or equal. + if curr.right: + curr = curr.right + else: + curr.right = node + break + + # Query the smaller count of the value. + def query(self, val): + count = 0 + curr = self.root + while curr: + # Insert left. + if val < curr.val: + curr = curr.left + elif val > curr.val: + count += 1 + curr.count # Count the number of the smaller nodes. + curr = curr.right + else: # Equal. + return count + curr.count + return 0 From cbd17dbed7b547834bd2348bb025386dd923817f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Dec 2015 00:19:37 +0800 Subject: [PATCH 1439/1939] Update count-of-smaller-numbers-after-self.py --- Python/count-of-smaller-numbers-after-self.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/count-of-smaller-numbers-after-self.py b/Python/count-of-smaller-numbers-after-self.py index 350491785..e1061fbd9 100644 --- a/Python/count-of-smaller-numbers-after-self.py +++ b/Python/count-of-smaller-numbers-after-self.py @@ -72,7 +72,7 @@ def countSmaller(self, nums): """ res = [0] * len(nums) bst = self.BST() - # Insert into BST and get right count. + # Insert into BST and get left count. for i in reversed(xrange(len(nums))): bst.insertNode(nums[i]) res[i] = bst.query(nums[i]) From e9c31d0fecd9b3caa97bee7dc950b2332fe84a3f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Dec 2015 00:19:51 +0800 Subject: [PATCH 1440/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index eeb69111c..5e3bf5d5e 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -20,7 +20,7 @@ class Solution { BSTreeNode *root = nullptr; - // Insert into BST and get right count. + // Insert into BST and get left count. for (int i = nums.size() - 1; i >= 0; --i) { BSTreeNode *node = new BSTreeNode(nums[i], 0); root = insertNode(root, node); From 197268ff54c700df7c8ebfb18d42b2b17f6f294e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:00:46 +0800 Subject: [PATCH 1441/1939] Create remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/remove-duplicate-letters.cpp diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp new file mode 100644 index 000000000..061c09436 --- /dev/null +++ b/C++/remove-duplicate-letters.cpp @@ -0,0 +1,32 @@ +// Time: O(n) +// Space: O(k) + +class Solution { +public: + string removeDuplicateLetters(string s) { + const int k = 26; + unordered_map cnts; + unordered_set visited; + string res; + stack stk; + for (const auto& c : s) { + ++cnts[c]; + } + for (int i = 0; i < s.size(); --cnts[s[i]], ++i) { + if (!visited.count(s[i]) && (stk.empty() || stk.top() != s[i])) { + while (!stk.empty() && stk.top() >= s[i] && cnts[stk.top()] > 0) { + visited.erase(stk.top()); + stk.pop(); + } + stk.emplace(s[i]); + visited.emplace(s[i]); + } + } + while (!stk.empty()) { + res.push_back(stk.top()); + stk.pop(); + } + reverse(res.begin(), res.end()); + return res; + } +}; From 3d22071d8c1919d98170c367b818b411b18cb7dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:02:15 +0800 Subject: [PATCH 1442/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index 061c09436..c698e7546 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -4,14 +4,14 @@ class Solution { public: string removeDuplicateLetters(string s) { - const int k = 26; unordered_map cnts; - unordered_set visited; - string res; - stack stk; for (const auto& c : s) { ++cnts[c]; } + + string res; + unordered_set visited; + stack stk; for (int i = 0; i < s.size(); --cnts[s[i]], ++i) { if (!visited.count(s[i]) && (stk.empty() || stk.top() != s[i])) { while (!stk.empty() && stk.top() >= s[i] && cnts[stk.top()] > 0) { From 85810f023fc2d8e30da24c546a5719806ef1dc91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:05:33 +0800 Subject: [PATCH 1443/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8067ecd5b..d8a652386 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-315%20%2F%20315-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-316%20%2F%20316-ff69b4.svg) -Up to date (2015-12-06), there are `298` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-09), there are `299` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `315` questions. +Here is the classification of all `316` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -427,6 +427,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 122| [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Python](./Python/best-time-to-buy-and-sell-stock-ii.py) | _O(n)_ | _O(1)_ | Medium || 134| [Gas Station](https://leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || 135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || +316| [Closest Binary Search Tree Value II](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./C++/remove-duplicate-letters.cpp) [Python](./Python/remove-duplicate-letters.py) | _O(n)_| _O(k)_| Medium || Stack | --- ##Design From 55cf750630d7b564605c1151b5af6eab894f5e38 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:06:12 +0800 Subject: [PATCH 1444/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d8a652386..12b868d29 100644 --- a/README.md +++ b/README.md @@ -427,7 +427,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 122| [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Python](./Python/best-time-to-buy-and-sell-stock-ii.py) | _O(n)_ | _O(1)_ | Medium || 134| [Gas Station](https://leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || 135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || -316| [Closest Binary Search Tree Value II](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./C++/remove-duplicate-letters.cpp) [Python](./Python/remove-duplicate-letters.py) | _O(n)_| _O(k)_| Medium || Stack | +316| [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./C++/remove-duplicate-letters.cpp) [Python](./Python/remove-duplicate-letters.py) | _O(n)_| _O(k)_| Medium || Stack | --- ##Design From a40f4091d0d15d08ec0c781f187936d2e9c2c365 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:06:58 +0800 Subject: [PATCH 1445/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index c698e7546..26b690952 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(k) +// Space: O(k), k is size of the alphabet class Solution { public: From faa77cd19c7a875bb9783a11cca83cd4964ee7c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:22:48 +0800 Subject: [PATCH 1446/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index 26b690952..dd09ae233 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -12,15 +12,16 @@ class Solution { string res; unordered_set visited; stack stk; - for (int i = 0; i < s.size(); --cnts[s[i]], ++i) { - if (!visited.count(s[i]) && (stk.empty() || stk.top() != s[i])) { - while (!stk.empty() && stk.top() >= s[i] && cnts[stk.top()] > 0) { + for (const auto& c : s) { + if (!visited.count(c) && (stk.empty() || stk.top() != c)) { + while (!stk.empty() && stk.top() >= c && cnts[stk.top()] > 0) { visited.erase(stk.top()); stk.pop(); } - stk.emplace(s[i]); - visited.emplace(s[i]); + stk.emplace(c); + visited.emplace(c); } + --cnts[c]; } while (!stk.empty()) { res.push_back(stk.top()); @@ -30,3 +31,4 @@ class Solution { return res; } }; + From 9e9f06056429f7a2b2a3001a8dec66e79420be3e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:29:55 +0800 Subject: [PATCH 1447/1939] Create remove-duplicate-letters.py --- Python/remove-duplicate-letters.py | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/remove-duplicate-letters.py diff --git a/Python/remove-duplicate-letters.py b/Python/remove-duplicate-letters.py new file mode 100644 index 000000000..b9a8310e3 --- /dev/null +++ b/Python/remove-duplicate-letters.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(k), k is size of the alphabet + +# 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" + +class Solution(object): + def removeDuplicateLetters(self, s): + """ + :type s: str + :rtype: str + """ + cnts = collections.defaultdict(int) + for c in s: + cnts[c] += 1 + + visited, stk = set(), [] + for c in s: + if c not in visited and (not stk or stk[-1] != c): + while stk and stk[-1] >= c and cnts[stk[-1]] > 0: + visited.remove(stk.pop()) + stk += c + visited.add(c) + cnts[c] -= 1 + return "".join(stk) From 162f2103ad36d2a98a64bcda01f28b2e6c50cadf Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:32:52 +0800 Subject: [PATCH 1448/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index dd09ae233..45ee1bf52 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -9,26 +9,19 @@ class Solution { ++cnts[c]; } - string res; unordered_set visited; - stack stk; + string res; for (const auto& c : s) { - if (!visited.count(c) && (stk.empty() || stk.top() != c)) { - while (!stk.empty() && stk.top() >= c && cnts[stk.top()] > 0) { - visited.erase(stk.top()); - stk.pop(); + if (!visited.count(c) && (res.empty() || res.back() != c)) { + while (!res.empty() && res.back() >= c && cnts[res.back()] > 0) { + visited.erase(res.back()); + res.pop_back(); } - stk.emplace(c); + res.push_back(c); visited.emplace(c); } --cnts[c]; } - while (!stk.empty()) { - res.push_back(stk.top()); - stk.pop(); - } - reverse(res.begin(), res.end()); return res; } }; - From 2d52013ef765501b1937995707e38a0c6ad1593d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:34:19 +0800 Subject: [PATCH 1449/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index 45ee1bf52..09b1bb7b3 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -10,18 +10,18 @@ class Solution { } unordered_set visited; - string res; + string stk; for (const auto& c : s) { - if (!visited.count(c) && (res.empty() || res.back() != c)) { - while (!res.empty() && res.back() >= c && cnts[res.back()] > 0) { - visited.erase(res.back()); - res.pop_back(); + if (!visited.count(c) && (stk.empty() || stk.back() != c)) { + while (!stk.empty() && stk.back() >= c && cnts[stk.back()] > 0) { + visited.erase(stk.back()); + stk.pop_back(); } - res.push_back(c); + stk.push_back(c); visited.emplace(c); } --cnts[c]; } - return res; + return stk; } }; From f016ae55940bce4aa78b57541dce41fd00eb3166 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:41:12 +0800 Subject: [PATCH 1450/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index 09b1bb7b3..a19e171df 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -1,7 +1,36 @@ // Time: O(n) // Space: O(k), k is size of the alphabet +// array solution (4ms) class Solution { +public: + string removeDuplicateLetters(string s) { + array cnts{0}; + for (const auto& c : s) { + ++cnts[c - 'a']; + } + + array visited{false}; + string stk; + for (const auto& c : s) { + if (!visited[c - 'a'] && (stk.empty() || stk.back() != c)) { + while (!stk.empty() && stk.back() >= c && cnts[stk.back() - 'a'] > 0) { + visited[stk.back() - 'a'] = false; + stk.pop_back(); + } + stk.push_back(c); + visited[c - 'a'] = true; + } + --cnts[c - 'a']; + } + return stk; + } +}; + +// Time: O(n) +// Space: O(k), k is size of the alphabet +// hash solution (16ms) +class Solution2 { public: string removeDuplicateLetters(string s) { unordered_map cnts; From 0e9f9d31c29a0d0e8660fee2ed81894e97760825 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:46:16 +0800 Subject: [PATCH 1451/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index a19e171df..ee472a3cc 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -1,16 +1,17 @@ // Time: O(n) // Space: O(k), k is size of the alphabet -// array solution (4ms) +// vector solution, need to know size of the alphabet in advace (4ms) class Solution { public: string removeDuplicateLetters(string s) { - array cnts{0}; + const int k = 26; + vector cnts(k); for (const auto& c : s) { ++cnts[c - 'a']; } - array visited{false}; + vector visited(k); string stk; for (const auto& c : s) { if (!visited[c - 'a'] && (stk.empty() || stk.back() != c)) { @@ -29,7 +30,7 @@ class Solution { // Time: O(n) // Space: O(k), k is size of the alphabet -// hash solution (16ms) +// hash solution, no need to know size of the alphabet in advance (16ms) class Solution2 { public: string removeDuplicateLetters(string s) { From ae1787e27f1040a353743c4cf94469d61016cb42 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Dec 2015 22:46:36 +0800 Subject: [PATCH 1452/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index ee472a3cc..501ed06a2 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -1,7 +1,7 @@ // Time: O(n) // Space: O(k), k is size of the alphabet -// vector solution, need to know size of the alphabet in advace (4ms) +// vector solution, need to know size of the alphabet in advance (4ms) class Solution { public: string removeDuplicateLetters(string s) { From dce7c56a57bd8165f583101001c8f76e65d1f9a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Dec 2015 07:37:36 +0800 Subject: [PATCH 1453/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index 501ed06a2..1ba3f9298 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -14,8 +14,8 @@ class Solution { vector visited(k); string stk; for (const auto& c : s) { - if (!visited[c - 'a'] && (stk.empty() || stk.back() != c)) { - while (!stk.empty() && stk.back() >= c && cnts[stk.back() - 'a'] > 0) { + if (!visited[c - 'a']) { + while (!stk.empty() && stk.back() > c && cnts[stk.back() - 'a']) { visited[stk.back() - 'a'] = false; stk.pop_back(); } @@ -42,8 +42,8 @@ class Solution2 { unordered_set visited; string stk; for (const auto& c : s) { - if (!visited.count(c) && (stk.empty() || stk.back() != c)) { - while (!stk.empty() && stk.back() >= c && cnts[stk.back()] > 0) { + if (!visited.count(c)) { + while (!stk.empty() && stk.back() > c && cnts[stk.back()]) { visited.erase(stk.back()); stk.pop_back(); } From 24a7be324f6cd2f9de0e5c0847274411c74ca1de Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Dec 2015 07:39:03 +0800 Subject: [PATCH 1454/1939] Update remove-duplicate-letters.py --- Python/remove-duplicate-letters.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/remove-duplicate-letters.py b/Python/remove-duplicate-letters.py index b9a8310e3..a5195b325 100644 --- a/Python/remove-duplicate-letters.py +++ b/Python/remove-duplicate-letters.py @@ -26,8 +26,8 @@ def removeDuplicateLetters(self, s): visited, stk = set(), [] for c in s: - if c not in visited and (not stk or stk[-1] != c): - while stk and stk[-1] >= c and cnts[stk[-1]] > 0: + if c not in visited: + while stk and stk[-1] > c and cnts[stk[-1]]: visited.remove(stk.pop()) stk += c visited.add(c) From bd423f4eb61ddc6addd9b5237a55cc6f4799e312 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Dec 2015 07:41:40 +0800 Subject: [PATCH 1455/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index 1ba3f9298..bbfb3be43 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -11,16 +11,16 @@ class Solution { ++cnts[c - 'a']; } - vector visited(k); + vector in_stack(k); string stk; for (const auto& c : s) { - if (!visited[c - 'a']) { + if (!in_stack[c - 'a']) { while (!stk.empty() && stk.back() > c && cnts[stk.back() - 'a']) { - visited[stk.back() - 'a'] = false; + in_stack[stk.back() - 'a'] = false; stk.pop_back(); } stk.push_back(c); - visited[c - 'a'] = true; + in_stack[c - 'a'] = true; } --cnts[c - 'a']; } @@ -39,16 +39,16 @@ class Solution2 { ++cnts[c]; } - unordered_set visited; + unordered_set in_stack; string stk; for (const auto& c : s) { - if (!visited.count(c)) { + if (!in_stack.count(c)) { while (!stk.empty() && stk.back() > c && cnts[stk.back()]) { - visited.erase(stk.back()); + in_stack.erase(stk.back()); stk.pop_back(); } stk.push_back(c); - visited.emplace(c); + in_stack.emplace(c); } --cnts[c]; } From e787f3aaf311addca1b96381aea2eba71482c5ef Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Dec 2015 07:43:10 +0800 Subject: [PATCH 1456/1939] Update remove-duplicate-letters.cpp --- C++/remove-duplicate-letters.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/remove-duplicate-letters.cpp b/C++/remove-duplicate-letters.cpp index bbfb3be43..9034bf7f7 100644 --- a/C++/remove-duplicate-letters.cpp +++ b/C++/remove-duplicate-letters.cpp @@ -6,23 +6,23 @@ class Solution { public: string removeDuplicateLetters(string s) { const int k = 26; - vector cnts(k); + vector remaining(k); for (const auto& c : s) { - ++cnts[c - 'a']; + ++remaining[c - 'a']; } vector in_stack(k); string stk; for (const auto& c : s) { if (!in_stack[c - 'a']) { - while (!stk.empty() && stk.back() > c && cnts[stk.back() - 'a']) { + while (!stk.empty() && stk.back() > c && remaining[stk.back() - 'a']) { in_stack[stk.back() - 'a'] = false; stk.pop_back(); } stk.push_back(c); in_stack[c - 'a'] = true; } - --cnts[c - 'a']; + --remaining[c - 'a']; } return stk; } @@ -34,23 +34,23 @@ class Solution { class Solution2 { public: string removeDuplicateLetters(string s) { - unordered_map cnts; + unordered_map remaining; for (const auto& c : s) { - ++cnts[c]; + ++remaining[c]; } unordered_set in_stack; string stk; for (const auto& c : s) { if (!in_stack.count(c)) { - while (!stk.empty() && stk.back() > c && cnts[stk.back()]) { + while (!stk.empty() && stk.back() > c && remaining[stk.back()]) { in_stack.erase(stk.back()); stk.pop_back(); } stk.push_back(c); in_stack.emplace(c); } - --cnts[c]; + --remaining[c]; } return stk; } From b3bd776050e53c7d764983fbedf711f4e5280d64 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Dec 2015 07:44:31 +0800 Subject: [PATCH 1457/1939] Update remove-duplicate-letters.py --- Python/remove-duplicate-letters.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Python/remove-duplicate-letters.py b/Python/remove-duplicate-letters.py index a5195b325..552643870 100644 --- a/Python/remove-duplicate-letters.py +++ b/Python/remove-duplicate-letters.py @@ -20,16 +20,16 @@ def removeDuplicateLetters(self, s): :type s: str :rtype: str """ - cnts = collections.defaultdict(int) + remaining = collections.defaultdict(int) for c in s: - cnts[c] += 1 + remaining[c] += 1 - visited, stk = set(), [] + in_stack, stk = set(), [] for c in s: - if c not in visited: - while stk and stk[-1] > c and cnts[stk[-1]]: - visited.remove(stk.pop()) + if c not in in_stack: + while stk and stk[-1] > c and remaining[stk[-1]]: + in_stack.remove(stk.pop()) stk += c - visited.add(c) - cnts[c] -= 1 + in_stack.add(c) + remaining[c] -= 1 return "".join(stk) From 4de3bf2177c2c696c7bdcf8e759d8dee7275d73c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Dec 2015 12:03:05 +0800 Subject: [PATCH 1458/1939] Update count-and-say.py --- Python/count-and-say.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/count-and-say.py b/Python/count-and-say.py index 325fdc8e5..f1b27c374 100644 --- a/Python/count-and-say.py +++ b/Python/count-and-say.py @@ -27,7 +27,7 @@ def getNext(self, seq): while i < len(seq) - 1 and seq[i] == seq[i + 1]: cnt += 1 i += 1 - next_seq += "{}{}".format(cnt, seq[i]) + next_seq += str(cnt) + seq[i] i += 1 return next_seq From 319f27236076ac80de7c2335f914f523445256a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 12 Dec 2015 20:56:33 +0800 Subject: [PATCH 1459/1939] Create happy-number.cpp --- C++/happy-number.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/happy-number.cpp diff --git a/C++/happy-number.cpp b/C++/happy-number.cpp new file mode 100644 index 000000000..b251abeb6 --- /dev/null +++ b/C++/happy-number.cpp @@ -0,0 +1,23 @@ +// Time: O(k), where k is the steps to be happy number +// Space: O(k) + +class Solution { +public: + bool isHappy(int n) { + unordered_set visited; + while (n != 1 && !visited.count(n)) { + visited.emplace(n); + n = nextNumber(n); + } + return n == 1; + } + + int nextNumber(int n) { + int sum = 0; + while (n) { + sum += pow(n % 10, 2); + n /= 10; + } + return sum; + } +}; From 1e0cf362a537200b2759c9704c885330e77fc561 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 12 Dec 2015 20:57:07 +0800 Subject: [PATCH 1460/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 12b868d29..0293e11eb 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 159| [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| 170| [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) | [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 📖 | 187| [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || -202| [Happy Number](https://leetcode.com/problems/happy-number/) | [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || +202| [Happy Number](https://leetcode.com/problems/happy-number/) | [C++](./C++/happy-number.cpp) [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || From 7cce1494fe268ea95ed6eacd5723ad5f001dbccf Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Dec 2015 16:43:49 +0800 Subject: [PATCH 1461/1939] Create shortest-distance-from-all-buildings.py --- .../shortest-distance-from-all-buildings.py | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/shortest-distance-from-all-buildings.py diff --git a/Python/shortest-distance-from-all-buildings.py b/Python/shortest-distance-from-all-buildings.py new file mode 100644 index 000000000..6b5fdb002 --- /dev/null +++ b/Python/shortest-distance-from-all-buildings.py @@ -0,0 +1,55 @@ +# Time: O(k * m * n), k is the number of the buildings +# Space: O(m * n) + +class Solution(object): + def shortestDistance(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + def bfs(grid, dists, reachable, x, y): + dist, m, n = 0, len(grid), len(grid[0]) + visited = [[False for _ in xrange(n)] for _ in xrange(m)] + + pre_level = [(x, y)] + visited[x][y] = True # enqueue, then visited + while pre_level: + cur_level = [] + for i, j in pre_level: + dists[i][j] += dist + + for dir in [(-1, 0), (1, 0), (0, -1), (0, 1)]: + I, J = i+dir[0], j+dir[1] + if 0 <= I < m and 0 <= J < n and grid[I][J] == 0 and not visited[I][J]: + cur_level.append((I, J)) + visited[I][J] = True + + dist += 1 + pre_level = cur_level + + for i in xrange(m): + for j in xrange(n): + if not visited[i][j]: + reachable[i][j] = False + + m, n = len(grid), len(grid[0]) + dists = [[0 for _ in xrange(n)] for _ in xrange(m)] + reachable = [[True for _ in xrange(n)] for _ in xrange(m)] + for i in xrange(m): + for j in xrange(n): + if grid[i][j] > 0: + reachable[i][j] = False + dists[i][j] = float("inf") + + for i in xrange(m): + for j in xrange(n): + if grid[i][j] == 1: + bfs(grid, dists, reachable, i, j) + + shortest = float("inf") + for i in xrange(m): + for j in xrange(n): + if dists[i][j] < shortest and reachable[i][j]: + shortest = dists[i][j] + + return shortest if shortest != float("inf") else -1 From 4a7b0eb3d8df214ab8d518c1ebda9bf864ee568e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Dec 2015 16:45:38 +0800 Subject: [PATCH 1462/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0293e11eb..0aacd7b75 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-316%20%2F%20316-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-317%20%2F%20317-ff69b4.svg) -Up to date (2015-12-09), there are `299` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-14), there are `300` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `316` questions. +Here is the classification of all `317` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -345,6 +345,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 269| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | [C++](./C++/alien-dictionary.cpp) [Python](./Python/alien-dictionary.py) | _O(n)_ | _O(1)_ | Hard |📖| Topological Sort, BFS, DFS | 286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [C++](./C++/walls-and-gates.cpp) [Python](./Python/walls-and-gates.py) | _O(m * n)_ | _O(g)_ | Medium | 📖 | 310| [Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/)| [C++](./C++/minimum-height-trees.cpp) [Python](./Python/minimum-height-trees.py) | _O(n)_ | _O(n)_ | Medium || +317| [Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings/)| [C++](./C++/shortest-distance-from-all-buildings.cpp) [Python](./Python/shortest-distance-from-all-buildings.py) | _O(k * m * n)_ | _O(m * n)_ | Hard | 📖 | ## Depth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 211ad570838f98d7377948db5f5999f57f8cd6f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Dec 2015 23:25:35 +0800 Subject: [PATCH 1463/1939] Update shortest-distance-from-all-buildings.py --- .../shortest-distance-from-all-buildings.py | 26 +++++++------------ 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/Python/shortest-distance-from-all-buildings.py b/Python/shortest-distance-from-all-buildings.py index 6b5fdb002..713756be4 100644 --- a/Python/shortest-distance-from-all-buildings.py +++ b/Python/shortest-distance-from-all-buildings.py @@ -7,7 +7,7 @@ def shortestDistance(self, grid): :type grid: List[List[int]] :rtype: int """ - def bfs(grid, dists, reachable, x, y): + def bfs(grid, dists, cnts, x, y): dist, m, n = 0, len(grid), len(grid[0]) visited = [[False for _ in xrange(n)] for _ in xrange(m)] @@ -22,34 +22,28 @@ def bfs(grid, dists, reachable, x, y): I, J = i+dir[0], j+dir[1] if 0 <= I < m and 0 <= J < n and grid[I][J] == 0 and not visited[I][J]: cur_level.append((I, J)) + cnts[I][J] += 1 visited[I][J] = True dist += 1 pre_level = cur_level - - for i in xrange(m): - for j in xrange(n): - if not visited[i][j]: - reachable[i][j] = False - m, n = len(grid), len(grid[0]) - dists = [[0 for _ in xrange(n)] for _ in xrange(m)] - reachable = [[True for _ in xrange(n)] for _ in xrange(m)] - for i in xrange(m): - for j in xrange(n): - if grid[i][j] > 0: - reachable[i][j] = False - dists[i][j] = float("inf") + m, n, cnt = len(grid), len(grid[0]), 0 + dists = [[0 for _ in xrange(n)] for _ in xrange(m)] + cnts = [[0 for _ in xrange(n)] for _ in xrange(m)] for i in xrange(m): for j in xrange(n): if grid[i][j] == 1: - bfs(grid, dists, reachable, i, j) + cnt += 1 + bfs(grid, dists, cnts, i, j) shortest = float("inf") for i in xrange(m): for j in xrange(n): - if dists[i][j] < shortest and reachable[i][j]: + if dists[i][j] < shortest and cnts[i][j] == cnt: shortest = dists[i][j] return shortest if shortest != float("inf") else -1 + + From c500bfbc77540a76a7ebd3c5ffd66e64437ff9f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Dec 2015 23:25:45 +0800 Subject: [PATCH 1464/1939] Update shortest-distance-from-all-buildings.py --- Python/shortest-distance-from-all-buildings.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Python/shortest-distance-from-all-buildings.py b/Python/shortest-distance-from-all-buildings.py index 713756be4..c765d9415 100644 --- a/Python/shortest-distance-from-all-buildings.py +++ b/Python/shortest-distance-from-all-buildings.py @@ -45,5 +45,3 @@ def bfs(grid, dists, cnts, x, y): shortest = dists[i][j] return shortest if shortest != float("inf") else -1 - - From c4acbd4fa8bc45aaee420dd46c51ae2d1ce24eb2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Dec 2015 23:34:07 +0800 Subject: [PATCH 1465/1939] Update shortest-distance-from-all-buildings.py --- Python/shortest-distance-from-all-buildings.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Python/shortest-distance-from-all-buildings.py b/Python/shortest-distance-from-all-buildings.py index c765d9415..bbeb3c326 100644 --- a/Python/shortest-distance-from-all-buildings.py +++ b/Python/shortest-distance-from-all-buildings.py @@ -14,18 +14,17 @@ def bfs(grid, dists, cnts, x, y): pre_level = [(x, y)] visited[x][y] = True # enqueue, then visited while pre_level: + dist += 1 cur_level = [] for i, j in pre_level: - dists[i][j] += dist - for dir in [(-1, 0), (1, 0), (0, -1), (0, 1)]: I, J = i+dir[0], j+dir[1] if 0 <= I < m and 0 <= J < n and grid[I][J] == 0 and not visited[I][J]: - cur_level.append((I, J)) cnts[I][J] += 1 + dists[I][J] += dist + cur_level.append((I, J)) visited[I][J] = True - dist += 1 pre_level = cur_level From 73eea61ca017d9d26ab6e5ee19706241c9ffadc1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Dec 2015 23:34:55 +0800 Subject: [PATCH 1466/1939] Update shortest-distance-from-all-buildings.py --- Python/shortest-distance-from-all-buildings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/shortest-distance-from-all-buildings.py b/Python/shortest-distance-from-all-buildings.py index bbeb3c326..7b5fd2ae5 100644 --- a/Python/shortest-distance-from-all-buildings.py +++ b/Python/shortest-distance-from-all-buildings.py @@ -12,7 +12,7 @@ def bfs(grid, dists, cnts, x, y): visited = [[False for _ in xrange(n)] for _ in xrange(m)] pre_level = [(x, y)] - visited[x][y] = True # enqueue, then visited + visited[x][y] = True while pre_level: dist += 1 cur_level = [] From 2b14b8af7f41c54166cbcea395a1ca6bf21229e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Dec 2015 23:52:41 +0800 Subject: [PATCH 1467/1939] Create shortest-distance-from-all-buildings.cpp --- C++/shortest-distance-from-all-buildings.cpp | 59 ++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/shortest-distance-from-all-buildings.cpp diff --git a/C++/shortest-distance-from-all-buildings.cpp b/C++/shortest-distance-from-all-buildings.cpp new file mode 100644 index 000000000..e44fae22b --- /dev/null +++ b/C++/shortest-distance-from-all-buildings.cpp @@ -0,0 +1,59 @@ +// Time: O(k * m * n), k is the number of the buildings +// Space: O(m * n) + +class Solution { +public: + int shortestDistance(vector>& grid) { + int m = grid.size(), n = grid[0].size(), cnt = 0; + vector> dists(m, vector(n)),cnts(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1) { + ++cnt; + BFS(grid, i, j, &dists, &cnts); + } + } + } + + int shortest = numeric_limits::max(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (dists[i][j] < shortest && cnts[i][j] == cnt) { + shortest = dists[i][j]; + } + } + } + + return shortest != numeric_limits::max() ? shortest : -1; + } + + void BFS(const vector>& grid, int x, int y, + vector> *dists, vector> *cnts) { + int dist = 0, m = grid.size(), n = grid[0].size(); + vector> visited(m, vector(n)); + + vector> pre_level{{x, y}}, cur_level; + visited[x][y] = true; + while (!pre_level.empty()) { + ++dist; + cur_level.clear(); + for (const auto& p : pre_level) { + int i, j; + tie(i, j) = p; + const vector> directions{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; + for (const auto& d : directions) { + const int I = i + d.first, J = j + d.second; + if (0 <= I && I < m && 0 <= J && J < n && + grid[I][J] == 0 && !visited[I][J]) { + (*dists)[I][J] += dist; + ++(*cnts)[I][J]; + cur_level.push_back({I, J}); + visited[I][J] = true; + } + } + } + swap(pre_level, cur_level); + } + } +}; From 5b54e2168da75888cb0b73c14ea5a27e8029dd0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 15 Dec 2015 00:11:54 +0800 Subject: [PATCH 1468/1939] Update shortest-distance-from-all-buildings.cpp --- C++/shortest-distance-from-all-buildings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/shortest-distance-from-all-buildings.cpp b/C++/shortest-distance-from-all-buildings.cpp index e44fae22b..218721bfa 100644 --- a/C++/shortest-distance-from-all-buildings.cpp +++ b/C++/shortest-distance-from-all-buildings.cpp @@ -5,7 +5,7 @@ class Solution { public: int shortestDistance(vector>& grid) { int m = grid.size(), n = grid[0].size(), cnt = 0; - vector> dists(m, vector(n)),cnts(m, vector(n)); + vector> dists(m, vector(n)), cnts(m, vector(n)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == 1) { From 294a873afaf98b30d6dce9ea35e357bd276c9bb7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 07:25:24 +0800 Subject: [PATCH 1469/1939] Create maximum-product-of-word-lengths.cpp --- C++/maximum-product-of-word-lengths.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/maximum-product-of-word-lengths.cpp diff --git a/C++/maximum-product-of-word-lengths.cpp b/C++/maximum-product-of-word-lengths.cpp new file mode 100644 index 000000000..12fc04595 --- /dev/null +++ b/C++/maximum-product-of-word-lengths.cpp @@ -0,0 +1,25 @@ +// Time: O(nlogn) ~ O(n^2) +// Space: O(n) + +// Sorting + Pruning + Bit Manipulation +class Solution { +public: + int maxProduct(vector& words) { + sort(words.begin(), words.end(), [](const string& a, const string& b) { return a.length() > b.length(); }); + vector bits(words.size()); + for (int i = 0; i < words.size(); ++i) { + for (const auto& c : words[i]) { + bits[i] |= (1 << (c - 'a')); + } + } + int max_product = 0; + for (int i = 0; i + 1 < words.size() && pow(words[i].length(), 2) > max_product; ++i) { + for (int j = i + 1; j < words.size() && words[i].length() * words[j].length() > max_product; ++j) { + if (!(bits[i] & bits[j])) { + max_product = words[i].length() * words[j].length(); + } + } + } + return max_product; + } +}; From 341efea37f7131ade79cdd095f365fdb36c659a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 07:47:18 +0800 Subject: [PATCH 1470/1939] Update maximum-product-of-word-lengths.cpp --- C++/maximum-product-of-word-lengths.cpp | 44 +++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/C++/maximum-product-of-word-lengths.cpp b/C++/maximum-product-of-word-lengths.cpp index 12fc04595..27e85f983 100644 --- a/C++/maximum-product-of-word-lengths.cpp +++ b/C++/maximum-product-of-word-lengths.cpp @@ -1,8 +1,48 @@ -// Time: O(nlogn) ~ O(n^2) +// Time: O(n) ~ O(n^2) // Space: O(n) -// Sorting + Pruning + Bit Manipulation +// Counting Sort + Pruning + Bit Manipulation class Solution { +public: + int maxProduct(vector& words) { + words = counting_sort(words); + vector bits(words.size()); + for (int i = 0; i < words.size(); ++i) { + for (const auto& c : words[i]) { + bits[i] |= (1 << (c - 'a')); + } + } + int max_product = 0; + for (int i = 0; i + 1 < words.size() && pow(words[i].length(), 2) > max_product; ++i) { + for (int j = i + 1; j < words.size() && words[i].length() * words[j].length() > max_product; ++j) { + if (!(bits[i] & bits[j])) { + max_product = words[i].length() * words[j].length(); + } + } + } + return max_product; + } + + vector counting_sort(vector& words) { + const int k = 1000; // k is max length of words in the dictionary + vector> buckets(k); + for (const auto& word : words) { + buckets[word.length()].emplace_back(word); + } + vector res; + for (int i = k - 1; i >= 0; --i) { + if (!buckets[i].empty()) { + move(buckets[i].begin(), buckets[i].end(), back_inserter(res)); + } + } + return res; + } +}; + +// Time: O(nlogn) ~ O(n^2) +// Space: O(n) +// Sorting + Pruning + Bit Manipulation +class Solution2 { public: int maxProduct(vector& words) { sort(words.begin(), words.end(), [](const string& a, const string& b) { return a.length() > b.length(); }); From c3b33855a6fdf5574c68aa353ba7496ec1e34b75 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 07:48:22 +0800 Subject: [PATCH 1471/1939] Update maximum-product-of-word-lengths.cpp --- C++/maximum-product-of-word-lengths.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/maximum-product-of-word-lengths.cpp b/C++/maximum-product-of-word-lengths.cpp index 27e85f983..bad7e7817 100644 --- a/C++/maximum-product-of-word-lengths.cpp +++ b/C++/maximum-product-of-word-lengths.cpp @@ -23,7 +23,7 @@ class Solution { return max_product; } - vector counting_sort(vector& words) { + vector counting_sort(const vector& words) { const int k = 1000; // k is max length of words in the dictionary vector> buckets(k); for (const auto& word : words) { From d5f9a8596a2fb463a8d5287ee36e0ba4fad1b777 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 07:58:12 +0800 Subject: [PATCH 1472/1939] Create maximum-product-of-word-lengths.py --- Python/maximum-product-of-word-lengths.py | 51 +++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/maximum-product-of-word-lengths.py diff --git a/Python/maximum-product-of-word-lengths.py b/Python/maximum-product-of-word-lengths.py new file mode 100644 index 000000000..07f01283a --- /dev/null +++ b/Python/maximum-product-of-word-lengths.py @@ -0,0 +1,51 @@ +# Time: O(nlogn) ~ O(n^2) +# Space: O(n) +# Sorting + Pruning + Bit Manipulation + +# 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. +# +# Follow up: +# Could you do better than O(n2), where n is the number of words? + +class Solution(object): + def maxProduct(self, words): + """ + :type words: List[str] + :rtype: int + """ + words.sort(key=lambda x: len(x), reverse=True) + bits = [0] * len(words) + for i, word in enumerate(words): + for c in word: + bits[i] |= (1 << (ord(c) - ord('a'))) + + max_product = 0 + for i in xrange(len(words) - 1): + if len(words[i]) ** 2 <= max_product: + break + for j in xrange(i + 1, len(words)): + if len(words[i]) * len(words[j]) <= max_product: + break + if not(bits[i] & bits[j]): + max_product = len(words[i]) * len(words[j]) + + return max_product From 5789badd43aa73d804100835a5e549ba7a9cb841 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 08:00:29 +0800 Subject: [PATCH 1473/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0aacd7b75..daca96818 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-317%20%2F%20317-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-318%20%2F%20318-ff69b4.svg) -Up to date (2015-12-14), there are `300` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-16), there are `301` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `317` questions. +Here is the classification of all `318` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -54,6 +54,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || 268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium | LintCode || +318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-lengths.py) | _O(n)_ | _O(1)_ | Medium || Bit Manipulation, Counting Sort, Pruning| ## Array # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 41bf6e05c44eaed620dd3b813b4d133393eae8f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 08:01:03 +0800 Subject: [PATCH 1474/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index daca96818..73f4e51a8 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || 268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium | LintCode || -318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-lengths.py) | _O(n)_ | _O(1)_ | Medium || Bit Manipulation, Counting Sort, Pruning| +318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-lengths.py) | _O(n ~ n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| ## Array # | Problem | Solution | Time | Space | Difficulty | Tag | Note From a3f4f6fa168d54ec1157f6cd7d623be74cd72865 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 08:02:13 +0800 Subject: [PATCH 1475/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 73f4e51a8..81f0d3383 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || 268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium | LintCode || -318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-lengths.py) | _O(n ~ n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| +318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-lengths.py) | _O(n)_ ~ _O(n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| ## Array # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 20439c80b058423c5d526df8def5914f580adf98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 08:08:42 +0800 Subject: [PATCH 1476/1939] Update maximum-product-of-word-lengths.py --- Python/maximum-product-of-word-lengths.py | 42 +++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/Python/maximum-product-of-word-lengths.py b/Python/maximum-product-of-word-lengths.py index 07f01283a..8e47fe738 100644 --- a/Python/maximum-product-of-word-lengths.py +++ b/Python/maximum-product-of-word-lengths.py @@ -1,6 +1,5 @@ -# Time: O(nlogn) ~ O(n^2) +# Time: O(n) ~ O(n^2) # Space: O(n) -# Sorting + Pruning + Bit Manipulation # Given a string array words, find the maximum value of # length(word[i]) * length(word[j]) where the two words @@ -26,7 +25,46 @@ # Follow up: # Could you do better than O(n2), where n is the number of words? +# Counting Sort + Pruning + Bit Manipulation class Solution(object): + def maxProduct(self, words): + """ + :type words: List[str] + :rtype: int + """ + def counting_sort(words): + k = 1000 + buckets = [[] for _ in xrange(k)] + for word in words: + buckets[len(word)].append(word) + res = [] + for i in reversed(xrange(k)): + if buckets[i]: + res.extend(buckets[i]) + return res + + words = counting_sort(words) + bits = [0] * len(words) + for i, word in enumerate(words): + for c in word: + bits[i] |= (1 << (ord(c) - ord('a'))) + + max_product = 0 + for i in xrange(len(words) - 1): + if len(words[i]) ** 2 <= max_product: + break + for j in xrange(i + 1, len(words)): + if len(words[i]) * len(words[j]) <= max_product: + break + if not(bits[i] & bits[j]): + max_product = len(words[i]) * len(words[j]) + + return max_product + +# Time: O(nlogn) ~ O(n^2) +# Space: O(n) +# Sorting + Pruning + Bit Manipulation +class Solution2(object): def maxProduct(self, words): """ :type words: List[str] From 350763371e418ee5b4b8ebcb1618286f439bb3ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 08:09:37 +0800 Subject: [PATCH 1477/1939] Update maximum-product-of-word-lengths.py --- Python/maximum-product-of-word-lengths.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximum-product-of-word-lengths.py b/Python/maximum-product-of-word-lengths.py index 8e47fe738..33e37add4 100644 --- a/Python/maximum-product-of-word-lengths.py +++ b/Python/maximum-product-of-word-lengths.py @@ -33,7 +33,7 @@ def maxProduct(self, words): :rtype: int """ def counting_sort(words): - k = 1000 + k = 1000 # k is max length of words in the dictionary buckets = [[] for _ in xrange(k)] for word in words: buckets[len(word)].append(word) From 9b7d6227eccdb4f4c75bb012ac3276cbf2df1918 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Dec 2015 08:11:59 +0800 Subject: [PATCH 1478/1939] Update maximum-product-of-word-lengths.py --- Python/maximum-product-of-word-lengths.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/maximum-product-of-word-lengths.py b/Python/maximum-product-of-word-lengths.py index 33e37add4..06444719f 100644 --- a/Python/maximum-product-of-word-lengths.py +++ b/Python/maximum-product-of-word-lengths.py @@ -56,7 +56,7 @@ def counting_sort(words): for j in xrange(i + 1, len(words)): if len(words[i]) * len(words[j]) <= max_product: break - if not(bits[i] & bits[j]): + if not (bits[i] & bits[j]): max_product = len(words[i]) * len(words[j]) return max_product @@ -83,7 +83,7 @@ def maxProduct(self, words): for j in xrange(i + 1, len(words)): if len(words[i]) * len(words[j]) <= max_product: break - if not(bits[i] & bits[j]): + if not (bits[i] & bits[j]): max_product = len(words[i]) * len(words[j]) return max_product From 0ae6331408bcc3ddb495aac941c313deec9f4109 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 17 Dec 2015 03:38:45 +0800 Subject: [PATCH 1479/1939] Update maximum-product-of-word-lengths.py --- Python/maximum-product-of-word-lengths.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Python/maximum-product-of-word-lengths.py b/Python/maximum-product-of-word-lengths.py index 06444719f..d189fdf9d 100644 --- a/Python/maximum-product-of-word-lengths.py +++ b/Python/maximum-product-of-word-lengths.py @@ -58,7 +58,6 @@ def counting_sort(words): break if not (bits[i] & bits[j]): max_product = len(words[i]) * len(words[j]) - return max_product # Time: O(nlogn) ~ O(n^2) @@ -85,5 +84,4 @@ def maxProduct(self, words): break if not (bits[i] & bits[j]): max_product = len(words[i]) * len(words[j]) - return max_product From b66bd6f1e5fccaac5fddce4cb416906590fafc11 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Dec 2015 19:54:50 +0900 Subject: [PATCH 1480/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 81f0d3383..38fa8a7d4 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-318%20%2F%20318-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-318%20%2F%20319-ff69b4.svg) -Up to date (2015-12-16), there are `301` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-19), there are `302` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `318` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From bab381eec6e7e6a23d20bfe539687d14c7540966 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Dec 2015 20:05:30 +0900 Subject: [PATCH 1481/1939] Create bulb-switcher.cpp --- C++/bulb-switcher.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 C++/bulb-switcher.cpp diff --git a/C++/bulb-switcher.cpp b/C++/bulb-switcher.cpp new file mode 100644 index 000000000..155ec67f8 --- /dev/null +++ b/C++/bulb-switcher.cpp @@ -0,0 +1,9 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int bulbSwitch(int n) { + return static_cast(sqrt(n)); + } +} From fae3225ffea6f9ee0707a83d0fa6fd8114a6a660 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Dec 2015 20:16:21 +0900 Subject: [PATCH 1482/1939] Create bulb-switcher.py --- Python/bulb-switcher.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Python/bulb-switcher.py diff --git a/Python/bulb-switcher.py b/Python/bulb-switcher.py new file mode 100644 index 000000000..ff2f9ad13 --- /dev/null +++ b/Python/bulb-switcher.py @@ -0,0 +1,10 @@ +# Time: O(1) +# Space: O(1) + +class Solution(object): + def bulbSwitch(self, n): + """ + type n: int + rtype: int + """ + return int(math.sqrt(n)) From 7aee010bbc817f315569218e7d2db42155bfc3d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Dec 2015 20:20:24 +0900 Subject: [PATCH 1483/1939] Update bulb-switcher.py --- Python/bulb-switcher.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Python/bulb-switcher.py b/Python/bulb-switcher.py index ff2f9ad13..e63903f29 100644 --- a/Python/bulb-switcher.py +++ b/Python/bulb-switcher.py @@ -1,6 +1,27 @@ # Time: O(1) # Space: O(1) +# 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. + class Solution(object): def bulbSwitch(self, n): """ From 567d81939106d686248330530afe2b266915a2a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Dec 2015 20:22:32 +0900 Subject: [PATCH 1484/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 38fa8a7d4..2403b83a8 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-318%20%2F%20319-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-319%20%2F%20319-ff69b4.svg) Up to date (2015-12-19), there are `302` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `318` questions. +Here is the classification of all `319` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From 584cb3a407e9208339814366441ea7205978da7b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Dec 2015 20:41:04 +0900 Subject: [PATCH 1485/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2403b83a8..23dad9661 100644 --- a/README.md +++ b/README.md @@ -238,6 +238,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 258| [Add Digits](https://leetcode.com/problems/add-digits/) | [C++](./C++/add-digits.cpp) [Python](./Python/add-digits.py) | _O(1)_ | _O(1)_ | Easy ||| 263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(logn)_ | _O(1)_ | Easy ||| 292| [Nim Game](https://leetcode.com/problems/nim-game/) | [C++](./C++/nim-game.cpp) [Python](./Python/nim-game.py) | _O(1)_ | _O(1)_ | Easy | LintCode || +319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./C++/bulb-switcher.cpp) [Python](./Python/bulb-switcher.py | _O(1)_ | _O(1)_ | Medium ||| ## Sort # | Problem | Solution | Time | Space | Difficulty | Tag | Note From b43190f83982e0196263ec804b1ebd3604f4409e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Dec 2015 20:42:07 +0900 Subject: [PATCH 1486/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 23dad9661..a72c331b2 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 258| [Add Digits](https://leetcode.com/problems/add-digits/) | [C++](./C++/add-digits.cpp) [Python](./Python/add-digits.py) | _O(1)_ | _O(1)_ | Easy ||| 263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(logn)_ | _O(1)_ | Easy ||| 292| [Nim Game](https://leetcode.com/problems/nim-game/) | [C++](./C++/nim-game.cpp) [Python](./Python/nim-game.py) | _O(1)_ | _O(1)_ | Easy | LintCode || -319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./C++/bulb-switcher.cpp) [Python](./Python/bulb-switcher.py | _O(1)_ | _O(1)_ | Medium ||| +319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./C++/bulb-switcher.cpp) [Python](./Python/bulb-switcher.py) | _O(1)_ | _O(1)_ | Medium ||| ## Sort # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 850b7697315cdd38bb77f25656407d4bec0af347 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Dec 2015 20:43:19 +0900 Subject: [PATCH 1487/1939] Update bulb-switcher.cpp --- C++/bulb-switcher.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/bulb-switcher.cpp b/C++/bulb-switcher.cpp index 155ec67f8..db71defe5 100644 --- a/C++/bulb-switcher.cpp +++ b/C++/bulb-switcher.cpp @@ -6,4 +6,4 @@ class Solution { int bulbSwitch(int n) { return static_cast(sqrt(n)); } -} +}; From 215277ea3bcf304e0a50dd4d242effe3f24ba0bd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 20 Dec 2015 18:57:15 +0900 Subject: [PATCH 1488/1939] Update bulb-switcher.py --- Python/bulb-switcher.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/bulb-switcher.py b/Python/bulb-switcher.py index e63903f29..a63b6c39e 100644 --- a/Python/bulb-switcher.py +++ b/Python/bulb-switcher.py @@ -28,4 +28,5 @@ def bulbSwitch(self, n): type n: int rtype: int """ + # The number of full squares. return int(math.sqrt(n)) From c88198976275b4fdfe75d05974291d88a292ffc4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 20 Dec 2015 18:58:07 +0900 Subject: [PATCH 1489/1939] Update bulb-switcher.cpp --- C++/bulb-switcher.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/bulb-switcher.cpp b/C++/bulb-switcher.cpp index db71defe5..f640a2f85 100644 --- a/C++/bulb-switcher.cpp +++ b/C++/bulb-switcher.cpp @@ -4,6 +4,7 @@ class Solution { public: int bulbSwitch(int n) { + // The number of full squares. return static_cast(sqrt(n)); } }; From e1b074931b94038946b3936020cc04238c9ff5da Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Dec 2015 21:52:34 +0800 Subject: [PATCH 1490/1939] Update restore-ip-addresses.py --- Python/restore-ip-addresses.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/restore-ip-addresses.py b/Python/restore-ip-addresses.py index 63e6b9a71..504ce6c6c 100644 --- a/Python/restore-ip-addresses.py +++ b/Python/restore-ip-addresses.py @@ -32,7 +32,7 @@ def restoreIpAddressesRecur(self, result, s, start, current, dots): current = current[:-(i - start + 2)] def isValid(self, s): - if len(s) == 0 or (s[0] == "0" and s != "0"): + if len(s) == 0 or (s[0] == '0' and s != "0"): return False return int(s) < 256 From 941fadd45d074fccbe473c75657c1d9f859ebe01 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Dec 2015 22:09:43 +0800 Subject: [PATCH 1491/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a72c331b2..f5e4e98fb 100644 --- a/README.md +++ b/README.md @@ -360,7 +360,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || 77| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || 79| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || -93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(n^m)_ ~ _O(3^4)_ | _O(n * m)_ ~ _O(3 * 4)_ | Medium || +93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || 112| [Path Sum](https://leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || 113| [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || 131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || From 63c9d03ae04a5c295855841dbddc1390422c050b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Dec 2015 13:52:52 +0800 Subject: [PATCH 1492/1939] Create generalized-abbreviation.cpp --- C++/generalized-abbreviation.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/generalized-abbreviation.cpp diff --git a/C++/generalized-abbreviation.cpp b/C++/generalized-abbreviation.cpp new file mode 100644 index 000000000..4eecbba64 --- /dev/null +++ b/C++/generalized-abbreviation.cpp @@ -0,0 +1,29 @@ +// Time: O(2^n) +// Space: O(n) + +class Solution { +public: + vector generateAbbreviations(string word) { + vector res; + string cur; + generateAbbreviationsHelper(word, 0, false, &cur, &res); + return res; + } + + void generateAbbreviationsHelper(const string& word, int i, bool is_prev_num, string *cur, vector *res) { + if (i == word.length()) { + res->emplace_back(*cur); + return; + } + cur->push_back(word[i]); + generateAbbreviationsHelper(word, i + 1, false, cur, res); + cur->pop_back(); + if (!is_prev_num) { + for (int len = 1; i + len <= word.length(); ++len) { + cur->append(to_string(len)); + generateAbbreviationsHelper(word, i + len, true, cur, res); + cur->resize(cur->length() - to_string(len).length()); + } + } + } +}; From 49c89cf8fa35802634aef0fc2fb0571d3aec1630 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Dec 2015 14:04:13 +0800 Subject: [PATCH 1493/1939] Update README.md --- README.md | 50 +++++++++++++++++++++++--------------------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index f5e4e98fb..90a24847d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-319%20%2F%20319-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-320%20%2F%20320-ff69b4.svg) -Up to date (2015-12-19), there are `302` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-22), there are `303` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `319` questions. +Here is the classification of all `320` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -22,7 +22,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates * [Math](https://github.com/kamyu104/LeetCode#math) * [Two Pointers](https://github.com/kamyu104/LeetCode#two-pointers) * [Sort](https://github.com/kamyu104/LeetCode#sort) -* [Brute Force Search](https://github.com/kamyu104/LeetCode#brute-force-search) * [Divide and Conquer](https://github.com/kamyu104/LeetCode#divide-and-conquer) * [Binary Search](https://github.com/kamyu104/LeetCode#binary-search) * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) @@ -175,7 +174,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS -212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT @@ -271,16 +269,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 283 | [Move Zeros](https://leetcode.com/problems/move-zeros/) | [C++](./C++/move-zeros.cpp) [Python](./Python/move-zeros.py) | _O(n)_ | _O(1)_ | Easy | | 287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Hard | | Binary Search, Two Pointers | -## Brute Force Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || -46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n * n!)_ | _O(n)_ | Medium || -47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Hard || -78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || -90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || -267| [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) | [C++](./C++/palindrome-permutation-ii.cpp) [Python](./Python/palindrome-permutation-ii.py) | _O(n * n!)_ | _O(n)_ | Medium |📖|| - ## Divide and Conquer # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- @@ -352,28 +340,17 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Depth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || -37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || -39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(k * n^k)_ | _O(k)_ | Medium || -40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(k * C(n, k))_| _O(k)_ | Medium || -51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || -52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || 77| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || 79| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || -93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || 112| [Path Sum](https://leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || 113| [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || -131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || 199| [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| Medium || -216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(k * C(n, k))_ | _O(k)_ | Medium || 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [C++](./C++/lowest-common-ancestor-of-a-binary-tree.cpp) [Python](./Python/lowest-common-ancestor-of-a-binary-tree.py) | _O(h)_ | _O(h)_ | Medium | EPI | 247| [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/) | [C++](./C++/strobogrammatic-number-ii.cpp) [Python](./Python/strobogrammatic-number-ii.py) | _O(n^2 * 5^(n/2))_ | _O(n)_ | Medium |📖|| 250| [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | [C++](./C++/count-univalue-subtrees.cpp) [Python](./Python/count-univalue-subtrees.py) | _O(n)_ | _O(h)_ | Medium |📖|| -254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| -291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| 301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(C(n, c))_ | _O(c)_ | Medium ||| ## Dynamic Programming @@ -396,7 +373,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 123| [Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) | [Python](./Python/best-time-to-buy-and-sell-stock-iii.py) | _O(n)_ | _O(1)_ | Hard || 132| [Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii/) | [Python](./Python/palindrome-partitioning-ii.py) | _O(n^2)_ | _O(n^2)_ | Hard || 139| [Word Break](https://leetcode.com/problems/word-break/) | [Python](./Python/word-break.py) | _O(n^2)_ | _O(n)_ | Medium || -140| [Word Break II](https://leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || 152| [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)|[Python](./Python/maximum-product-subarray.py)| _O(n)_ | _O(1)_ | Medium || 174| [Dungeon Game](https://leetcode.com/problems/dungeon-game/) | [Python](./Python/dungeon-game.py)| _O(m * n)_ | _O(m + n)_ | Hard || 188| [Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](./Python/best-time-to-buy-and-sell-stock-iv.py) | _O(k * n)_ | _O(k)_ | Hard || @@ -415,8 +391,28 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Backtracking # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || +22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || +37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || +39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(k * n^k)_ | _O(k)_ | Medium || +40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(k * C(n, k))_| _O(k)_ | Medium || +46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n * n!)_ | _O(n)_ | Medium || +47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Hard || +51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || +52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || +93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || +78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || 126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || +131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || +140| [Word Break II](https://leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || +212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(k * C(n, k))_ | _O(k)_ | Medium || +254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| +267| [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) | [C++](./C++/palindrome-permutation-ii.cpp) [Python](./Python/palindrome-permutation-ii.py) | _O(n * n!)_ | _O(n)_ | Medium |📖|| +291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| 294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n + c^2)_ | _O(c)_ | Medium |📖| DP, Hash | +320| [Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation/) | [C++](./C++/generalized-abbreviation.cpp) [Python](./Python/generalized-abbreviation.py) | _O(2^n)_ | _O(n)_ | Medium |📖|| ## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 3db64e76706d0f3bf1581eef5aa03b309529515b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Dec 2015 14:05:08 +0800 Subject: [PATCH 1494/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 90a24847d..f64ee678a 100644 --- a/README.md +++ b/README.md @@ -341,7 +341,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 77| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || -79| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || 112| [Path Sum](https://leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || 113| [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || 199| [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || @@ -400,6 +399,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Hard || 51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || 52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || +79| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || 93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || 78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || 90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || From 7f176ba7cffb2e2f0685b033b617b6716c095c1e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Dec 2015 14:08:45 +0800 Subject: [PATCH 1495/1939] Update README.md --- README.md | 56 +++++++++++++++++++++++++++---------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index f64ee678a..cc8359b4e 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search](https://github.com/kamyu104/LeetCode#depth-first-search) -* [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) * [Backtracking](https://github.com/kamyu104/LeetCode#backtracking) +* [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) * [Greedy](https://github.com/kamyu104/LeetCode#greedy) * [Design](https://github.com/kamyu104/LeetCode#design) @@ -352,6 +352,33 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| 301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(C(n, c))_ | _O(c)_ | Medium ||| +## Backtracking + # | Problem | Solution | Time | Space | Difficulty | Tag | Note +-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || +22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || +37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || +39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(k * n^k)_ | _O(k)_ | Medium || +40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(k * C(n, k))_| _O(k)_ | Medium || +46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n * n!)_ | _O(n)_ | Medium || +47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Hard || +51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || +52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || +79| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || +93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || +78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || +131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || +140| [Word Break II](https://leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || +212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS +216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(k * C(n, k))_ | _O(k)_ | Medium || +254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| +267| [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) | [C++](./C++/palindrome-permutation-ii.cpp) [Python](./Python/palindrome-permutation-ii.py) | _O(n * n!)_ | _O(n)_ | Medium |📖|| +291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| +294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n + c^2)_ | _O(c)_ | Medium |📖| DP, Hash | +320| [Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation/) | [C++](./C++/generalized-abbreviation.cpp) [Python](./Python/generalized-abbreviation.py) | _O(2^n)_ | _O(n)_ | Medium |📖|| + ## Dynamic Programming # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- @@ -387,33 +414,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 309| [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-cooldown.py) | _O(n)_ | _O(1)_ | Medium || 312| [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./C++/burst-balloons.cpp) [Python](./Python/burst-balloons.py) | _O(n^3)_ | _O(n^2)_ | Medium || -## Backtracking - # | Problem | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || -22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || -37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || -39| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(k * n^k)_ | _O(k)_ | Medium || -40| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(k * C(n, k))_| _O(k)_ | Medium || -46| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n * n!)_ | _O(n)_ | Medium || -47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Hard || -51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || -52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || -79| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || -93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || -78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || -90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || -126| [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) |[Python](./Python/word-ladder-ii.py) | _O(n * d)_ | _O(d)_ | Hard || -131| [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Python](./Python/palindrome-partitioning.py) | _O(n^2)_ ~ _O(2^n)_ | _O(n^2)_ | Medium || -140| [Word Break II](https://leetcode.com/problems/word-break-ii/) | [Python](./Python/word-break-ii.py) | _O(n^2)_ | _O(n)_ | Hard || -212| [Word Search II](https://leetcode.com/problems/word-search-ii/) | [C++](./C++/word-search-ii.cpp) [Python](./Python/word-search-ii.py) | _O(m * n * l)_ | _O(l)_ | Hard | LintCode | Trie, DFS -216| [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./C++/combination-sum-iii.cpp) [Python](./Python/combination-sum-iii.py) | _O(k * C(n, k))_ | _O(k)_ | Medium || -254| [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | [C++](./C++/factor-combinations.cpp) [Python](./Python/factor-combinations.py) | _O(nlogn)_ | _O(logn)_ | Medium |📖|| -267| [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) | [C++](./C++/palindrome-permutation-ii.cpp) [Python](./Python/palindrome-permutation-ii.py) | _O(n * n!)_ | _O(n)_ | Medium |📖|| -291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| -294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n + c^2)_ | _O(c)_ | Medium |📖| DP, Hash | -320| [Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation/) | [C++](./C++/generalized-abbreviation.cpp) [Python](./Python/generalized-abbreviation.py) | _O(2^n)_ | _O(n)_ | Medium |📖|| - ## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- From eb0326123d70d93d9a2d14298591db741732b236 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Dec 2015 14:18:02 +0800 Subject: [PATCH 1496/1939] Update generalized-abbreviation.cpp --- C++/generalized-abbreviation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/generalized-abbreviation.cpp b/C++/generalized-abbreviation.cpp index 4eecbba64..9f4e5b3ad 100644 --- a/C++/generalized-abbreviation.cpp +++ b/C++/generalized-abbreviation.cpp @@ -1,4 +1,4 @@ -// Time: O(2^n) +// Time: O(n * 2^n) // Space: O(n) class Solution { From 9a54918e0073d3f072ff7f6d0f4cf7a2f7ccd0b9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Dec 2015 14:18:20 +0800 Subject: [PATCH 1497/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cc8359b4e..a1a891708 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 267| [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) | [C++](./C++/palindrome-permutation-ii.cpp) [Python](./Python/palindrome-permutation-ii.py) | _O(n * n!)_ | _O(n)_ | Medium |📖|| 291| [Word Pattern II](https://leetcode.com/problems/word-pattern-ii/) | [C++](./C++/word-pattern-ii.cpp) [Python](./Python/word-pattern-ii.py) | _O(n * C(n - 1, c - 1))_ | _O(n + c)_ | Hard |📖|| 294| [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | [C++](./C++/flip-game-ii.cpp) [Python](./Python/flip-game-ii.py) | _O(n + c^2)_ | _O(c)_ | Medium |📖| DP, Hash | -320| [Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation/) | [C++](./C++/generalized-abbreviation.cpp) [Python](./Python/generalized-abbreviation.py) | _O(2^n)_ | _O(n)_ | Medium |📖|| +320| [Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation/) | [C++](./C++/generalized-abbreviation.cpp) [Python](./Python/generalized-abbreviation.py) | _O(n * 2^n)_ | _O(n)_ | Medium |📖|| ## Dynamic Programming # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 7d9830c2c5d72571c2440490992ad07a934212ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Dec 2015 14:29:58 +0800 Subject: [PATCH 1498/1939] Create generalized-abbreviation.py --- Python/generalized-abbreviation.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Python/generalized-abbreviation.py diff --git a/Python/generalized-abbreviation.py b/Python/generalized-abbreviation.py new file mode 100644 index 000000000..e881201c9 --- /dev/null +++ b/Python/generalized-abbreviation.py @@ -0,0 +1,25 @@ +# Time: O(n * 2^n) +# Space: O(n) + +class Solution(object): + def generateAbbreviations(self, word): + """ + :type word: str + :rtype: List[str] + """ + def generateAbbreviationsHelper(word, i, is_prev_num, cur, res): + if i == len(word): + res.append("".join(cur)) + return + cur.append(word[i]) + generateAbbreviationsHelper(word, i + 1, False, cur, res) + cur.pop() + if not is_prev_num: + for l in xrange(1, len(word) - i + 1): + cur.append(str(l)) + generateAbbreviationsHelper(word, i + l, True, cur, res) + cur.pop() + + res, cur = [], [] + generateAbbreviationsHelper(word, 0, False, cur, res) + return res From ad52a6c1d66a4176a952a796ef517a3274a176b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Dec 2015 14:30:53 +0800 Subject: [PATCH 1499/1939] Update generalized-abbreviation.cpp --- C++/generalized-abbreviation.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/generalized-abbreviation.cpp b/C++/generalized-abbreviation.cpp index 9f4e5b3ad..efe4fa72d 100644 --- a/C++/generalized-abbreviation.cpp +++ b/C++/generalized-abbreviation.cpp @@ -19,10 +19,10 @@ class Solution { generateAbbreviationsHelper(word, i + 1, false, cur, res); cur->pop_back(); if (!is_prev_num) { - for (int len = 1; i + len <= word.length(); ++len) { - cur->append(to_string(len)); - generateAbbreviationsHelper(word, i + len, true, cur, res); - cur->resize(cur->length() - to_string(len).length()); + for (int l = 1; i + l <= word.length(); ++l) { + cur->append(to_string(l)); + generateAbbreviationsHelper(word, i + l, true, cur, res); + cur->resize(cur->length() - to_string(l).length()); } } } From 2527ca045e8baa8b1d4e54a95368bcf609f8e64c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Dec 2015 14:32:29 +0800 Subject: [PATCH 1500/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a1a891708..816f34f53 100644 --- a/README.md +++ b/README.md @@ -340,7 +340,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Depth-First Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -77| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || 112| [Path Sum](https://leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || 113| [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || 199| [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | [Python](./Python/binary-tree-right-side-view.py) | _O(n)_ | _O(h)_ | Medium || @@ -364,6 +363,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Hard || 51| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || 52| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || +77| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || 79| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || 93| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || 78| [Subsets](https://leetcode.com/problems/subsets/) | [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || From d0e9c6182aab8f569dfb361075f8377c11d858b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Dec 2015 09:07:01 +0800 Subject: [PATCH 1501/1939] Update generalized-abbreviation.py --- Python/generalized-abbreviation.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Python/generalized-abbreviation.py b/Python/generalized-abbreviation.py index e881201c9..850259e04 100644 --- a/Python/generalized-abbreviation.py +++ b/Python/generalized-abbreviation.py @@ -7,19 +7,20 @@ def generateAbbreviations(self, word): :type word: str :rtype: List[str] """ - def generateAbbreviationsHelper(word, i, is_prev_num, cur, res): + def generateAbbreviationsHelper(word, i, cur, res): if i == len(word): res.append("".join(cur)) return cur.append(word[i]) - generateAbbreviationsHelper(word, i + 1, False, cur, res) + generateAbbreviationsHelper(word, i + 1, cur, res) cur.pop() - if not is_prev_num: + if not cur or not cur[-1][-1].isdigit(): for l in xrange(1, len(word) - i + 1): cur.append(str(l)) - generateAbbreviationsHelper(word, i + l, True, cur, res) + generateAbbreviationsHelper(word, i + l, cur, res) cur.pop() res, cur = [], [] - generateAbbreviationsHelper(word, 0, False, cur, res) + generateAbbreviationsHelper(word, 0, cur, res) return res + From 9f25cc91bc49cb8305ba888938ada08148f1b9ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Dec 2015 09:09:00 +0800 Subject: [PATCH 1502/1939] Update generalized-abbreviation.cpp --- C++/generalized-abbreviation.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/generalized-abbreviation.cpp b/C++/generalized-abbreviation.cpp index efe4fa72d..92188af56 100644 --- a/C++/generalized-abbreviation.cpp +++ b/C++/generalized-abbreviation.cpp @@ -6,23 +6,23 @@ class Solution { vector generateAbbreviations(string word) { vector res; string cur; - generateAbbreviationsHelper(word, 0, false, &cur, &res); + generateAbbreviationsHelper(word, 0, &cur, &res); return res; } - void generateAbbreviationsHelper(const string& word, int i, bool is_prev_num, string *cur, vector *res) { + void generateAbbreviationsHelper(const string& word, int i, string *cur, vector *res) { if (i == word.length()) { res->emplace_back(*cur); return; } cur->push_back(word[i]); - generateAbbreviationsHelper(word, i + 1, false, cur, res); + generateAbbreviationsHelper(word, i + 1, cur, res); cur->pop_back(); - if (!is_prev_num) { - for (int l = 1; i + l <= word.length(); ++l) { - cur->append(to_string(l)); - generateAbbreviationsHelper(word, i + l, true, cur, res); - cur->resize(cur->length() - to_string(l).length()); + if (cur->empty() || not isdigit(cur->back())) { + for (int len = 1; i + len <= word.length(); ++len) { + cur->append(to_string(len)); + generateAbbreviationsHelper(word, i + len, cur, res); + cur->resize(cur->length() - to_string(len).length()); } } } From 5f0133f00230d51201346fce5290b86cb3ae67c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Dec 2015 09:09:47 +0800 Subject: [PATCH 1503/1939] Update generalized-abbreviation.cpp --- C++/generalized-abbreviation.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/generalized-abbreviation.cpp b/C++/generalized-abbreviation.cpp index 92188af56..afb3f9335 100644 --- a/C++/generalized-abbreviation.cpp +++ b/C++/generalized-abbreviation.cpp @@ -19,10 +19,10 @@ class Solution { generateAbbreviationsHelper(word, i + 1, cur, res); cur->pop_back(); if (cur->empty() || not isdigit(cur->back())) { - for (int len = 1; i + len <= word.length(); ++len) { - cur->append(to_string(len)); - generateAbbreviationsHelper(word, i + len, cur, res); - cur->resize(cur->length() - to_string(len).length()); + for (int l = 1; i + l <= word.length(); ++l) { + cur->append(to_string(l)); + generateAbbreviationsHelper(word, i + l, cur, res); + cur->resize(cur->length() - to_string(l).length()); } } } From 445f8e42edcd8fdf96ea2f5d7502301913997e76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 21:22:28 +0800 Subject: [PATCH 1504/1939] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 816f34f53..5ec385a83 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-320%20%2F%20320-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-320%20%2F%20321-ff69b4.svg) -Up to date (2015-12-22), there are `303` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-23), there are `304` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `320` questions. +Here is the classification of all `321` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From 3285da7afbb64b6edab0cb7754bf746ca1dd1746 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 22:39:20 +0800 Subject: [PATCH 1505/1939] Create create-maximum-number.cpp --- C++/create-maximum-number.cpp | 113 ++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 C++/create-maximum-number.cpp diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp new file mode 100644 index 000000000..065f1939e --- /dev/null +++ b/C++/create-maximum-number.cpp @@ -0,0 +1,113 @@ +// Time: O(k * n^2) +// Space: O(k * n) + +// DP + Greedy solution. (48ms) +class Solution { +public: + vector maxNumber(vector& nums1, vector& nums2, int k) { + vector res(k); + const int size1 = nums1.size(), size2 = nums2.size(); + vector> dp1(k + 1), dp2(k + 1); + getDp(nums1, max(0, k - size2), min(k, size1), dp1); // O(k * n) time + getDp(nums2, max(0, k - size1), min(k, size2), dp2); // O(k * n) time + for (int i = max(0, k - size2); i <= min(k, size1); ++i) { // O(k * n^2) time + int j = k - i; + vector tmp(k); + merge(dp1[i].begin(), dp1[i].end(), dp2[j].begin(), dp2[j].end(), tmp.begin()); + if (compareVector(tmp, res)) { + res = tmp; + } + } + return res; + } + + void getDp(vector nums, int start, int end, vector> &dp) { + dp[end] = maxDigit(nums, end); + for (int i = end - 1; i >= start; --i) { + dp[i] = deleteDigit(dp[i + 1]); + } + } + + // Time: O(n) + // Space: O(n) + vector maxDigit(const vector& nums, int k) { + vector res; + int delete_cnt = nums.size() - k; + for (const auto& num : nums) { + while (delete_cnt > 0 && !res.empty() && res.back() < num) { + res.pop_back(); + --delete_cnt; + } + res.emplace_back(num); + } + while (delete_cnt > 0) { + res.pop_back(); + --delete_cnt; + } + return res; + } + + // Time: O(n) + // Space: O(n) + vector deleteDigit(const vector& nums) { + vector res(nums); + for (int j = 0; j < res.size(); ++j) { + if (j == res.size() - 1 || res[j] < res[j + 1]) { + res.erase(res.begin() + j); + break; + } + } + return res; + } + + // Time: O(n) + // Space: O(1) + template + bool compareVector (T vec1, T vec2) { + auto first1 = vec1.begin(), last1 = vec1.end(), first2 = vec2.begin(), last2 = vec2.end(); + for (; first1 != last1 && first2 != last2; ++first1, ++first2) { + if (*first1 > *first2) { + return true; + } else if (*first1 < *first2) { + return false; + } + } + if (first1 == last1) { + return false; + } else { + return true; + } + } + + // Time: O(n^2) + // Space: O(1) + template + T merge(T first1, T last1, T first2, T last2, T result) { + while (true) { + if (first1 == last1) { + return std::copy(first2,last2,result); + } + if (first2 == last2) { + return std::copy(first1,last1,result); + } + if (*first2 > *first1) { + *result++ = *first2++; + } else if (*first2 < *first1) { + *result++ = *first1++; + } else { + auto pos1 = first1, pos2 = first2; + while (true) { // Worst case O(n^2) time. + int v1 = (++pos1 != last1) ? *(pos1) : numeric_limits::min(); + int v2 = (++pos2 != last2) ? *(pos2) : numeric_limits::min(); + if (v1 > v2) { + *result++ = *first1++; + break; + } else if (v1 < v2) { + *result++ = *first2++; + break; + } + } + } + } + } +}; From 9a5895f520214dbb55b82da2cca25b2ee314e3ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 22:40:21 +0800 Subject: [PATCH 1506/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 065f1939e..d16ceff12 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -63,7 +63,7 @@ class Solution { // Time: O(n) // Space: O(1) template - bool compareVector (T vec1, T vec2) { + bool compareVector(T vec1, T vec2) { auto first1 = vec1.begin(), last1 = vec1.end(), first2 = vec2.begin(), last2 = vec2.end(); for (; first1 != last1 && first2 != last2; ++first1, ++first2) { if (*first1 > *first2) { From f46cec75492935cd7c851584b9e3c062acfca0e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:06:33 +0800 Subject: [PATCH 1507/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 37 +++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index d16ceff12..08ba7097b 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -7,13 +7,13 @@ class Solution { vector maxNumber(vector& nums1, vector& nums2, int k) { vector res(k); const int size1 = nums1.size(), size2 = nums2.size(); - vector> dp1(k + 1), dp2(k + 1); - getDp(nums1, max(0, k - size2), min(k, size1), dp1); // O(k * n) time - getDp(nums2, max(0, k - size1), min(k, size2), dp2); // O(k * n) time + vector> maxDigits1(k + 1), maxDigits2(k + 1); + getmaxDigits(nums1, max(0, k - size2), min(k, size1), &maxDigits1); // O(k * n) time + getmaxDigits(nums2, max(0, k - size1), min(k, size2), &maxDigits2); // O(k * n) time for (int i = max(0, k - size2); i <= min(k, size1); ++i) { // O(k * n^2) time int j = k - i; vector tmp(k); - merge(dp1[i].begin(), dp1[i].end(), dp2[j].begin(), dp2[j].end(), tmp.begin()); + merge(maxDigits1[i], maxDigits2[j], &tmp); if (compareVector(tmp, res)) { res = tmp; } @@ -21,10 +21,10 @@ class Solution { return res; } - void getDp(vector nums, int start, int end, vector> &dp) { - dp[end] = maxDigit(nums, end); + void getmaxDigits(vector nums, int start, int end, vector> *maxDigits) { + (*maxDigits)[end] = maxDigit(nums, end); for (int i = end - 1; i >= start; --i) { - dp[i] = deleteDigit(dp[i + 1]); + (*maxDigits)[i] = deleteDigit((*maxDigits)[i + 1]); } } @@ -62,8 +62,7 @@ class Solution { // Time: O(n) // Space: O(1) - template - bool compareVector(T vec1, T vec2) { + bool compareVector(const vector& vec1, const vector& vec2) { auto first1 = vec1.begin(), last1 = vec1.end(), first2 = vec2.begin(), last2 = vec2.end(); for (; first1 != last1 && first2 != last2; ++first1, ++first2) { if (*first1 > *first2) { @@ -81,14 +80,18 @@ class Solution { // Time: O(n^2) // Space: O(1) - template - T merge(T first1, T last1, T first2, T last2, T result) { + void merge(const vector& vec1, const vector& vec2, vector *res) { + auto first1 = vec1.begin(), last1 = vec1.end(), + first2 = vec2.begin(), last2 = vec2.end(); + auto result = res->begin(); while (true) { if (first1 == last1) { - return std::copy(first2,last2,result); + std::copy(first2, last2, result); + return; } if (first2 == last2) { - return std::copy(first1,last1,result); + std::copy(first1, last1, result); + return; } if (*first2 > *first1) { *result++ = *first2++; @@ -97,12 +100,12 @@ class Solution { } else { auto pos1 = first1, pos2 = first2; while (true) { // Worst case O(n^2) time. - int v1 = (++pos1 != last1) ? *(pos1) : numeric_limits::min(); - int v2 = (++pos2 != last2) ? *(pos2) : numeric_limits::min(); - if (v1 > v2) { + int val1 = (++pos1 != last1) ? *(pos1) : numeric_limits::min(); + int val2 = (++pos2 != last2) ? *(pos2) : numeric_limits::min(); + if (val1 > val2) { *result++ = *first1++; break; - } else if (v1 < v2) { + } else if (val1 < val2) { *result++ = *first2++; break; } From 1e0ad58685aa42f33d30f6a7ffc4ce9be9028190 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:09:21 +0800 Subject: [PATCH 1508/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 08ba7097b..1a3bb03f7 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -84,15 +84,7 @@ class Solution { auto first1 = vec1.begin(), last1 = vec1.end(), first2 = vec2.begin(), last2 = vec2.end(); auto result = res->begin(); - while (true) { - if (first1 == last1) { - std::copy(first2, last2, result); - return; - } - if (first2 == last2) { - std::copy(first1, last1, result); - return; - } + while (first1 != last1 && first2 != last2) { if (*first2 > *first1) { *result++ = *first2++; } else if (*first2 < *first1) { @@ -112,5 +104,10 @@ class Solution { } } } + if (first1 == last1) { + std::copy(first2, last2, result); + } else if (first2 == last2) { + std::copy(first1, last1, result); + } } }; From df6485dc541185ed8474c004c3dc6c09363ef231 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:10:38 +0800 Subject: [PATCH 1509/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 1a3bb03f7..9da7a634d 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -8,8 +8,8 @@ class Solution { vector res(k); const int size1 = nums1.size(), size2 = nums2.size(); vector> maxDigits1(k + 1), maxDigits2(k + 1); - getmaxDigits(nums1, max(0, k - size2), min(k, size1), &maxDigits1); // O(k * n) time - getmaxDigits(nums2, max(0, k - size1), min(k, size2), &maxDigits2); // O(k * n) time + getMaxDigits(nums1, max(0, k - size2), min(k, size1), &maxDigits1); // O(k * n) time + getMaxDigits(nums2, max(0, k - size1), min(k, size2), &maxDigits2); // O(k * n) time for (int i = max(0, k - size2); i <= min(k, size1); ++i) { // O(k * n^2) time int j = k - i; vector tmp(k); @@ -21,7 +21,7 @@ class Solution { return res; } - void getmaxDigits(vector nums, int start, int end, vector> *maxDigits) { + void getMaxDigits(vector nums, int start, int end, vector> *maxDigits) { (*maxDigits)[end] = maxDigit(nums, end); for (int i = end - 1; i >= start; --i) { (*maxDigits)[i] = deleteDigit((*maxDigits)[i + 1]); From 0d71159ca7f2bc9961030a3e24744b430ee0e888 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:12:08 +0800 Subject: [PATCH 1510/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 9da7a634d..932c279a0 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -63,7 +63,8 @@ class Solution { // Time: O(n) // Space: O(1) bool compareVector(const vector& vec1, const vector& vec2) { - auto first1 = vec1.begin(), last1 = vec1.end(), first2 = vec2.begin(), last2 = vec2.end(); + auto first1 = vec1.begin(), last1 = vec1.end(), + first2 = vec2.begin(), last2 = vec2.end(); for (; first1 != last1 && first2 != last2; ++first1, ++first2) { if (*first1 > *first2) { return true; From bbf93e62cd847c9fe100f202afd2af6d4c4304bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:26:24 +0800 Subject: [PATCH 1511/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 932c279a0..b9d71cfa5 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -1,16 +1,16 @@ -// Time: O(k * n^2) -// Space: O(k * n) +// Time: O(k * (m + n + k^2)) +// Space: O(k * (m + n)) // DP + Greedy solution. (48ms) class Solution { public: vector maxNumber(vector& nums1, vector& nums2, int k) { vector res(k); - const int size1 = nums1.size(), size2 = nums2.size(); + const int m = nums1.size(), n = nums2.size(); vector> maxDigits1(k + 1), maxDigits2(k + 1); - getMaxDigits(nums1, max(0, k - size2), min(k, size1), &maxDigits1); // O(k * n) time - getMaxDigits(nums2, max(0, k - size1), min(k, size2), &maxDigits2); // O(k * n) time - for (int i = max(0, k - size2); i <= min(k, size1); ++i) { // O(k * n^2) time + getMaxDigits(nums1, max(0, k - n), min(k, m), &maxDigits1); // O(k * m) time + getMaxDigits(nums2, max(0, k - m), min(k, n), &maxDigits2); // O(k * n) time + for (int i = max(0, k - n); i <= min(k, m); ++i) { // k * O(k^2) time int j = k - i; vector tmp(k); merge(maxDigits1[i], maxDigits2[j], &tmp); @@ -60,7 +60,7 @@ class Solution { return res; } - // Time: O(n) + // Time: O(k) // Space: O(1) bool compareVector(const vector& vec1, const vector& vec2) { auto first1 = vec1.begin(), last1 = vec1.end(), @@ -79,7 +79,7 @@ class Solution { } } - // Time: O(n^2) + // Time: O(k^2) // Space: O(1) void merge(const vector& vec1, const vector& vec2, vector *res) { auto first1 = vec1.begin(), last1 = vec1.end(), @@ -92,7 +92,7 @@ class Solution { *result++ = *first1++; } else { auto pos1 = first1, pos2 = first2; - while (true) { // Worst case O(n^2) time. + while (true) { // Worst case O(k^2) time. int val1 = (++pos1 != last1) ? *(pos1) : numeric_limits::min(); int val2 = (++pos2 != last2) ? *(pos2) : numeric_limits::min(); if (val1 > val2) { From d8bc0af2432925b50d1bc466b71538a4b807cdf7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:30:22 +0800 Subject: [PATCH 1512/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index b9d71cfa5..0bb39ace8 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -1,4 +1,4 @@ -// Time: O(k * (m + n + k^2)) +// Time: O(k * (m + n + k)) ~ O(k * (m + n + k^2)) // Space: O(k * (m + n)) // DP + Greedy solution. (48ms) @@ -10,7 +10,7 @@ class Solution { vector> maxDigits1(k + 1), maxDigits2(k + 1); getMaxDigits(nums1, max(0, k - n), min(k, m), &maxDigits1); // O(k * m) time getMaxDigits(nums2, max(0, k - m), min(k, n), &maxDigits2); // O(k * n) time - for (int i = max(0, k - n); i <= min(k, m); ++i) { // k * O(k^2) time + for (int i = max(0, k - n); i <= min(k, m); ++i) { // k * O(k) ~ k * O(k^2) time int j = k - i; vector tmp(k); merge(maxDigits1[i], maxDigits2[j], &tmp); @@ -79,7 +79,7 @@ class Solution { } } - // Time: O(k^2) + // Time: O(k) ~ O(k^2) // Space: O(1) void merge(const vector& vec1, const vector& vec2, vector *res) { auto first1 = vec1.begin(), last1 = vec1.end(), @@ -92,7 +92,7 @@ class Solution { *result++ = *first1++; } else { auto pos1 = first1, pos2 = first2; - while (true) { // Worst case O(k^2) time. + while (true) { // O(1) ~ O(k) time. int val1 = (++pos1 != last1) ? *(pos1) : numeric_limits::min(); int val2 = (++pos2 != last2) ? *(pos2) : numeric_limits::min(); if (val1 > val2) { From 5ccfcf0b92d1b6336fbd753784554d3be794608d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:33:55 +0800 Subject: [PATCH 1513/1939] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5ec385a83..46c599275 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-320%20%2F%20321-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-321%20%2F%20321-ff69b4.svg) Up to date (2015-12-23), there are `304` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. @@ -427,6 +427,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 134| [Gas Station](https://leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || 135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || 316| [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./C++/remove-duplicate-letters.cpp) [Python](./Python/remove-duplicate-letters.py) | _O(n)_| _O(k)_| Medium || Stack | +321| [Create Maximum Number](https://leetcode.com/problems/create-maximum-number/)| [C++](./C++/create-maximum-number.cpp) [Python](./Python/create-maximum-number.py) | _O(k * (m + n + k))_ ~ _O(k * (m + n + k^2))_| _O(k^2)_ | Hard || --- ##Design From 28d8a587760a28d15846a199329c61bd00c1b785 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:36:40 +0800 Subject: [PATCH 1514/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 0bb39ace8..37dbf0c2c 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -1,5 +1,5 @@ // Time: O(k * (m + n + k)) ~ O(k * (m + n + k^2)) -// Space: O(k * (m + n)) +// Space: O(m + n + k^2) // DP + Greedy solution. (48ms) class Solution { @@ -8,8 +8,8 @@ class Solution { vector res(k); const int m = nums1.size(), n = nums2.size(); vector> maxDigits1(k + 1), maxDigits2(k + 1); - getMaxDigits(nums1, max(0, k - n), min(k, m), &maxDigits1); // O(k * m) time - getMaxDigits(nums2, max(0, k - m), min(k, n), &maxDigits2); // O(k * n) time + getMaxDigits(nums1, max(0, k - n), min(k, m), &maxDigits1); // O(k * m) time, O(m + k^2) space. + getMaxDigits(nums2, max(0, k - m), min(k, n), &maxDigits2); // O(k * n) time, O(n + k^2) space. for (int i = max(0, k - n); i <= min(k, m); ++i) { // k * O(k) ~ k * O(k^2) time int j = k - i; vector tmp(k); From 3de045e3dd9121be682223801e67582e346ffa71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:37:01 +0800 Subject: [PATCH 1515/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 46c599275..4b2c3f61c 100644 --- a/README.md +++ b/README.md @@ -427,7 +427,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 134| [Gas Station](https://leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || 135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || 316| [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./C++/remove-duplicate-letters.cpp) [Python](./Python/remove-duplicate-letters.py) | _O(n)_| _O(k)_| Medium || Stack | -321| [Create Maximum Number](https://leetcode.com/problems/create-maximum-number/)| [C++](./C++/create-maximum-number.cpp) [Python](./Python/create-maximum-number.py) | _O(k * (m + n + k))_ ~ _O(k * (m + n + k^2))_| _O(k^2)_ | Hard || +321| [Create Maximum Number](https://leetcode.com/problems/create-maximum-number/)| [C++](./C++/create-maximum-number.cpp) [Python](./Python/create-maximum-number.py) | _O(k * (m + n + k))_ ~ _O(k * (m + n + k^2))_| _O(m + n + k^2)_ | Hard || --- ##Design From 95e9d7ab8869b7c538bdb6e862e282bd8347f0ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:39:20 +0800 Subject: [PATCH 1516/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4b2c3f61c..b958fac1a 100644 --- a/README.md +++ b/README.md @@ -427,7 +427,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 134| [Gas Station](https://leetcode.com/problems/gas-station/)| [Python](./Python/gas-station.py) | _O(n)_ | _O(1)_ | Medium || 135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || 316| [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./C++/remove-duplicate-letters.cpp) [Python](./Python/remove-duplicate-letters.py) | _O(n)_| _O(k)_| Medium || Stack | -321| [Create Maximum Number](https://leetcode.com/problems/create-maximum-number/)| [C++](./C++/create-maximum-number.cpp) [Python](./Python/create-maximum-number.py) | _O(k * (m + n + k))_ ~ _O(k * (m + n + k^2))_| _O(m + n + k^2)_ | Hard || +321| [Create Maximum Number](https://leetcode.com/problems/create-maximum-number/)| [C++](./C++/create-maximum-number.cpp) [Python](./Python/create-maximum-number.py) | _O(k * (m + n + k))_ ~ _O(k * (m + n + k^2))_| _O(m + n + k^2)_ | Hard | variant of [Delete Digits](http://www.lintcode.com/en/problem/delete-digits/) | Greedy, DP --- ##Design From c6f23a11ac9ac1dd73ec4cc7ec08e01de64339c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:50:32 +0800 Subject: [PATCH 1517/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 37dbf0c2c..bf01cb3db 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -32,17 +32,17 @@ class Solution { // Space: O(n) vector maxDigit(const vector& nums, int k) { vector res; - int delete_cnt = nums.size() - k; + int drop = nums.size() - k; for (const auto& num : nums) { - while (delete_cnt > 0 && !res.empty() && res.back() < num) { + while (drop > 0 && !res.empty() && res.back() < num) { res.pop_back(); - --delete_cnt; + --drop; } res.emplace_back(num); } - while (delete_cnt > 0) { + while (drop > 0) { res.pop_back(); - --delete_cnt; + --drop; } return res; } From e8494ecd4a5cdeaa50c102c25636ac926944159f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Dec 2015 23:52:12 +0800 Subject: [PATCH 1518/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index bf01cb3db..e179e761a 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -40,10 +40,7 @@ class Solution { } res.emplace_back(num); } - while (drop > 0) { - res.pop_back(); - --drop; - } + res.resize(k); return res; } From 896d5283929dc261fa488544b55b00e0e7f008d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Dec 2015 00:09:00 +0800 Subject: [PATCH 1519/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index e179e761a..2ec267811 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -7,13 +7,13 @@ class Solution { vector maxNumber(vector& nums1, vector& nums2, int k) { vector res(k); const int m = nums1.size(), n = nums2.size(); - vector> maxDigits1(k + 1), maxDigits2(k + 1); - getMaxDigits(nums1, max(0, k - n), min(k, m), &maxDigits1); // O(k * m) time, O(m + k^2) space. - getMaxDigits(nums2, max(0, k - m), min(k, n), &maxDigits2); // O(k * n) time, O(n + k^2) space. + vector> max_digits1(k + 1), max_digits2(k + 1); + getMaxDigits(nums1, max(0, k - n), min(k, m), &max_digits1); // O(k * m) time, O(m + k^2) space. + getMaxDigits(nums2, max(0, k - m), min(k, n), &max_digits2); // O(k * n) time, O(n + k^2) space. for (int i = max(0, k - n); i <= min(k, m); ++i) { // k * O(k) ~ k * O(k^2) time int j = k - i; vector tmp(k); - merge(maxDigits1[i], maxDigits2[j], &tmp); + merge(max_digits1[i], max_digits2[j], &tmp); if (compareVector(tmp, res)) { res = tmp; } From 2e686f18a747906c01a9717e8ee16d1af6cc3e27 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Dec 2015 00:25:49 +0800 Subject: [PATCH 1520/1939] Create create-maximum-number.py --- Python/create-maximum-number.py | 71 +++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Python/create-maximum-number.py diff --git a/Python/create-maximum-number.py b/Python/create-maximum-number.py new file mode 100644 index 000000000..36b2d024c --- /dev/null +++ b/Python/create-maximum-number.py @@ -0,0 +1,71 @@ +# Time: O(k * (m + n + k)) ~ O(k * (m + n + k^2)) +# Space: O(m + n + k^2) +# +# Given two arrays of length m and n with digits 0-9 representing two numbers. +# Create the maximum number of length k <= m + n 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] +# + +# DP + Greedy solution. (280ms) +class Solution(object): + def maxNumber(self, nums1, nums2, k): + """ + :type nums1: List[int] + :type nums2: List[int] + :type k: int + :rtype: List[int] + """ + def get_max_digits(nums, start, end, max_digits): + max_digits[end] = max_digit(nums, end) + for i in reversed(xrange(start, end)): + max_digits[i] = delete_digit(max_digits[i + 1]) + + def max_digit(nums, k): + drop = len(nums) - k + res = [] + for num in nums: + while drop and res and res[-1] < num: + res.pop() + drop -= 1 + res.append(num) + return res[:k] + + def delete_digit(nums): + res = list(nums) + for j in xrange(len(res)): + if j == len(res) - 1 or res[j] < res[j + 1]: + res = res[:j] + res[j+1:] + break + return res + + def merge(a, b): + return [max(a, b).pop(0) for _ in xrange(len(a)+len(b))] + + m, n = len(nums1), len(nums2) + + max_digits1, max_digits2 = [[] for _ in xrange(k + 1)], [[] for _ in xrange(k + 1)] + get_max_digits(nums1, max(0, k - n), min(k, m), max_digits1) + get_max_digits(nums2, max(0, k - m), min(k, n), max_digits2) + + return max(merge(max_digits1[i], max_digits2[k-i]) + for i in xrange(max(0, k - n), min(k, m) + 1)) From ad71a43aa528fdf4a267c4dae787ff61642b0078 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Dec 2015 00:27:07 +0800 Subject: [PATCH 1521/1939] Update create-maximum-number.py --- Python/create-maximum-number.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/create-maximum-number.py b/Python/create-maximum-number.py index 36b2d024c..c52c859af 100644 --- a/Python/create-maximum-number.py +++ b/Python/create-maximum-number.py @@ -52,9 +52,9 @@ def max_digit(nums, k): def delete_digit(nums): res = list(nums) - for j in xrange(len(res)): - if j == len(res) - 1 or res[j] < res[j + 1]: - res = res[:j] + res[j+1:] + for i in xrange(len(res)): + if i == len(res) - 1 or res[i] < res[i + 1]: + res = res[:i] + res[i+1:] break return res From 71c580531e7a0d58e3cc1fca4712c96f8c84ef73 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Dec 2015 00:28:07 +0800 Subject: [PATCH 1522/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 2ec267811..407330cd6 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -48,9 +48,9 @@ class Solution { // Space: O(n) vector deleteDigit(const vector& nums) { vector res(nums); - for (int j = 0; j < res.size(); ++j) { - if (j == res.size() - 1 || res[j] < res[j + 1]) { - res.erase(res.begin() + j); + for (int i = 0; i < res.size(); ++i) { + if (i == res.size() - 1 || res[i] < res[i + 1]) { + res.erase(res.begin() + i); break; } } From a2f8416b5101bcc5c2b5d739d7b84bdbb6bc825d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Dec 2015 01:34:12 +0800 Subject: [PATCH 1523/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 407330cd6..4f9a24e47 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -21,6 +21,7 @@ class Solution { return res; } +private: void getMaxDigits(vector nums, int start, int end, vector> *maxDigits) { (*maxDigits)[end] = maxDigit(nums, end); for (int i = end - 1; i >= start; --i) { From 87fbaf4e90c2accceb6f8153e8f5d54165b71905 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Dec 2015 09:37:15 +0800 Subject: [PATCH 1524/1939] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 4f9a24e47..7891f8827 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -10,7 +10,7 @@ class Solution { vector> max_digits1(k + 1), max_digits2(k + 1); getMaxDigits(nums1, max(0, k - n), min(k, m), &max_digits1); // O(k * m) time, O(m + k^2) space. getMaxDigits(nums2, max(0, k - m), min(k, n), &max_digits2); // O(k * n) time, O(n + k^2) space. - for (int i = max(0, k - n); i <= min(k, m); ++i) { // k * O(k) ~ k * O(k^2) time + for (int i = max(0, k - n); i <= min(k, m); ++i) { // k * O(k) ~ k * O(k^2) time. int j = k - i; vector tmp(k); merge(max_digits1[i], max_digits2[j], &tmp); From 6d81aa8385b3795f3b7814038d79e7cc0029db59 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Dec 2015 20:22:30 +0800 Subject: [PATCH 1525/1939] Update create-maximum-number.py --- Python/create-maximum-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/create-maximum-number.py b/Python/create-maximum-number.py index c52c859af..af1d98541 100644 --- a/Python/create-maximum-number.py +++ b/Python/create-maximum-number.py @@ -67,5 +67,5 @@ def merge(a, b): get_max_digits(nums1, max(0, k - n), min(k, m), max_digits1) get_max_digits(nums2, max(0, k - m), min(k, n), max_digits2) - return max(merge(max_digits1[i], max_digits2[k-i]) + return max(merge(max_digits1[i], max_digits2[k-i]) \ for i in xrange(max(0, k - n), min(k, m) + 1)) From ee097546a149e0140946d6957a60579d8d120564 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Dec 2015 14:31:51 +0800 Subject: [PATCH 1526/1939] Create coin-change.py --- Python/coin-change.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/coin-change.py diff --git a/Python/coin-change.py b/Python/coin-change.py new file mode 100644 index 000000000..d575a3a76 --- /dev/null +++ b/Python/coin-change.py @@ -0,0 +1,38 @@ +# Time: O(n * k), n is the number of coins, k is the amount of money +# Space: O(k) +# +# 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. + +# DP solution. (1680ms) +class Solution(object): + def coinChange(self, coins, amount): + """ + :type coins: List[int] + :type amount: int + :rtype: int + """ + INF = 0x7ffffffe # Using float("int") would be slower. + amounts = [INF] * (amount + 1) + amounts[0] = 0 + for i in xrange(amount + 1): + if amounts[i] != INF: + for coin in coins: + if i + coin <= amount: + amounts[i + coin] = min(amounts[i + coin], amounts[i] + 1) + return amounts[amount] if amounts[amount] != INF else -1 + From fc580d8d2ae8e23467921ed976291fd9ea19acf5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Dec 2015 14:33:36 +0800 Subject: [PATCH 1527/1939] Create coin-change.cpp --- C++/coin-change.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/coin-change.cpp diff --git a/C++/coin-change.cpp b/C++/coin-change.cpp new file mode 100644 index 000000000..7d3562590 --- /dev/null +++ b/C++/coin-change.cpp @@ -0,0 +1,20 @@ +// Time: O(n * k), n is the number of coins, k is the amount of money +// Space: O(k) + +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector amounts(amount + 1, numeric_limits::max()); + amounts[0] = 0; + for (int i = 0; i <= amount; ++i) { + if (amounts[i] != numeric_limits::max()) { + for (const auto& coin : coins) { + if (i + coin <= amount) { + amounts[i + coin] = min(amounts[i + coin], amounts[i] + 1); + } + } + } + } + return amounts[amount] == numeric_limits::max() ? -1 : amounts[amount]; + } +}; From 360081cc57f1c31432e871ef496659306fc99813 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Dec 2015 14:39:01 +0800 Subject: [PATCH 1528/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b958fac1a..de9914341 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-321%20%2F%20321-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-322%20%2F%20322-ff69b4.svg) -Up to date (2015-12-23), there are `304` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-27), there are `305` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `321` questions. +Here is the classification of all `322` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -413,6 +413,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 304| [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/)| [C++](./C++/range-sum-query-2d-immutable.cpp) [Python](./Python/range-sum-query-2d-immutable.py) | ctor: _O(m * n)_, lookup: _O(1)_ | _O(m * n)_ | Medium || 309| [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-cooldown.py) | _O(n)_ | _O(1)_ | Medium || 312| [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./C++/burst-balloons.cpp) [Python](./Python/burst-balloons.py) | _O(n^3)_ | _O(n^2)_ | Medium || +321| [Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./C++/coin-change.cpp) [Python](./Python/coin-change.py) | _O(n * k)_ | _O(k)_ | Medium || ## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 6621f2b955a121859ec736fe5ddaf16ec2a4bec7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Dec 2015 14:39:25 +0800 Subject: [PATCH 1529/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index de9914341..f4266d1e9 100644 --- a/README.md +++ b/README.md @@ -413,7 +413,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 304| [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/)| [C++](./C++/range-sum-query-2d-immutable.cpp) [Python](./Python/range-sum-query-2d-immutable.py) | ctor: _O(m * n)_, lookup: _O(1)_ | _O(m * n)_ | Medium || 309| [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-cooldown.py) | _O(n)_ | _O(1)_ | Medium || 312| [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./C++/burst-balloons.cpp) [Python](./Python/burst-balloons.py) | _O(n^3)_ | _O(n^2)_ | Medium || -321| [Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./C++/coin-change.cpp) [Python](./Python/coin-change.py) | _O(n * k)_ | _O(k)_ | Medium || +322| [Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./C++/coin-change.cpp) [Python](./Python/coin-change.py) | _O(n * k)_ | _O(k)_ | Medium || ## Greedy # | Problem | Solution | Time | Space | Difficulty | Tag | Note From e4cd3e7c1e182d0e05424e54eb599a7709e531a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Dec 2015 14:40:17 +0800 Subject: [PATCH 1530/1939] Update coin-change.cpp --- C++/coin-change.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/coin-change.cpp b/C++/coin-change.cpp index 7d3562590..87f16941d 100644 --- a/C++/coin-change.cpp +++ b/C++/coin-change.cpp @@ -1,6 +1,7 @@ // Time: O(n * k), n is the number of coins, k is the amount of money // Space: O(k) +// DP solution. (164ms) class Solution { public: int coinChange(vector& coins, int amount) { From c708e6a82db1734affc1fb441e214f1b809d1ad3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Dec 2015 21:25:00 +0800 Subject: [PATCH 1531/1939] Create number-of-connected-components-in-an-undirected-graph.ot --- ...ected-components-in-an-undirected-graph.ot | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/number-of-connected-components-in-an-undirected-graph.ot diff --git a/Python/number-of-connected-components-in-an-undirected-graph.ot b/Python/number-of-connected-components-in-an-undirected-graph.ot new file mode 100644 index 000000000..e8b27f59e --- /dev/null +++ b/Python/number-of-connected-components-in-an-undirected-graph.ot @@ -0,0 +1,31 @@ +# Time: O(nlog*n) ~= O(n), n is the length of the positions +# Space: O(n) + +class UnionFind(object): + def __init__(self, n): + self.set = range(n) + self.count = n + + def find_set(self, x): + if self.set[x] != x: + self.set[x] = self.find_set(self.set[x]) # path compression. + return self.set[x] + + def union_set(self, x, y): + x_root, y_root = map(self.find_set, (x, y)) + if x_root != y_root: + self.set[min(x_root, y_root)] = max(x_root, y_root) + self.count -= 1 + + +class Solution(object): + def countComponents(self, n, edges): + """ + :type n: int + :type edges: List[List[int]] + :rtype: int + """ + union_find = UnionFind(n) + for i, j in edges: + union_find.union_set(i, j) + return union_find.count From efd38c062cd4adc4c657a22ff406cad028bd4616 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Dec 2015 21:27:33 +0800 Subject: [PATCH 1532/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f4266d1e9..01f89d1df 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-322%20%2F%20322-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-323%20%2F%20323-ff69b4.svg) -Up to date (2015-12-27), there are `305` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-29), there are `306` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `322` questions. +Here is the classification of all `323` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -208,6 +208,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 299| [Bulls and Cow](https://leetcode.com/problems/bulls-and-cow/) | [C++](./C++/bulls-and-cow.cpp) [Python](./Python/bulls-and-cow.py) | _O(n)_ | _O(1)_ | Easy ||| 305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k)_ | _O(k)_| Hard | LintCode, 📖 | Union Find 314| [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) | [C++](./C++/binary-tree-vertical-order-traversal.cpp) [Python](./Python/binary-tree-vertical-order-traversal.py) | _O(n)_ | _O(n)_| Medium | 📖 | BFS +323| [Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) | [C++](./C++/number-of-connected-components-in-an-undirected-graph.cpp) [Python](./Python/number-of-connected-components-in-an-undirected-graph.py) | _O(n)_ | _O(n)_| Medium | 📖 | Union Find ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From db0d11055867a612776205f15e4e01dbe5d068ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Dec 2015 21:28:45 +0800 Subject: [PATCH 1533/1939] Rename number-of-connected-components-in-an-undirected-graph.ot to number-of-connected-components-in-an-undirected-graph.py --- ...t => number-of-connected-components-in-an-undirected-graph.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{number-of-connected-components-in-an-undirected-graph.ot => number-of-connected-components-in-an-undirected-graph.py} (100%) diff --git a/Python/number-of-connected-components-in-an-undirected-graph.ot b/Python/number-of-connected-components-in-an-undirected-graph.py similarity index 100% rename from Python/number-of-connected-components-in-an-undirected-graph.ot rename to Python/number-of-connected-components-in-an-undirected-graph.py From 6b2a557cb5ab251a3de91d373661baf320ed8bf8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Dec 2015 00:09:50 +0800 Subject: [PATCH 1534/1939] Create number-of-connected-components-in-an-undirected-graph.cpp --- ...cted-components-in-an-undirected-graph.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/number-of-connected-components-in-an-undirected-graph.cpp diff --git a/C++/number-of-connected-components-in-an-undirected-graph.cpp b/C++/number-of-connected-components-in-an-undirected-graph.cpp new file mode 100644 index 000000000..322d30bd0 --- /dev/null +++ b/C++/number-of-connected-components-in-an-undirected-graph.cpp @@ -0,0 +1,45 @@ +// Time: O(nlog*n) ~= O(n), n is the length of the positions +// Space: O(n) + +class Solution { +public: + int countComponents(int n, vector>& edges) { + UnionFind union_find(n); + for (const auto& e : edges) { + union_find.union_set(e.first, e.second); + } + return union_find.length(); + } + +private: + class UnionFind { + public: + UnionFind(const int n) : set(n) { + iota(set.begin(), set.end(), 0); + count_ = n; + } + + int find_set(int x) { + if (set[x] != x) { + set[x] = find_set(set[x]); // Path compression. + } + return set[x]; + } + + void union_set(const int x, const int y) { + int x_root = find_set(x), y_root = find_set(y); + if (x_root != y_root) { + set[min(x_root, y_root)] = max(x_root, y_root); + --count_; + } + } + + int length() const { + return count_; + } + + private: + vector set; + int count_; + }; +}; From ff64bbaf55d0d4ce2e2b434e1b510c4cfda65a9d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Dec 2015 00:12:09 +0800 Subject: [PATCH 1535/1939] Update number-of-connected-components-in-an-undirected-graph.cpp --- ...onnected-components-in-an-undirected-graph.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/C++/number-of-connected-components-in-an-undirected-graph.cpp b/C++/number-of-connected-components-in-an-undirected-graph.cpp index 322d30bd0..ddd05e2c6 100644 --- a/C++/number-of-connected-components-in-an-undirected-graph.cpp +++ b/C++/number-of-connected-components-in-an-undirected-graph.cpp @@ -14,22 +14,21 @@ class Solution { private: class UnionFind { public: - UnionFind(const int n) : set(n) { - iota(set.begin(), set.end(), 0); - count_ = n; + UnionFind(const int n) : set_(n), count_(n) { + iota(set_.begin(), set_.end(), 0); } int find_set(int x) { - if (set[x] != x) { - set[x] = find_set(set[x]); // Path compression. + if (set_[x] != x) { + set_[x] = find_set(set_[x]); // Path compression. } - return set[x]; + return set_[x]; } void union_set(const int x, const int y) { int x_root = find_set(x), y_root = find_set(y); if (x_root != y_root) { - set[min(x_root, y_root)] = max(x_root, y_root); + set_[min(x_root, y_root)] = max(x_root, y_root); --count_; } } @@ -39,7 +38,7 @@ class Solution { } private: - vector set; + vector set_; int count_; }; }; From 48e9adcb6357134c7ba0d5a99391e0aa41780a9b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Dec 2015 00:45:20 +0800 Subject: [PATCH 1536/1939] Update number-of-connected-components-in-an-undirected-graph.cpp --- C++/number-of-connected-components-in-an-undirected-graph.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/number-of-connected-components-in-an-undirected-graph.cpp b/C++/number-of-connected-components-in-an-undirected-graph.cpp index ddd05e2c6..73bbdf533 100644 --- a/C++/number-of-connected-components-in-an-undirected-graph.cpp +++ b/C++/number-of-connected-components-in-an-undirected-graph.cpp @@ -18,7 +18,7 @@ class Solution { iota(set_.begin(), set_.end(), 0); } - int find_set(int x) { + int find_set(const int x) { if (set_[x] != x) { set_[x] = find_set(set_[x]); // Path compression. } From 895f95ac1d7704a418aab285750447be3c54ecfb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 31 Dec 2015 15:54:02 +0800 Subject: [PATCH 1537/1939] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 01f89d1df..d0a13611c 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-323%20%2F%20323-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-323%20%2F%20324-ff69b4.svg) -Up to date (2015-12-29), there are `306` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2015-12-31), there are `307` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `323` questions. +Here is the classification of all `324` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) From a80dd96aecf28c10029c4a001958ce5abad68591 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 17:26:37 +0800 Subject: [PATCH 1538/1939] Create wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/wiggle-sort-ii.cpp diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp new file mode 100644 index 000000000..f9cf5f5f8 --- /dev/null +++ b/C++/wiggle-sort-ii.cpp @@ -0,0 +1,33 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + void wiggleSort(vector& nums) { + const int n = nums.size(); + int mid = (n - 1) / 2; + nth_element(nums.begin(), nums.begin() + mid, nums.end()); + dutchFlagSort(nums, nums[mid]); + + vector res(n); + for (int i = 0, smallEnd = mid; i < n; i += 2, --smallEnd) { + res[i] = nums[smallEnd]; + } + for (int i = 1, largeEnd = n - 1; i < n; i += 2, --largeEnd) { + res[i] = nums[largeEnd]; + } + nums = res; + } + + void dutchFlagSort(vector& nums, int val) { + for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { + if (nums[j] < val) { + swap(nums[i++], nums[j++]); + } else if (nums[j] > val) { + swap(nums[j], nums[n--]); + } else { + ++j; + } + } + } +}; From b5aa6d8373712ece7bc07071d73e04249b9594c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 17:45:01 +0800 Subject: [PATCH 1539/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index f9cf5f5f8..6288fd6fe 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -1,7 +1,33 @@ // Time: O(n) -// Space: O(n) +// Space: O(1) +// Using virtual index solution. class Solution { +public: + void wiggleSort(vector& nums) { + const int n = nums.size(); + int mid = (n - 1) / 2; + nth_element(nums.begin(), nums.begin() + mid, nums.end()); + dutchFlagSort(nums, nums[mid]); + } + + void dutchFlagSort(vector& nums, int val) { + #define Nums(i) nums[(1 + 2 * (i)) % N] + for (int i = 0, j = 0, n = nums.size() - 1, N = nums.size() + n % 2; j <= n;) { + if (Nums(j) > val) { + swap(Nums(i++), Nums(j++)); + } else if (Nums(j) < val) { + swap(Nums(j), Nums(n--)); + } else { + j++; + } + } + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { public: void wiggleSort(vector& nums) { const int n = nums.size(); From b28e2b80bbcea8c81aed2e30549e4d7bce068886 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 17:48:04 +0800 Subject: [PATCH 1540/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index 6288fd6fe..08f8505d5 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -13,7 +13,8 @@ class Solution { void dutchFlagSort(vector& nums, int val) { #define Nums(i) nums[(1 + 2 * (i)) % N] - for (int i = 0, j = 0, n = nums.size() - 1, N = nums.size() + n % 2; j <= n;) { + const int N = nums.size() % 2 ? nums.size() : nums.size() + 1; + for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { if (Nums(j) > val) { swap(Nums(i++), Nums(j++)); } else if (Nums(j) < val) { From 57519ce72a53cf0a02ecd0aded6966d82a5d881e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 17:57:49 +0800 Subject: [PATCH 1541/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index 08f8505d5..dddb46588 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -8,10 +8,10 @@ class Solution { const int n = nums.size(); int mid = (n - 1) / 2; nth_element(nums.begin(), nums.begin() + mid, nums.end()); - dutchFlagSort(nums, nums[mid]); + reversedDutchFlagSortWithVI(nums, nums[mid]); } - void dutchFlagSort(vector& nums, int val) { + void reversedDutchFlagSortWithVI(vector& nums, int val) { #define Nums(i) nums[(1 + 2 * (i)) % N] const int N = nums.size() % 2 ? nums.size() : nums.size() + 1; for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { From 8b82a73254d58fd0c42b4a5fd48a4c0cc0cbef1f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 18:01:33 +0800 Subject: [PATCH 1542/1939] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d0a13611c..cf408879c 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |📖| | 274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Medium || Counting Sort | 280| [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) | [C++](./C++/wiggle-sort.cpp) [Python](./Python/wiggle-sort.py) | _O(n)_ | _O(1)_ | Medium |📖| | +324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | | ## Two Pointers # | Problem | Solution | Time | Space | Difficulty | Tag | Note From f47380368f0463f9c52a6f4d6f01c1c220772897 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 18:02:44 +0800 Subject: [PATCH 1543/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index dddb46588..8875772b4 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -1,7 +1,7 @@ // Time: O(n) // Space: O(1) -// Using virtual index solution. +// Dutch flag sorting with virtual index solution. class Solution { public: void wiggleSort(vector& nums) { @@ -28,6 +28,7 @@ class Solution { // Time: O(n) // Space: O(n) +// Dutch flag sorting solution. class Solution2 { public: void wiggleSort(vector& nums) { From c1d3ab23443232b7f8a74de47e961311e66752eb Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 18:11:52 +0800 Subject: [PATCH 1544/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cf408879c..e5cee1103 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-323%20%2F%20324-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-324%20%2F%20324-ff69b4.svg) Up to date (2015-12-31), there are `307` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. From 85343785095ae47cdc4bdeceb163c1540cf15304 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 18:32:03 +0800 Subject: [PATCH 1545/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index 8875772b4..5271b6f60 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -20,7 +20,7 @@ class Solution { } else if (Nums(j) < val) { swap(Nums(j), Nums(n--)); } else { - j++; + ++j; } } } From 10c9e92944a61412f2295cb2172ae2af6fd7099a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 20:49:03 +0800 Subject: [PATCH 1546/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index 5271b6f60..ea55fbd04 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -12,8 +12,8 @@ class Solution { } void reversedDutchFlagSortWithVI(vector& nums, int val) { + const int N = nums.size() / 2 * 2 + 1; #define Nums(i) nums[(1 + 2 * (i)) % N] - const int N = nums.size() % 2 ? nums.size() : nums.size() + 1; for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { if (Nums(j) > val) { swap(Nums(i++), Nums(j++)); From aac57dc77eb997f864ac561cae4c77f82124891b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 20:49:53 +0800 Subject: [PATCH 1547/1939] Update kth-largest-element-in-an-array.py --- Python/kth-largest-element-in-an-array.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/kth-largest-element-in-an-array.py b/Python/kth-largest-element-in-an-array.py index fe6b8d9c0..03895e2ee 100644 --- a/Python/kth-largest-element-in-an-array.py +++ b/Python/kth-largest-element-in-an-array.py @@ -25,7 +25,7 @@ def PartitionAroundPivot(self, left, right, pivot_idx, nums): nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx] for i in xrange(left, right): if nums[i] > pivot_value: - nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] + nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] new_pivot_idx += 1 nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right] From 1296811e33312d33011fb27e101356c48c1261f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 20:52:52 +0800 Subject: [PATCH 1548/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index ea55fbd04..096d7b8fd 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -5,8 +5,7 @@ class Solution { public: void wiggleSort(vector& nums) { - const int n = nums.size(); - int mid = (n - 1) / 2; + int mid = (nums.size() - 1) / 2; nth_element(nums.begin(), nums.begin() + mid, nums.end()); reversedDutchFlagSortWithVI(nums, nums[mid]); } From 64918e611ea36f18b30cb3b57e8f26a92a2cce5e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:26:29 +0800 Subject: [PATCH 1549/1939] Create wiggle-sort-ii.py --- Python/wiggle-sort-ii.py | 78 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Python/wiggle-sort-ii.py diff --git a/Python/wiggle-sort-ii.py b/Python/wiggle-sort-ii.py new file mode 100644 index 000000000..736dcfcc3 --- /dev/null +++ b/Python/wiggle-sort-ii.py @@ -0,0 +1,78 @@ +# Time: O(nlogn) +# Space: O(n) + +# Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... +# +# 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? + +class Solution(object): + def wiggleSort(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + nums.sort() + half = len(nums[::2]) - 1 + nums[::2], nums[1::2] = nums[half::-1], nums[:half:-1] + +# Time: O(n) ~ O(n^2) +# Space: O(1) +# Dutch flag sorting with virtual index solution. (TLE) +from random import randint +class Solution2(object): + def wiggleSort(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + def findKthLargest(nums, k): + left, right = 0, len(nums) - 1 + while left <= right: + pivot_idx = randint(left, right) + new_pivot_idx = partitionAroundPivot(left, right, pivot_idx, nums) + if new_pivot_idx == k - 1: + return nums[new_pivot_idx] + elif new_pivot_idx > k - 1: + right = new_pivot_idx - 1 + else: # new_pivot_idx < k - 1. + left = new_pivot_idx + 1 + + def partitionAroundPivot(left, right, pivot_idx, nums): + pivot_value = nums[pivot_idx] + new_pivot_idx = left + nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx] + for i in xrange(left, right): + if nums[i] > pivot_value: + nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] + new_pivot_idx += 1 + nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right] + return new_pivot_idx + + def reversedDutchFlagSortWithVI(nums, val): + def idx(i, N): + return (1 + 2 * (i)) % N + + N = len(nums) / 2 * 2 + 1 + i, j, n = 0, 0, len(nums) - 1 + while j <= n: + if nums[idx(j, N)] > val: + nums[idx(i, N)], nums[idx(j, N)] = nums[idx(j, N)], nums[idx(i, N)] + i += 1 + j += 1 + elif nums[idx(j, N)] < val: + nums[idx(j, N)], nums[idx(n, N)] = nums[idx(n, N)], nums[idx(j, N)] + n -= 1 + else: + j += 1 + + mid = (len(nums) - 1) / 2 + findKthLargest(nums, mid + 1) + reversedDutchFlagSortWithVI(nums, nums[mid]) From b8f502d80a71f00f08346788184586e4db59e63f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:27:30 +0800 Subject: [PATCH 1550/1939] Update wiggle-sort-ii.py --- Python/wiggle-sort-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/wiggle-sort-ii.py b/Python/wiggle-sort-ii.py index 736dcfcc3..a191bc6d2 100644 --- a/Python/wiggle-sort-ii.py +++ b/Python/wiggle-sort-ii.py @@ -20,8 +20,8 @@ def wiggleSort(self, nums): :rtype: void Do not return anything, modify nums in-place instead. """ nums.sort() - half = len(nums[::2]) - 1 - nums[::2], nums[1::2] = nums[half::-1], nums[:half:-1] + med = (len(nums) - 1) / 2 + nums[::2], nums[1::2] = nums[med::-1], nums[:med:-1] # Time: O(n) ~ O(n^2) # Space: O(1) From b7d2fdf8e39ce2f933ee6f055bd0311365622c06 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:31:26 +0800 Subject: [PATCH 1551/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index 096d7b8fd..962d4ee8c 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(n) ~ O(n^2) // Space: O(1) // Dutch flag sorting with virtual index solution. @@ -25,7 +25,7 @@ class Solution { } }; -// Time: O(n) +// Time: O(n) ~ O(n^2) // Space: O(n) // Dutch flag sorting solution. class Solution2 { From d0f4738291635e8278d5f979dfd621e0170dfb0f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:36:13 +0800 Subject: [PATCH 1552/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index 962d4ee8c..1727a020a 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -1,12 +1,12 @@ // Time: O(n) ~ O(n^2) // Space: O(1) -// Dutch flag sorting with virtual index solution. +// Dutch flag sorting with virtual index solution. (44ms) class Solution { public: void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; - nth_element(nums.begin(), nums.begin() + mid, nums.end()); + nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2) reversedDutchFlagSortWithVI(nums, nums[mid]); } @@ -27,20 +27,19 @@ class Solution { // Time: O(n) ~ O(n^2) // Space: O(n) -// Dutch flag sorting solution. +// Dutch flag sorting solution. (64ms) class Solution2 { public: void wiggleSort(vector& nums) { - const int n = nums.size(); - int mid = (n - 1) / 2; - nth_element(nums.begin(), nums.begin() + mid, nums.end()); + int mid = (nums.size() - 1) / 2; + nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2) dutchFlagSort(nums, nums[mid]); - vector res(n); - for (int i = 0, smallEnd = mid; i < n; i += 2, --smallEnd) { + vector res(nums.size()); + for (int i = 0, smallEnd = mid; i < nums.size(); i += 2, --smallEnd) { res[i] = nums[smallEnd]; } - for (int i = 1, largeEnd = n - 1; i < n; i += 2, --largeEnd) { + for (int i = 1, largeEnd = nums.size() - 1; i < nums.size(); i += 2, --largeEnd) { res[i] = nums[largeEnd]; } nums = res; @@ -58,3 +57,22 @@ class Solution2 { } } }; + +// Time: O(nlogn) +// Space: O(n) +// Sorting and reorder solution. (64ms) +class Solution3 { +public: + void wiggleSort(vector& nums) { + int mid = (nums.size() - 1) / 2; + sort(nums.begin(), nums.end()); + vector res(nums.size()); + for (int i = 0, smallEnd = mid; i < nums.size(); i += 2, --smallEnd) { + res[i] = nums[smallEnd]; + } + for (int i = 1, largeEnd = nums.size() - 1; i < nums.size(); i += 2, --largeEnd) { + res[i] = nums[largeEnd]; + } + nums = res; + } +}; From c1fbda22269392d813e70ad09f059d984a3e1b31 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:37:32 +0800 Subject: [PATCH 1553/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e5cee1103..d38301be5 100644 --- a/README.md +++ b/README.md @@ -256,7 +256,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |📖| | 274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Medium || Counting Sort | 280| [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) | [C++](./C++/wiggle-sort.cpp) [Python](./Python/wiggle-sort.py) | _O(n)_ | _O(1)_ | Medium |📖| | -324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | | +324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | | ## Two Pointers # | Problem | Solution | Time | Space | Difficulty | Tag | Note From fd037e519237623ce6b842886e3c578e8120923b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:38:07 +0800 Subject: [PATCH 1554/1939] Update kth-largest-element-in-an-array.cpp --- C++/kth-largest-element-in-an-array.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/kth-largest-element-in-an-array.cpp b/C++/kth-largest-element-in-an-array.cpp index 095b917e6..caa643239 100644 --- a/C++/kth-largest-element-in-an-array.cpp +++ b/C++/kth-largest-element-in-an-array.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(n) ~ O(n^2) // Space: O(1) class Solution { @@ -36,7 +36,7 @@ class Solution { } }; -// Time: O(n) +// Time: O(n) ~ O(n^2) // Space: O(1) class Solution2 { public: From 0ae1de2a04aacbcdd23f349426e5f367331dd571 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:38:26 +0800 Subject: [PATCH 1555/1939] Update kth-largest-element-in-an-array.py --- Python/kth-largest-element-in-an-array.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/kth-largest-element-in-an-array.py b/Python/kth-largest-element-in-an-array.py index 03895e2ee..08dd0b788 100644 --- a/Python/kth-largest-element-in-an-array.py +++ b/Python/kth-largest-element-in-an-array.py @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(n) ~ O(n^2) # Space: O(1) from random import randint From 20109210d21976d1d85e1f1d5210e6a61094d70d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:38:59 +0800 Subject: [PATCH 1556/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d38301be5..ab4bc10c0 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search -215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ | _O(1)_ | Medium | EPI| +215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | EPI| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Easy | | 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [C++](./C++/product-of-array-except-self.cpp) [Python](./Python/product-of-array-except-self.py) | _O(n)_ | _O(1)_ | Medium | LintCode | From f9dd1ac665cc664806fcff94f43845d8e00e88fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:45:36 +0800 Subject: [PATCH 1557/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index 1727a020a..d394008cc 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -58,10 +58,36 @@ class Solution2 { } }; +// Time: O(nlogn) +// Space: O(1) +// Sorting and Dutch flag sorting with virtual index solution. (64ms) +class Solution3 { +public: + void wiggleSort(vector& nums) { + int mid = (nums.size() - 1) / 2; + sort(nums.begin(), nums.end()); + reversedDutchFlagSortWithVI(nums, nums[mid]); + } + + void reversedDutchFlagSortWithVI(vector& nums, int val) { + const int N = nums.size() / 2 * 2 + 1; + #define Nums(i) nums[(1 + 2 * (i)) % N] + for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { + if (Nums(j) > val) { + swap(Nums(i++), Nums(j++)); + } else if (Nums(j) < val) { + swap(Nums(j), Nums(n--)); + } else { + ++j; + } + } + } +}; + // Time: O(nlogn) // Space: O(n) // Sorting and reorder solution. (64ms) -class Solution3 { +class Solution4 { public: void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; From d528f0dff9550ce5f1213006519aad76d7a792fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:47:57 +0800 Subject: [PATCH 1558/1939] Update wiggle-sort-ii.py --- Python/wiggle-sort-ii.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/wiggle-sort-ii.py b/Python/wiggle-sort-ii.py index a191bc6d2..aaedc8f4d 100644 --- a/Python/wiggle-sort-ii.py +++ b/Python/wiggle-sort-ii.py @@ -13,6 +13,7 @@ # Follow Up: # Can you do it in O(n) time and/or in-place with O(1) extra space? +# Sorting and reoder solution. (92ms) class Solution(object): def wiggleSort(self, nums): """ From 4454bcb920aa88d800989465506309bb5a7d9801 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jan 2016 21:51:14 +0800 Subject: [PATCH 1559/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index d394008cc..76de581d7 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -6,8 +6,8 @@ class Solution { public: void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; - nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2) - reversedDutchFlagSortWithVI(nums, nums[mid]); + nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2) time + reversedDutchFlagSortWithVI(nums, nums[mid]); // O(n) time, O(1) space } void reversedDutchFlagSortWithVI(vector& nums, int val) { @@ -32,10 +32,10 @@ class Solution2 { public: void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; - nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2) - dutchFlagSort(nums, nums[mid]); + nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2) time + dutchFlagSort(nums, nums[mid]); // O(n) time, O(1) space - vector res(nums.size()); + vector res(nums.size()); // O(n) space for (int i = 0, smallEnd = mid; i < nums.size(); i += 2, --smallEnd) { res[i] = nums[smallEnd]; } @@ -65,8 +65,8 @@ class Solution3 { public: void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; - sort(nums.begin(), nums.end()); - reversedDutchFlagSortWithVI(nums, nums[mid]); + sort(nums.begin(), nums.end()); // O(nlogn) time + reversedDutchFlagSortWithVI(nums, nums[mid]); // O(n) time, O(1) space } void reversedDutchFlagSortWithVI(vector& nums, int val) { @@ -91,8 +91,8 @@ class Solution4 { public: void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; - sort(nums.begin(), nums.end()); - vector res(nums.size()); + sort(nums.begin(), nums.end()); // O(nlogn) time + vector res(nums.size()); // O(n) space for (int i = 0, smallEnd = mid; i < nums.size(); i += 2, --smallEnd) { res[i] = nums[smallEnd]; } From 84401442e1be5fb321ec65d222130df18a99354a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Jan 2016 20:43:48 +0800 Subject: [PATCH 1560/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index 76de581d7..d86a47f45 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -1,16 +1,16 @@ // Time: O(n) ~ O(n^2) // Space: O(1) -// Dutch flag sorting with virtual index solution. (44ms) +// Tri Partition (aka Dutch National Flag Problem) with virtual index solution. (44ms) class Solution { public: void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2) time - reversedDutchFlagSortWithVI(nums, nums[mid]); // O(n) time, O(1) space + reversedTriPartitionWithVI(nums, nums[mid]); // O(n) time, O(1) space } - void reversedDutchFlagSortWithVI(vector& nums, int val) { + void reversedTriPartitionWithVI(vector& nums, int val) { const int N = nums.size() / 2 * 2 + 1; #define Nums(i) nums[(1 + 2 * (i)) % N] for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { @@ -27,13 +27,13 @@ class Solution { // Time: O(n) ~ O(n^2) // Space: O(n) -// Dutch flag sorting solution. (64ms) +// Tri Partition (aka Dutch National Flag Problem) solution. (64ms) class Solution2 { public: void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2) time - dutchFlagSort(nums, nums[mid]); // O(n) time, O(1) space + TriPartition(nums, nums[mid]); // O(n) time, O(1) space vector res(nums.size()); // O(n) space for (int i = 0, smallEnd = mid; i < nums.size(); i += 2, --smallEnd) { @@ -45,7 +45,7 @@ class Solution2 { nums = res; } - void dutchFlagSort(vector& nums, int val) { + void TriPartition(vector& nums, int val) { for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { if (nums[j] < val) { swap(nums[i++], nums[j++]); @@ -60,16 +60,16 @@ class Solution2 { // Time: O(nlogn) // Space: O(1) -// Sorting and Dutch flag sorting with virtual index solution. (64ms) +// Sorting and Tri Partition (aka Dutch National Flag Problem) with virtual index solution. (64ms) class Solution3 { public: void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; sort(nums.begin(), nums.end()); // O(nlogn) time - reversedDutchFlagSortWithVI(nums, nums[mid]); // O(n) time, O(1) space + reversedTriPartitionWithVI(nums, nums[mid]); // O(n) time, O(1) space } - void reversedDutchFlagSortWithVI(vector& nums, int val) { + void reversedTriPartitionWithVI(vector& nums, int val) { const int N = nums.size() / 2 * 2 + 1; #define Nums(i) nums[(1 + 2 * (i)) % N] for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { From e8c3bc65029e0d74893486c96dcb1972c23418a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Jan 2016 20:44:40 +0800 Subject: [PATCH 1561/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index d86a47f45..53e7aa47d 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -33,7 +33,7 @@ class Solution2 { void wiggleSort(vector& nums) { int mid = (nums.size() - 1) / 2; nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2) time - TriPartition(nums, nums[mid]); // O(n) time, O(1) space + triPartition(nums, nums[mid]); // O(n) time, O(1) space vector res(nums.size()); // O(n) space for (int i = 0, smallEnd = mid; i < nums.size(); i += 2, --smallEnd) { @@ -45,7 +45,7 @@ class Solution2 { nums = res; } - void TriPartition(vector& nums, int val) { + void triPartition(vector& nums, int val) { for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { if (nums[j] < val) { swap(nums[i++], nums[j++]); From 580db7945903a571e8e08940bd2a2e22149f5756 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Jan 2016 20:46:41 +0800 Subject: [PATCH 1562/1939] Update wiggle-sort-ii.py --- Python/wiggle-sort-ii.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/wiggle-sort-ii.py b/Python/wiggle-sort-ii.py index aaedc8f4d..15b625f07 100644 --- a/Python/wiggle-sort-ii.py +++ b/Python/wiggle-sort-ii.py @@ -26,7 +26,7 @@ def wiggleSort(self, nums): # Time: O(n) ~ O(n^2) # Space: O(1) -# Dutch flag sorting with virtual index solution. (TLE) +# Tri Partition (aka Dutch National Flag Problem) with virtual index solution. (TLE) from random import randint class Solution2(object): def wiggleSort(self, nums): @@ -57,7 +57,7 @@ def partitionAroundPivot(left, right, pivot_idx, nums): nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right] return new_pivot_idx - def reversedDutchFlagSortWithVI(nums, val): + def reversedTriPartitionWithVI(nums, val): def idx(i, N): return (1 + 2 * (i)) % N @@ -76,4 +76,4 @@ def idx(i, N): mid = (len(nums) - 1) / 2 findKthLargest(nums, mid + 1) - reversedDutchFlagSortWithVI(nums, nums[mid]) + reversedTriPartitionWithVI(nums, nums[mid]) From 571c284e66c3e52a1e52938467693de7c0cdc200 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Jan 2016 20:47:31 +0800 Subject: [PATCH 1563/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ab4bc10c0..0b3d81d2f 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || 57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || -75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || +75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium | Tri Partition | 88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || @@ -256,7 +256,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |📖| | 274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Medium || Counting Sort | 280| [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) | [C++](./C++/wiggle-sort.cpp) [Python](./Python/wiggle-sort.py) | _O(n)_ | _O(1)_ | Medium |📖| | -324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | | +324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | ## Two Pointers # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 0ea9eba88c96f62f8b5bc8b6c545069091412b6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Jan 2016 20:48:04 +0800 Subject: [PATCH 1564/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0b3d81d2f..8328f4bb9 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || 57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || -75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium | Tri Partition | +75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || Tri Partition 88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || From 41dbc40ce054ccab43a92bafacc861bdeaead700 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jan 2016 21:22:36 +0800 Subject: [PATCH 1565/1939] Update sort-colors.py --- Python/sort-colors.py | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/Python/sort-colors.py b/Python/sort-colors.py index d6bef9682..5e42aa69b 100644 --- a/Python/sort-colors.py +++ b/Python/sort-colors.py @@ -19,23 +19,29 @@ # Could you come up with an one-pass algorithm using only constant space? # -class Solution: - # @param A a list of integers - # @return nothing, sort in place - def sortColors(self, A): - i, last_zero, first_two = 0, -1, len(A) - - while i < first_two: - if A[i] == 0: - last_zero += 1 - A[last_zero], A[i] = A[i], A[last_zero] - elif A[i] == 2: - first_two -= 1 - A[first_two], A[i] = A[i], A[first_two] - i -= 1 - i += 1 +class Solution(object): + def sortColors(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + def triPartition(nums, target): + i, j, n = 0, 0, len(nums) - 1 + + while j <= n: + if nums[j] < target: + nums[i], nums[j] = nums[j], nums[i] + i += 1 + j += 1 + elif nums[j] > target: + nums[j], nums[n] = nums[n], nums[j] + n -= 1 + else: + j += 1 + + triPartition(nums, 1) if __name__ == "__main__": A = [2, 1, 1, 0, 0, 2] Solution().sortColors(A) - print A \ No newline at end of file + print A From a7bfb31bb7114832ba343c7ddb490d5d901d0b4c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jan 2016 20:04:06 +0800 Subject: [PATCH 1566/1939] Create sort-colors.cpp --- C++/sort-colors.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/sort-colors.cpp diff --git a/C++/sort-colors.cpp b/C++/sort-colors.cpp new file mode 100644 index 000000000..9eb088944 --- /dev/null +++ b/C++/sort-colors.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +// Tri-Partition solution. +class Solution { +public: + void sortColors(vector& nums) { + const int target = 1; + for (int i = 0, j = 0, n = nums.size() - 1; j <= n;) { + if (nums[j] < target) { + swap(nums[i++], nums[j++]); + } else if (nums[j] > target) { + swap(nums[j], nums[n--]); + } else { + ++j; + } + } + } +}; From 2f92e4fa4c27ebd73fe907c5189e5516f38db80b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jan 2016 20:04:54 +0800 Subject: [PATCH 1567/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8328f4bb9..052e4fa06 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || 57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || -75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || Tri Partition +75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [C++](./C++/sort-colors.cpp) [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || Tri Partition 88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || 148| [Sort List](https://leetcode.com/problems/sort-list/) | [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || From 9470bca64df323975c0fd0bb8a62c3056b49cb28 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jan 2016 22:40:27 +0800 Subject: [PATCH 1568/1939] Update best-meeting-point.cpp --- C++/best-meeting-point.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/best-meeting-point.cpp b/C++/best-meeting-point.cpp index 9a6839fa4..dc83344b0 100644 --- a/C++/best-meeting-point.cpp +++ b/C++/best-meeting-point.cpp @@ -1,5 +1,5 @@ -// Time: O(n) -// Space: O(n) +// Time: O(m * n) +// Space: O(m + n) class Solution { public: From 8486ee9d04d1aa9cc6d718e6a5a4193d769277be Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jan 2016 22:40:50 +0800 Subject: [PATCH 1569/1939] Update best-meeting-point.py --- Python/best-meeting-point.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/best-meeting-point.py b/Python/best-meeting-point.py index f9232a3a0..52b481624 100644 --- a/Python/best-meeting-point.py +++ b/Python/best-meeting-point.py @@ -1,5 +1,5 @@ -# Time: O(n) -# Space: O(n) +# Time: O(m * n) +# Space: O(m + n) from random import randint From 6e305c5e0acadb19db95823629261871d61ff7c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jan 2016 22:41:16 +0800 Subject: [PATCH 1570/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 052e4fa06..53e403fa0 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |📖, EPI || 289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| 293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(n * (c+1))_ | _O(1)_ | Easy |📖|| -296| [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) | [C++](./C++/best-meeting-point.cpp) [Python](./Python/best-meeting-point.py) | _O(n)_ | _O(n)_ | Medium |📖|| +296| [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) | [C++](./C++/best-meeting-point.cpp) [Python](./Python/best-meeting-point.py) | _O(m * n)_ | _O(m + n)_ | Medium |📖|| 311| [Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/) | [C++](./C++/sparse-matrix-multiplication.cpp) [Python](./Python/sparse-matrix-multiplication.py) | _O(m * n * l)_ | _O(m * l)_ | Medium |📖|| ## String From fdf607c1e276b229c26b042c506600db26bc763d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Jan 2016 19:16:30 +0800 Subject: [PATCH 1571/1939] Create maximum-size-subarray-sum-equals-k.py --- Python/maximum-size-subarray-sum-equals-k.py | 21 ++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/maximum-size-subarray-sum-equals-k.py diff --git a/Python/maximum-size-subarray-sum-equals-k.py b/Python/maximum-size-subarray-sum-equals-k.py new file mode 100644 index 000000000..393505529 --- /dev/null +++ b/Python/maximum-size-subarray-sum-equals-k.py @@ -0,0 +1,21 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def maxSubArrayLen(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + sums = {} + cur_sum, max_len = 0, 0 + for i in xrange(len(nums)): + cur_sum += nums[i] + if cur_sum == k: + max_len = i + 1 + elif cur_sum - k in sums: + max_len = max(max_len, i - sums[cur_sum - k]) + if cur_sum not in sums: + sums[cur_sum] = i # Only keep the smallest index. + return max_len From 66097379add60f3763f1e28d2340cc91027dcd2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Jan 2016 19:19:03 +0800 Subject: [PATCH 1572/1939] Create maximum-size-subarray-sum-equals-k.cpp --- C++/maximum-size-subarray-sum-equals-k.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/maximum-size-subarray-sum-equals-k.cpp diff --git a/C++/maximum-size-subarray-sum-equals-k.cpp b/C++/maximum-size-subarray-sum-equals-k.cpp new file mode 100644 index 000000000..29a6d0a99 --- /dev/null +++ b/C++/maximum-size-subarray-sum-equals-k.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int maxSubArrayLen(vector& nums, int k) { + unordered_map sums; + int cur_sum = 0, max_len = 0; + for (int i = 0; i < nums.size(); ++i) { + cur_sum += nums[i]; + if (cur_sum == k) { + max_len = i + 1; + } else if (sums.find(cur_sum - k) != sums.end()) { + max_len = max(max_len, i - sums[cur_sum - k]); + } + if (sums.find(cur_sum) == sums.end()) { + sums[cur_sum] = i; + } + } + return max_len; + } +}; From ad32a3f62ba29d93ebd960788ca43c164a2067f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Jan 2016 19:22:00 +0800 Subject: [PATCH 1573/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 53e403fa0..e539808a8 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-324%20%2F%20324-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-325%20%2F%20325-ff69b4.svg) -Up to date (2015-12-31), there are `307` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-01-05), there are `308` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `324` questions. +Here is the classification of all `325` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -209,6 +209,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k)_ | _O(k)_| Hard | LintCode, 📖 | Union Find 314| [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) | [C++](./C++/binary-tree-vertical-order-traversal.cpp) [Python](./Python/binary-tree-vertical-order-traversal.py) | _O(n)_ | _O(n)_| Medium | 📖 | BFS 323| [Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) | [C++](./C++/number-of-connected-components-in-an-undirected-graph.cpp) [Python](./Python/number-of-connected-components-in-an-undirected-graph.py) | _O(n)_ | _O(n)_| Medium | 📖 | Union Find +325| [Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/) | [C++](./C++/maximum-size-subarray-sum-equals-k.cpp) [Python](./Python/maximum-size-subarray-sum-equals-k.py) | _O(n)_ | _O(n)_| Medium | 📖 | ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 4013425622f0c7ac6c9b9805b6cd940d4bb41ca6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Jan 2016 19:23:32 +0800 Subject: [PATCH 1574/1939] Update maximum-size-subarray-sum-equals-k.cpp --- C++/maximum-size-subarray-sum-equals-k.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/maximum-size-subarray-sum-equals-k.cpp b/C++/maximum-size-subarray-sum-equals-k.cpp index 29a6d0a99..9784071ef 100644 --- a/C++/maximum-size-subarray-sum-equals-k.cpp +++ b/C++/maximum-size-subarray-sum-equals-k.cpp @@ -14,7 +14,7 @@ class Solution { max_len = max(max_len, i - sums[cur_sum - k]); } if (sums.find(cur_sum) == sums.end()) { - sums[cur_sum] = i; + sums[cur_sum] = i; // Only keep the smallest index. } } return max_len; From 9c6364d33fdf9b26329016d5e211bebb1b9315e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Jan 2016 17:23:45 +0800 Subject: [PATCH 1575/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e539808a8..3caa3ae57 100644 --- a/README.md +++ b/README.md @@ -209,7 +209,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k)_ | _O(k)_| Hard | LintCode, 📖 | Union Find 314| [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) | [C++](./C++/binary-tree-vertical-order-traversal.cpp) [Python](./Python/binary-tree-vertical-order-traversal.py) | _O(n)_ | _O(n)_| Medium | 📖 | BFS 323| [Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) | [C++](./C++/number-of-connected-components-in-an-undirected-graph.cpp) [Python](./Python/number-of-connected-components-in-an-undirected-graph.py) | _O(n)_ | _O(n)_| Medium | 📖 | Union Find -325| [Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/) | [C++](./C++/maximum-size-subarray-sum-equals-k.cpp) [Python](./Python/maximum-size-subarray-sum-equals-k.py) | _O(n)_ | _O(n)_| Medium | 📖 | +325| [Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/) | [C++](./C++/maximum-size-subarray-sum-equals-k.cpp) [Python](./Python/maximum-size-subarray-sum-equals-k.py) | _O(n)_ | _O(n)_| Easy | 📖 | ## Data Structure # | Problem | Solution | Time | Space | Difficulty | Tag | Note From bfadd3e5c114a3650142bd1de10b4692ccbb054c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jan 2016 22:12:46 +0800 Subject: [PATCH 1576/1939] Update 3sum.py --- Python/3sum.py | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/Python/3sum.py b/Python/3sum.py index 2ad5ea356..a622d76bf 100644 --- a/Python/3sum.py +++ b/Python/3sum.py @@ -15,29 +15,31 @@ # (-1, -1, 2) # -class Solution: - # @return a list of lists of length 3, [[val1,val2,val3]] +class Solution(object): def threeSum(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ nums, result, i = sorted(nums), [], 0 while i < len(nums) - 2: - j, k = i + 1, len(nums) - 1 - while j < k: - if nums[i] + nums[j] + nums[k] < 0: - j += 1 - elif nums[i] + nums[j] + nums[k] > 0: - k -= 1 - else: - result.append([nums[i], nums[j], nums[k]]) - j, k = j + 1, k - 1 - while j < k and nums[j] == nums[j - 1]: + if i == 0 or nums[i] != nums[i - 1]: + j, k = i + 1, len(nums) - 1 + while j < k: + if nums[i] + nums[j] + nums[k] < 0: j += 1 - while j < k and nums[k] == nums[k + 1]: + elif nums[i] + nums[j] + nums[k] > 0: k -= 1 + else: + result.append([nums[i], nums[j], nums[k]]) + j, k = j + 1, k - 1 + while j < k and nums[j] == nums[j - 1]: + j += 1 + while j < k and nums[k] == nums[k + 1]: + k -= 1 i += 1 - while i < len(nums) - 2 and nums[i] == nums[i - 1]: - i += 1 return result if __name__ == '__main__': result = Solution().threeSum([-1, 0, 1, 2, -1, -4]) - print result \ No newline at end of file + print result From bb5f19b3317c6124e77c078fc765be21f9f80ab9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jan 2016 22:23:21 +0800 Subject: [PATCH 1577/1939] Update 3sum-closest.py --- Python/3sum-closest.py | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/Python/3sum-closest.py b/Python/3sum-closest.py index 0681ae221..35301b24a 100644 --- a/Python/3sum-closest.py +++ b/Python/3sum-closest.py @@ -11,26 +11,29 @@ # The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). # -class Solution: - # @return an integer +class Solution(object): def threeSumClosest(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ nums, result, min_diff, i = sorted(nums), float("inf"), float("inf"), 0 while i < len(nums) - 2: - j, k = i + 1, len(nums) - 1 - while j < k: - diff = nums[i] + nums[j] + nums[k] - target - if abs(diff) < min_diff: - min_diff = abs(diff) - result = nums[i] + nums[j] + nums[k] - if diff < 0: - j += 1 - elif diff > 0: - k -= 1 - else: - return target + if i == 0 or nums[i] != nums[i - 1]: + j, k = i + 1, len(nums) - 1 + while j < k: + diff = nums[i] + nums[j] + nums[k] - target + if abs(diff) < min_diff: + min_diff = abs(diff) + result = nums[i] + nums[j] + nums[k] + if diff < 0: + j += 1 + elif diff > 0: + k -= 1 + else: + return target i += 1 - while i < len(nums) - 2 and nums[i] == nums[i - 1]: - i += 1 return result if __name__ == '__main__': From b170df3c4b6e4c4c1db2e8cf436c8f73e6057d6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jan 2016 22:28:46 +0800 Subject: [PATCH 1578/1939] Update and rename threeSum.cpp to 3-sum.cpp --- C++/3-sum.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ C++/threeSum.cpp | 47 ----------------------------------------------- 2 files changed, 42 insertions(+), 47 deletions(-) create mode 100644 C++/3-sum.cpp delete mode 100644 C++/threeSum.cpp diff --git a/C++/3-sum.cpp b/C++/3-sum.cpp new file mode 100644 index 000000000..343bcff18 --- /dev/null +++ b/C++/3-sum.cpp @@ -0,0 +1,42 @@ +// Time: O(n^2) +// Space: O(1) + +class Solution { +public: + /** + * @param numbers : Give an array numbers of n integer + * @return : Find all unique triplets in the array which gives the sum of zero. + */ + vector> threeSum(vector &nums) { + vector> ans; + const int target = 0; + + // Make nums in increasing order. Time: O(nlogn) + sort(nums.begin(), nums.end()); + + for (int i = 0; i < static_cast(nums.size()) - 2; ++i) { + if (i == 0 || nums[i] != nums[i - 1]) { // Skip duplicated. + for (int j = i + 1, k = nums.size() - 1; j < k; ) { // Time: O(n) for each i. + if (j - 1 > i && nums[j] == nums[j - 1]) { // Skip duplicated. + ++j; + } else if (k + 1 < nums.size() && nums[k] == nums[k + 1]) { // Skip duplicated. + --k; + } else { + const auto sum = nums[i] + nums[j] + nums[k]; + if (sum > target) { // Should decrease sum. + --k; + } else if (sum < target) { // Should increase sum. + ++j; + } else { + ans.push_back({nums[i], nums[j], nums[k]}); + ++j; + --k; + } + } + } + } + } + + return ans; + } +}; diff --git a/C++/threeSum.cpp b/C++/threeSum.cpp deleted file mode 100644 index 8cbea6c72..000000000 --- a/C++/threeSum.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(1) - -class Solution { - public: - vector > threeSum(vector &num) { - vector > ans; - const int target = 0; - - if(num.size() < 3) - return ans; - - sort(num.begin(), num.end()); - auto last = num.end(); - for(auto a = num.begin(); a < prev(last, 2); ++a) { - if(a > num.begin() && *a == *(a - 1)) - continue; - auto b = next(a); - auto c = prev(last); - - while(b < c) { - if(b > next(a) && *b == *(b - 1)) { - ++b; - } - else if(c < prev(last) && *c == *(c + 1)) { - --c; - } - else { - const int sum = *a + *b + *c; - - if(sum < target) - ++b; - else if(sum > target) - --c; - else { - ans.push_back({ *a, *b, *c}); - ++b; - --c; - } - } - } - } - - return ans; - } -}; - From ed47c8caf0dcf564b8af1d832d3f4b90d02352ad Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jan 2016 22:29:47 +0800 Subject: [PATCH 1579/1939] Update 3-sum.cpp --- C++/3-sum.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/3-sum.cpp b/C++/3-sum.cpp index 343bcff18..d1889e4a8 100644 --- a/C++/3-sum.cpp +++ b/C++/3-sum.cpp @@ -29,8 +29,7 @@ class Solution { ++j; } else { ans.push_back({nums[i], nums[j], nums[k]}); - ++j; - --k; + ++j, --k; } } } From f955a53e059a2d0305a55f6327fc17c841642b83 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jan 2016 22:32:28 +0800 Subject: [PATCH 1580/1939] Update and rename threeSumCloset.cpp to 3-sum-closest.cpp --- C++/3-sum-closest.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++ C++/threeSumCloset.cpp | 32 ------------------------------ 2 files changed, 44 insertions(+), 32 deletions(-) create mode 100644 C++/3-sum-closest.cpp delete mode 100644 C++/threeSumCloset.cpp diff --git a/C++/3-sum-closest.cpp b/C++/3-sum-closest.cpp new file mode 100644 index 000000000..02e0aaa7e --- /dev/null +++ b/C++/3-sum-closest.cpp @@ -0,0 +1,44 @@ +// Time: O(n^2) +// Space: O(1) + +class Solution { +public: + /** + * @param numbers: Give an array numbers of n integer + * @param target: An integer + * @return: return the sum of the three integers, the sum closest target. + */ + int threeSumClosest(vector nums, int target) { + int ans = numeric_limits::max(); + int min_diff = numeric_limits::max(); + + // Make nums in increasing order. Time: O(nlogn) + sort(nums.begin(), nums.end()); + + for (int i = 0; i < static_cast(nums.size()) - 2; ++i) { + if (i == 0 || nums[i] != nums[i - 1]) { // Skip duplicated. + int j = i + 1; + int k = nums.size() - 1; + + while (j < k) { // Time: O(n) for each i. + const auto sum = nums[i] + nums[j] + nums[k]; + + if (sum > target) { // Should decrease sum. + --k; + } else if (sum < target) { // Should increase sum. + ++j; + } else { + return target; + } + + if (abs(sum - target) < min_diff) { + min_diff = abs(sum - target); + ans = sum; + } + } + } + } + + return ans; + } +}; diff --git a/C++/threeSumCloset.cpp b/C++/threeSumCloset.cpp deleted file mode 100644 index 67034d769..000000000 --- a/C++/threeSumCloset.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(1) - -class Solution { - public: - int threeSumClosest(vector &num, int target) { - int ans = 0; - int gap = INT_MAX; - - sort(num.begin(), num.end()); - auto last = num.end(); - for(auto a = num.begin(); a != prev(last, 2); a++) { - auto b = next(a); - auto c = prev(last); - - while(b != c) { - const int sum = *a + *b + *c; - - if(gap > abs(target - sum)) { - gap = abs(target - sum); - ans = sum; - } - if(sum < target) - ++b; - else - --c; - } - } - - return ans; - } -}; From 26103f93019b559a28c4d1da11762011388211df Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jan 2016 22:33:33 +0800 Subject: [PATCH 1581/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3caa3ae57..6504e09f6 100644 --- a/README.md +++ b/README.md @@ -58,8 +58,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Array # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -15 | [3 Sum](https://leetcode.com/problems/3sum/) | [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || -16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py)| _O(n^2)_ | _O(1)_ | Medium || +15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || +16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py) [C++](./C++/3sum-closest.cpp)| _O(n^2)_ | _O(1)_ | Medium || 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky From cb2d77f2fca59cbdb7d68606aa822ed1395af801 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jan 2016 22:34:10 +0800 Subject: [PATCH 1582/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6504e09f6..40920190c 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || -16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](./Python/3sum-closest.py) [C++](./C++/3sum-closest.cpp)| _O(n^2)_ | _O(1)_ | Medium || +16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [C++](./C++/3sum-closest.cpp) [Python](./Python/3sum-closest.py) | _O(n^2)_ | _O(1)_ | Medium || 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky From 77623ed8459a56ac803f06709fc16004ed82cb68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jan 2016 22:34:38 +0800 Subject: [PATCH 1583/1939] Rename 3-sum-closest.cpp to 3sum-closest.cpp --- C++/{3-sum-closest.cpp => 3sum-closest.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{3-sum-closest.cpp => 3sum-closest.cpp} (100%) diff --git a/C++/3-sum-closest.cpp b/C++/3sum-closest.cpp similarity index 100% rename from C++/3-sum-closest.cpp rename to C++/3sum-closest.cpp From 3a7e0a2e2112c71192fb506c11a64c8bc6987308 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jan 2016 22:34:55 +0800 Subject: [PATCH 1584/1939] Rename 3-sum.cpp to 3sum.cpp --- C++/{3-sum.cpp => 3sum.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{3-sum.cpp => 3sum.cpp} (100%) diff --git a/C++/3-sum.cpp b/C++/3sum.cpp similarity index 100% rename from C++/3-sum.cpp rename to C++/3sum.cpp From 6e38efc02c19ee7c35769de1111fd235f7ca0447 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Jan 2016 21:50:13 +0800 Subject: [PATCH 1585/1939] Create power-of-three.cpp --- C++/power-of-three.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/power-of-three.cpp diff --git a/C++/power-of-three.cpp b/C++/power-of-three.cpp new file mode 100644 index 000000000..743b0dadf --- /dev/null +++ b/C++/power-of-three.cpp @@ -0,0 +1,14 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + bool isPowerOfThree(int n) { + if (n <= 0) { + return 0; + } + + const int max_pow3 = log(numeric_limits::max()) / log(3); + return static_cast(pow(3, max_pow3)) % n == 0; + } +}; From 8851c8a3e5a78d2810c1ff3fbc28b41ce9db3cc5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Jan 2016 21:59:10 +0800 Subject: [PATCH 1586/1939] Create power-of-three.py --- Python/power-of-three.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/power-of-three.py diff --git a/Python/power-of-three.py b/Python/power-of-three.py new file mode 100644 index 000000000..5c458c5cd --- /dev/null +++ b/Python/power-of-three.py @@ -0,0 +1,17 @@ +# Time: O(1) +# Space: O(1) + +# 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? +# + +class Solution(object): + def isPowerOfThree(self, n): + """ + :type n: int + :rtype: bool + """ + return n > 0 and 3**19 % n == 0 From 3a86bd3e0dd5d549f4e16930292dd6c5333df69f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Jan 2016 22:01:23 +0800 Subject: [PATCH 1587/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 40920190c..ab54a2fdf 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-325%20%2F%20325-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-326%20%2F%20326-ff69b4.svg) -Up to date (2016-01-05), there are `308` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-01-08), there are `309` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `325` questions. +Here is the classification of all `326` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -239,6 +239,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(logn)_ | _O(1)_ | Easy ||| 292| [Nim Game](https://leetcode.com/problems/nim-game/) | [C++](./C++/nim-game.cpp) [Python](./Python/nim-game.py) | _O(1)_ | _O(1)_ | Easy | LintCode || 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./C++/bulb-switcher.cpp) [Python](./Python/bulb-switcher.py) | _O(1)_ | _O(1)_ | Medium ||| +326 | [Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./C++/power-of-three.cpp) [Python](./Python/power-of-three.py) | _O(1)_ | _O(1)_ | Easy ||| ## Sort # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 2ec57ec60e2d13e014836ab0a349fe5e2dc3f11b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Jan 2016 13:02:30 +0800 Subject: [PATCH 1588/1939] Update power-of-three.cpp --- C++/power-of-three.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/C++/power-of-three.cpp b/C++/power-of-three.cpp index 743b0dadf..05f4c0e69 100644 --- a/C++/power-of-three.cpp +++ b/C++/power-of-three.cpp @@ -7,8 +7,10 @@ class Solution { if (n <= 0) { return 0; } - - const int max_pow3 = log(numeric_limits::max()) / log(3); - return static_cast(pow(3, max_pow3)) % n == 0; + return max_pow3_ % n == 0; } + +private: + const int max_log3_ = log(numeric_limits::max()) / log(3); + const int max_pow3_ = pow(3, max_log3_); }; From 9058d915928b27e186b3221911cadfb53de24c02 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Jan 2016 13:03:07 +0800 Subject: [PATCH 1589/1939] Update power-of-three.cpp --- C++/power-of-three.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/C++/power-of-three.cpp b/C++/power-of-three.cpp index 05f4c0e69..0560c3a5a 100644 --- a/C++/power-of-three.cpp +++ b/C++/power-of-three.cpp @@ -4,10 +4,7 @@ class Solution { public: bool isPowerOfThree(int n) { - if (n <= 0) { - return 0; - } - return max_pow3_ % n == 0; + return n > 0 && max_pow3_ % n == 0; } private: From 2900dd8193d98c94da4cff71df78617135eebc38 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Jan 2016 13:14:44 +0800 Subject: [PATCH 1590/1939] Update coin-change.py --- Python/coin-change.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/coin-change.py b/Python/coin-change.py index d575a3a76..cd1b46389 100644 --- a/Python/coin-change.py +++ b/Python/coin-change.py @@ -26,7 +26,7 @@ def coinChange(self, coins, amount): :type amount: int :rtype: int """ - INF = 0x7ffffffe # Using float("int") would be slower. + INF = 0x7fffffff # Using float("int") would be slower. amounts = [INF] * (amount + 1) amounts[0] = 0 for i in xrange(amount + 1): From 6838abefa07d2905c4506fc5c6d9f15e10ed02c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Jan 2016 13:17:29 +0800 Subject: [PATCH 1591/1939] Update power-of-three.py --- Python/power-of-three.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Python/power-of-three.py b/Python/power-of-three.py index 5c458c5cd..182c44b9f 100644 --- a/Python/power-of-three.py +++ b/Python/power-of-three.py @@ -9,9 +9,13 @@ # class Solution(object): + def __init__(self): + self.__max_log3 = int(math.log(0x7fffffff) / math.log(3)) + self.__max_pow3 = 3 ** self.__max_log3 + def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ - return n > 0 and 3**19 % n == 0 + return n > 0 and self.__max_pow3 % n == 0 From 80e6a03a20cc0656992b38032002c2fce0853f13 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Jan 2016 13:18:36 +0800 Subject: [PATCH 1592/1939] Update coin-change.py --- Python/coin-change.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/coin-change.py b/Python/coin-change.py index cd1b46389..f762c382a 100644 --- a/Python/coin-change.py +++ b/Python/coin-change.py @@ -26,7 +26,7 @@ def coinChange(self, coins, amount): :type amount: int :rtype: int """ - INF = 0x7fffffff # Using float("int") would be slower. + INF = 0x7fffffff # Using float("inf") would be slower. amounts = [INF] * (amount + 1) amounts[0] = 0 for i in xrange(amount + 1): From 45b32a02965f2151829a74424c4f4a7cbbd3700d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Jan 2016 13:41:45 +0800 Subject: [PATCH 1593/1939] Update power-of-three.cpp --- C++/power-of-three.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/C++/power-of-three.cpp b/C++/power-of-three.cpp index 0560c3a5a..73f196331 100644 --- a/C++/power-of-three.cpp +++ b/C++/power-of-three.cpp @@ -3,11 +3,10 @@ class Solution { public: + static const int max_log3 = log(numeric_limits::max()) / log(3); + static const int max_pow3 = pow(3, max_log3); + bool isPowerOfThree(int n) { - return n > 0 && max_pow3_ % n == 0; + return n > 0 && max_pow3 % n == 0; } - -private: - const int max_log3_ = log(numeric_limits::max()) / log(3); - const int max_pow3_ = pow(3, max_log3_); }; From 92a45d2ee475644374d078303585f1f9d2c20bbf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jan 2016 15:51:27 +0800 Subject: [PATCH 1594/1939] Create count-of-range-sum.cpp --- C++/count-of-range-sum.cpp | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/count-of-range-sum.cpp diff --git a/C++/count-of-range-sum.cpp b/C++/count-of-range-sum.cpp new file mode 100644 index 000000000..f73aee46f --- /dev/null +++ b/C++/count-of-range-sum.cpp @@ -0,0 +1,44 @@ +// Time: O(nlogn) +// Space: O(n) + +// Divide and Conquer solution. +class Solution { +public: + int countRangeSum(vector& nums, int lower, int upper) { + vector sums(nums.size() + 1); + for (int i = 0; i < nums.size(); ++i) { + sums[i + 1] = sums[i] + nums[i]; + } + return countAndMergeSort(&sums, 0, sums.size(), lower, upper); + } + + int countAndMergeSort(vector *sums, int start, int end, int lower, int upper) { + if (end - start <= 1) { // The size of range [start, end) less than 2 is always with count 0. + return 0; + } + int mid = start + (end - start) / 2; + int count = countAndMergeSort(sums, start, mid, lower, upper) + + countAndMergeSort(sums, mid, end, lower, upper); + int j = mid, k = mid, r = mid; + vector tmp; + for (int i = start; i < mid; ++i) { + // Count the number of range sums that lie in [lower, upper]. + while (k < end && (*sums)[k] - (*sums)[i] < lower) { + ++k; + } + while (j < end && (*sums)[j] - (*sums)[i] <= upper) { + ++j; + } + count += j - k; + + // Merge the two sorted arrays into tmp. + while (r < end && (*sums)[r] < (*sums)[i]) { + tmp.emplace_back((*sums)[r++]); + } + tmp.emplace_back((*sums)[i]); + } + // Copy tmp back to sums. + copy(tmp.begin(), tmp.end(), sums->begin() + start); + return count; + } +}; From 6873eac86a25de1942e9323ca1532de1fe7a0506 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jan 2016 15:53:34 +0800 Subject: [PATCH 1595/1939] Update count-of-range-sum.cpp --- C++/count-of-range-sum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-of-range-sum.cpp b/C++/count-of-range-sum.cpp index f73aee46f..ab480f5c9 100644 --- a/C++/count-of-range-sum.cpp +++ b/C++/count-of-range-sum.cpp @@ -13,7 +13,7 @@ class Solution { } int countAndMergeSort(vector *sums, int start, int end, int lower, int upper) { - if (end - start <= 1) { // The size of range [start, end) less than 2 is always with count 0. + if (end - start <= 1) { // The number of range [start, end) of which size is less than 2 is always 0. return 0; } int mid = start + (end - start) / 2; From 54680d65f91d0b739bf16835272ab050c8f49999 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jan 2016 16:14:15 +0800 Subject: [PATCH 1596/1939] Create count-of-range-sum.py --- Python/count-of-range-sum.py | 55 ++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/count-of-range-sum.py diff --git a/Python/count-of-range-sum.py b/Python/count-of-range-sum.py new file mode 100644 index 000000000..9148eb9cd --- /dev/null +++ b/Python/count-of-range-sum.py @@ -0,0 +1,55 @@ +# Time: O(nlogn) +# Space: O(n) + +# 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(n^2) 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. + +# Divide and Conquer solution. +class Solution(object): + def countRangeSum(self, nums, lower, upper): + """ + :type nums: List[int] + :type lower: int + :type upper: int + :rtype: int + """ + def countAndMergeSort(sums, start, end, lower, upper): + if end - start <= 1: # The size of range [start, end) less than 2 is always with count 0. + return 0 + mid = start + (end - start) / 2 + count = countAndMergeSort(sums, start, mid, lower, upper) + \ + countAndMergeSort(sums, mid, end, lower, upper); + j, k, r = mid, mid, mid + tmp = [] + for i in xrange(start, mid): + # Count the number of range sums that lie in [lower, upper]. + while k < end and sums[k] - sums[i] < lower: + k += 1 + while j < end and sums[j] - sums[i] <= upper: + j += 1 + count += j - k + + # Merge the two sorted arrays into tmp. + while r < end and sums[r] < sums[i]: + tmp.append(sums[r]) + r += 1 + tmp.append(sums[i]) + # Copy tmp back to sums. + sums[start:start+len(tmp)] = tmp + return count + + sums = [0] * (len(nums) + 1) + for i in xrange(len(nums)): + sums[i + 1] = sums[i] + nums[i] + return countAndMergeSort(sums, 0, len(sums), lower, upper); From 821df70824fbe37f50abfea986eb7cb2ef339d03 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jan 2016 16:17:34 +0800 Subject: [PATCH 1597/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ab54a2fdf..4e4c1f0b8 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-326%20%2F%20326-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-327%20%2F%20327-ff69b4.svg) -Up to date (2016-01-08), there are `309` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-01-08), there are `310` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `326` questions. +Here is the classification of all `327` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -293,6 +293,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 156| [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | [Python](./Python/binary-tree-upside-down.py) | _O(n)_ | _O(1)_ | Medium |📖| 241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n * 4^n / n^(3/2))_ | Medium || 298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) | [C++](./C++/binary-tree-longest-consecutive-sequence.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence.py) | _O(n)_ | _O(h)_ | Medium |📖| +327| [Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./C++/count-of-range-sum.cpp) [Python](./Python/count-of-range-sum.py) | _O(nlogn)_ | _O(n)_ | Hard || ## Binary Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 5e9c4689dc3d5680b466b6eccf99a46101d2f5d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jan 2016 16:34:25 +0800 Subject: [PATCH 1598/1939] Update count-of-range-sum.py --- Python/count-of-range-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/count-of-range-sum.py b/Python/count-of-range-sum.py index 9148eb9cd..15980e86e 100644 --- a/Python/count-of-range-sum.py +++ b/Python/count-of-range-sum.py @@ -52,4 +52,4 @@ def countAndMergeSort(sums, start, end, lower, upper): sums = [0] * (len(nums) + 1) for i in xrange(len(nums)): sums[i + 1] = sums[i] + nums[i] - return countAndMergeSort(sums, 0, len(sums), lower, upper); + return countAndMergeSort(sums, 0, len(sums), lower, upper) From 9da34b847255be221bd66d0c57a98d5ba0565fa2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jan 2016 16:48:52 +0800 Subject: [PATCH 1599/1939] Update count-of-range-sum.py --- Python/count-of-range-sum.py | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/Python/count-of-range-sum.py b/Python/count-of-range-sum.py index 15980e86e..3b2becd41 100644 --- a/Python/count-of-range-sum.py +++ b/Python/count-of-range-sum.py @@ -53,3 +53,45 @@ def countAndMergeSort(sums, start, end, lower, upper): for i in xrange(len(nums)): sums[i + 1] = sums[i] + nums[i] return countAndMergeSort(sums, 0, len(sums), lower, upper) + + +# Divide and Conquer solution. +class Solution2(object): + def countRangeSum(self, nums, lower, upper): + """ + :type nums: List[int] + :type lower: int + :type upper: int + :rtype: int + """ + def countAndMergeSort(sums, start, end, lower, upper): + if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0. + return 0 + + mid = start + (end - start) / 2 + count = countAndMergeSort(sums, start, mid, lower, upper) + \ + countAndMergeSort(sums, mid + 1, end, lower, upper); + j, k, r = mid + 1, mid + 1, mid + 1 + tmp = [] + for i in xrange(start, mid + 1): + # Count the number of range sums that lie in [lower, upper]. + while k <= end and sums[k] - sums[i] < lower: + k += 1 + while j <= end and sums[j] - sums[i] <= upper: + j += 1 + count += j - k + + # Merge the two sorted arrays into tmp. + while r <= end and sums[r] < sums[i]: + tmp.append(sums[r]) + r += 1 + tmp.append(sums[i]) + + # Copy tmp back to sums + sums[start:start+len(tmp)] = tmp + return count + + sums = [0] * (len(nums) + 1) + for i in xrange(len(nums)): + sums[i + 1] = sums[i] + nums[i] + return countAndMergeSort(sums, 0, len(sums) - 1, lower, upper); From 6bbe9564a1127c5ceec0864900420590ccf4af33 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jan 2016 16:51:02 +0800 Subject: [PATCH 1600/1939] Update count-of-range-sum.cpp --- C++/count-of-range-sum.cpp | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/C++/count-of-range-sum.cpp b/C++/count-of-range-sum.cpp index ab480f5c9..15e48abef 100644 --- a/C++/count-of-range-sum.cpp +++ b/C++/count-of-range-sum.cpp @@ -42,3 +42,45 @@ class Solution { return count; } }; + +// Divide and Conquer solution. +class Solution2 { +public: + int countRangeSum(vector& nums, int lower, int upper) { + vector sums(nums.size() + 1); + for (int i = 0; i < nums.size(); ++i) { + sums[i + 1] = sums[i] + nums[i]; + } + return countAndMergeSort(&sums, 0, sums.size() - 1, lower, upper); + } + + int countAndMergeSort(vector *sums, int start, int end, int lower, int upper) { + if (end - start <= 0) { // The number of range [start, end] of which size is less than 2 is always 0. + return 0; + } + int mid = start + (end - start) / 2; + int count = countAndMergeSort(sums, start, mid, lower, upper) + + countAndMergeSort(sums, mid + 1, end, lower, upper); + int j = mid + 1, k = mid + 1, r = mid + 1; + vector tmp; + for (int i = start; i <= mid; ++i) { + // Count the number of range sums that lie in [lower, upper]. + while (k <= end && (*sums)[k] - (*sums)[i] < lower) { + ++k; + } + while (j <= end && (*sums)[j] - (*sums)[i] <= upper) { + ++j; + } + count += j - k; + + // Merge the two sorted arrays into tmp. + while (r <= end && (*sums)[r] < (*sums)[i]) { + tmp.emplace_back((*sums)[r++]); + } + tmp.emplace_back((*sums)[i]); + } + // Copy tmp back to sums. + copy(tmp.begin(), tmp.end(), sums->begin() + start); + return count; + } +}; From 6b283649ae8ec020076b4546c367c7bcab2551e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jan 2016 07:32:04 +0800 Subject: [PATCH 1601/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index 5e3bf5d5e..13d3083eb 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -122,3 +122,41 @@ class Solution2 { return i & -i; } }; + +// Time: O(nlogn) +// Space: O(n) +// Divide and Conquer solution. (80ms) +class Solution { +public: + vector countSmaller(vector& nums) { + vector counts(nums.size()); + vector> num_idxs; + for (int i = 0; i < nums.size(); ++i) { + num_idxs.emplace_back(nums[i], i); + } + countAndMergeSort(&num_idxs, 0, num_idxs.size() - 1, &counts); + return counts; + } + + void countAndMergeSort(vector> *num_idxs, int start, int end, vector *counts) { + if (end - start <= 0) { // The number of range [start, end] of which size is less than 2 doesn't need sort. + return; + } + int mid = start + (end - start) / 2; + countAndMergeSort(num_idxs, start, mid, counts); + countAndMergeSort(num_idxs, mid + 1, end, counts); + + int j = mid + 1, k = mid + 1, r = mid + 1; + vector> tmp; + for (int i = start; i <= mid; ++i) { + // Merge the two sorted arrays into tmp. + while (r <= end && (*num_idxs)[r].first < (*num_idxs)[i].first) { + tmp.emplace_back((*num_idxs)[r++]); + } + tmp.emplace_back((*num_idxs)[i]); + (*counts)[(*num_idxs)[i].second] += r - (mid + 1); + } + // Copy tmp back to num_idxs. + copy(tmp.begin(), tmp.end(), num_idxs->begin() + start); + } +}; From 1f391b669d80fa6562197d80faff9390578e53fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jan 2016 07:32:30 +0800 Subject: [PATCH 1602/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index 13d3083eb..8104004af 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -126,7 +126,7 @@ class Solution2 { // Time: O(nlogn) // Space: O(n) // Divide and Conquer solution. (80ms) -class Solution { +class Solution3 { public: vector countSmaller(vector& nums) { vector counts(nums.size()); From 7d4a50468edb1fd40bce079025449b2b93bff10f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jan 2016 07:40:26 +0800 Subject: [PATCH 1603/1939] Update count-of-smaller-numbers-after-self.cpp --- C++/count-of-smaller-numbers-after-self.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-of-smaller-numbers-after-self.cpp b/C++/count-of-smaller-numbers-after-self.cpp index 8104004af..dcfe10ed2 100644 --- a/C++/count-of-smaller-numbers-after-self.cpp +++ b/C++/count-of-smaller-numbers-after-self.cpp @@ -146,7 +146,7 @@ class Solution3 { countAndMergeSort(num_idxs, start, mid, counts); countAndMergeSort(num_idxs, mid + 1, end, counts); - int j = mid + 1, k = mid + 1, r = mid + 1; + int r = mid + 1; vector> tmp; for (int i = start; i <= mid; ++i) { // Merge the two sorted arrays into tmp. From c08038f3a8a45191cafec35823a0be22d51e0c37 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jan 2016 08:10:06 +0800 Subject: [PATCH 1604/1939] Update count-of-range-sum.py --- Python/count-of-range-sum.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/count-of-range-sum.py b/Python/count-of-range-sum.py index 3b2becd41..5c99bea69 100644 --- a/Python/count-of-range-sum.py +++ b/Python/count-of-range-sum.py @@ -70,7 +70,7 @@ def countAndMergeSort(sums, start, end, lower, upper): mid = start + (end - start) / 2 count = countAndMergeSort(sums, start, mid, lower, upper) + \ - countAndMergeSort(sums, mid + 1, end, lower, upper); + countAndMergeSort(sums, mid + 1, end, lower, upper) j, k, r = mid + 1, mid + 1, mid + 1 tmp = [] for i in xrange(start, mid + 1): @@ -94,4 +94,4 @@ def countAndMergeSort(sums, start, end, lower, upper): sums = [0] * (len(nums) + 1) for i in xrange(len(nums)): sums[i + 1] = sums[i] + nums[i] - return countAndMergeSort(sums, 0, len(sums) - 1, lower, upper); + return countAndMergeSort(sums, 0, len(sums) - 1, lower, upper) From 3c195c6380f765b8084cee1a3ef7a1f9727e019c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jan 2016 08:10:24 +0800 Subject: [PATCH 1605/1939] Update count-of-range-sum.py --- Python/count-of-range-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/count-of-range-sum.py b/Python/count-of-range-sum.py index 5c99bea69..eb87af804 100644 --- a/Python/count-of-range-sum.py +++ b/Python/count-of-range-sum.py @@ -29,7 +29,7 @@ def countAndMergeSort(sums, start, end, lower, upper): return 0 mid = start + (end - start) / 2 count = countAndMergeSort(sums, start, mid, lower, upper) + \ - countAndMergeSort(sums, mid, end, lower, upper); + countAndMergeSort(sums, mid, end, lower, upper) j, k, r = mid, mid, mid tmp = [] for i in xrange(start, mid): From 24b0d540156887a8fabaf6dcd81ee864fe099eef Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jan 2016 08:17:57 +0800 Subject: [PATCH 1606/1939] Update count-of-smaller-numbers-after-self.py --- Python/count-of-smaller-numbers-after-self.py | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/Python/count-of-smaller-numbers-after-self.py b/Python/count-of-smaller-numbers-after-self.py index e1061fbd9..971e78c32 100644 --- a/Python/count-of-smaller-numbers-after-self.py +++ b/Python/count-of-smaller-numbers-after-self.py @@ -16,8 +16,44 @@ # To the right of 1 there is 0 smaller element. # Return the array [2, 1, 1, 0]. -# BIT solution. +# Divide and Conquer solution. class Solution(object): + def countSmaller(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + def countAndMergeSort(sums, start, end, counts): + if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0. + return 0 + + mid = start + (end - start) / 2 + countAndMergeSort(num_idxs, start, mid, counts) + countAndMergeSort(num_idxs, mid + 1, end, counts) + r = mid + 1 + tmp = [] + for i in xrange(start, mid + 1): + # Merge the two sorted arrays into tmp. + while r <= end and num_idxs[r][0] < num_idxs[i][0]: + tmp.append(num_idxs[r]) + r += 1 + tmp.append(num_idxs[i]) + counts[num_idxs[i][1]] += r - (mid + 1) + + # Copy tmp back to num_idxs + num_idxs[start:start+len(tmp)] = tmp + + num_idxs = [] + counts = [0] * len(nums) + for i, num in enumerate(nums): + num_idxs.append((num, i)) + countAndMergeSort(num_idxs, 0, len(num_idxs) - 1, counts) + return counts + +# Time: O(nlogn) +# Space: O(n) +# BIT solution. +class Solution2(object): def countSmaller(self, nums): """ :type nums: List[int] @@ -64,7 +100,7 @@ def query(self, i): # Time: O(nlogn) # Space: O(n) # BST solution. -class Solution2(object): +class Solution3(object): def countSmaller(self, nums): """ :type nums: List[int] From 107b7f80679b81cd199c644111fafc492f085f4e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jan 2016 08:18:40 +0800 Subject: [PATCH 1607/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4e4c1f0b8..176124e76 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT -315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT | +315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | ## Hash Table # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 9b7cc05c257110e7e0cea052f347ea36b54503ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jan 2016 08:21:13 +0800 Subject: [PATCH 1608/1939] Update count-of-smaller-numbers-after-self.py --- Python/count-of-smaller-numbers-after-self.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/count-of-smaller-numbers-after-self.py b/Python/count-of-smaller-numbers-after-self.py index 971e78c32..7011fa583 100644 --- a/Python/count-of-smaller-numbers-after-self.py +++ b/Python/count-of-smaller-numbers-after-self.py @@ -23,7 +23,7 @@ def countSmaller(self, nums): :type nums: List[int] :rtype: List[int] """ - def countAndMergeSort(sums, start, end, counts): + def countAndMergeSort(num_idxs, start, end, counts): if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0. return 0 From 9ea70a874b3a4b037235aeb462af8581acf75af3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jan 2016 09:22:23 +0800 Subject: [PATCH 1609/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 176124e76..83ef6e794 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-327%20%2F%20327-ff69b4.svg) -Up to date (2016-01-08), there are `310` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-01-10), there are `310` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `327` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From df382fd5db826338f323575d3449439b16f99cd1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Jan 2016 23:03:46 +0800 Subject: [PATCH 1610/1939] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 66af2e6d7..24b51a481 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -23,7 +23,7 @@ def getKth(self, A, B, k): while left < right: mid = left + (right - left) / 2 j = k - 1 - mid - if 0 <= j and j < n and A[mid] >= B[j]: + if 0 <= j < n and A[mid] >= B[j]: right = mid else: left = mid + 1 From 09e522f5b35215b7633c4bcba960b955069c4d4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Jan 2016 16:38:57 +0800 Subject: [PATCH 1611/1939] Update and rename findMedianSortedArrays.cpp to median-of-two-sorted-arrays.cpp --- C++/findMedianSortedArrays.cpp | 33 ---------------------- C++/median-of-two-sorted-arrays.cpp | 44 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 33 deletions(-) delete mode 100644 C++/findMedianSortedArrays.cpp create mode 100644 C++/median-of-two-sorted-arrays.cpp diff --git a/C++/findMedianSortedArrays.cpp b/C++/findMedianSortedArrays.cpp deleted file mode 100644 index d48822f66..000000000 --- a/C++/findMedianSortedArrays.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// LeetCode, Median of Two Sorted Arrays -// Complexity: -// O(log(m+n)) -// O(log(m+n)) - -class Solution { -public: - double findMedianSortedArrays(int A[], int m, int B[], int n) { - int total = m + n; - if (total & 0x1) - return find_kth(A, m, B, n, total / 2 + 1); - else - return (find_kth(A, m, B, n, total / 2) - + find_kth(A, m, B, n, total / 2 + 1)) / 2.0; - } - -private: - static int find_kth(int A[], int m, int B[], int n, int k) { - //always assume that m is equal or smaller than n - if (m > n) return find_kth(B, n, A, m, k); - if (m == 0) return B[k - 1]; - if (k == 1) return min(A[0], B[0]); - - //divide k into two parts - int ia = min(k / 2, m), ib = k - ia; - if (A[ia - 1] < B[ib - 1]) - return find_kth(A + ia, m - ia, B, n, k - ia); - else if (A[ia - 1] > B[ib - 1]) - return find_kth(A, m, B + ib, n - ib, k - ib); - else - return A[ia - 1]; - } -}; \ No newline at end of file diff --git a/C++/median-of-two-sorted-arrays.cpp b/C++/median-of-two-sorted-arrays.cpp new file mode 100644 index 000000000..654b4c540 --- /dev/null +++ b/C++/median-of-two-sorted-arrays.cpp @@ -0,0 +1,44 @@ +// Time: O(log(min(m, n))) +// Space: O(1) + +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + if ((nums1.size() + nums2.size()) % 2 == 1) { + return findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1); + } else { + return (findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2) + + findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0; + } + } + + int findKthInTwoSortedArrays(const vector& A, const vector& B, + int k) { + int m = A.size(); + int n = B.size(); + + // Make sure m is the smaller one. + if (m > n) { + return findKthInTwoSortedArrays(B, A, k); + } + + int left = 0; + int right = m; + // Find a partition of A and B + // where min left s.t. A[left] >= B[k - 1 - left]. Thus left is the (k + 1)-th element. + while (left < right) { + int mid = left + (right - left) / 2; + if (0 <= k - 1 - mid && k - 1 - mid < n && A[mid] >= B[k - 1 - mid]) { + right = mid; + } else { + left = mid + 1; + } + } + + int Ai_minus_1 = left - 1 >= 0 ? A[left - 1] : numeric_limits::min(); + int Bj = k - 1 - left >= 0 ? B[k - 1 - left] : numeric_limits::min(); + + // kth element would be A[left - 1] or B[k - 1 - left]. + return max(Ai_minus_1, Bj); + } +}; From 22d1f618c1355d0f0738d49bb612cd8c1cba91f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Jan 2016 16:39:56 +0800 Subject: [PATCH 1612/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 83ef6e794..67fdffd15 100644 --- a/README.md +++ b/README.md @@ -298,7 +298,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Binary Search # | Problem | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(min(m, n)))_ | _O(1)_ | Hard || +4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [C++](./C++/median-of-two-sorted-arrays.cpp) [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(min(m, n)))_ | _O(1)_ | Hard || 33| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || 34| [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || 35| [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || From a12ff8747e15afcd6ca8c1f88eb12afa73b469a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Jan 2016 16:40:58 +0800 Subject: [PATCH 1613/1939] Update median-of-two-sorted-arrays.cpp --- C++/median-of-two-sorted-arrays.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/median-of-two-sorted-arrays.cpp b/C++/median-of-two-sorted-arrays.cpp index 654b4c540..9bbd45091 100644 --- a/C++/median-of-two-sorted-arrays.cpp +++ b/C++/median-of-two-sorted-arrays.cpp @@ -14,8 +14,8 @@ class Solution { int findKthInTwoSortedArrays(const vector& A, const vector& B, int k) { - int m = A.size(); - int n = B.size(); + const int m = A.size(); + const int n = B.size(); // Make sure m is the smaller one. if (m > n) { From 51c3b212e9d5126e4f9f5c3982256c086da85cac Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Jan 2016 23:08:24 +0800 Subject: [PATCH 1614/1939] Update and rename removeDuplicates.cpp to remove-duplicates-from-sorted-array.cpp --- C++/remove-duplicates-from-sorted-array.cpp | 16 ++++++++++++++++ C++/removeDuplicates.cpp | 19 ------------------- 2 files changed, 16 insertions(+), 19 deletions(-) create mode 100644 C++/remove-duplicates-from-sorted-array.cpp delete mode 100644 C++/removeDuplicates.cpp diff --git a/C++/remove-duplicates-from-sorted-array.cpp b/C++/remove-duplicates-from-sorted-array.cpp new file mode 100644 index 000000000..1193aade5 --- /dev/null +++ b/C++/remove-duplicates-from-sorted-array.cpp @@ -0,0 +1,16 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int removeDuplicates(vector& nums) { + int last = -1; + for (const auto& num : nums) { + if (last == -1 || nums[last] != num) { + nums[++last] = num; + } + } + + return last + 1; + } +}; diff --git a/C++/removeDuplicates.cpp b/C++/removeDuplicates.cpp deleted file mode 100644 index f059dfe4c..000000000 --- a/C++/removeDuplicates.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - int removeDuplicates(int A[], int n) { - const int occur = 2; - if(n <= occur) return n; - - int cnt = occur; - - for(int i = occur; i < n; ++i) { - if(A[i] != A[cnt - occur]) - A[cnt++] = A[i]; - } - - return cnt; - } -}; From 4a7eea3d5ef62556330065073ac0fd1336bd7e43 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Jan 2016 23:08:38 +0800 Subject: [PATCH 1615/1939] Update remove-duplicates-from-sorted-array.cpp --- C++/remove-duplicates-from-sorted-array.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/remove-duplicates-from-sorted-array.cpp b/C++/remove-duplicates-from-sorted-array.cpp index 1193aade5..0d8a71832 100644 --- a/C++/remove-duplicates-from-sorted-array.cpp +++ b/C++/remove-duplicates-from-sorted-array.cpp @@ -10,7 +10,6 @@ class Solution { nums[++last] = num; } } - return last + 1; } }; From 5b1f0dc81bc08b643c537fc38917166a45d17b5b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Jan 2016 23:09:22 +0800 Subject: [PATCH 1616/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 67fdffd15..d375789e1 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || 16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [C++](./C++/3sum-closest.cpp) [Python](./Python/3sum-closest.py) | _O(n^2)_ | _O(1)_ | Medium || -26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp) [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky From 9c93d163c7dad123d4042a08cf0f43963abdaa3b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Jan 2016 17:50:01 +0800 Subject: [PATCH 1617/1939] Create remove-element.cpp --- C++/remove-element.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/remove-element.cpp diff --git a/C++/remove-element.cpp b/C++/remove-element.cpp new file mode 100644 index 000000000..522d6af4b --- /dev/null +++ b/C++/remove-element.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int removeElement(vector& nums, int val) { + int left = 0, right = nums.size(); + while (left < right) { + if (nums[left] != val) { + ++left; + } else { + swap(nums[left], nums[--right]); + } + } + return right; + } +}; From 2425ed2ce1793133b4acf565259456e958fd7d0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Jan 2016 17:50:36 +0800 Subject: [PATCH 1618/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d375789e1..c402bf98d 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || 16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [C++](./C++/3sum-closest.cpp) [Python](./Python/3sum-closest.py) | _O(n^2)_ | _O(1)_ | Medium || 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp) [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || -27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || +27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C++](./C++/remove-element.cpp) [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || From 82334c7dfeb7b845cfcc94027775c07179e64673 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Jan 2016 14:32:28 +0800 Subject: [PATCH 1619/1939] Create odd-even-linked-list.cpp --- C++/odd-even-linked-list.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/odd-even-linked-list.cpp diff --git a/C++/odd-even-linked-list.cpp b/C++/odd-even-linked-list.cpp new file mode 100644 index 000000000..0f3adc5ca --- /dev/null +++ b/C++/odd-even-linked-list.cpp @@ -0,0 +1,29 @@ +// Time: O(n) +// Space: O(1) + +/** + * 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) { + for (ListNode *odd_tail = head, *cur = odd_tail->next; + cur && cur->next; + cur = cur->next) { + + ListNode *even_head = odd_tail->next; + odd_tail->next = cur->next; + odd_tail = odd_tail->next; + cur->next = cur->next->next; + odd_tail->next = even_head; + } + } + return head; + } +}; From e0f04ba104144bc4a92bb04f27d8c7cb928a83c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Jan 2016 14:34:23 +0800 Subject: [PATCH 1620/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c402bf98d..7818e1a4d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-327%20%2F%20327-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-328%20%2F%20328-ff69b4.svg) -Up to date (2016-01-10), there are `310` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-01-16), there are `311` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `327` questions. +Here is the classification of all `328` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -134,6 +134,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 237| [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./C++/delete-node-in-a-linked-list.cpp) [Python](./Python/delete-node-in-a-linked-list.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 242| [Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./C++/valid-anagram.cpp) [Python](./Python/valid-anagram.py) | _O(n)_ | _O(1)_ | Easy | LintCode | +328| [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/)| [C++](./C++/odd-even-linked-list.cpp) [Python](./Python/odd-even-linked-list.py) | _O(n)_ | _O(1)_ | Easy | | ## Stack # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 9da39d8f4d64b9fe197769c97271019466ee8325 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Jan 2016 14:35:53 +0800 Subject: [PATCH 1621/1939] Update odd-even-linked-list.cpp --- C++/odd-even-linked-list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/odd-even-linked-list.cpp b/C++/odd-even-linked-list.cpp index 0f3adc5ca..53758495d 100644 --- a/C++/odd-even-linked-list.cpp +++ b/C++/odd-even-linked-list.cpp @@ -13,7 +13,7 @@ class Solution { public: ListNode* oddEvenList(ListNode* head) { if (head) { - for (ListNode *odd_tail = head, *cur = odd_tail->next; + for (ListNode *odd_tail = head, *cur = head->next; cur && cur->next; cur = cur->next) { From 9c696d4ee26534684f1cd7ee91d0eaeb45645507 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Jan 2016 14:43:51 +0800 Subject: [PATCH 1622/1939] Update odd-even-linked-list.cpp --- C++/odd-even-linked-list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/odd-even-linked-list.cpp b/C++/odd-even-linked-list.cpp index 53758495d..4eb5e8fca 100644 --- a/C++/odd-even-linked-list.cpp +++ b/C++/odd-even-linked-list.cpp @@ -20,7 +20,7 @@ class Solution { ListNode *even_head = odd_tail->next; odd_tail->next = cur->next; odd_tail = odd_tail->next; - cur->next = cur->next->next; + cur->next = odd_tail->next; odd_tail->next = even_head; } } From f27740e5cda4f5c30df6dd220ae09711bc423913 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Jan 2016 14:46:50 +0800 Subject: [PATCH 1623/1939] Create odd-even-linked-list.py --- Python/odd-even-linked-list.py | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/odd-even-linked-list.py diff --git a/Python/odd-even-linked-list.py b/Python/odd-even-linked-list.py new file mode 100644 index 000000000..457c48ac3 --- /dev/null +++ b/Python/odd-even-linked-list.py @@ -0,0 +1,43 @@ +# Time: O(n) +# Space: O(1) + +# 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 ... + +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def oddEvenList(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + if head: + odd_tail, cur = head, head.next + while cur and cur.next: + even_head = odd_tail.next + odd_tail.next = cur.next + odd_tail = odd_tail.next + cur.next = odd_tail.next + odd_tail.next = even_head + cur = cur.next + return head From 8d441402326e3d93fa2c8d7567a4689f1a700e35 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Jan 2016 16:20:29 +0800 Subject: [PATCH 1624/1939] Update odd-even-linked-list.cpp --- C++/odd-even-linked-list.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/odd-even-linked-list.cpp b/C++/odd-even-linked-list.cpp index 4eb5e8fca..4c6efad0a 100644 --- a/C++/odd-even-linked-list.cpp +++ b/C++/odd-even-linked-list.cpp @@ -16,7 +16,6 @@ class Solution { for (ListNode *odd_tail = head, *cur = head->next; cur && cur->next; cur = cur->next) { - ListNode *even_head = odd_tail->next; odd_tail->next = cur->next; odd_tail = odd_tail->next; From f1e4e6fd4186b392c9f27e9d74baef6a0a23fda6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jan 2016 20:31:56 +0800 Subject: [PATCH 1625/1939] Update plusOne.cpp --- C++/plusOne.cpp | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/C++/plusOne.cpp b/C++/plusOne.cpp index d158b2a77..78d484a18 100644 --- a/C++/plusOne.cpp +++ b/C++/plusOne.cpp @@ -1,21 +1,19 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) +// Time: O(n) +// Space: O(1) class Solution { - public: - vector plusOne(vector &digits) { - int c = 1; - - for(auto it = digits.rbegin(); it != digits.rend(); ++it) { - *it += c; - c = *it / 10; - *it %= 10; - } - - if(c > 0) { - digits.insert(digits.begin(), 1); - } - - return digits; +public: + vector plusOne(vector& digits) { + vector result(digits.cbegin(), digits.cend()); + int carry = 1; + for (auto it = result.rbegin(); it != result.rend(); ++it) { + *it += carry; + carry = *it / 10; + *it %= 10; + } + if (carry == 1) { + result.emplace(result.begin(), carry); } + return result; + } }; From 3cd1a39e7a88dd182a3c9db961d75dccfb8bf073 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jan 2016 20:32:47 +0800 Subject: [PATCH 1626/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7818e1a4d..b314cc60e 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [C++](./C++/spiral-matrix-ii.cpp) [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || -66 | [Plus One](https://leetcode.com/problems/plus-one/) | [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || +66 | [Plus One](https://leetcode.com/problems/plus-one/) | [C++](./C++/plus-one.cpp) [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || From 638373cb8cbafa334cc80849bf46d6bf4537b502 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jan 2016 20:33:22 +0800 Subject: [PATCH 1627/1939] Rename plusOne.cpp to plus-one.cpp --- C++/{plusOne.cpp => plus-one.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{plusOne.cpp => plus-one.cpp} (100%) diff --git a/C++/plusOne.cpp b/C++/plus-one.cpp similarity index 100% rename from C++/plusOne.cpp rename to C++/plus-one.cpp From 1b4ed70601937e2c30c54c851bbef280251d1ac6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Jan 2016 11:58:57 +0800 Subject: [PATCH 1628/1939] Update next-permutation.py --- Python/next-permutation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/next-permutation.py b/Python/next-permutation.py index f3aa730ba..48056e9c6 100644 --- a/Python/next-permutation.py +++ b/Python/next-permutation.py @@ -26,7 +26,7 @@ def nextPermutation(self, num): num.reverse() return - for i in xrange(len(num)): + for i in xrange(k + 1, len(num)): if num[i] > num[k]: l = i From 5cf3e36fd0270220a7b6d4b725bd68ea3cba4de0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Jan 2016 12:01:11 +0800 Subject: [PATCH 1629/1939] Update and rename nextPermutation.cpp to next-permutation.cpp --- C++/next-permutation.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ C++/nextPermutation.cpp | 37 ------------------------------------- 2 files changed, 40 insertions(+), 37 deletions(-) create mode 100644 C++/next-permutation.cpp delete mode 100644 C++/nextPermutation.cpp diff --git a/C++/next-permutation.cpp b/C++/next-permutation.cpp new file mode 100644 index 000000000..5586bcee3 --- /dev/null +++ b/C++/next-permutation.cpp @@ -0,0 +1,40 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + void nextPermutation(vector &num) { + nextPermutation(num.begin(), num.end()); + } + +private: + template + bool nextPermutation(BidiIt begin, BidiIt end) { + const auto rbegin = reverse_iterator(end); + const auto rend = reverse_iterator(begin); + + // Find the first element (pivot) which is less than its successor. + auto pivot = next(rbegin); + while (pivot != rend && *pivot >= *prev(pivot)) { + ++pivot; + } + + if (pivot != rend) { + // Find the number which is greater than pivot, and swap it with pivot + auto change = find_if(rbegin, pivot, bind1st(less(), *pivot)); + swap(*change, *pivot); + } + + // Make the sequence after pivot non-descending + reverse(rbegin, pivot); + + return true; + } +}; + +class Solution2 { +public: + void nextPermutation(vector &num) { + next_permutation(num.begin(), num.end()); + } +}; diff --git a/C++/nextPermutation.cpp b/C++/nextPermutation.cpp deleted file mode 100644 index 371f8b07c..000000000 --- a/C++/nextPermutation.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - void nextPermutation(vector &num) { - nextPermutation(begin(num), end(num)); - } - - private: - template - bool nextPermutation(BidiIt begin, BidiIt end) { - const auto rbegin = reverse_iterator(end); - const auto rend = reverse_iterator(begin); - - // find the firt element (pivot) which is less than its successor - auto pivot = next(rbegin); - while(pivot != rend && *pivot >= *prev(pivot)) { - ++pivot; - } - - // no next permutation, just reverse the whole sequence - if(pivot == rend) { - reverse(rbegin, rend); - return false; - } - - // find the number which is greater than pivot, and swap it with pivot - auto change = find_if(rbegin, pivot, bind1st(less(), *pivot)); - swap(*change, *pivot); - - // make the sequence after pivot non-descending - reverse(rbegin, pivot); - - return true; // return next permutation - } -}; From 0b4415e37deb75f522a9697626edcead1293bf06 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Jan 2016 12:01:48 +0800 Subject: [PATCH 1630/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b314cc60e..f45ec6a62 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [C++](./C++/3sum-closest.cpp) [Python](./Python/3sum-closest.py) | _O(n^2)_ | _O(1)_ | Medium || 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp) [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C++](./C++/remove-element.cpp) [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || -31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky +31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [C++](./C++/next-permutation.cpp) [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || From 2ffa8433ff4ab95a3625770e5011138fd1124bb0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Jan 2016 16:39:38 +0800 Subject: [PATCH 1631/1939] Update next-permutation.cpp --- C++/next-permutation.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/C++/next-permutation.cpp b/C++/next-permutation.cpp index 5586bcee3..a6f8a9e4b 100644 --- a/C++/next-permutation.cpp +++ b/C++/next-permutation.cpp @@ -18,17 +18,20 @@ class Solution { while (pivot != rend && *pivot >= *prev(pivot)) { ++pivot; } - + + bool is_greater = true; if (pivot != rend) { // Find the number which is greater than pivot, and swap it with pivot auto change = find_if(rbegin, pivot, bind1st(less(), *pivot)); swap(*change, *pivot); + } else { + is_greater = false; } // Make the sequence after pivot non-descending reverse(rbegin, pivot); - return true; + return is_greater; } }; From d493e7761c2a4e9079cfabe50b99bbcff0f0345a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jan 2016 13:57:23 +0800 Subject: [PATCH 1632/1939] Create longest-increasing-path-in-a-matrix.cpp --- C++/longest-increasing-path-in-a-matrix.cpp | 45 +++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/longest-increasing-path-in-a-matrix.cpp diff --git a/C++/longest-increasing-path-in-a-matrix.cpp b/C++/longest-increasing-path-in-a-matrix.cpp new file mode 100644 index 000000000..c45d9b810 --- /dev/null +++ b/C++/longest-increasing-path-in-a-matrix.cpp @@ -0,0 +1,45 @@ +// Time: O(m * n) +// Space: O(m * n) + +// DFS + Memorization solution. +class Solution { +public: + int longestIncreasingPath(vector>& matrix) { + if (matrix.empty()) { + return 0; + } + + int res = 0; + vector> states(matrix.size(), vector(matrix[0].size())); + for (int i = 0; i < matrix.size(); ++i) { + for (int j = 0; j < matrix[0].size(); ++j) { + res = max(res, longestpath(matrix, i, j, &states)); + } + } + + return res; + } + +private: + int longestpath(const vector>& matrix, const int i, const int j, + vector> *states) { + if ((*states)[i][j] > 0) { + return (*states)[i][j]; + } + + int max_depth = 0; + const vector> directions{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; + for (const auto& d : directions) { + const int x = i + d.first, y = j + d.second; + if (x >= 0 && x < matrix.size() && + y >= 0 && y < matrix[0].size() && + matrix[x][y] < matrix[i][j]) { + max_depth = max(max_depth, + longestpath(matrix, x, y, states)); + } + } + (*states)[i][j] = max_depth + 1; + return (*states)[i][j]; + } +}; From edf19667a8a4715e3927af07dd9cdda7784b1ca0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jan 2016 13:58:49 +0800 Subject: [PATCH 1633/1939] Update longest-increasing-path-in-a-matrix.cpp --- C++/longest-increasing-path-in-a-matrix.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/longest-increasing-path-in-a-matrix.cpp b/C++/longest-increasing-path-in-a-matrix.cpp index c45d9b810..c65de5c1b 100644 --- a/C++/longest-increasing-path-in-a-matrix.cpp +++ b/C++/longest-increasing-path-in-a-matrix.cpp @@ -10,10 +10,10 @@ class Solution { } int res = 0; - vector> states(matrix.size(), vector(matrix[0].size())); + vector> max_lengths(matrix.size(), vector(matrix[0].size())); for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[0].size(); ++j) { - res = max(res, longestpath(matrix, i, j, &states)); + res = max(res, longestpath(matrix, i, j, &max_lengths)); } } @@ -22,9 +22,9 @@ class Solution { private: int longestpath(const vector>& matrix, const int i, const int j, - vector> *states) { - if ((*states)[i][j] > 0) { - return (*states)[i][j]; + vector> *max_lengths) { + if ((*max_lengths)[i][j] > 0) { + return (*max_lengths)[i][j]; } int max_depth = 0; @@ -36,10 +36,10 @@ class Solution { y >= 0 && y < matrix[0].size() && matrix[x][y] < matrix[i][j]) { max_depth = max(max_depth, - longestpath(matrix, x, y, states)); + longestpath(matrix, x, y, max_lengths)); } } - (*states)[i][j] = max_depth + 1; - return (*states)[i][j]; + (*max_lengths)[i][j] = max_depth + 1; + return (*max_lengths)[i][j]; } }; From 0a157a6ad714d7f630ccb43c1a75916a1da84089 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jan 2016 14:02:24 +0800 Subject: [PATCH 1634/1939] Update longest-increasing-path-in-a-matrix.cpp --- C++/longest-increasing-path-in-a-matrix.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-increasing-path-in-a-matrix.cpp b/C++/longest-increasing-path-in-a-matrix.cpp index c65de5c1b..0bfda805f 100644 --- a/C++/longest-increasing-path-in-a-matrix.cpp +++ b/C++/longest-increasing-path-in-a-matrix.cpp @@ -13,7 +13,7 @@ class Solution { vector> max_lengths(matrix.size(), vector(matrix[0].size())); for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[0].size(); ++j) { - res = max(res, longestpath(matrix, i, j, &max_lengths)); + res = max(res, longestpath(matrix, i, j, &max_lengths)); } } From 15a103f204b0a28097a6628b85db2f172335b175 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jan 2016 14:11:26 +0800 Subject: [PATCH 1635/1939] Create longest-increasing-path-in-a-matrix.py --- Python/longest-increasing-path-in-a-matrix.py | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/longest-increasing-path-in-a-matrix.py diff --git a/Python/longest-increasing-path-in-a-matrix.py b/Python/longest-increasing-path-in-a-matrix.py new file mode 100644 index 000000000..f5685d3a7 --- /dev/null +++ b/Python/longest-increasing-path-in-a-matrix.py @@ -0,0 +1,60 @@ +# Time: O(m * n) +# Space: O(m * n) + +# 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. + +# DFS + Memorization solution. +class Solution(object): + def longestIncreasingPath(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: int + """ + if not matrix: + return 0 + + def longestpath(matrix, i, j, max_lengths): + if max_lengths[i][j]: + return max_lengths[i][j] + + max_depth = 0 + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + for d in directions: + x, y = i + d[0], j + d[1] + if 0 <= x < len(matrix) and 0 <= y < len(matrix[0]) and \ + matrix[x][y] < matrix[i][j]: + max_depth = max(max_depth, longestpath(matrix, x, y, max_lengths)); + max_lengths[i][j] = max_depth + 1 + return max_lengths[i][j] + + res = 0 + max_lengths = [[0 for _ in xrange(len(matrix[0]))] for _ in xrange(len(matrix))] + for i in xrange(len(matrix)): + for j in xrange(len(matrix[0])): + res = max(res, longestpath(matrix, i, j, max_lengths)) + + return res From 1d6c2e3df8df7aa33c8de2c18c22b62574bc13e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jan 2016 14:13:27 +0800 Subject: [PATCH 1636/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f45ec6a62..2507b86ff 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-328%20%2F%20328-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-329%20%2F%20329-ff69b4.svg) -Up to date (2016-01-16), there are `311` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-01-20), there are `312` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `328` questions. +Here is the classification of all `329` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -356,6 +356,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 257| [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | [C++](./C++/binary-tree-paths.cpp) [Python](./Python/binary-tree-paths.py) | _O(n * h)_ | _O(h)_ | Easy ||| 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| 301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(C(n, c))_ | _O(c)_ | Medium ||| +329| [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./C++/longest-increasing-path-in-a-matrix.cpp) [Python](./Python/longest-increasing-path-in-a-matrix.py) | _O(m * n)_ | _O(m * n)_ | Medium ||| ## Backtracking # | Problem | Solution | Time | Space | Difficulty | Tag | Note From 71684a3be9d126195aacc6ef7114e06eca8b7c13 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jan 2016 14:14:48 +0800 Subject: [PATCH 1637/1939] Update longest-increasing-path-in-a-matrix.cpp --- C++/longest-increasing-path-in-a-matrix.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/longest-increasing-path-in-a-matrix.cpp b/C++/longest-increasing-path-in-a-matrix.cpp index 0bfda805f..a6e09e1ca 100644 --- a/C++/longest-increasing-path-in-a-matrix.cpp +++ b/C++/longest-increasing-path-in-a-matrix.cpp @@ -39,6 +39,7 @@ class Solution { longestpath(matrix, x, y, max_lengths)); } } + (*max_lengths)[i][j] = max_depth + 1; return (*max_lengths)[i][j]; } From 5d3a39a14be4627b5787249844de6d53954901a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Jan 2016 20:21:34 +0800 Subject: [PATCH 1638/1939] Update firstMissingPositive.cpp --- C++/firstMissingPositive.cpp | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/C++/firstMissingPositive.cpp b/C++/firstMissingPositive.cpp index 2c82d651f..e5f939b64 100644 --- a/C++/firstMissingPositive.cpp +++ b/C++/firstMissingPositive.cpp @@ -1,21 +1,25 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) +// Time: O(n) +// Space: O(1) class Solution { - public: - int firstMissingPositive(int A[], int n) { - int i; - bucketSort(A, n); - for(i = 0; i < n && A[i] == i + 1; ++i); - return i + 1; - } +public: + int firstMissingPositive(vector& nums) { + int i; + bucketSort(&nums); + for (i = 0; i < nums.size() && nums[i] == i + 1; ++i); + return i + 1; + } - private: - void bucketSort(int A[], int n) { - for(int i = 0; i < n; ++i) { - for (; A[i] != i + 1 && A[i] > 0 && A[i] <= n && A[i] != A[A[i] - 1];) { - swap(A[i], A[A[i] - 1]); - } +private: + void bucketSort(vector *nums) { + int i = 0; + while (i < nums->size()) { + if ((*nums)[i] > 0 && (*nums)[i] <= nums->size() && + (*nums)[i] != (*nums)[(*nums)[i] - 1]) { + swap((*nums)[i], (*nums)[(*nums)[i] - 1]); + } else { + ++i; } } + } }; From 5079368d24921fef6e7e0de6f4539b98511e844a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Jan 2016 20:22:59 +0800 Subject: [PATCH 1639/1939] Update and rename firstMissingPositive.cpp to first-missing-positive.cpp --- C++/{firstMissingPositive.cpp => first-missing-positive.cpp} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename C++/{firstMissingPositive.cpp => first-missing-positive.cpp} (86%) diff --git a/C++/firstMissingPositive.cpp b/C++/first-missing-positive.cpp similarity index 86% rename from C++/firstMissingPositive.cpp rename to C++/first-missing-positive.cpp index e5f939b64..f896ad909 100644 --- a/C++/firstMissingPositive.cpp +++ b/C++/first-missing-positive.cpp @@ -4,9 +4,9 @@ class Solution { public: int firstMissingPositive(vector& nums) { - int i; + int i = 0; bucketSort(&nums); - for (i = 0; i < nums.size() && nums[i] == i + 1; ++i); + for (; i < nums.size() && nums[i] == i + 1; ++i); return i + 1; } From 1c9d2083a637f1993d86ac82b0538d5fd1b263ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Jan 2016 20:23:09 +0800 Subject: [PATCH 1640/1939] Update first-missing-positive.cpp --- C++/first-missing-positive.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/first-missing-positive.cpp b/C++/first-missing-positive.cpp index f896ad909..48112803e 100644 --- a/C++/first-missing-positive.cpp +++ b/C++/first-missing-positive.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(n) // Space: O(1) class Solution { From da379bf571c9f74f6b8502e8884ae46c5fb74250 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Jan 2016 20:24:25 +0800 Subject: [PATCH 1641/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2507b86ff..ae5b136d7 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp) [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C++](./C++/remove-element.cpp) [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [C++](./C++/next-permutation.cpp) [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky -41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky +41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [C++](./C++/first-missing-positive.cpp) [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [C++](./C++/spiral-matrix-ii.cpp) [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || From 9f601cd9af3c784597afe766c86bacc87f043256 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Jan 2016 00:33:34 +0800 Subject: [PATCH 1642/1939] Update rotate.cpp --- C++/rotate.cpp | 45 ++++++++++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/C++/rotate.cpp b/C++/rotate.cpp index 04d9b392c..70ff90fcd 100644 --- a/C++/rotate.cpp +++ b/C++/rotate.cpp @@ -1,18 +1,37 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(1) +// Time: O(n^2) +// Space: O(1) class Solution { - public: - void rotate(vector > &matrix) { - int n = matrix.size(); - for(int i = 0; i < n / 2; i++) { - for(int j = i; j < n - 1 - i; j++) { - int tmp = matrix[i][j]; - matrix[i][j] = matrix[n-1-j][i]; - matrix[n-1-j][i] = matrix[n-1-i][n-1-j]; - matrix[n-1-i][n-1-j]= matrix[j][n-1-i]; - matrix[j][n-1-i] = tmp; - } +public: + void rotate(vector>& matrix) { + const int n = matrix.size(); + for (int i = 0; i < n / 2; ++i) { + for (int j = i; j < n - 1 - i; ++j) { + int tmp = matrix[i][j]; + matrix[i][j] = matrix[n - 1 - j][i]; + matrix[n - 1- j][i] = matrix[n - 1 - i][n - 1 - j]; + matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]; + matrix[j][n - 1 - i] = tmp; } } + } +}; + +class Solution2 { +public: + void rotate(vector>& matrix) { + const int n = matrix.size(); + // Anti-diagonal mirror. + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n - i; ++j) { + swap(matrix[i][j], matrix[n - 1 - j][n - 1 - i]); + } + } + // Horizontal mirror. + for (int i = 0; i < n / 2; ++i) { + for (int j = 0; j < n; ++j) { + swap(matrix[i][j], matrix[n - 1 - i][j]); + } + } + } }; From c7a639b8f7885d63a480c7467cfd706b1bbdc717 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Jan 2016 00:34:24 +0800 Subject: [PATCH 1643/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ae5b136d7..b954466be 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C++](./C++/remove-element.cpp) [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [C++](./C++/next-permutation.cpp) [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [C++](./C++/first-missing-positive.cpp) [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky -48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || +48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [C++](./C++/rotate-image.cpp) [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [C++](./C++/spiral-matrix-ii.cpp) [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [C++](./C++/plus-one.cpp) [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || From 3542fe6ad131ccf423cc3455a85528fdac0c4236 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Jan 2016 00:34:49 +0800 Subject: [PATCH 1644/1939] Rename rotate.cpp to rotate-image.cpp --- C++/{rotate.cpp => rotate-image.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{rotate.cpp => rotate-image.cpp} (100%) diff --git a/C++/rotate.cpp b/C++/rotate-image.cpp similarity index 100% rename from C++/rotate.cpp rename to C++/rotate-image.cpp From 1be49779445f9a9d24e7df126cc7661b175df4d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Jan 2016 16:18:49 +0800 Subject: [PATCH 1645/1939] Create set-matrix-zeroes.cpp --- C++/set-matrix-zeroes.cpp | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 C++/set-matrix-zeroes.cpp diff --git a/C++/set-matrix-zeroes.cpp b/C++/set-matrix-zeroes.cpp new file mode 100644 index 000000000..b251ce394 --- /dev/null +++ b/C++/set-matrix-zeroes.cpp @@ -0,0 +1,50 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + void setZeroes(vector>& matrix) { + if (matrix.empty()) { + return; + } + + bool has_zero = false; + int zero_i = -1, zero_j = -1; + + for (int i = 0; i < matrix.size(); ++i) { + for (int j = 0; j < matrix[0].size(); ++j) { + if (matrix[i][j] == 0) { + if (!has_zero) { + zero_i = i; + zero_j = j; + has_zero = true; + } + matrix[zero_i][j] = 0; + matrix[i][zero_j] = 0; + } + } + } + + if (has_zero) { + for (int i = 0; i < matrix.size(); ++i) { + if (i == zero_i) { + continue; + } + for (int j = 0; j < matrix[0].size(); ++j) { + if (j == zero_j) { + continue; + } + if (matrix[zero_i][j] == 0 || matrix[i][zero_j] == 0) { + matrix[i][j] = 0; + } + } + } + for (int i = 0; i < matrix.size(); ++i) { + matrix[i][zero_j] = 0; + } + for (int j = 0; j < matrix[0].size(); ++j) { + matrix[zero_i][j] = 0; + } + } + } +}; From 80a45676a32bcb72e8049e6e68743163f618b86b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Jan 2016 16:19:27 +0800 Subject: [PATCH 1646/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b954466be..4bc6f5891 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [C++](./C++/spiral-matrix-ii.cpp) [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [C++](./C++/plus-one.cpp) [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || -73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || +73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [C++](./C++/set-matrix-zeroes.cpp) [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || From c74c48e17392531ab76028e18f46dbeafeb6e97c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jan 2016 17:38:54 +0800 Subject: [PATCH 1647/1939] Create remove-duplicates-from-sorted-array-ii.cpp --- ...remove-duplicates-from-sorted-array-ii.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/remove-duplicates-from-sorted-array-ii.cpp diff --git a/C++/remove-duplicates-from-sorted-array-ii.cpp b/C++/remove-duplicates-from-sorted-array-ii.cpp new file mode 100644 index 000000000..764fdfa74 --- /dev/null +++ b/C++/remove-duplicates-from-sorted-array-ii.cpp @@ -0,0 +1,27 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int removeDuplicates(vector& nums) { + if (nums.empty()) { + return 0; + } + + const int k = 2; // At most k duplicated. + + int left = 0; + int right = 1; + + while (right < nums.size()) { + if (nums[left] != nums[right] || + (left - k + 1 < 0 || nums[left] != nums[left - k + 1])) { + ++left; + nums[left] = nums[right]; + } + ++right; + } + + return left + 1; + } +}; From 4002c4e1c66984542ac2e1c622c0dac639cc5521 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jan 2016 17:40:36 +0800 Subject: [PATCH 1648/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4bc6f5891..f8b8b762c 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || 16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [C++](./C++/3sum-closest.cpp) [Python](./Python/3sum-closest.py) | _O(n^2)_ | _O(1)_ | Medium || -26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp) [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp) [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || Two Pointers 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C++](./C++/remove-element.cpp) [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [C++](./C++/next-permutation.cpp) [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [C++](./C++/first-missing-positive.cpp) [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky @@ -69,7 +69,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [C++](./C++/spiral-matrix-ii.cpp) [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [C++](./C++/plus-one.cpp) [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [C++](./C++/set-matrix-zeroes.cpp) [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || -80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || +80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [C++](./C++/remove-duplicates-from-sorted-array-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || Two Pointers 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || From 7b2dd45132371d7177aefb06bd315f5b55976a48 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Jan 2016 10:45:12 +0800 Subject: [PATCH 1649/1939] Update README.md --- README.md | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index f8b8b762c..448108e66 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates * [Shell Script](https://github.com/kamyu104/LeetCode#shell-script) ## Bit Manipulation - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 136 | [Single Number](https://leetcode.com/problems/single-number/) | [C++](./C++/single-number.cpp) [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Medium || 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [C++](./C++/single-number-ii.cpp) [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium || @@ -56,7 +56,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-lengths.py) | _O(n)_ ~ _O(n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| ## Array - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || 16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [C++](./C++/3sum-closest.cpp) [Python](./Python/3sum-closest.py) | _O(n^2)_ | _O(1)_ | Medium || @@ -95,7 +95,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 311| [Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/) | [C++](./C++/sparse-matrix-multiplication.cpp) [Python](./Python/sparse-matrix-multiplication.py) | _O(m * n * l)_ | _O(m * l)_ | Medium |📖|| ## String - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || @@ -118,7 +118,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 306| [Addictive Number](https://leetcode.com/problems/additive-number/) | [C++](./C++/additive-number.cpp) [Python](./Python/additive-number.py) | _O(n^3)_ | _O(n)_ | Medium | | ## Linked List - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || 24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || @@ -137,7 +137,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 328| [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/)| [C++](./C++/odd-even-linked-list.cpp) [Python](./Python/odd-even-linked-list.py) | _O(n)_ | _O(1)_ | Easy | | ## Stack - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || @@ -153,13 +153,13 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 272| [Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(h)_| Hard |📖|| ## Queue - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard | EPI, LintCode | 281| [Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator/)| [C++](./C++/zigzag-iterator.cpp) [Python](./Python/zigzag-iterator.py) | _O(n)_ | _O(k)_ | Medium |📖|| ## Heap - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(k)_| Hard || 264| [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [C++](./C++/ugly-number-ii.cpp) [Python](./Python/ugly-number-ii.py) | _O(n)_ | _O(1)_ | Medium | CTCI, LintCode | BST, Heap | @@ -167,7 +167,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 313| [Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | [C++](./C++/super-ugly-number.cpp) [Python](./Python/super-ugly-number.py) | _O(n * k)_ | _O(n + k)_ | Medium || BST, Heap | ## Tree - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | ## Hash Table - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || @@ -213,13 +213,13 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 325| [Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/) | [C++](./C++/maximum-size-subarray-sum-equals-k.cpp) [Python](./Python/maximum-size-subarray-sum-equals-k.py) | _O(n)_ | _O(n)_| Easy | 📖 | ## Data Structure - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](./Python/lru-cache.py) | _O(1)_ | _O(n)_ | Hard || 225| [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | [C++](./C++/implement-stack-using-queues.cpp) [Python](./Python/implement-stack-using-queues.py) | push: _O(n)_, pop: _O(1)_, top: _O(1)_ | _O(n)_ | Medium || ## Math - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || @@ -243,7 +243,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 326 | [Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./C++/power-of-three.cpp) [Python](./Python/power-of-three.py) | _O(1)_ | _O(1)_ | Easy ||| ## Sort - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || @@ -262,7 +262,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | ## Two Pointers - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || 86| [Partition List](https://leetcode.com/problems/partition-list/)| [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || @@ -275,7 +275,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Hard | | Binary Search, Two Pointers | ## Divide and Conquer - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || 98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || @@ -297,7 +297,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 327| [Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./C++/count-of-range-sum.cpp) [Python](./Python/count-of-range-sum.py) | _O(nlogn)_ | _O(n)_ | Hard || ## Binary Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 4| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [C++](./C++/median-of-two-sorted-arrays.cpp) [Python](./Python/median-of-two-sorted-arrays.py) | _O(log(min(m, n)))_ | _O(1)_ | Hard || 33| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || @@ -317,7 +317,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 302| [Smallest Rectangle Enclosing Black Pixels](https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/)| [C++](./C++/smallest-rectangle-enclosing-black-pixels.cpp) [Python](./Python/smallest-rectangle-enclosing-black-pixels.py) | _O(nlogn)_ | _O(1)_ | Medium | 📖 | ## Binary Search Tree - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 220| [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [C++](./C++/contains-duplicate-iii.cpp) [Python](./Python/contains-duplicate-iii.py) | _O(nlogk)_ | _O(k)_ | medium || 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C++](./C++/kth-smallest-element-in-a-bst.cpp) [Python](./Python/kth-smallest-element-in-a-bst.py) | _O(max(h, k))_ | _O(min(h, k))_ | Medium || @@ -326,7 +326,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 285| [Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/)| [C++](./C++/inorder-successor-in-bst.cpp) [Python](./Python/inorder-successor-in-bst.py) | _O(h)_ | _O(1)_ | Medium | 📖 | ## Breadth-First Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 102| [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || 107| [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](./Python/binary-tree-level-order-traversal-ii.py) | _O(n)_| _O(n)_| Easy || @@ -344,7 +344,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 317| [Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings/)| [C++](./C++/shortest-distance-from-all-buildings.cpp) [Python](./Python/shortest-distance-from-all-buildings.py) | _O(k * m * n)_ | _O(m * n)_ | Hard | 📖 | ## Depth-First Search - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 112| [Path Sum](https://leetcode.com/problems/path-sum/) | [Python](./Python/path-sum.py) | _O(n)_ | _O(h)_ | Easy || 113| [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | [Python](./Python/path-sum-ii.py) | _O(n)_ | _O(h)_ | Medium || @@ -359,7 +359,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 329| [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./C++/longest-increasing-path-in-a-matrix.cpp) [Python](./Python/longest-increasing-path-in-a-matrix.py) | _O(m * n)_ | _O(m * n)_ | Medium ||| ## Backtracking - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 17| [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](./Python/letter-combinations-of-a-phone-number.py) | _O(n * 4^n)_ | _O(n)_ | Medium || 22| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || @@ -387,7 +387,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 320| [Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation/) | [C++](./C++/generalized-abbreviation.cpp) [Python](./Python/generalized-abbreviation.py) | _O(n * 2^n)_ | _O(n)_ | Medium |📖|| ## Dynamic Programming - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 10| [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || 53| [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || @@ -423,7 +423,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 322| [Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./C++/coin-change.cpp) [Python](./Python/coin-change.py) | _O(n * k)_ | _O(k)_ | Medium || ## Greedy - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || 42| [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky @@ -439,12 +439,12 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates --- ##Design - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 284| [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [C++](./C++/peeking-iterator.cpp) [Python](./Python/peeking-iterator.py) | _O(1)_ | _O(1)_ | Medium || ## SQL - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 175| [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/) | [MySQL](./MySQL/combine-two-tables.sql) | _O(m + n)_ | _O(m + n)_ | Easy || 176| [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/) | [MySQL](./MySQL/second-highest-salary.sql) | _O(n)_ | _O(1)_ | Easy || @@ -461,7 +461,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 262| [Trips and Users ](https://leetcode.com/problems/trips-and-users/) | [MySQL](./MySQL/trips-and-users.sql) | _O((t * u) + tlogt)_ | _O(t)_ | Hard || ## Shell Script - # | Problem | Solution | Time | Space | Difficulty | Tag | Note + # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 192 | [Word Frequency](https://leetcode.com/problems/word-frequency/) | [Shell](./Shell/word-frequency.sh) | _O(n)_ | _O(k)_ | Medium || 193 | [Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/) | [Shell](./Shell/valid-phone-numbers.sh) | _O(n)_ | _O(1)_ | Easy || From 08be51f5de2330f70f9212fb640f44c658eb18cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Jan 2016 13:19:36 +0800 Subject: [PATCH 1650/1939] Update pascals-triangle.py --- Python/pascals-triangle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/pascals-triangle.py b/Python/pascals-triangle.py index 96bbf51f7..822acab84 100644 --- a/Python/pascals-triangle.py +++ b/Python/pascals-triangle.py @@ -1,5 +1,5 @@ # Time: O(n^2) -# Space: O(n) +# Space: O(1) # # Given numRows, generate the first numRows of Pascal's triangle. # From 0764552fdf8eca9fdb00a2e9f9d7b65ee8829fec Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Jan 2016 13:20:13 +0800 Subject: [PATCH 1651/1939] Create pascals-triangle.cpp --- C++/pascals-triangle.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/pascals-triangle.cpp diff --git a/C++/pascals-triangle.cpp b/C++/pascals-triangle.cpp new file mode 100644 index 000000000..95a723551 --- /dev/null +++ b/C++/pascals-triangle.cpp @@ -0,0 +1,21 @@ +// Time: O(n^2) +// Space: O(1) + +class Solution { +public: + vector> generate(int numRows) { + vector> result; + for (int i = 0; i < numRows; ++i) { + result.push_back({}); + for (int j = 0; j <= i; ++j) { + if (j == 0 || j == i) { + result[i].emplace_back(1); + } else { + result[i].emplace_back(result[i - 1][j - 1] + + result[i - 1][j]); + } + } + } + return result; + } +}; From fb7f0ccc89001be6ecfe6d13a055c685eaca2df0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Jan 2016 13:22:54 +0800 Subject: [PATCH 1652/1939] Update pascals-triangle-ii.py --- Python/pascals-triangle-ii.py | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/Python/pascals-triangle-ii.py b/Python/pascals-triangle-ii.py index f8aaa06d1..390a804cb 100644 --- a/Python/pascals-triangle-ii.py +++ b/Python/pascals-triangle-ii.py @@ -1,6 +1,6 @@ # Time: O(n^2) -# Space: O(n) -# +# Space: O(1) + # Given an index k, return the kth row of the Pascal's triangle. # # For example, given k = 3, @@ -11,14 +11,6 @@ # class Solution: - # @return a list of integers - def getRow(self, rowIndex): - result = [1] - for i in range(1, rowIndex + 1): - result = [1] + [result[j - 1] + result[j] for j in range(1, i)] + [1] - return result - -class Solution2: # @return a list of integers def getRow(self, rowIndex): result = [0] * (rowIndex + 1) @@ -28,5 +20,17 @@ def getRow(self, rowIndex): old, result[j] = result[j], old + result[j] return result + +# Time: O(n^2) +# Space: O(n) +class Solution2: + # @return a list of integers + def getRow(self, rowIndex): + result = [1] + for i in range(1, rowIndex + 1): + result = [1] + [result[j - 1] + result[j] for j in xrange(1, i)] + [1] + return result + + if __name__ == "__main__": - print Solution().getRow(3) \ No newline at end of file + print Solution().getRow(3) From 1e391f3cb97574cfae44f8bb3b40a642d197c63e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Jan 2016 13:30:30 +0800 Subject: [PATCH 1653/1939] Create pascals-triangle-ii.cpp --- C++/pascals-triangle-ii.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/pascals-triangle-ii.cpp diff --git a/C++/pascals-triangle-ii.cpp b/C++/pascals-triangle-ii.cpp new file mode 100644 index 000000000..49c5da0fd --- /dev/null +++ b/C++/pascals-triangle-ii.cpp @@ -0,0 +1,18 @@ +// Time: O(n^2) +// Space: O(1) + +class Solution { +public: + vector getRow(int rowIndex) { + vector result(rowIndex + 1); + for (int i = 0; i < result.size(); ++i) { + int prev_result = result[0] = 1; + for (int j = 1; j <= i; ++j) { + int tmp = result[j]; + result[j] += prev_result; + prev_result = tmp; + } + } + return result; + } +}; From 554bad6216506eea7f68ebd541522048a4f5a4c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Jan 2016 13:31:36 +0800 Subject: [PATCH 1654/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 448108e66..aa38f47a9 100644 --- a/README.md +++ b/README.md @@ -70,8 +70,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [C++](./C++/plus-one.cpp) [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [C++](./C++/set-matrix-zeroes.cpp) [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [C++](./C++/remove-duplicates-from-sorted-array-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || Two Pointers -118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(n)_ | Easy || -119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(n)_ | Easy || +118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [C++](./C++/pascals-triangle.cpp) [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(1)_ | Easy || +119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [C++](./C++/pascals-triangle-ii.cpp) [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(1)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| From cbfda0e3e6e5a8056e81946d7d31af736753ab3e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Jan 2016 13:32:43 +0800 Subject: [PATCH 1655/1939] Update pascals-triangle-ii.cpp --- C++/pascals-triangle-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/pascals-triangle-ii.cpp b/C++/pascals-triangle-ii.cpp index 49c5da0fd..5c11c9346 100644 --- a/C++/pascals-triangle-ii.cpp +++ b/C++/pascals-triangle-ii.cpp @@ -8,7 +8,7 @@ class Solution { for (int i = 0; i < result.size(); ++i) { int prev_result = result[0] = 1; for (int j = 1; j <= i; ++j) { - int tmp = result[j]; + const int tmp = result[j]; result[j] += prev_result; prev_result = tmp; } From 1a1cf8007a56dcc135ef18f4196c80ca3170eff1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Jan 2016 13:03:51 +0800 Subject: [PATCH 1656/1939] Update and rename maxProfitI.cpp to best-time-to-buy-and-sell-stock.cpp --- C++/best-time-to-buy-and-sell-stock.cpp | 21 +++++++++++++++++++++ C++/maxProfitI.cpp | 21 --------------------- 2 files changed, 21 insertions(+), 21 deletions(-) create mode 100644 C++/best-time-to-buy-and-sell-stock.cpp delete mode 100644 C++/maxProfitI.cpp diff --git a/C++/best-time-to-buy-and-sell-stock.cpp b/C++/best-time-to-buy-and-sell-stock.cpp new file mode 100644 index 000000000..9105909a9 --- /dev/null +++ b/C++/best-time-to-buy-and-sell-stock.cpp @@ -0,0 +1,21 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maxProfit(vector &prices) { + if (prices.empty()) { + return 0; + } + + int hold1 = numeric_limits::min(); + int release1 = numeric_limits::min(); + + for (const auto& p : prices) { + hold1 = max(hold1, -p); + release1 = max(release1, hold1 + p); + } + + return release1; + } +}; diff --git a/C++/maxProfitI.cpp b/C++/maxProfitI.cpp deleted file mode 100644 index c7d4dea53..000000000 --- a/C++/maxProfitI.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - int maxProfit(vector &prices) { - const int n = prices.size(); - - if(n < 2) - return 0; - - // Greedy Algorithm - int ans = 0; - for(int i = 1, valley = prices[0]; i < n; ++i) { - ans = max(ans, prices[i] - valley); - valley = min(valley, prices[i]); - } - - return ans; - } -}; From 561916a0f0e08297c97df9e7cb75b4788e3c80ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Jan 2016 13:04:26 +0800 Subject: [PATCH 1657/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aa38f47a9..612a105fb 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [C++](./C++/remove-duplicates-from-sorted-array-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || Two Pointers 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [C++](./C++/pascals-triangle.cpp) [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(1)_ | Easy || 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [C++](./C++/pascals-triangle-ii.cpp) [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(1)_ | Easy || -121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || +121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [C++](./C++/best-time-to-buy-and-sell-stock.cpp) [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| From cba7bcaf3ee5da6aadecb611a2ab8167819936e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Jan 2016 14:45:56 +0800 Subject: [PATCH 1658/1939] Create patching-array.cpp --- C++/patching-array.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/patching-array.cpp diff --git a/C++/patching-array.cpp b/C++/patching-array.cpp new file mode 100644 index 000000000..374f5784f --- /dev/null +++ b/C++/patching-array.cpp @@ -0,0 +1,18 @@ +// Time: O(n + logN) +// Space: O(1) + +class Solution { +public: + int minPatches(vector& nums, int n) { + int patch = 0; + for (uint64_t miss = 1, i = 0; miss <= n;) { + if (i < nums.size() && nums[i] <= miss) { + miss += nums[i++]; + } else { + ++patch; + miss += miss; + } + } + return patch; + } +}; From 4ad53672e1200dc529338d077f6403b219065add Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Jan 2016 14:50:46 +0800 Subject: [PATCH 1659/1939] Create patching-array.py --- Python/patching-array.py | 48 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/patching-array.py diff --git a/Python/patching-array.py b/Python/patching-array.py new file mode 100644 index 000000000..ce91f1f6e --- /dev/null +++ b/Python/patching-array.py @@ -0,0 +1,48 @@ +# Time: O(s + logn), s is the number of elements in the array +# Space: O(1) + +# 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. + + +class Solution(object): + def minPatches(self, nums, n): + """ + :type nums: List[int] + :type n: int + :rtype: int + """ + patch, miss, i = 0, 1, 0 + while miss <= n: + if i < len(nums) and nums[i] <= miss: + miss += nums[i] + i += 1 + else: + miss += miss + patch += 1 + + return patch From 7ec740eab67acf8fb27d352664ba4b8432cf4c70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Jan 2016 14:51:36 +0800 Subject: [PATCH 1660/1939] Update patching-array.cpp --- C++/patching-array.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/patching-array.cpp b/C++/patching-array.cpp index 374f5784f..0559936cc 100644 --- a/C++/patching-array.cpp +++ b/C++/patching-array.cpp @@ -1,4 +1,4 @@ -// Time: O(n + logN) +// Time: O(s + logn), s is the number of elements in the array // Space: O(1) class Solution { @@ -9,8 +9,8 @@ class Solution { if (i < nums.size() && nums[i] <= miss) { miss += nums[i++]; } else { - ++patch; miss += miss; + ++patch; } } return patch; From b246908ea20d66bf1acc2c210180ff67ab956e3d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Jan 2016 14:54:22 +0800 Subject: [PATCH 1661/1939] Update README.md --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 612a105fb..e1df6a554 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-329%20%2F%20329-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-330%20%2F%20330-ff69b4.svg) -Up to date (2016-01-20), there are `312` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-01-27), there are `313` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `329` questions. +Here is the classification of all `330` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -436,6 +436,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || 316| [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./C++/remove-duplicate-letters.cpp) [Python](./Python/remove-duplicate-letters.py) | _O(n)_| _O(k)_| Medium || Stack | 321| [Create Maximum Number](https://leetcode.com/problems/create-maximum-number/)| [C++](./C++/create-maximum-number.cpp) [Python](./Python/create-maximum-number.py) | _O(k * (m + n + k))_ ~ _O(k * (m + n + k^2))_| _O(m + n + k^2)_ | Hard | variant of [Delete Digits](http://www.lintcode.com/en/problem/delete-digits/) | Greedy, DP +330| [Patching Array](https://leetcode.com/problems/patching-array/) | C++](./C++/patching-array.cpp) [Python](./Python/patching-array.py) | _O(s + logn)_ | _O(1)_ | Medium || --- ##Design @@ -458,7 +459,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 185| [Department Top Three Salaries](https://leetcode.com/problems/department-top-three-salaries/) | [MySQL](./MySQL/department-top-three-salaries.sql) | _O(n^2)_ | _O(n)_ | Hard || 196| [Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/) | [MySQL](./MySQL/delete-duplicate-emails.sql) | _O(n^2)_ | _O(n)_ | Easy || 197| [Rising Temperature](https://leetcode.com/problems/rising-temperature/) | [MySQL](./MySQL/rising-temperature.sql) | _O(n^2)_ | _O(n)_ | Easy || -262| [Trips and Users ](https://leetcode.com/problems/trips-and-users/) | [MySQL](./MySQL/trips-and-users.sql) | _O((t * u) + tlogt)_ | _O(t)_ | Hard || +262| [Trips and Users](https://leetcode.com/problems/trips-and-users/) | [MySQL](./MySQL/trips-and-users.sql) | _O((t * u) + tlogt)_ | _O(t)_ | Hard || ## Shell Script # | Title | Solution | Time | Space | Difficulty | Tag | Note From 36fa25a81d98dcc4eb86e1fe3c289132893e89df Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Jan 2016 14:54:50 +0800 Subject: [PATCH 1662/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e1df6a554..ffaf36f88 100644 --- a/README.md +++ b/README.md @@ -436,7 +436,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 135| [Candy](https://leetcode.com/problems/candy/)| [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || 316| [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./C++/remove-duplicate-letters.cpp) [Python](./Python/remove-duplicate-letters.py) | _O(n)_| _O(k)_| Medium || Stack | 321| [Create Maximum Number](https://leetcode.com/problems/create-maximum-number/)| [C++](./C++/create-maximum-number.cpp) [Python](./Python/create-maximum-number.py) | _O(k * (m + n + k))_ ~ _O(k * (m + n + k^2))_| _O(m + n + k^2)_ | Hard | variant of [Delete Digits](http://www.lintcode.com/en/problem/delete-digits/) | Greedy, DP -330| [Patching Array](https://leetcode.com/problems/patching-array/) | C++](./C++/patching-array.cpp) [Python](./Python/patching-array.py) | _O(s + logn)_ | _O(1)_ | Medium || +330| [Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./C++/patching-array.cpp) [Python](./Python/patching-array.py) | _O(s + logn)_ | _O(1)_ | Medium || --- ##Design From 73f11bc349512d04307e494193595c0f4cc22ded Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Jan 2016 15:10:02 +0800 Subject: [PATCH 1663/1939] Update patching-array.cpp --- C++/patching-array.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/patching-array.cpp b/C++/patching-array.cpp index 0559936cc..81e054547 100644 --- a/C++/patching-array.cpp +++ b/C++/patching-array.cpp @@ -9,7 +9,7 @@ class Solution { if (i < nums.size() && nums[i] <= miss) { miss += nums[i++]; } else { - miss += miss; + miss += miss; // miss may overflow, thus prefer to use uint64_t. ++patch; } } From fc6ad39e6025afe7551dceccbd8457319797bdb3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Jan 2016 13:30:18 +0800 Subject: [PATCH 1664/1939] Update and rename longestConsecutive.cpp to longest-consecutive-sequence.cpp --- C++/longest-consecutive-sequence.cpp | 58 ++++++++++++++++++++++++++++ C++/longestConsecutive.cpp | 22 ----------- 2 files changed, 58 insertions(+), 22 deletions(-) create mode 100644 C++/longest-consecutive-sequence.cpp delete mode 100644 C++/longestConsecutive.cpp diff --git a/C++/longest-consecutive-sequence.cpp b/C++/longest-consecutive-sequence.cpp new file mode 100644 index 000000000..253cc2c97 --- /dev/null +++ b/C++/longest-consecutive-sequence.cpp @@ -0,0 +1,58 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int longestConsecutive(vector& nums) { + // unprocessed_entries records the existence of each entry in num. + unordered_set unprocessed_entries; + for (const auto& num : nums) { + unprocessed_entries.emplace(num); + } + + int max_interval_size = 0; + while (!unprocessed_entries.empty()) { + int num = *unprocessed_entries.begin(); + unprocessed_entries.erase(num); + + // Finds the lower bound of the largest range containing a. + int lower_bound = num - 1; + while (unprocessed_entries.count(lower_bound)) { + unprocessed_entries.erase(lower_bound); + --lower_bound; + } + + // Finds the upper bound of the largest range containing a. + int upper_bound = num + 1; + while (unprocessed_entries.count(upper_bound)) { + unprocessed_entries.erase(upper_bound); + ++upper_bound; + } + max_interval_size = + max(max_interval_size, upper_bound - lower_bound - 1); + } + return max_interval_size; + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { +public: + int longestConsecutive(vector &nums) { + if (nums.empty()) { + return 0; + } + unordered_map hash; + int ans{1}; + for (const auto& i : nums) { + if (!hash[i]) { + hash[i] = 1; + int leftbound{hash[i - 1]}, rightbound{hash[i + 1]}; // Get neighbor info. + hash[i - leftbound] = hash[i + rightbound] = 1 + leftbound + rightbound; // Update left and right bound info. + ans = max(ans, 1 + leftbound + rightbound); + } + } + return ans; + } +}; diff --git a/C++/longestConsecutive.cpp b/C++/longestConsecutive.cpp deleted file mode 100644 index 08a929e02..000000000 --- a/C++/longestConsecutive.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(n) - -class Solution { - public: - int longestConsecutive(vector &num) { - if (num.size() == 0) - return 0; - unordered_map hash; - int ans{1}; - for (auto &i: num) { - if (hash[i] != 0) { - continue; - } - hash[i] = 1; - int leftbound{hash[i - 1]}, rightbound{hash[i + 1]}; // get neighbor info - hash[i - leftbound] = hash[i + rightbound] = 1 + leftbound + rightbound; // update left and right bound info - ans = max(ans, 1 + leftbound + rightbound); - } - return ans; - } -}; From 4b52ba1517e5f2ebddc3a11129767b6477779cea Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Jan 2016 13:30:54 +0800 Subject: [PATCH 1665/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ffaf36f88..124b345fb 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [C++](./C++/pascals-triangle.cpp) [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(1)_ | Easy || 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [C++](./C++/pascals-triangle-ii.cpp) [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(1)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [C++](./C++/best-time-to-buy-and-sell-stock.cpp) [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || -128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky +128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [C++](./C++/longest-consecutive-sequence.cpp) [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | From 48f638aa70a810b2cd06329314d4130f8778d585 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 Jan 2016 22:28:38 +0800 Subject: [PATCH 1666/1939] Update read-n-characters-given-read4.py --- Python/read-n-characters-given-read4.py | 30 ++++++++++++------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Python/read-n-characters-given-read4.py b/Python/read-n-characters-given-read4.py index 912eb1c25..1581cca20 100644 --- a/Python/read-n-characters-given-read4.py +++ b/Python/read-n-characters-given-read4.py @@ -27,23 +27,23 @@ def read4(buf): file_content = "" return i -class Solution: - # @param buf, Destination buffer (a list of characters) - # @param n, Maximum number of characters to read (an integer) - # @return The number of characters read (an integer) +class Solution(object): def read(self, buf, n): + """ + :type buf: Destination buffer (List[str]) + :type n: Maximum number of characters to read (int) + :rtype: The number of characters read (int) + """ read_bytes = 0 - eof = False - buffer = ['' for _ in xrange(4)] - while not eof and read_bytes < n: + buffer = [''] * 4 + for i in xrange(n / 4 + 1): size = read4(buffer) - if size < 4: - eof = True - bytes = min(n - read_bytes, size) - for i in xrange(bytes): - buf[read_bytes + i] = buffer[i] - read_bytes += bytes - return read_bytes + if size: + buf[read_bytes:read_bytes+size] = buffer + read_bytes += size + else: + break + return min(read_bytes, n) if __name__ == "__main__": global file_content @@ -51,4 +51,4 @@ def read(self, buf, n): file_content = "a" print buf[:Solution().read(buf, 9)] file_content = "abcdefghijklmnop" - print buf[:Solution().read(buf, 9)] \ No newline at end of file + print buf[:Solution().read(buf, 9)] From 054c6462ee18393906d3d2da8db3479c27159312 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 Jan 2016 22:30:52 +0800 Subject: [PATCH 1667/1939] Create read-n-characters-given-read4.cpp --- C++/read-n-characters-given-read4.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/read-n-characters-given-read4.cpp diff --git a/C++/read-n-characters-given-read4.cpp b/C++/read-n-characters-given-read4.cpp new file mode 100644 index 000000000..7128ab1fa --- /dev/null +++ b/C++/read-n-characters-given-read4.cpp @@ -0,0 +1,24 @@ +// Time: O(n) +// Space: O(1) + +int read4(char *buf); + +class Solution { +public: + /** + * @param buf Destination buffer + * @param n Maximum number of characters to read + * @return The number of characters read + */ + int read(char *buf, int n) { + int read_bytes = 0; + for (int i = 0; i <= n / 4; ++i) { + if (int size = read4(buf + read_bytes)) { + read_bytes += size; + } else { + break; + } + } + return min(read_bytes, n); + } +}; From ba7f3695cbe55206b01edb3248ead466a9425eac Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 Jan 2016 22:31:35 +0800 Subject: [PATCH 1668/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 124b345fb..dc62ea4b9 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [C++](./C++/pascals-triangle-ii.cpp) [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(1)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [C++](./C++/best-time-to-buy-and-sell-stock.cpp) [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [C++](./C++/longest-consecutive-sequence.cpp) [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky -157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| +157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [C++](./C++/read-n-characters-given-read4.cpp) [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | From dee58444dd155d7e91c6a0d29adb93ff05051573 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Jan 2016 20:53:27 +0800 Subject: [PATCH 1669/1939] Create read-n-characters-given-read4-ii-call-multiple-times.cpp --- ...ers-given-read4-ii-call-multiple-times.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/read-n-characters-given-read4-ii-call-multiple-times.cpp diff --git a/C++/read-n-characters-given-read4-ii-call-multiple-times.cpp b/C++/read-n-characters-given-read4-ii-call-multiple-times.cpp new file mode 100644 index 000000000..fb53207c8 --- /dev/null +++ b/C++/read-n-characters-given-read4-ii-call-multiple-times.cpp @@ -0,0 +1,31 @@ +// Time: O(n) +// Space: O(1) + +// Forward declaration of the read4 API. +int read4(char *buf); + +class Solution { +public: + /** + * @param buf Destination buffer + * @param n Maximum number of characters to read + * @return The number of characters read + */ + int read(char *buf, int n) { + int i = 0; + while (i < n) { + if (i4_ < n4_) { // Any characters in buf4. + buf[i++] = buf4_[i4_++]; + } else if (n4_ = read4(buf4_)) { // Read more characters. + i4_ = 0; + } else { // Buffer has been empty. + break; + } + } + return i; + } + +private: + char buf4_[4]; + int i4_ = 0, n4_ = 0; +}; From 812e3d51e488c3efeba07993e7d336b7565ee2f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Jan 2016 21:11:53 +0800 Subject: [PATCH 1670/1939] Update read-n-characters-given-read4-ii-call-multiple-times.py --- ...ters-given-read4-ii-call-multiple-times.py | 50 +++++++++++-------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/Python/read-n-characters-given-read4-ii-call-multiple-times.py b/Python/read-n-characters-given-read4-ii-call-multiple-times.py index 91532e01c..2645c5fd0 100644 --- a/Python/read-n-characters-given-read4-ii-call-multiple-times.py +++ b/Python/read-n-characters-given-read4-ii-call-multiple-times.py @@ -27,31 +27,37 @@ def read4(buf): file_content = "" return i -class Solution: +# The read4 API is already defined for you. +# @param buf, a list of characters +# @return an integer +# def read4(buf): + +class Solution(object): def __init__(self): - self.buffer_size, self.offset = 0, 0 - self.buffer = [None for _ in xrange(4)] - - # @param buf, Destination buffer (a list of characters) - # @param n, Maximum number of characters to read (an integer) - # @return The number of characters read (an integer) + self.__buf4 = [''] * 4 + self.__i4 = 0 + self.__n4 = 0 + def read(self, buf, n): - read_bytes = 0 - eof = False - while not eof and read_bytes < n: - if self.buffer_size == 0: - size = read4(self.buffer) + """ + :type buf: Destination buffer (List[str]) + :type n: Maximum number of characters to read (int) + :rtype: The number of characters read (int) + """ + i = 0 + while i < n: + if self.__i4 < self.__n4: # Any characters in buf4. + buf[i] = self.__buf4[self.__i4] + i += 1 + self.__i4 += 1 else: - size = self.buffer_size - if self.buffer_size == 0 and size < 4: - eof = True - bytes = min(n - read_bytes, size) - for i in xrange(bytes): - buf[read_bytes + i] = self.buffer[self.offset + i] - self.offset = (self.offset + bytes) % 4 - self.buffer_size = size - bytes - read_bytes += bytes - return read_bytes + self.__n4 = read4(self.__buf4) # Read more characters. + if self.__n4: + self.__i4 = 0 + else: # Buffer has been empty. + break + + return i if __name__ == "__main__": global file_content From c9760d9960d04fa6b94f4d69c73a104102a4ef9e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Jan 2016 21:13:05 +0800 Subject: [PATCH 1671/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dc62ea4b9..7c9c3d562 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [C++](./C++/best-time-to-buy-and-sell-stock.cpp) [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Medium || 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [C++](./C++/longest-consecutive-sequence.cpp) [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [C++](./C++/read-n-characters-given-read4.cpp) [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| -158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| +158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [C++](./C++/read-n-characters-given-read4-ii-call-multiple-times.cpp) [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || From 5441d2106bfa7984a30c8755ac88b0c2a01c73dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Jan 2016 10:53:39 +0800 Subject: [PATCH 1672/1939] Update add-two-numbers.py --- Python/add-two-numbers.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Python/add-two-numbers.py b/Python/add-two-numbers.py index 158d85fd1..ee93acf4c 100644 --- a/Python/add-two-numbers.py +++ b/Python/add-two-numbers.py @@ -14,18 +14,22 @@ def __init__(self, x): self.val = x self.next = None -class Solution: - # @return a ListNode +class Solution(object): def addTwoNumbers(self, l1, l2): + """ + :type l1: ListNode + :type l2: ListNode + :rtype: ListNode + """ dummy = ListNode(0) current, carry = dummy, 0 - while l1 is not None or l2 is not None: + while l1 or l2: val = carry - if l1 is not None: + if l1: val += l1.val l1 = l1.next - if l2 is not None: + if l2: val += l2.val l2 = l2.next carry, val = val / 10, val % 10 @@ -42,4 +46,4 @@ def addTwoNumbers(self, l1, l2): b, b.next, b.next.next = ListNode(5), ListNode(6), ListNode(4) result = Solution().addTwoNumbers(a, b) print "{0} -> {1} -> {2}".format(result.val, result.next.val, result.next.next.val) - \ No newline at end of file + From dd8a3712355e8179e12c2b3c5800424ddac54972 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Feb 2016 09:57:22 +0800 Subject: [PATCH 1673/1939] Create verify-preorder-serialization-of-a-binary-tree.cpp --- ...reorder-serialization-of-a-binary-tree.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 C++/verify-preorder-serialization-of-a-binary-tree.cpp diff --git a/C++/verify-preorder-serialization-of-a-binary-tree.cpp b/C++/verify-preorder-serialization-of-a-binary-tree.cpp new file mode 100644 index 000000000..0e79a1196 --- /dev/null +++ b/C++/verify-preorder-serialization-of-a-binary-tree.cpp @@ -0,0 +1,52 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool isValidSerialization(string preorder) { + if (preorder.empty()) { + return false; + } + Tokenizer tokens(preorder); + int depth = 0; + for (int i = 0; i < tokens.size() - 1; ++i) { + if (tokens.get_next() == "#") { + --depth; + if (depth < 0) { + return false; + } + } else { + ++depth; + } + } + return depth == 0 && tokens.get_next() == "#"; + } + +class Tokenizer { + public: + Tokenizer(const string& str) : str_(str), i_(0), cnt_(0) { + size_ = count(str_.cbegin(), str_.cend(), ',') + 1; + } + + string get_next() { + string next; + if (cnt_ < size_) { + size_t j = str_.find(",", i_); + next = str_.substr(i_, j - i_); + i_ = j + 1; + ++cnt_; + } + return next; + } + + size_t size() { + return size_; + } + + private: + const string& str_; + size_t size_; + size_t cnt_; + size_t i_; + }; +}; From c25cbfcdb8c10210df9b5e34eb11634d5c8532d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Feb 2016 10:36:00 +0800 Subject: [PATCH 1674/1939] Update verify-preorder-serialization-of-a-binary-tree.cpp --- C++/verify-preorder-serialization-of-a-binary-tree.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/C++/verify-preorder-serialization-of-a-binary-tree.cpp b/C++/verify-preorder-serialization-of-a-binary-tree.cpp index 0e79a1196..bfb0c0526 100644 --- a/C++/verify-preorder-serialization-of-a-binary-tree.cpp +++ b/C++/verify-preorder-serialization-of-a-binary-tree.cpp @@ -9,17 +9,18 @@ class Solution { } Tokenizer tokens(preorder); int depth = 0; - for (int i = 0; i < tokens.size() - 1; ++i) { + int i = 0; + for (; i < tokens.size(); ++i) { if (tokens.get_next() == "#") { --depth; if (depth < 0) { - return false; + break; } } else { ++depth; } } - return depth == 0 && tokens.get_next() == "#"; + return i == tokens.size() - 1; } class Tokenizer { @@ -49,4 +50,5 @@ class Tokenizer { size_t cnt_; size_t i_; }; + }; From 6d344fe5e5c0214c065c171d0cac9195ac282caa Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Feb 2016 10:38:15 +0800 Subject: [PATCH 1675/1939] Create verify-preorder-serialization-of-a-binary-tree.py --- ...preorder-serialization-of-a-binary-tree.py | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Python/verify-preorder-serialization-of-a-binary-tree.py diff --git a/Python/verify-preorder-serialization-of-a-binary-tree.py b/Python/verify-preorder-serialization-of-a-binary-tree.py new file mode 100644 index 000000000..5e9a269dc --- /dev/null +++ b/Python/verify-preorder-serialization-of-a-binary-tree.py @@ -0,0 +1,66 @@ +# Time: O(n) +# Space: O(1) + +# One way to serialize a binary tree is to use pre-oder 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 + +class Solution(object): + def isValidSerialization(self, preorder): + """ + :type preorder: str + :rtype: bool + """ + def split_iter(s, tok): + start = 0 + for i in xrange(len(s)): + if s[i] == tok: + yield s[start:i] + start = i + 1 + yield s[start:] + + if not preorder: + return False + + depth, cnt = 0, preorder.count(',') + 1 + for tok in split_iter(preorder, ','): + cnt -= 1 + if tok == "#": + depth -= 1; + if depth < 0: + break + else: + depth += 1 + return cnt == 0 and depth == -1 From c5041356d69b450474946627463f310604a2b03d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Feb 2016 10:40:46 +0800 Subject: [PATCH 1676/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7c9c3d562..2a8c7c88b 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-330%20%2F%20330-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-331%20%2F%20331-ff69b4.svg) -Up to date (2016-01-27), there are `313` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-02-01), there are `314` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `330` questions. +Here is the classification of all `331` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -151,6 +151,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| Easy | EPI, LintCode | 255| [Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/verify-preorder-sequence-in-binary-search-tree.cpp) [Python](./Python/verify-preorder-sequence-in-binary-search-tree.py) | _O(n)_| _O(1)_| Medium |📖|| 272| [Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(h)_| Hard |📖|| +331| [Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/) | [C++](./C++/verify-preorder-serialization-of-a-binary-tree.cpp) [Python](./Python/verify-preorder-serialization-of-a-binary-tree.py) | _O(n)_| _O(1)_| Medium ||| ## Queue # | Title | Solution | Time | Space | Difficulty | Tag | Note From 304c025daf46a2b6480f334a21f5214374ed019c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Feb 2016 10:59:44 +0800 Subject: [PATCH 1677/1939] Update verify-preorder-serialization-of-a-binary-tree.cpp --- C++/verify-preorder-serialization-of-a-binary-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/verify-preorder-serialization-of-a-binary-tree.cpp b/C++/verify-preorder-serialization-of-a-binary-tree.cpp index bfb0c0526..debcf0152 100644 --- a/C++/verify-preorder-serialization-of-a-binary-tree.cpp +++ b/C++/verify-preorder-serialization-of-a-binary-tree.cpp @@ -23,7 +23,7 @@ class Solution { return i == tokens.size() - 1; } -class Tokenizer { + class Tokenizer { public: Tokenizer(const string& str) : str_(str), i_(0), cnt_(0) { size_ = count(str_.cbegin(), str_.cend(), ',') + 1; From aa95b57fdbb9491c2486118a668538f59946e626 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Feb 2016 14:14:39 +0800 Subject: [PATCH 1678/1939] Update verify-preorder-serialization-of-a-binary-tree.cpp --- C++/verify-preorder-serialization-of-a-binary-tree.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/C++/verify-preorder-serialization-of-a-binary-tree.cpp b/C++/verify-preorder-serialization-of-a-binary-tree.cpp index debcf0152..42c34086a 100644 --- a/C++/verify-preorder-serialization-of-a-binary-tree.cpp +++ b/C++/verify-preorder-serialization-of-a-binary-tree.cpp @@ -10,17 +10,14 @@ class Solution { Tokenizer tokens(preorder); int depth = 0; int i = 0; - for (; i < tokens.size(); ++i) { + for (; i < tokens.size() && depth >= 0; ++i) { if (tokens.get_next() == "#") { --depth; - if (depth < 0) { - break; - } } else { ++depth; } } - return i == tokens.size() - 1; + return i == tokens.size() && depth < 0; } class Tokenizer { From e79f3abf93835b3a10290366204dca9bb88ea72c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Feb 2016 14:28:07 +0800 Subject: [PATCH 1679/1939] Update verify-preorder-serialization-of-a-binary-tree.py --- Python/verify-preorder-serialization-of-a-binary-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/verify-preorder-serialization-of-a-binary-tree.py b/Python/verify-preorder-serialization-of-a-binary-tree.py index 5e9a269dc..ee7d23f75 100644 --- a/Python/verify-preorder-serialization-of-a-binary-tree.py +++ b/Python/verify-preorder-serialization-of-a-binary-tree.py @@ -63,4 +63,4 @@ def split_iter(s, tok): break else: depth += 1 - return cnt == 0 and depth == -1 + return cnt == 0 and depth < 0 From aa551aa68a586523b6c85f9ec3b1432e72181db4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Feb 2016 18:02:55 +0800 Subject: [PATCH 1680/1939] Create missing-ranges.cpp --- C++/missing-ranges.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/missing-ranges.cpp diff --git a/C++/missing-ranges.cpp b/C++/missing-ranges.cpp new file mode 100644 index 000000000..e097d37b6 --- /dev/null +++ b/C++/missing-ranges.cpp @@ -0,0 +1,28 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector findMissingRanges(vector& nums, int lower, int upper) { + vector ranges; + for (int i = 0, pre = lower - 1, cur = 0; i <= nums.size(); ++i, pre = cur) { + if (i == nums.size()) { + cur = upper + 1; + } else { + cur = nums[i]; + } + if (cur - pre >= 2) { + ranges.emplace_back(getRange(pre + 1, cur - 1)); + } + } + return ranges; + } + + string getRange(const int lower, const int upper) { + if (lower == upper) { + return to_string(lower); + } else { + return to_string(lower) + "->" + to_string(upper); + } + } +}; From a5afe6e13c4a23df10f66550c24b78613696a50b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Feb 2016 18:03:35 +0800 Subject: [PATCH 1681/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2a8c7c88b..9865ed13e 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [C++](./C++/longest-consecutive-sequence.cpp) [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [C++](./C++/read-n-characters-given-read4.cpp) [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [C++](./C++/read-n-characters-given-read4-ii-call-multiple-times.cpp) [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| -163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [C++](./C++/missing-ranges.cpp) [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search From 13867d366286da85f50ef4217c86702535d1e3cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Feb 2016 18:06:19 +0800 Subject: [PATCH 1682/1939] Update missing-ranges.py --- Python/missing-ranges.py | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/Python/missing-ranges.py b/Python/missing-ranges.py index a4d0d1378..e43b6104c 100644 --- a/Python/missing-ranges.py +++ b/Python/missing-ranges.py @@ -8,33 +8,34 @@ # return ["2", "4->49", "51->74", "76->99"]. # -class Solution: - # @param A, a list of integers - # @param lower, an integer - # @param upper, an integer - # @return a list of strings - def findMissingRanges(self, A, lower, upper): +class Solution(object): + def findMissingRanges(self, nums, lower, upper): + """ + :type nums: List[int] + :type lower: int + :type upper: int + :rtype: List[str] + """ + def getRange(lower, upper): + if lower == upper: + return "{}".format(lower) + else: + return "{}->{}".format(lower, upper) ranges = [] pre = lower - 1 - for i in xrange(len(A) + 1): - if i == len(A): + for i in xrange(len(nums) + 1): + if i == len(nums): cur = upper + 1 else: - cur = A[i] - + cur = nums[i] if cur - pre >= 2: - ranges.append(self.getRange(pre + 1, cur - 1)) + ranges.append(getRange(pre + 1, cur - 1)) pre = cur return ranges - - def getRange(self, lower, upper): - if lower == upper: - return "{}".format(lower) - else: - return "{}->{}".format(lower, upper) - + + if __name__ == "__main__": - print Solution().findMissingRanges([0, 1, 3, 50, 75], 0, 99) \ No newline at end of file + print Solution().findMissingRanges([0, 1, 3, 50, 75], 0, 99) From ce58d3c82c9f27d209809187cd8454632e52baa6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Feb 2016 14:29:38 +0800 Subject: [PATCH 1683/1939] Create majority-element.cpp --- C++/majority-element.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/majority-element.cpp diff --git a/C++/majority-element.cpp b/C++/majority-element.cpp new file mode 100644 index 000000000..4d0d38cb8 --- /dev/null +++ b/C++/majority-element.cpp @@ -0,0 +1,21 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int majorityElement(vector& nums) { + int ans = nums[0], cnt = 1; + for (const auto& i : nums) { + if (i == ans) { + ++cnt; + } else { + --cnt; + if (cnt == 0) { + ans = i; + cnt = 1; + } + } + } + return ans; + } +}; From 3a5f61cedbd93e9108254aa1e59cead30d07df95 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Feb 2016 14:30:19 +0800 Subject: [PATCH 1684/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9865ed13e..32df0ab53 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [C++](./C++/read-n-characters-given-read4.cpp) [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |📖| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [C++](./C++/read-n-characters-given-read4-ii-call-multiple-times.cpp) [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [C++](./C++/missing-ranges.cpp) [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | -169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | +169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [C++](./C++/majority-element.cpp) [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | EPI| From cad42e9fcef471bbb5951402b472db40ee765f5b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 16:15:04 +0800 Subject: [PATCH 1685/1939] Create reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/reconstruct-itinerary.cpp diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp new file mode 100644 index 000000000..b3767f008 --- /dev/null +++ b/C++/reconstruct-itinerary.cpp @@ -0,0 +1,38 @@ +// Time: O((n-1)!) +// Space: O(n) + +class Solution { +public: + vector findItinerary(vector> tickets) { + unordered_map> graph; + for (const auto& ticket : tickets) { + ++graph[ticket.first][ticket.second]; + } + const string start = "JFK"; + vector ans{start}; + routeHelper(start, tickets.size(), &graph, &ans); + return ans; + } + +private: + bool routeHelper(const string& start, const int size, + unordered_map> *graph, vector *ans) { + + if (size == 0) { + return true; + } + + for (const auto& neighbor : (*graph)[start]) { + if ((*graph)[start][neighbor.first]) { + --(*graph)[start][neighbor.first]; + ans->emplace_back(neighbor.first); + if (dfs(neighbor.first, size - 1, graph, ans)) { + return true; + } + ans->pop_back(); + ++(*graph)[start][neighbor.first]; + } + } + return false; + } +}; From 214fe9d51bd7cc7234d828aa57bcc1da6da17376 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 16:18:19 +0800 Subject: [PATCH 1686/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 32df0ab53..a92454723 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-331%20%2F%20331-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-332%20%2F%20332-ff69b4.svg) -Up to date (2016-02-01), there are `314` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-02-04), there are `315` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `331` questions. +Here is the classification of all `332` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -358,6 +358,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| 301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(C(n, c))_ | _O(c)_ | Medium ||| 329| [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./C++/longest-increasing-path-in-a-matrix.cpp) [Python](./Python/longest-increasing-path-in-a-matrix.py) | _O(m * n)_ | _O(m * n)_ | Medium ||| +332| [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [C++](./C++/longest-increasing-path-in-a-matrix.cpp) [Python](./Python/reconstruct-itinerary.py) | _O(n!)_ | _O(n)_ | Medium ||| ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From fb715b40490c9eab83c5b72a5436e2e169f54955 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 16:18:58 +0800 Subject: [PATCH 1687/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a92454723..1b4b5c229 100644 --- a/README.md +++ b/README.md @@ -358,7 +358,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| 301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(C(n, c))_ | _O(c)_ | Medium ||| 329| [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./C++/longest-increasing-path-in-a-matrix.cpp) [Python](./Python/longest-increasing-path-in-a-matrix.py) | _O(m * n)_ | _O(m * n)_ | Medium ||| -332| [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [C++](./C++/longest-increasing-path-in-a-matrix.cpp) [Python](./Python/reconstruct-itinerary.py) | _O(n!)_ | _O(n)_ | Medium ||| +332| [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [C++](./C++/reconstruct-itinerary.cpp) [Python](./Python/reconstruct-itinerary.py) | _O(n!)_ | _O(n)_ | Medium ||| ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From 59853df254a3c1337dfd40be45cac0a0e65516f7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 16:19:19 +0800 Subject: [PATCH 1688/1939] Update reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp index b3767f008..ba2bc3d83 100644 --- a/C++/reconstruct-itinerary.cpp +++ b/C++/reconstruct-itinerary.cpp @@ -1,4 +1,4 @@ -// Time: O((n-1)!) +// Time: O(n!) // Space: O(n) class Solution { From f9a4a3ec55439c3c3546c1415de3f509915ee4bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 16:20:02 +0800 Subject: [PATCH 1689/1939] Update reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp index ba2bc3d83..549c9d6b6 100644 --- a/C++/reconstruct-itinerary.cpp +++ b/C++/reconstruct-itinerary.cpp @@ -26,7 +26,7 @@ class Solution { if ((*graph)[start][neighbor.first]) { --(*graph)[start][neighbor.first]; ans->emplace_back(neighbor.first); - if (dfs(neighbor.first, size - 1, graph, ans)) { + if (routeHelper(neighbor.first, size - 1, graph, ans)) { return true; } ans->pop_back(); From 45230350053b31189605a8c9aadf7823a325f813 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 16:48:07 +0800 Subject: [PATCH 1690/1939] Create reconstruct-itinerary.py --- Python/reconstruct-itinerary.py | 54 +++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/reconstruct-itinerary.py diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py new file mode 100644 index 000000000..54ea00905 --- /dev/null +++ b/Python/reconstruct-itinerary.py @@ -0,0 +1,54 @@ +# Time: O(n!) +# Space: O(1) + +# 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 may 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. + +class Solution(object): + def findItinerary(self, tickets): + """ + :type tickets: List[List[str]] + :rtype: List[str] + """ + def route_helper(start, graph, size, ans): + if size == 0: + return True + + for i, (end, valid) in enumerate(graph[start]): + if valid: + graph[start][i][1] = 0 + ans.append(end) + if route_helper(end, graph, size - 1, ans): + return ans + ans.pop() + graph[start][i][1] = 1 + return False + + graph = collections.defaultdict(list) + for ticket in tickets: + graph[ticket[0]].append([ticket[1], 1]) + for k in graph.keys(): + graph[k].sort() + + start = "JFK" + ans = [start] + route_helper(start, graph, len(tickets), ans) + return ans From f2eb1c8dbd0b7d688e128774c32347aad422cb07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 16:49:44 +0800 Subject: [PATCH 1691/1939] Update reconstruct-itinerary.py --- Python/reconstruct-itinerary.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py index 54ea00905..bff03d710 100644 --- a/Python/reconstruct-itinerary.py +++ b/Python/reconstruct-itinerary.py @@ -34,17 +34,17 @@ def route_helper(start, graph, size, ans): for i, (end, valid) in enumerate(graph[start]): if valid: - graph[start][i][1] = 0 + graph[start][i][1] = False ans.append(end) if route_helper(end, graph, size - 1, ans): return ans ans.pop() - graph[start][i][1] = 1 + graph[start][i][1] = True return False graph = collections.defaultdict(list) for ticket in tickets: - graph[ticket[0]].append([ticket[1], 1]) + graph[ticket[0]].append([ticket[1], True]) for k in graph.keys(): graph[k].sort() From 6b6093be6eaad29a76db3f45bb69c30869ca2f6f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 16:50:49 +0800 Subject: [PATCH 1692/1939] Update reconstruct-itinerary.py --- Python/reconstruct-itinerary.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py index bff03d710..3d227d7e1 100644 --- a/Python/reconstruct-itinerary.py +++ b/Python/reconstruct-itinerary.py @@ -28,7 +28,7 @@ def findItinerary(self, tickets): :type tickets: List[List[str]] :rtype: List[str] """ - def route_helper(start, graph, size, ans): + def route_helper(start, size, graph, ans): if size == 0: return True @@ -36,7 +36,7 @@ def route_helper(start, graph, size, ans): if valid: graph[start][i][1] = False ans.append(end) - if route_helper(end, graph, size - 1, ans): + if route_helper(end, size - 1, graph, ans): return ans ans.pop() graph[start][i][1] = True @@ -50,5 +50,5 @@ def route_helper(start, graph, size, ans): start = "JFK" ans = [start] - route_helper(start, graph, len(tickets), ans) + route_helper(start, len(tickets), graph, ans) return ans From ff965b282722fa78cfb72fa0fced8ece39368d59 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 17:04:10 +0800 Subject: [PATCH 1693/1939] Update reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp index 549c9d6b6..d307240f0 100644 --- a/C++/reconstruct-itinerary.cpp +++ b/C++/reconstruct-itinerary.cpp @@ -1,5 +1,5 @@ -// Time: O(n!) -// Space: O(n) +// Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, ni is the number of ticket which from is node i +// Space: O(t) class Solution { public: From 491b1ce982ccfe7aac352d794b7d882efbaa0c1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 17:05:05 +0800 Subject: [PATCH 1694/1939] Update reconstruct-itinerary.py --- Python/reconstruct-itinerary.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py index 3d227d7e1..1dc66fe7f 100644 --- a/Python/reconstruct-itinerary.py +++ b/Python/reconstruct-itinerary.py @@ -1,5 +1,5 @@ -# Time: O(n!) -# Space: O(1) +# Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, ni is the number of ticket which from is node i +# Space: O(t) # Given a list of airline tickets represented by pairs of departure # and arrival airports [from, to], reconstruct the itinerary in order. From 874c51d1519769c489db82dcdbff049a7ef36b02 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 17:06:36 +0800 Subject: [PATCH 1695/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1b4b5c229..b6a0108e9 100644 --- a/README.md +++ b/README.md @@ -358,7 +358,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| 301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(C(n, c))_ | _O(c)_ | Medium ||| 329| [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./C++/longest-increasing-path-in-a-matrix.cpp) [Python](./Python/longest-increasing-path-in-a-matrix.py) | _O(m * n)_ | _O(m * n)_ | Medium ||| -332| [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [C++](./C++/reconstruct-itinerary.cpp) [Python](./Python/reconstruct-itinerary.py) | _O(n!)_ | _O(n)_ | Medium ||| +332| [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [C++](./C++/reconstruct-itinerary.cpp) [Python](./Python/reconstruct-itinerary.py) | _O(t! / (n1! * n2! * ... * nk!))_ | _O(t)_ | Medium ||| ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From 12460b86799069b40b703e322bacaf061fc08259 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 17:07:53 +0800 Subject: [PATCH 1696/1939] Update reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp index d307240f0..6ee3e52da 100644 --- a/C++/reconstruct-itinerary.cpp +++ b/C++/reconstruct-itinerary.cpp @@ -1,4 +1,6 @@ -// Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, ni is the number of ticket which from is node i +// Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, +// ni is the number of ticket which from is node i, +// k is the total number of cities. // Space: O(t) class Solution { From 04c873c8069a333ddfb9c4a352295f60290074f8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 17:08:18 +0800 Subject: [PATCH 1697/1939] Update reconstruct-itinerary.py --- Python/reconstruct-itinerary.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py index 1dc66fe7f..1d5ca67f1 100644 --- a/Python/reconstruct-itinerary.py +++ b/Python/reconstruct-itinerary.py @@ -1,5 +1,6 @@ -# Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, ni is the number of ticket which from is node i -# Space: O(t) +# Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, +# ni is the number of ticket which from is node i, +# k is the total number of cities. # Given a list of airline tickets represented by pairs of departure # and arrival airports [from, to], reconstruct the itinerary in order. From 1774dd8146c3edb879f9decb0b094cd36a694e07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 17:08:38 +0800 Subject: [PATCH 1698/1939] Update reconstruct-itinerary.py --- Python/reconstruct-itinerary.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py index 1d5ca67f1..449958bf3 100644 --- a/Python/reconstruct-itinerary.py +++ b/Python/reconstruct-itinerary.py @@ -1,6 +1,7 @@ # Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, # ni is the number of ticket which from is node i, # k is the total number of cities. +# Space: O(t) # Given a list of airline tickets represented by pairs of departure # and arrival airports [from, to], reconstruct the itinerary in order. From b24759cb2a4e5c7af7d51d41fdb7d428dbb0dd72 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 17:09:27 +0800 Subject: [PATCH 1699/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b6a0108e9..88cec92fd 100644 --- a/README.md +++ b/README.md @@ -358,7 +358,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 282| [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | [C++](./C++/expression-add-operators.cpp) [Python](./Python/expression-add-operators.py) | _O(4^n)_ | _O(n)_ | Hard ||| 301| [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./C++/remove-invalid-parentheses.cpp) [Python](./Python/remove-invalid-parentheses.py) | _O(C(n, c))_ | _O(c)_ | Medium ||| 329| [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./C++/longest-increasing-path-in-a-matrix.cpp) [Python](./Python/longest-increasing-path-in-a-matrix.py) | _O(m * n)_ | _O(m * n)_ | Medium ||| -332| [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [C++](./C++/reconstruct-itinerary.cpp) [Python](./Python/reconstruct-itinerary.py) | _O(t! / (n1! * n2! * ... * nk!))_ | _O(t)_ | Medium ||| +332| [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [C++](./C++/reconstruct-itinerary.cpp) [Python](./Python/reconstruct-itinerary.py) | _O(t! / (n1! * n2! * ... nk!))_ | _O(t)_ | Medium ||| ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From 5fb4b2ac38a43a09879e9a1e54681b5059b786fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 17:31:13 +0800 Subject: [PATCH 1700/1939] Update reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp index 6ee3e52da..32041844d 100644 --- a/C++/reconstruct-itinerary.cpp +++ b/C++/reconstruct-itinerary.cpp @@ -24,15 +24,15 @@ class Solution { return true; } - for (const auto& neighbor : (*graph)[start]) { + for (auto& neighbor : (*graph)[start]) { if ((*graph)[start][neighbor.first]) { - --(*graph)[start][neighbor.first]; + --neighbor.second; ans->emplace_back(neighbor.first); if (routeHelper(neighbor.first, size - 1, graph, ans)) { return true; } ans->pop_back(); - ++(*graph)[start][neighbor.first]; + ++neighbor.second; } } return false; From 802b7b5274792522bdeff6170a7f51b7746800e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 17:46:16 +0800 Subject: [PATCH 1701/1939] Update reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp index 32041844d..97d5dd6a6 100644 --- a/C++/reconstruct-itinerary.cpp +++ b/C++/reconstruct-itinerary.cpp @@ -10,7 +10,7 @@ class Solution { for (const auto& ticket : tickets) { ++graph[ticket.first][ticket.second]; } - const string start = "JFK"; + const string start{"JFK"}; vector ans{start}; routeHelper(start, tickets.size(), &graph, &ans); return ans; @@ -18,14 +18,14 @@ class Solution { private: bool routeHelper(const string& start, const int size, - unordered_map> *graph, vector *ans) { + unordered_map> *graph, vector *ans) { if (size == 0) { return true; } for (auto& neighbor : (*graph)[start]) { - if ((*graph)[start][neighbor.first]) { + if (neighbor.second) { --neighbor.second; ans->emplace_back(neighbor.first); if (routeHelper(neighbor.first, size - 1, graph, ans)) { From 13a5751e616cfd85978b644bbb38ae8c2a0a9a97 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 18:42:39 +0800 Subject: [PATCH 1702/1939] Update reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp index 97d5dd6a6..835ce8b38 100644 --- a/C++/reconstruct-itinerary.cpp +++ b/C++/reconstruct-itinerary.cpp @@ -10,29 +10,29 @@ class Solution { for (const auto& ticket : tickets) { ++graph[ticket.first][ticket.second]; } - const string start{"JFK"}; - vector ans{start}; - routeHelper(start, tickets.size(), &graph, &ans); + const string from{"JFK"}; + vector ans{from}; + routeHelper(from, tickets.size(), &graph, &ans); return ans; } private: - bool routeHelper(const string& start, const int size, + bool routeHelper(const string& from, const int size, unordered_map> *graph, vector *ans) { if (size == 0) { return true; } - for (auto& neighbor : (*graph)[start]) { - if (neighbor.second) { - --neighbor.second; - ans->emplace_back(neighbor.first); - if (routeHelper(neighbor.first, size - 1, graph, ans)) { + for (auto& to : (*graph)[from]) { + if (to.second) { + --to.second; + ans->emplace_back(to.first); + if (routeHelper(to.first, size - 1, graph, ans)) { return true; } ans->pop_back(); - ++neighbor.second; + ++to.second; } } return false; From 7d992c310cb1d9e60dced6b3cca31bf5ab21c738 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 18:46:02 +0800 Subject: [PATCH 1703/1939] Update reconstruct-itinerary.py --- Python/reconstruct-itinerary.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py index 449958bf3..e25f02658 100644 --- a/Python/reconstruct-itinerary.py +++ b/Python/reconstruct-itinerary.py @@ -30,18 +30,18 @@ def findItinerary(self, tickets): :type tickets: List[List[str]] :rtype: List[str] """ - def route_helper(start, size, graph, ans): + def route_helper(origin, size, graph, ans): if size == 0: return True - for i, (end, valid) in enumerate(graph[start]): + for i, (dest, valid) in enumerate(graph[origin]): if valid: - graph[start][i][1] = False - ans.append(end) - if route_helper(end, size - 1, graph, ans): + graph[origin][i][1] = False + ans.append(dest) + if route_helper(dest, size - 1, graph, ans): return ans ans.pop() - graph[start][i][1] = True + graph[origin][i][1] = True return False graph = collections.defaultdict(list) @@ -50,7 +50,7 @@ def route_helper(start, size, graph, ans): for k in graph.keys(): graph[k].sort() - start = "JFK" - ans = [start] - route_helper(start, len(tickets), graph, ans) + origin = "JFK" + ans = [origin] + route_helper(origin, len(tickets), graph, ans) return ans From 3ed4650407c7404702927296105f759bd555a33f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 18:55:01 +0800 Subject: [PATCH 1704/1939] Update reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp index 835ce8b38..379a79d09 100644 --- a/C++/reconstruct-itinerary.cpp +++ b/C++/reconstruct-itinerary.cpp @@ -17,10 +17,10 @@ class Solution { } private: - bool routeHelper(const string& from, const int size, + bool routeHelper(const string& from, const int ticket_cnt, unordered_map> *graph, vector *ans) { - if (size == 0) { + if (ticket_cnt == 0) { return true; } @@ -28,7 +28,7 @@ class Solution { if (to.second) { --to.second; ans->emplace_back(to.first); - if (routeHelper(to.first, size - 1, graph, ans)) { + if (routeHelper(to.first, ticket_cnt - 1, graph, ans)) { return true; } ans->pop_back(); From 23381e5115ea390ed6e3d1a15f46a158876a4ec4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 18:55:45 +0800 Subject: [PATCH 1705/1939] Update reconstruct-itinerary.py --- Python/reconstruct-itinerary.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py index e25f02658..d2b77090a 100644 --- a/Python/reconstruct-itinerary.py +++ b/Python/reconstruct-itinerary.py @@ -30,15 +30,15 @@ def findItinerary(self, tickets): :type tickets: List[List[str]] :rtype: List[str] """ - def route_helper(origin, size, graph, ans): - if size == 0: + def route_helper(origin, ticket_cnt, graph, ans): + if ticket_cnt == 0: return True for i, (dest, valid) in enumerate(graph[origin]): if valid: graph[origin][i][1] = False ans.append(dest) - if route_helper(dest, size - 1, graph, ans): + if route_helper(dest, ticket_cnt - 1, graph, ans): return ans ans.pop() graph[origin][i][1] = True From a1a96b04909e51cb59a5ba2b5ad16c626285c636 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 22:42:29 +0800 Subject: [PATCH 1706/1939] Update reconstruct-itinerary.cpp --- C++/reconstruct-itinerary.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/reconstruct-itinerary.cpp b/C++/reconstruct-itinerary.cpp index 379a79d09..d53398a59 100644 --- a/C++/reconstruct-itinerary.cpp +++ b/C++/reconstruct-itinerary.cpp @@ -1,5 +1,5 @@ // Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, -// ni is the number of ticket which from is node i, +// ni is the number of the ticket which from is city i, // k is the total number of cities. // Space: O(t) From d296997d74f605eaeee2ebdee70f2a2df12249a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Feb 2016 22:42:45 +0800 Subject: [PATCH 1707/1939] Update reconstruct-itinerary.py --- Python/reconstruct-itinerary.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py index d2b77090a..2305889b4 100644 --- a/Python/reconstruct-itinerary.py +++ b/Python/reconstruct-itinerary.py @@ -1,5 +1,5 @@ # Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, -# ni is the number of ticket which from is node i, +# ni is the number of the ticket which from is city i, # k is the total number of cities. # Space: O(t) From 8f357f5b4ab5f842ccb4e2f2a0c2f765fed5482b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 5 Feb 2016 11:35:53 +0800 Subject: [PATCH 1708/1939] Create rotate.cpp --- C++/rotate.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/rotate.cpp diff --git a/C++/rotate.cpp b/C++/rotate.cpp new file mode 100644 index 000000000..ad98c3b4a --- /dev/null +++ b/C++/rotate.cpp @@ -0,0 +1,14 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + void rotate(vector& nums, int k) { + if (!nums.empty()) { + k %= nums.size(); + reverse(nums.begin(), nums.begin() + nums.size() - k); + reverse(nums.begin() + nums.size() - k, nums.end()); + reverse(nums.begin(), nums.end()); + } + } +}; From 0639fd54e70608fc0a369beab9c84a30ae3506b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 5 Feb 2016 11:37:15 +0800 Subject: [PATCH 1709/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88cec92fd..da0671795 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [C++](./C++/read-n-characters-given-read4-ii-call-multiple-times.cpp) [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |📖| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [C++](./C++/missing-ranges.cpp) [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [C++](./C++/majority-element.cpp) [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | -189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || +189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [C++](./C++/rotate-array.cpp) [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | EPI| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Easy | | From c54ae4388f83b758501aa69de9845f07070ed3cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 5 Feb 2016 11:37:17 +0800 Subject: [PATCH 1710/1939] Rename rotate.cpp to rotate-array.cpp --- C++/{rotate.cpp => rotate-array.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{rotate.cpp => rotate-array.cpp} (100%) diff --git a/C++/rotate.cpp b/C++/rotate-array.cpp similarity index 100% rename from C++/rotate.cpp rename to C++/rotate-array.cpp From eeef683e40c982b451327816051f04f5849cbc31 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 Feb 2016 21:42:22 +0800 Subject: [PATCH 1711/1939] Create minimum-size-subarray-sum.cpp --- C++/minimum-size-subarray-sum.cpp | 46 +++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/minimum-size-subarray-sum.cpp diff --git a/C++/minimum-size-subarray-sum.cpp b/C++/minimum-size-subarray-sum.cpp new file mode 100644 index 000000000..cb3a91994 --- /dev/null +++ b/C++/minimum-size-subarray-sum.cpp @@ -0,0 +1,46 @@ +// Time: O(n) +// Space: O(1) + +// Sliding window solution. +class Solution { +public: + int minSubArrayLen(int s, vector& nums) { + int start = -1, sum = 0, min_size = numeric_limits::max(); + for (int i = 0; i < nums.size(); ++i) { + sum += nums[i]; + while (sum >= s) { + min_size = min(min_size, i - start); + sum -= nums[++start]; + } + } + if (min_size == numeric_limits::max()) { + return 0; + } + return min_size; + } +}; + +// Time: O(nlogn) +// Space: O(n) +// Binary search solution. +class Solution2 { +public: + int minSubArrayLen(int s, vector& nums) { + int min_size = numeric_limits::max(); + vector sum_from_start(nums.size() + 1); + partial_sum(nums.cbegin(), nums.cend(), sum_from_start.begin() + 1); + for (int i = 0; i < nums.size(); ++i) { + const auto& end_it = lower_bound(sum_from_start.cbegin() + i, + sum_from_start.cend(), + sum_from_start[i] + s); + if (end_it != sum_from_start.cend()) { + int end = static_cast(end_it - sum_from_start.cbegin()); + min_size = min(min_size, end - i); + } + } + if (min_size == numeric_limits::max()) { + return 0; + } + return min_size; + } +}; From 768d403a4361e051614a8758832fbfbbe753256c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 Feb 2016 21:43:02 +0800 Subject: [PATCH 1712/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index da0671795..cf3e218da 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [C++](./C++/missing-ranges.cpp) [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [C++](./C++/majority-element.cpp) [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [C++](./C++/rotate-array.cpp) [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || -209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search +209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [C++] (./C++/minimum-size-subarray-sum.cpp) [Python] (./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++] (./C++/kth-largest-element-in-an-array.cpp) [Python] (./Python/kth-largest-element-in-an-array.py)| _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | EPI| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Easy | | 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | | From 85940f0f9e4a5cc8c0d6d8fc974176c67a2416ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Feb 2016 23:25:35 +0800 Subject: [PATCH 1713/1939] Update and rename longestPalindrome.cpp to longest-palindromic-substring.cpp --- C++/longest-palindromic-substring.cpp | 54 +++++++++++++++++++++++++++ C++/longestPalindrome.cpp | 52 -------------------------- 2 files changed, 54 insertions(+), 52 deletions(-) create mode 100644 C++/longest-palindromic-substring.cpp delete mode 100644 C++/longestPalindrome.cpp diff --git a/C++/longest-palindromic-substring.cpp b/C++/longest-palindromic-substring.cpp new file mode 100644 index 000000000..857d82150 --- /dev/null +++ b/C++/longest-palindromic-substring.cpp @@ -0,0 +1,54 @@ +// Time: O(n) +// Space: O(n) + +// Manacher's Algorithm. +class Solution { +public: + string longestPalindrome(string s) { + string T = preProcess(s); + int n = T.length(); + vector P(n); + int C = 0, R = 0; + for (int i = 1; i < n - 1; ++i) { + int i_mirror = 2*C-i; // equals to i' = C - (i-C) + + P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; + + // Attempt to expand palindrome centered at i + while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) { + ++P[i]; + } + + // If palindrome centered at i expand past R, + // adjust center based on expanded palindrome. + if (i + P[i] > R) { + C = i; + R = i + P[i]; + } + } + + // Find the maximum element in P. + int max_len = 0, center_index = 0; + for (int i = 1; i < n - 1; ++i) { + if (P[i] > max_len) { + max_len = P[i]; + center_index = i; + } + } + + return s.substr((center_index - 1 - max_len) / 2, max_len); + } + private: + string preProcess(const string& s) { + if (s.empty()) { + return "^$"; + } + string ret = "^"; + for (int i = 0; i < s.length(); ++i) { + ret += "#" + s.substr(i, 1); + } + + ret += "#$"; + return ret; + } +}; diff --git a/C++/longestPalindrome.cpp b/C++/longestPalindrome.cpp deleted file mode 100644 index 51e4acc9b..000000000 --- a/C++/longestPalindrome.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(n) - -class Solution { - public: - // Manacher's Algorithm - string longestPalindrome(string s) { - string T = preProcess(s); - int n = T.length(); - vector P(n); - int C = 0, R = 0; - for (int i = 1; i < n-1; i++) { - int i_mirror = 2*C-i; // equals to i' = C - (i-C) - - P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0; - - // Attempt to expand palindrome centered at i - while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) - P[i]++; - - // If palindrome centered at i expand past R, - // adjust center based on expanded palindrome. - if (i + P[i] > R) { - C = i; - R = i + P[i]; - } - } - - // Find the maximum element in P. - int maxLen = 0; - int centerIndex = 0; - for (int i = 1; i < n-1; i++) { - if (P[i] > maxLen) { - maxLen = P[i]; - centerIndex = i; - } - } - - return s.substr((centerIndex - 1 - maxLen)/2, maxLen); - } - private: - string preProcess(string s) { - int n = s.length(); - if (n == 0) return "^$"; - string ret = "^"; - for (int i = 0; i < n; i++) - ret += "#" + s.substr(i, 1); - - ret += "#$"; - return ret; - } -}; From 19fc9ef66170f3c6c68f8f5e7b638cf3154a2ed8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Feb 2016 23:26:22 +0800 Subject: [PATCH 1714/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cf3e218da..fb9fb5ef0 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## String # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` +5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [C++](./C++/longest-palindromic-substring.cpp) [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n)_ | _O(1)_ | Easy || From b02b8e0adba1ee1116ac75bdd493532280341240 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Feb 2016 23:26:58 +0800 Subject: [PATCH 1715/1939] Update longest-palindromic-substring.cpp --- C++/longest-palindromic-substring.cpp | 74 +++++++++++++-------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/C++/longest-palindromic-substring.cpp b/C++/longest-palindromic-substring.cpp index 857d82150..394585160 100644 --- a/C++/longest-palindromic-substring.cpp +++ b/C++/longest-palindromic-substring.cpp @@ -5,50 +5,50 @@ class Solution { public: string longestPalindrome(string s) { - string T = preProcess(s); - int n = T.length(); - vector P(n); - int C = 0, R = 0; - for (int i = 1; i < n - 1; ++i) { - int i_mirror = 2*C-i; // equals to i' = C - (i-C) + string T = preProcess(s); + int n = T.length(); + vector P(n); + int C = 0, R = 0; + for (int i = 1; i < n - 1; ++i) { + int i_mirror = 2*C-i; // equals to i' = C - (i-C) - P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; + P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; - // Attempt to expand palindrome centered at i - while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) { - ++P[i]; - } - - // If palindrome centered at i expand past R, - // adjust center based on expanded palindrome. - if (i + P[i] > R) { - C = i; - R = i + P[i]; - } + // Attempt to expand palindrome centered at i + while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) { + ++P[i]; } - // Find the maximum element in P. - int max_len = 0, center_index = 0; - for (int i = 1; i < n - 1; ++i) { - if (P[i] > max_len) { - max_len = P[i]; - center_index = i; - } + // If palindrome centered at i expand past R, + // adjust center based on expanded palindrome. + if (i + P[i] > R) { + C = i; + R = i + P[i]; } - - return s.substr((center_index - 1 - max_len) / 2, max_len); } - private: - string preProcess(const string& s) { - if (s.empty()) { - return "^$"; - } - string ret = "^"; - for (int i = 0; i < s.length(); ++i) { - ret += "#" + s.substr(i, 1); + + // Find the maximum element in P. + int max_len = 0, center_index = 0; + for (int i = 1; i < n - 1; ++i) { + if (P[i] > max_len) { + max_len = P[i]; + center_index = i; } + } - ret += "#$"; - return ret; + return s.substr((center_index - 1 - max_len) / 2, max_len); + } +private: + string preProcess(const string& s) { + if (s.empty()) { + return "^$"; + } + string ret = "^"; + for (int i = 0; i < s.length(); ++i) { + ret += "#" + s.substr(i, 1); } + + ret += "#$"; + return ret; + } }; From 1aa0c69f701bea7bc87bc7e0c8db6aeea8d91fb4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Feb 2016 23:28:03 +0800 Subject: [PATCH 1716/1939] Update longest-palindromic-substring.cpp --- C++/longest-palindromic-substring.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-palindromic-substring.cpp b/C++/longest-palindromic-substring.cpp index 394585160..c18a5d92d 100644 --- a/C++/longest-palindromic-substring.cpp +++ b/C++/longest-palindromic-substring.cpp @@ -10,7 +10,7 @@ class Solution { vector P(n); int C = 0, R = 0; for (int i = 1; i < n - 1; ++i) { - int i_mirror = 2*C-i; // equals to i' = C - (i-C) + int i_mirror = 2 * C - i; // equals to i' = C - (i-C) P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; From d2669f5d38d68e826e2077e006c9aa5cf507fd96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Feb 2016 23:30:53 +0800 Subject: [PATCH 1717/1939] Update longest-palindromic-substring.cpp --- C++/longest-palindromic-substring.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-palindromic-substring.cpp b/C++/longest-palindromic-substring.cpp index c18a5d92d..4f68af2be 100644 --- a/C++/longest-palindromic-substring.cpp +++ b/C++/longest-palindromic-substring.cpp @@ -38,6 +38,7 @@ class Solution { return s.substr((center_index - 1 - max_len) / 2, max_len); } + private: string preProcess(const string& s) { if (s.empty()) { @@ -47,7 +48,6 @@ class Solution { for (int i = 0; i < s.length(); ++i) { ret += "#" + s.substr(i, 1); } - ret += "#$"; return ret; } From 713f1f82717cc8620002e3315078e62c42543981 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Feb 2016 23:31:34 +0800 Subject: [PATCH 1718/1939] Update longest-palindromic-substring.cpp --- C++/longest-palindromic-substring.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-palindromic-substring.cpp b/C++/longest-palindromic-substring.cpp index 4f68af2be..a23ebfbcf 100644 --- a/C++/longest-palindromic-substring.cpp +++ b/C++/longest-palindromic-substring.cpp @@ -6,7 +6,7 @@ class Solution { public: string longestPalindrome(string s) { string T = preProcess(s); - int n = T.length(); + const int n = T.length(); vector P(n); int C = 0, R = 0; for (int i = 1; i < n - 1; ++i) { From 31f28477742268f52d34d155b6b7074898a1ca73 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Feb 2016 00:27:57 +0800 Subject: [PATCH 1719/1939] Update longest-palindromic-substring.cpp --- C++/longest-palindromic-substring.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-palindromic-substring.cpp b/C++/longest-palindromic-substring.cpp index a23ebfbcf..0a441016c 100644 --- a/C++/longest-palindromic-substring.cpp +++ b/C++/longest-palindromic-substring.cpp @@ -19,7 +19,7 @@ class Solution { ++P[i]; } - // If palindrome centered at i expand past R, + // If palindrome centered at i expands the past R, // adjust center based on expanded palindrome. if (i + P[i] > R) { C = i; From a661227ad954d880ff8046948e5c8e7f894d69ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Feb 2016 21:31:47 +0800 Subject: [PATCH 1720/1939] Update zigzag-conversion.py --- Python/zigzag-conversion.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Python/zigzag-conversion.py b/Python/zigzag-conversion.py index ebe4be0da..5f1b30ae9 100644 --- a/Python/zigzag-conversion.py +++ b/Python/zigzag-conversion.py @@ -14,20 +14,22 @@ # convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". # -class Solution: - # @return a string - def convert(self, s, nRows): - step, zigzag = 2 * nRows - 2, "" - if s == None or len(s) == 0 or nRows <= 0: - return "" - if nRows == 1: +class Solution(object): + def convert(self, s, numRows): + """ + :type s: str + :type numRows: int + :rtype: str + """ + step, zigzag = 2 * numRows - 2, "" + if numRows == 1: return s - for i in xrange(nRows): + for i in xrange(numRows): for j in xrange(i, len(s), step): zigzag += s[j] - if i > 0 and i < nRows - 1 and j + step - 2 * i < len(s): + if 0 < i < numRows - 1 and j + step - 2 * i < len(s): zigzag += s[j + step - 2 * i] return zigzag if __name__ == "__main__": - print Solution().convert("PAYPALISHIRING", 3) \ No newline at end of file + print Solution().convert("PAYPALISHIRING", 3) From d6f345b526462e817ead4303178a4d01c4398f58 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Feb 2016 21:32:27 +0800 Subject: [PATCH 1721/1939] Update zigzag-conversion.py --- Python/zigzag-conversion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/zigzag-conversion.py b/Python/zigzag-conversion.py index 5f1b30ae9..f5381a1b5 100644 --- a/Python/zigzag-conversion.py +++ b/Python/zigzag-conversion.py @@ -21,9 +21,9 @@ def convert(self, s, numRows): :type numRows: int :rtype: str """ - step, zigzag = 2 * numRows - 2, "" if numRows == 1: return s + step, zigzag = 2 * numRows - 2, "" for i in xrange(numRows): for j in xrange(i, len(s), step): zigzag += s[j] From b2a1fbb59cce60d9108bb3e54485f1a353aada0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Feb 2016 21:42:06 +0800 Subject: [PATCH 1722/1939] Create zigzag-conversion.cpp --- C++/zigzag-conversion.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/zigzag-conversion.cpp diff --git a/C++/zigzag-conversion.cpp b/C++/zigzag-conversion.cpp new file mode 100644 index 000000000..3cb96df9b --- /dev/null +++ b/C++/zigzag-conversion.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string convert(string s, int numRows) { + if (numRows == 1) { + return s; + } + const int step = 2 * numRows - 2; + string zigzag; + for (int i = 0; i < numRows; ++i) { + for (int j = i; j < s.length(); j += step) { + zigzag.push_back(s[j]); + if (0 < i && i < numRows - 1 && + j + step - 2 * i < s.length()) { + zigzag.push_back(s[j + step - 2 * i]); + } + } + } + return zigzag; + } +}; From 5c26b331d2bcf2c9c911f20d52782fdb27a46611 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 8 Feb 2016 21:42:47 +0800 Subject: [PATCH 1723/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fb9fb5ef0..ed559341a 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [C++](./C++/longest-palindromic-substring.cpp) [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` -6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || +6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [C++](./C++/zigzag-conversion.cpp) [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` From 1b380d5e4d280c82f26366e9ecd82f54ee3da0c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Feb 2016 18:09:20 +0800 Subject: [PATCH 1724/1939] Update and rename atoi.cpp to string-to-integer-atoi.cpp --- C++/atoi.cpp | 35 -------------------------------- C++/string-to-integer-atoi.cpp | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 35 deletions(-) delete mode 100644 C++/atoi.cpp create mode 100644 C++/string-to-integer-atoi.cpp diff --git a/C++/atoi.cpp b/C++/atoi.cpp deleted file mode 100644 index f2256ec0e..000000000 --- a/C++/atoi.cpp +++ /dev/null @@ -1,35 +0,0 @@ - -// LeetCode, String to Integer (atoi) -// Complexity: -// O(n) time -// O(1) space - -class Solution { -public: - int atoi(const char *str) { - int num = 0; - int sign = 1; - const int n = strlen(str); - int i = 0; - while (str[i] == ' ' && i < n) i++; - // parse sign - if (str[i] == '+') i++; - if (str[i] == '-') { - sign = -1; - i++; - } - - for (; i < n; i++) { - // handle non-digital character - if (str[i] < '0' || str[i] > '9') - break; - // handle overflow - if ( num > INT_MAX / 10 - || (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10)) { - return sign == -1 ? INT_MIN : INT_MAX; - } - num = num * 10 + str[i] - '0'; - } - return num * sign; - } -}; \ No newline at end of file diff --git a/C++/string-to-integer-atoi.cpp b/C++/string-to-integer-atoi.cpp new file mode 100644 index 000000000..103790639 --- /dev/null +++ b/C++/string-to-integer-atoi.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int myAtoi(string str) { + if (str.empty()) { + return 0; + } + + int ans = 0; + int sign = 1; + int i = 0; + + // Skip ' '. + while (str[i] == ' ') { + ++i; + } + + // Parse sign. + if (str[i] == '+') { + ++i; + } else if (str[i] == '-') { + sign = -1; + ++i; + } + + // Compute integer. + for (; i < str.length() && isdigit(str[i]); ++i) { + if (ans > (numeric_limits::max() - (str[i] - '0')) / 10) { + return sign > 0 ? numeric_limits::max() : numeric_limits::min(); + } + ans *= 10; + ans += str[i] - '0'; + } + + ans *= sign; + return ans; + } +}; From 48d50980d98bd609ea376284df91b40a04f6d7c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Feb 2016 18:16:40 +0800 Subject: [PATCH 1725/1939] Update string-to-integer-atoi.py --- Python/string-to-integer-atoi.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py index 17b23e886..970fd09b6 100644 --- a/Python/string-to-integer-atoi.py +++ b/Python/string-to-integer-atoi.py @@ -26,9 +26,12 @@ # If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. # -class Solution: - # @return an integer - def atoi(self, str): +class Solution(object): + def myAtoi(self, str): + """ + :type str: str + :rtype: int + """ INT_MAX = 2147483647 INT_MIN = -2147483648 result = 0 @@ -48,12 +51,8 @@ def atoi(self, str): i += 1 while i < len(str) and str[i] >= '0' and str[i] <= '9': - if result > INT_MAX / 10 or (result == INT_MAX / 10 and ord(str[i]) - ord('0') > INT_MAX % 10): - if sign > 0: - return INT_MAX - else: - return INT_MIN - + if result > (INT_MAX - (ord(str[i]) - ord('0'))) / 10: + return INT_MAX if sign > 0 else INT_MIN result = result * 10 + ord(str[i]) - ord('0') i += 1 From 9f14b50d8918a4448815b90e95c1f6c5729b4cc4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Feb 2016 18:18:28 +0800 Subject: [PATCH 1726/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ed559341a..c900a2374 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [C++](./C++/longest-palindromic-substring.cpp) [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [C++](./C++/zigzag-conversion.cpp) [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || -8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || +8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [C++](./C++/string-to-integer-atoi.cpp) [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || From 016c6ba611b472da4a00ad8381d008c7405bc851 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Feb 2016 18:19:11 +0800 Subject: [PATCH 1727/1939] Update string-to-integer-atoi.cpp --- C++/string-to-integer-atoi.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/string-to-integer-atoi.cpp b/C++/string-to-integer-atoi.cpp index 103790639..f82d208a6 100644 --- a/C++/string-to-integer-atoi.cpp +++ b/C++/string-to-integer-atoi.cpp @@ -1,3 +1,6 @@ +// Time: O(n) +// Space: O(1) + class Solution { public: int myAtoi(string str) { From 5244ff3defc1ba4c15bcf9fe9a54a7dedc4e02fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Feb 2016 16:45:52 +0800 Subject: [PATCH 1728/1939] Create longest-common-prefix.cpp --- C++/longest-common-prefix.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/longest-common-prefix.cpp diff --git a/C++/longest-common-prefix.cpp b/C++/longest-common-prefix.cpp new file mode 100644 index 000000000..1dfb32258 --- /dev/null +++ b/C++/longest-common-prefix.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string longestCommonPrefix(vector& strs) { + if (strs.empty()) { + return ""; + } + + for (int i = 0; i < strs[0].length(); ++i) { + for (const auto& str : strs) { + if (str[i] != strs[0][i]) { + return strs[0].substr(0, i); + } + } + } + return strs[0]; + } +}; From 5bc08eb8c3291b060e3bfa3c48875d7b2ec6abd6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Feb 2016 16:46:31 +0800 Subject: [PATCH 1729/1939] Update longest-common-prefix.cpp --- C++/longest-common-prefix.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-common-prefix.cpp b/C++/longest-common-prefix.cpp index 1dfb32258..444f57b11 100644 --- a/C++/longest-common-prefix.cpp +++ b/C++/longest-common-prefix.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(n * k), k is the length of the common prefix // Space: O(1) class Solution { From e401f10b62df5b8fba51dbd3710e1777c2d2c932 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Feb 2016 16:52:02 +0800 Subject: [PATCH 1730/1939] Update longest-common-prefix.cpp --- C++/longest-common-prefix.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-common-prefix.cpp b/C++/longest-common-prefix.cpp index 444f57b11..aa362d047 100644 --- a/C++/longest-common-prefix.cpp +++ b/C++/longest-common-prefix.cpp @@ -10,7 +10,7 @@ class Solution { for (int i = 0; i < strs[0].length(); ++i) { for (const auto& str : strs) { - if (str[i] != strs[0][i]) { + if (i >= str.length() || str[i] != strs[0][i]) { return strs[0].substr(0, i); } } From 487036ba4024716604c14ce685265ffc05cb4773 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Feb 2016 16:52:34 +0800 Subject: [PATCH 1731/1939] Update longest-common-prefix.py --- Python/longest-common-prefix.py | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/Python/longest-common-prefix.py b/Python/longest-common-prefix.py index 29520fc63..5faaae780 100644 --- a/Python/longest-common-prefix.py +++ b/Python/longest-common-prefix.py @@ -1,21 +1,24 @@ -# Time: O(n) +# Time: O(n * k), k is the length of the common prefix # Space: O(1) -# -# Write a function to find the longest common prefix string amongst an array of strings. -# -class Solution: - # @return a string +# Write a function to find the longest common prefix string +# amongst an array of strings. + + +class Solution(object): def longestCommonPrefix(self, strs): + """ + :type strs: List[str] + :rtype: str + """ if not strs: return "" - longest = strs[0] - for string in strs[1:]: - i = 0 - while i < len(string) and i < len(longest) and string[i] == longest[i]: - i += 1 - longest = longest[:i] - return longest + + for i in xrange(len(strs[0])): + for string in strs: + if i >= len(string) or string[i] != strs[0][i]: + return strs[0][:i] + return strs[0] if __name__ == "__main__": print Solution().longestCommonPrefix(["hello", "heaven", "heavy"]) From 588455790e395757e7b08ca1264ea16875538bf7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Feb 2016 16:54:28 +0800 Subject: [PATCH 1732/1939] Update longest-common-prefix.py --- Python/longest-common-prefix.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Python/longest-common-prefix.py b/Python/longest-common-prefix.py index 5faaae780..970d4a11b 100644 --- a/Python/longest-common-prefix.py +++ b/Python/longest-common-prefix.py @@ -4,7 +4,6 @@ # Write a function to find the longest common prefix string # amongst an array of strings. - class Solution(object): def longestCommonPrefix(self, strs): """ @@ -19,7 +18,7 @@ def longestCommonPrefix(self, strs): if i >= len(string) or string[i] != strs[0][i]: return strs[0][:i] return strs[0] - + + if __name__ == "__main__": print Solution().longestCommonPrefix(["hello", "heaven", "heavy"]) - From ac29a01bd1427fe217aadb832b650735f0e134cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Feb 2016 16:55:18 +0800 Subject: [PATCH 1733/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c900a2374..b00856fc4 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [C++](./C++/longest-palindromic-substring.cpp) [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [C++](./C++/zigzag-conversion.cpp) [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [C++](./C++/string-to-integer-atoi.cpp) [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || -14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Python](./Python/longest-common-prefix.py) | _O(n)_ | _O(1)_ | Easy || +14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [C++](./C++/longest-common-prefix.cpp) [Python](./Python/longest-common-prefix.py) | _O(n * k)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || From 424cc636fb7b6f3b98f6e1d0705baba99d3315bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Feb 2016 17:01:47 +0800 Subject: [PATCH 1734/1939] Update implement-strstr.py --- Python/implement-strstr.py | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index b57b11261..cd3515b3b 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -9,22 +9,19 @@ # Wiki of KMP algorithm: # http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm -class Solution: - # @param haystack, a string - # @param needle, a string - # @return a string or None +class Solution(object): def strStr(self, haystack, needle): + """ + :type haystack: str + :type needle: str + :rtype: int + """ if not needle: return 0 - if len(haystack) < len(needle): - return -1 - - i = self.KMP(haystack, needle) - if i > -1: - return i - else: - return -1 + if len(haystack) >= len(needle): + return self.KMP(haystack, needle) + return -1 def KMP(self, text, pattern): prefix = self.getPrefix(pattern) From 2dcb1455393f480e35a69552d04287b7c6ec70a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Feb 2016 11:44:41 +0800 Subject: [PATCH 1735/1939] Update implement-strstr.py --- Python/implement-strstr.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index cd3515b3b..ee092917c 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -1,5 +1,5 @@ -# Time: O(n + m) -# Space: O(m) +# Time: O(n + k) +# Space: O(k) # # Implement strStr(). # @@ -46,8 +46,8 @@ def getPrefix(self, pattern): prefix[i] = j return prefix -# Time: (n * m) -# Space: (1) +# Time: (n * k) +# Space: (k) class Solution2: # @param haystack, a string # @param needle, a string From 34d067490caa741a657b537cfc428f4578811817 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Feb 2016 11:45:23 +0800 Subject: [PATCH 1736/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b00856fc4..702e8babf 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [C++](./C++/zigzag-conversion.cpp) [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [C++](./C++/string-to-integer-atoi.cpp) [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [C++](./C++/longest-common-prefix.cpp) [Python](./Python/longest-common-prefix.py) | _O(n * k)_ | _O(1)_ | Easy || -28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](./Python/implement-strstr.py) | _O(n + m)_ | _O(m)_ | Easy || `KMP Algorithm` +28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [C++](./C++/implement-strstr.cpp) [Python](./Python/implement-strstr.py) | _O(n + k)_ | _O(k)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || From 5b061a163d57efef065be84060f8fbdbd6439e24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Feb 2016 11:48:46 +0800 Subject: [PATCH 1737/1939] Update implement-strstr.py --- Python/implement-strstr.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index ee092917c..c85213cd3 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -19,9 +19,7 @@ def strStr(self, haystack, needle): if not needle: return 0 - if len(haystack) >= len(needle): - return self.KMP(haystack, needle) - return -1 + return self.KMP(haystack, needle) def KMP(self, text, pattern): prefix = self.getPrefix(pattern) From fcad81198e025a10bd6037ee90373cc0df774aa0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Feb 2016 11:54:35 +0800 Subject: [PATCH 1738/1939] Update and rename strStr.cpp to implement-strstr.cpp --- C++/implement-strstr.cpp | 66 ++++++++++++++++++++++++++++++++++++++++ C++/strStr.cpp | 46 ---------------------------- 2 files changed, 66 insertions(+), 46 deletions(-) create mode 100644 C++/implement-strstr.cpp delete mode 100644 C++/strStr.cpp diff --git a/C++/implement-strstr.cpp b/C++/implement-strstr.cpp new file mode 100644 index 000000000..ca1140f77 --- /dev/null +++ b/C++/implement-strstr.cpp @@ -0,0 +1,66 @@ +// Time: O(n + k) +// Space: O(k) + +// Wiki of KMP algorithm: +// http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm +class Solution { +public: + int strStr(string haystack, string needle) { + if (needle.empty()) { + return 0; + } + + return KMP(haystack, needle); + } + + int KMP(const string& text, const string& pattern) { + const vector prefix = getPrefix(pattern); + int j = -1; + for (int i = 0; i < text.length(); ++i) { + while (j > -1 && pattern[j + 1] != text[i]) { + j = prefix[j]; + } + if (pattern[j + 1] == text[i]) { + ++j; + } + if (j == pattern.length() - 1) { + return i - j; + } + } + return -1; + } + + vector getPrefix(const string& pattern) { + vector prefix(pattern.length(), -1); + int j = -1; + for (int i = 1; i < pattern.length(); ++i) { + while (j > -1 && pattern[j + 1] != pattern[i]) { + j = prefix[j]; + } + if (pattern[j + 1] == pattern[i]) { + ++j; + } + prefix[i] = j; + } + return prefix; + } +}; + + +// Time: O(n * k) +// Space: O(k) +class Solution2 { +public: + int strStr(string haystack, string needle) { + if (needle.empty()) { + return 0; + } + + for (int i = 0; i + needle.length() < haystack.length() + 1; ++i) { + if (haystack.substr(i, needle.length()) == needle) { + return i; + } + } + return -1; + } +}; diff --git a/C++/strStr.cpp b/C++/strStr.cpp deleted file mode 100644 index 6320e9f73..000000000 --- a/C++/strStr.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// Time Complexity: O(m + n) -// Space Complexity: O(n) - -class Solution { - public: - char *strStr(char *haystack, char *needle) { - string target(haystack); - string pattern(needle); - - if(target.size() < pattern.size()) - return nullptr; - - if(pattern.size() == 0) - return haystack; - - int i = kmp(target, pattern); - - return (i != -1)? haystack + i : nullptr; - } - private: - int kmp(const string &target, const string &pattern) { - const auto m = target.size(); - const auto n = pattern.size(); - - vector failure(n, -1); - for(int i = 1, j = -1; i < n; ++i) { - while(j >= 0 && pattern[j + 1] != pattern[i]) - j = failure[j]; - if(pattern[j + 1] == pattern[i]) - ++j; - failure[i] = j; - } - - for(int i = 0, j = -1; i < m; ++i) { - while(j >= 0 && pattern[j + 1] != target[i]) - j = failure[j]; - if(pattern[j + 1] == target[i]) - ++j; - if(j == n - 1) { - return i - j; - } - } - - return -1; - } -}; From 499bf72d3af1ddf575ab6c9cbc27646cb8dca527 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Feb 2016 11:56:58 +0800 Subject: [PATCH 1739/1939] Update implement-strstr.py --- Python/implement-strstr.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index c85213cd3..97042a17f 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -44,17 +44,19 @@ def getPrefix(self, pattern): prefix[i] = j return prefix -# Time: (n * k) -# Space: (k) -class Solution2: - # @param haystack, a string - # @param needle, a string - # @return a string or None +# Time: O(n * k) +# Space: O(k) +class Solution2(object): def strStr(self, haystack, needle): + """ + :type haystack: str + :type needle: str + :rtype: int + """ for i in xrange(len(haystack) - len(needle) + 1): if haystack[i : i + len(needle)] == needle: - return haystack[i:] - return None + return i + return -1 if __name__ == "__main__": print Solution().strStr("a", "") From 0b065c5af586cad39fb5dac383a48a4f41f7db8e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 15:20:39 +0800 Subject: [PATCH 1740/1939] Create largest-bst-subtree.py --- Python/largest-bst-subtree.py | 46 +++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/largest-bst-subtree.py diff --git a/Python/largest-bst-subtree.py b/Python/largest-bst-subtree.py new file mode 100644 index 000000000..3de83b052 --- /dev/null +++ b/Python/largest-bst-subtree.py @@ -0,0 +1,46 @@ +# Time: O(n) +# Space: O(h) + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def largestBSTSubtree(self, root): + """ + :type root: TreeNode + :rtype: int + """ + if not root: + return 0 + + max_size = [1] + def largestBSTSubtreeHelper(root): + if root.left is None and root.right is None: + return 1, root.val, root.val + + if root.left is None: + size, min_val, max_val = largestBSTSubtreeHelper(root.right) + if size > 0 and root.val < min_val: + max_size[0] = max(max_size[0], 1 + size) + return 1 + size, root.val, max_val + elif root.right is None: + size, min_val, max_val = largestBSTSubtreeHelper(root.left) + if size > 0 and max_val < root.val: + max_size[0] = max(max_size[0], 1 + size) + return 1 + size, min_val, root.val + else: + left_size, left_min, left_max = largestBSTSubtreeHelper(root.left) + right_size, right_min, right_max = largestBSTSubtreeHelper(root.right) + if left_max < root.val < right_min and left_size > 0 and right_size > 0: + size = 1 + left_size + right_size + max_size[0] = max(max_size[0], size) + return size, left_min, right_max + + return 0, root.val, root.val + + largestBSTSubtreeHelper(root) + return max_size[0] From 61eae3cca657947c51f12ff3e3b091f61801a0ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 15:36:42 +0800 Subject: [PATCH 1741/1939] Create largest-bst-subtree.cpp --- C++/largest-bst-subtree.cpp | 58 +++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 C++/largest-bst-subtree.cpp diff --git a/C++/largest-bst-subtree.cpp b/C++/largest-bst-subtree.cpp new file mode 100644 index 000000000..e45d9ebbd --- /dev/null +++ b/C++/largest-bst-subtree.cpp @@ -0,0 +1,58 @@ +// Time: O(n) +// Space: O(h) + +/** + * 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: + int largestBSTSubtree(TreeNode* root) { + if (!root) { + return 0; + } + + int max_size = 1; + largestBSTSubtreeHelper(root, &max_size); + return max_size; + } + +private: + tuple largestBSTSubtreeHelper(TreeNode* root, int *max_size) { + if (!root->left && !root->right) { + return make_tuple(1, root->val, root->val); + } + + if (!root->left) { + int size, min_val, max_val; + tie(size, min_val, max_val) = largestBSTSubtreeHelper(root->right, max_size); + if (size > 0 && root->val < min_val) { + *max_size = max(*max_size, 1 + size); + return make_tuple(1 + size, root->val, max_val); + } + } else if (!root->right) { + int size, min_val, max_val; + tie(size, min_val, max_val) = largestBSTSubtreeHelper(root->left, max_size); + if (size > 0 && max_val < root->val) { + *max_size = max(*max_size, 1 + size); + return make_tuple(1 + size, min_val, root->val); + } + } else { + int left_size, left_min, left_max, right_size, right_min, right_max; + tie(left_size, left_min, left_max) = largestBSTSubtreeHelper(root->left, max_size); + tie(right_size, right_min, right_max) = largestBSTSubtreeHelper(root->right, max_size); + if (left_size > 0 && right_size > 0 && + left_max < root->val && root->val < right_min) { + *max_size = max(*max_size, 1 + left_size + right_size); + return make_tuple(1 + left_size + right_size, left_min, right_max); + } + } + + return make_tuple(0, root->val, root->val); + } +}; From c41bc1ee0ddc01179ff19db5bbc8ed7326a31a47 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 15:59:21 +0800 Subject: [PATCH 1742/1939] Update largest-bst-subtree.py --- Python/largest-bst-subtree.py | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/Python/largest-bst-subtree.py b/Python/largest-bst-subtree.py index 3de83b052..6a235f2cb 100644 --- a/Python/largest-bst-subtree.py +++ b/Python/largest-bst-subtree.py @@ -14,31 +14,27 @@ def largestBSTSubtree(self, root): :type root: TreeNode :rtype: int """ - if not root: + if root is None: return 0 max_size = [1] def largestBSTSubtreeHelper(root): - if root.left is None and root.right is None: - return 1, root.val, root.val + if root is None or (root.left is None and root.right is None): + return int(root is not None), root.val, root.val - if root.left is None: - size, min_val, max_val = largestBSTSubtreeHelper(root.right) - if size > 0 and root.val < min_val: - max_size[0] = max(max_size[0], 1 + size) - return 1 + size, root.val, max_val - elif root.right is None: - size, min_val, max_val = largestBSTSubtreeHelper(root.left) - if size > 0 and max_val < root.val: - max_size[0] = max(max_size[0], 1 + size) - return 1 + size, min_val, root.val - else: + left_size, left_min, left_max = 0, root.val, root.val - 1 + if root.left is not None: left_size, left_min, left_max = largestBSTSubtreeHelper(root.left) + + right_size, right_min, right_max = 0, root.val + 1, root.val + if root.right is not None: right_size, right_min, right_max = largestBSTSubtreeHelper(root.right) - if left_max < root.val < right_min and left_size > 0 and right_size > 0: - size = 1 + left_size + right_size - max_size[0] = max(max_size[0], size) - return size, left_min, right_max + + if (root.left is None or left_size > 0) and \ + (root.right is None or right_size > 0) and \ + left_max < root.val < right_min: + max_size[0] = max(max_size[0], 1 + left_size + right_size) + return 1 + left_size + right_size, left_min, right_max return 0, root.val, root.val From cc2995db6665b9f6ed3ee42ad674d1a52762bb49 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 16:05:24 +0800 Subject: [PATCH 1743/1939] Update largest-bst-subtree.cpp --- C++/largest-bst-subtree.cpp | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/C++/largest-bst-subtree.cpp b/C++/largest-bst-subtree.cpp index e45d9ebbd..624d4a888 100644 --- a/C++/largest-bst-subtree.cpp +++ b/C++/largest-bst-subtree.cpp @@ -28,29 +28,21 @@ class Solution { return make_tuple(1, root->val, root->val); } - if (!root->left) { - int size, min_val, max_val; - tie(size, min_val, max_val) = largestBSTSubtreeHelper(root->right, max_size); - if (size > 0 && root->val < min_val) { - *max_size = max(*max_size, 1 + size); - return make_tuple(1 + size, root->val, max_val); - } - } else if (!root->right) { - int size, min_val, max_val; - tie(size, min_val, max_val) = largestBSTSubtreeHelper(root->left, max_size); - if (size > 0 && max_val < root->val) { - *max_size = max(*max_size, 1 + size); - return make_tuple(1 + size, min_val, root->val); - } - } else { - int left_size, left_min, left_max, right_size, right_min, right_max; + int left_size = 0, left_min = root->val, left_max = root->val - 1; + if (root->left) { tie(left_size, left_min, left_max) = largestBSTSubtreeHelper(root->left, max_size); + } + + int right_size = 0, right_min = root->val + 1, right_max = root->val; + if (root->right) { tie(right_size, right_min, right_max) = largestBSTSubtreeHelper(root->right, max_size); - if (left_size > 0 && right_size > 0 && - left_max < root->val && root->val < right_min) { - *max_size = max(*max_size, 1 + left_size + right_size); - return make_tuple(1 + left_size + right_size, left_min, right_max); - } + } + + if ((!root->left || left_size > 0) && + (!root->right || right_size > 0) && + left_max < root->val && root->val < right_min) { + *max_size = max(*max_size, 1 + left_size + right_size); + return make_tuple(1 + left_size + right_size, left_min, right_max); } return make_tuple(0, root->val, root->val); From 86492fd150161b111fa931ce16577e579a67e43c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 16:14:40 +0800 Subject: [PATCH 1744/1939] Update largest-bst-subtree.cpp --- C++/largest-bst-subtree.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/C++/largest-bst-subtree.cpp b/C++/largest-bst-subtree.cpp index 624d4a888..0fbe79f6c 100644 --- a/C++/largest-bst-subtree.cpp +++ b/C++/largest-bst-subtree.cpp @@ -28,23 +28,24 @@ class Solution { return make_tuple(1, root->val, root->val); } - int left_size = 0, left_min = root->val, left_max = root->val - 1; + int left_size = 0, left_min = root->val, left_max = root->val; if (root->left) { tie(left_size, left_min, left_max) = largestBSTSubtreeHelper(root->left, max_size); } - int right_size = 0, right_min = root->val + 1, right_max = root->val; + int right_size = 0, right_min = root->val, right_max = root->val; if (root->right) { tie(right_size, right_min, right_max) = largestBSTSubtreeHelper(root->right, max_size); } + int size = 0; if ((!root->left || left_size > 0) && (!root->right || right_size > 0) && - left_max < root->val && root->val < right_min) { - *max_size = max(*max_size, 1 + left_size + right_size); - return make_tuple(1 + left_size + right_size, left_min, right_max); + left_max <= root->val && root->val <= right_min) { + size = 1 + left_size + right_size; + *max_size = max(*max_size, size); } - return make_tuple(0, root->val, root->val); + return make_tuple(size, left_min, right_max); } }; From 40e5474251c875d36dd8ec2b7a3f4cb4cd01b404 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 16:17:47 +0800 Subject: [PATCH 1745/1939] Update largest-bst-subtree.py --- Python/largest-bst-subtree.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Python/largest-bst-subtree.py b/Python/largest-bst-subtree.py index 6a235f2cb..5d42f6433 100644 --- a/Python/largest-bst-subtree.py +++ b/Python/largest-bst-subtree.py @@ -22,21 +22,22 @@ def largestBSTSubtreeHelper(root): if root is None or (root.left is None and root.right is None): return int(root is not None), root.val, root.val - left_size, left_min, left_max = 0, root.val, root.val - 1 + left_size, left_min, left_max = 0, root.val, root.val if root.left is not None: left_size, left_min, left_max = largestBSTSubtreeHelper(root.left) - right_size, right_min, right_max = 0, root.val + 1, root.val + right_size, right_min, right_max = 0, root.val, root.val if root.right is not None: right_size, right_min, right_max = largestBSTSubtreeHelper(root.right) + size = 0 if (root.left is None or left_size > 0) and \ (root.right is None or right_size > 0) and \ - left_max < root.val < right_min: - max_size[0] = max(max_size[0], 1 + left_size + right_size) - return 1 + left_size + right_size, left_min, right_max + left_max <= root.val <= right_min: + size = 1 + left_size + right_size + max_size[0] = max(max_size[0], size) - return 0, root.val, root.val + return size, left_min, right_max largestBSTSubtreeHelper(root) return max_size[0] From 23ab87778edb62e7ac1c3d867f91ba9d33379f9f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 16:19:24 +0800 Subject: [PATCH 1746/1939] Update largest-bst-subtree.py --- Python/largest-bst-subtree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/largest-bst-subtree.py b/Python/largest-bst-subtree.py index 5d42f6433..35d18f1be 100644 --- a/Python/largest-bst-subtree.py +++ b/Python/largest-bst-subtree.py @@ -19,8 +19,8 @@ def largestBSTSubtree(self, root): max_size = [1] def largestBSTSubtreeHelper(root): - if root is None or (root.left is None and root.right is None): - return int(root is not None), root.val, root.val + if root.left is None and root.right is None: + return 1, root.val, root.val left_size, left_min, left_max = 0, root.val, root.val if root.left is not None: From 57e5201379c1be9cab85794638743da8e89fda9a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 16:22:07 +0800 Subject: [PATCH 1747/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 702e8babf..8c69cf93c 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-332%20%2F%20332-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-333%20%2F%20333-ff69b4.svg) -Up to date (2016-02-04), there are `315` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-02-12), there are `316` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `332` questions. +Here is the classification of all `333` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -296,6 +296,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 241| [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | [C++](./C++/different-ways-to-add-parentheses.cpp) [Python](./Python/different-ways-to-add-parentheses.py) | _O(n * 4^n / n^(3/2))_ | _O(n * 4^n / n^(3/2))_ | Medium || 298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) | [C++](./C++/binary-tree-longest-consecutive-sequence.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence.py) | _O(n)_ | _O(h)_ | Medium |📖| 327| [Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./C++/count-of-range-sum.cpp) [Python](./Python/count-of-range-sum.py) | _O(nlogn)_ | _O(n)_ | Hard || +333 | [Largest BST Subtree](https://leetcode.com/problems/largest-bst-subtree/) | [C++](./C++/largest-bst-subtree.cpp) [Python](./Python/largest-bst-subtree.py) | _O(n)_ | _O(h)_ | Medium |📖| ## Binary Search # | Title | Solution | Time | Space | Difficulty | Tag | Note From 797beff4249cbdb44a7ad280651a9b776ca74754 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 16:53:29 +0800 Subject: [PATCH 1748/1939] Update and rename coundAndSay.cpp to count-and-say.cpp --- C++/coundAndSay.cpp | 24 ------------------------ C++/count-and-say.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 24 deletions(-) delete mode 100644 C++/coundAndSay.cpp create mode 100644 C++/count-and-say.cpp diff --git a/C++/coundAndSay.cpp b/C++/coundAndSay.cpp deleted file mode 100644 index d1285589d..000000000 --- a/C++/coundAndSay.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(n) - -class Solution { - public: - string countAndSay(int n) { - string s{"1"}; - while(--n) { - s = getNext(s); - } - return s; - } - - private: - string getNext(const string &s) { - stringstream ss; - for(auto i = s.begin(); i != s.end();) { - auto j = find_if(i, s.end(), bind1st(not_equal_to(), *i)); - ss << distance(i, j) << *i; - i = j; - } - return ss.str(); - } -}; diff --git a/C++/count-and-say.cpp b/C++/count-and-say.cpp new file mode 100644 index 000000000..491b0f2d9 --- /dev/null +++ b/C++/count-and-say.cpp @@ -0,0 +1,25 @@ +// Time: O(n * 2^n) +// Space: O(2^n) + +class Solution { +public: + string countAndSay(int n) { + string seq{"1"}; + for (int i = 0; i < n - 1; ++i) { + seq = getNext(seq); + } + return seq; + } + +private: + string getNext(const string& seq) { + string next_seq; + for(auto i = seq.cbegin(); i != seq.cend();) { + auto j = find_if(i, seq.cend(), bind1st(not_equal_to(), *i)); + next_seq.append(to_string(distance(i, j))); + next_seq.push_back(*i); + i = j; + } + return next_seq; + } +}; From 8f0d872ed1b47f8809b3368699a4d09597b62e19 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 16:55:23 +0800 Subject: [PATCH 1749/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8c69cf93c..0afef65be 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [C++](./C++/string-to-integer-atoi.cpp) [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [C++](./C++/longest-common-prefix.cpp) [Python](./Python/longest-common-prefix.py) | _O(n * k)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [C++](./C++/implement-strstr.cpp) [Python](./Python/implement-strstr.py) | _O(n + k)_ | _O(k)_ | Easy || `KMP Algorithm` -38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || +38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [C++](./C++/count-and-say.cpp [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || From eb3b7153c1f00a4775df40460fd14e43807436d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Feb 2016 16:55:58 +0800 Subject: [PATCH 1750/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0afef65be..0b4e41eb1 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [C++](./C++/string-to-integer-atoi.cpp) [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [C++](./C++/longest-common-prefix.cpp) [Python](./Python/longest-common-prefix.py) | _O(n * k)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [C++](./C++/implement-strstr.cpp) [Python](./Python/implement-strstr.py) | _O(n + k)_ | _O(k)_ | Easy || `KMP Algorithm` -38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [C++](./C++/count-and-say.cpp [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || +38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [C++](./C++/count-and-say.cpp) [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || From c2a7d2e8c23217bcf6fba5e59b071f6036879ffd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 11:33:54 +0800 Subject: [PATCH 1751/1939] Update and rename multiply.cpp to multiply-strings.cpp --- C++/multiply-strings.cpp | 59 ++++++++++++++++++++++++++++++++++++++++ C++/multiply.cpp | 57 -------------------------------------- 2 files changed, 59 insertions(+), 57 deletions(-) create mode 100644 C++/multiply-strings.cpp delete mode 100644 C++/multiply.cpp diff --git a/C++/multiply-strings.cpp b/C++/multiply-strings.cpp new file mode 100644 index 000000000..c8a3c89be --- /dev/null +++ b/C++/multiply-strings.cpp @@ -0,0 +1,59 @@ +// Time: O(m * n) +// Space: O(m + n) + +class Solution { +public: + string multiply(string num1, string num2) { + return BigInt(num1) * BigInt(num2); + } + + class BigInt { + public: + BigInt(const string& s) { + transform(s.rbegin(), s.rend(), back_inserter(n_), + [](const char c) { return c - '0';}); + } + + operator string() { + string s; + transform(find_if(n_.rbegin(), prev(n_.rend()), + [](const int i) { return i != 0; }), + n_.rend(), back_inserter(s), + [](const int i) { return i + '0'; }); + return s; + } + + BigInt operator*(const BigInt &rhs) const { + BigInt z(n_.size() + rhs.size() + 1, 0); + for(auto i = 0; i < n_.size(); ++i) { + for(auto j = 0; j < rhs.size(); ++j) { + z[i + j] += n_[i] * rhs[j]; + z[i + j + 1] += z[i + j] / 10; + z[i + j] %= 10; + } + } + return z; + } + + private: + vector n_; + + BigInt(int num, int val): n_(num, val) { + } + + // Getter. + int operator[] (int i) const { + return n_[i]; + } + + // Setter. + int & operator[] (int i) { + return n_[i]; + } + + size_t size() const { + return n_.size(); + } + }; + +}; diff --git a/C++/multiply.cpp b/C++/multiply.cpp deleted file mode 100644 index 6989e837b..000000000 --- a/C++/multiply.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class BigInt { - public: - BigInt(string s) { - transform(s.rbegin(), s.rend(), back_inserter(n), - [](const char c) { return c - '0';}); - } - - operator string() { - string s; - transform(find_if(this->n.rbegin(), prev(this->n.rend()), - [](const int i) { return i != 0; }), this->n.rend(), back_inserter(s), - [](const int i) { return i + '0'; }); - - return s; - } - - BigInt operator*(const BigInt &rhs) const { - BigInt z(n.size() + rhs.size() + 1, 0); - for(auto i = 0; i < n.size(); ++i) { - for(auto j = 0; j < rhs.size(); ++j) { - z[i + j] += n[i] * rhs[j]; - z[i + j + 1] += z[i + j] / 10; - z[i + j] %= 10; - } - } - return z; - } - private: - vector n; - - BigInt(int num, int val): n(num, val) { - } - - // getter - int operator[] (int i) const { - return this->n[i]; - } - - // setter - int & operator[] (int i) { - return this->n[i]; - } - - int size() const { - return this->n.size(); - } -}; - -class Solution { - public: - string multiply(string num1, string num2) { - return BigInt(num1) * BigInt(num2); - } -}; From 2c4b4e8470ab5fa7d9824f2ba1f61bac1e0c78f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 11:35:14 +0800 Subject: [PATCH 1752/1939] Update multiply-strings.cpp --- C++/multiply-strings.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/multiply-strings.cpp b/C++/multiply-strings.cpp index c8a3c89be..718622150 100644 --- a/C++/multiply-strings.cpp +++ b/C++/multiply-strings.cpp @@ -24,15 +24,15 @@ class Solution { } BigInt operator*(const BigInt &rhs) const { - BigInt z(n_.size() + rhs.size() + 1, 0); + BigInt res(n_.size() + rhs.size() + 1, 0); for(auto i = 0; i < n_.size(); ++i) { for(auto j = 0; j < rhs.size(); ++j) { - z[i + j] += n_[i] * rhs[j]; - z[i + j + 1] += z[i + j] / 10; - z[i + j] %= 10; + res[i + j] += n_[i] * rhs[j]; + res[i + j + 1] += res[i + j] / 10; + res[i + j] %= 10; } } - return z; + return res; } private: From 87f3cf311375733c3b2067145eec24c90e57e168 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 11:56:52 +0800 Subject: [PATCH 1753/1939] Update multiply-strings.cpp --- C++/multiply-strings.cpp | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/C++/multiply-strings.cpp b/C++/multiply-strings.cpp index 718622150..c2be9cb02 100644 --- a/C++/multiply-strings.cpp +++ b/C++/multiply-strings.cpp @@ -2,6 +2,37 @@ // Space: O(m + n) class Solution { +public: + string multiply(string num1, string num2) { + const auto char_to_int = [](const char c) { return c - '0'; }; + const auto int_to_char = [](const int i) { return i + '0'; }; + + vector n1; + transform(num1.rbegin(), num1.rend(), back_inserter(n1), char_to_int); + vector n2; + transform(num2.rbegin(), num2.rend(), back_inserter(n2), char_to_int); + + vector tmp(n1.size() + n2.size() + 1); + for(int i = 0; i < n1.size(); ++i) { + for(int j = 0; j < n2.size(); ++j) { + tmp[i + j] += n1[i] * n2[j]; + tmp[i + j + 1] += tmp[i + j] / 10; + tmp[i + j] %= 10; + } + } + + string res; + transform(find_if(tmp.rbegin(), prev(tmp.rend()), + [](const int i) { return i != 0; }), + tmp.rend(), back_inserter(res), int_to_char); + return res; + } +}; + +// Time: O(m * n) +// Space: O(m + n) +// Define a new BigInt class solutioin. +class Solution2 { public: string multiply(string num1, string num2) { return BigInt(num1) * BigInt(num2); @@ -11,7 +42,7 @@ class Solution { public: BigInt(const string& s) { transform(s.rbegin(), s.rend(), back_inserter(n_), - [](const char c) { return c - '0';}); + [](const char c) { return c - '0'; }); } operator string() { @@ -55,5 +86,4 @@ class Solution { return n_.size(); } }; - }; From 3c87cd967b0e72fd46df95fe0e72428ee67825fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:13:05 +0800 Subject: [PATCH 1754/1939] Update multiply-strings.py --- Python/multiply-strings.py | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index e5af568af..5f93af035 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -10,23 +10,30 @@ class Solution: # @param num1, a string # @param num2, a string # @return a string +class Solution(object): def multiply(self, num1, num2): + """ + :type num1: str + :type num2: str + :rtype: str + """ num1, num2 = num1[::-1], num2[::-1] - result = [0 for i in xrange(len(num1) + len(num2))] + res = [0] * (len(num1) + len(num2)) for i in xrange(len(num1)): for j in xrange(len(num2)): - result[i + j] += int(num1[i]) * int(num2[j]) - - carry, num3 = 0, [] - for digit in result: - sum = carry + digit - carry = sum / 10 - num3.insert(0, str(sum % 10)) - - while len(num3) > 1 and num3[0] == "0": - del num3[0] - - return ''.join(num3) + res[i + j] += int(num1[i]) * int(num2[j]) + res[i + j + 1] += res[i + j] / 10 + res[i + j] %= 10 + + res.reverse() + + # Skip leading 0s. + i = 0 + while i < len(res) and res[i] == 0: + i += 1 + + res = ''.join(map(str, res[i:])) + return res if res else "0" if __name__ == "__main__": - print Solution().multiply("123", "1000") \ No newline at end of file + print Solution().multiply("123", "1000") From e8b37f599f63ffb9235c9cc2d44f2945420e2cf6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:15:08 +0800 Subject: [PATCH 1755/1939] Update multiply-strings.py --- Python/multiply-strings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index 5f93af035..6b2774ba6 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -18,7 +18,7 @@ def multiply(self, num1, num2): :rtype: str """ num1, num2 = num1[::-1], num2[::-1] - res = [0] * (len(num1) + len(num2)) + res = [0] * (len(num1) + len(num2) + 1) for i in xrange(len(num1)): for j in xrange(len(num2)): res[i + j] += int(num1[i]) * int(num2[j]) From be5934c5881b3afe3b8af889a1843a781a942a95 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:18:27 +0800 Subject: [PATCH 1756/1939] Update multiply-strings.py --- Python/multiply-strings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index 6b2774ba6..5f93af035 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -18,7 +18,7 @@ def multiply(self, num1, num2): :rtype: str """ num1, num2 = num1[::-1], num2[::-1] - res = [0] * (len(num1) + len(num2) + 1) + res = [0] * (len(num1) + len(num2)) for i in xrange(len(num1)): for j in xrange(len(num2)): res[i + j] += int(num1[i]) * int(num2[j]) From dd526d3c3778ecdbd81960bed6a818c59cb5c0a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:20:17 +0800 Subject: [PATCH 1757/1939] Update multiply-strings.py --- Python/multiply-strings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index 5f93af035..6b2774ba6 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -18,7 +18,7 @@ def multiply(self, num1, num2): :rtype: str """ num1, num2 = num1[::-1], num2[::-1] - res = [0] * (len(num1) + len(num2)) + res = [0] * (len(num1) + len(num2) + 1) for i in xrange(len(num1)): for j in xrange(len(num2)): res[i + j] += int(num1[i]) * int(num2[j]) From 942289b8f8903abe08fbbe6cf767656bfd51755b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:22:07 +0800 Subject: [PATCH 1758/1939] Update multiply-strings.py --- Python/multiply-strings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index 6b2774ba6..5f93af035 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -18,7 +18,7 @@ def multiply(self, num1, num2): :rtype: str """ num1, num2 = num1[::-1], num2[::-1] - res = [0] * (len(num1) + len(num2) + 1) + res = [0] * (len(num1) + len(num2)) for i in xrange(len(num1)): for j in xrange(len(num2)): res[i + j] += int(num1[i]) * int(num2[j]) From 70c1556ef6a629e798ba943547409c81a097a0ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:22:24 +0800 Subject: [PATCH 1759/1939] Update multiply-strings.cpp --- C++/multiply-strings.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/multiply-strings.cpp b/C++/multiply-strings.cpp index c2be9cb02..27604ca3d 100644 --- a/C++/multiply-strings.cpp +++ b/C++/multiply-strings.cpp @@ -12,7 +12,7 @@ class Solution { vector n2; transform(num2.rbegin(), num2.rend(), back_inserter(n2), char_to_int); - vector tmp(n1.size() + n2.size() + 1); + vector tmp(n1.size() + n2.size()); for(int i = 0; i < n1.size(); ++i) { for(int j = 0; j < n2.size(); ++j) { tmp[i + j] += n1[i] * n2[j]; @@ -55,7 +55,7 @@ class Solution2 { } BigInt operator*(const BigInt &rhs) const { - BigInt res(n_.size() + rhs.size() + 1, 0); + BigInt res(n_.size() + rhs.size(), 0); for(auto i = 0; i < n_.size(); ++i) { for(auto j = 0; j < rhs.size(); ++j) { res[i + j] += n_[i] * rhs[j]; From dec43a4ec8259f5c1c7c648941bb7522f8603911 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:23:23 +0800 Subject: [PATCH 1760/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0b4e41eb1..88a5af612 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [C++](./C++/longest-common-prefix.cpp) [Python](./Python/longest-common-prefix.py) | _O(n * k)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [C++](./C++/implement-strstr.cpp) [Python](./Python/implement-strstr.py) | _O(n + k)_ | _O(k)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [C++](./C++/count-and-say.cpp) [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || -43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || +43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [C++](./C++/multiply-strings.cpp) [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || From 8425bafa9feb43e6ea380b395add638f2d3c3713 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:26:55 +0800 Subject: [PATCH 1761/1939] Update multiply-strings.cpp --- C++/multiply-strings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/multiply-strings.cpp b/C++/multiply-strings.cpp index 27604ca3d..a661246f4 100644 --- a/C++/multiply-strings.cpp +++ b/C++/multiply-strings.cpp @@ -31,7 +31,7 @@ class Solution { // Time: O(m * n) // Space: O(m + n) -// Define a new BigInt class solutioin. +// Define a new BigInt class solution. class Solution2 { public: string multiply(string num1, string num2) { From 3be91a8355e53c8c33d5a57d6a9d9f6263bad9b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:28:25 +0800 Subject: [PATCH 1762/1939] Update multiply-strings.py --- Python/multiply-strings.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index 5f93af035..e79d36c79 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -6,10 +6,6 @@ # Note: The numbers can be arbitrarily large and are non-negative. # -class Solution: - # @param num1, a string - # @param num2, a string - # @return a string class Solution(object): def multiply(self, num1, num2): """ @@ -19,21 +15,22 @@ def multiply(self, num1, num2): """ num1, num2 = num1[::-1], num2[::-1] res = [0] * (len(num1) + len(num2)) + print res for i in xrange(len(num1)): for j in xrange(len(num2)): res[i + j] += int(num1[i]) * int(num2[j]) res[i + j + 1] += res[i + j] / 10 res[i + j] %= 10 - + print res res.reverse() # Skip leading 0s. i = 0 - while i < len(res) and res[i] == 0: + while i < len(res) - 1 and res[i] == 0: i += 1 res = ''.join(map(str, res[i:])) - return res if res else "0" + return res if __name__ == "__main__": print Solution().multiply("123", "1000") From c85b53834d987d4b9a0651d3d5674b7a48c5587d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:30:23 +0800 Subject: [PATCH 1763/1939] Update multiply-strings.py --- Python/multiply-strings.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index e79d36c79..5274d3656 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -15,13 +15,12 @@ def multiply(self, num1, num2): """ num1, num2 = num1[::-1], num2[::-1] res = [0] * (len(num1) + len(num2)) - print res for i in xrange(len(num1)): for j in xrange(len(num2)): res[i + j] += int(num1[i]) * int(num2[j]) res[i + j + 1] += res[i + j] / 10 res[i + j] %= 10 - print res + res.reverse() # Skip leading 0s. From 3e707b762449794b3d86ecddb69e2b6238ccc8b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:32:29 +0800 Subject: [PATCH 1764/1939] Update multiply-strings.py --- Python/multiply-strings.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index 5274d3656..2abd1e40d 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -21,14 +21,13 @@ def multiply(self, num1, num2): res[i + j + 1] += res[i + j] / 10 res[i + j] %= 10 - res.reverse() # Skip leading 0s. - i = 0 - while i < len(res) - 1 and res[i] == 0: - i += 1 + i = len(res) - 1 + while i > 0 and res[i] == 0: + i -= 1 - res = ''.join(map(str, res[i:])) + res = ''.join(map(str, res[i::-1])) return res if __name__ == "__main__": From 514833070443812a9636d4a74e9fc194ca8ac338 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:33:17 +0800 Subject: [PATCH 1765/1939] Update multiply-strings.py --- Python/multiply-strings.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index 2abd1e40d..36af7959f 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -27,8 +27,8 @@ def multiply(self, num1, num2): while i > 0 and res[i] == 0: i -= 1 - res = ''.join(map(str, res[i::-1])) - return res + return ''.join(map(str, res[i::-1])) + if __name__ == "__main__": print Solution().multiply("123", "1000") From 8732fc228f40b6de90d17bc1f5fe036645ad4327 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Feb 2016 12:33:29 +0800 Subject: [PATCH 1766/1939] Update multiply-strings.py --- Python/multiply-strings.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index 36af7959f..a90999ffe 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -21,7 +21,6 @@ def multiply(self, num1, num2): res[i + j + 1] += res[i + j] / 10 res[i + j] %= 10 - # Skip leading 0s. i = len(res) - 1 while i > 0 and res[i] == 0: From d173cb5684d7e44237dfd6444e90a98ab549a05c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Feb 2016 15:52:20 +0800 Subject: [PATCH 1767/1939] Update multiply-strings.py --- Python/multiply-strings.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index a90999ffe..6df6c3f12 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -28,6 +28,18 @@ def multiply(self, num1, num2): return ''.join(map(str, res[i::-1])) +# Time: O(m * n) +# Space: O(m + n) +# Using built-in bignum solution. +class Solution2(object): + def multiply(self, num1, num2): + """ + :type num1: str + :type num2: str + :rtype: str + """ + return str(int(num1) * int(num2)) + if __name__ == "__main__": print Solution().multiply("123", "1000") From 8c40f31feca07e264209723002a19b724a523ae5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Feb 2016 17:25:23 +0800 Subject: [PATCH 1768/1939] Update and rename lengthOfLastWord.cpp to length-of-last-word.cpp --- C++/length-of-last-word.cpp | 12 ++++++++++++ C++/lengthOfLastWord.cpp | 16 ---------------- 2 files changed, 12 insertions(+), 16 deletions(-) create mode 100644 C++/length-of-last-word.cpp delete mode 100644 C++/lengthOfLastWord.cpp diff --git a/C++/length-of-last-word.cpp b/C++/length-of-last-word.cpp new file mode 100644 index 000000000..7806368cb --- /dev/null +++ b/C++/length-of-last-word.cpp @@ -0,0 +1,12 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int lengthOfLastWord(string s) { + const auto is_space = [](const char c) { return c == ' '; }; + const auto it = find_if_not(s.rbegin(), s.rend(), is_space); + const auto jt = find_if(it, s.rend(), is_space); + return distance(it, jt); + } +}; diff --git a/C++/lengthOfLastWord.cpp b/C++/lengthOfLastWord.cpp deleted file mode 100644 index fc6ce929c..000000000 --- a/C++/lengthOfLastWord.cpp +++ /dev/null @@ -1,16 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - int lengthOfLastWord(const char *s) { - int len = 0; - for(; *s; ++s) { - if (*s != ' ') - ++len; - else if (*(s+1) && *(s+1) != ' ') - len = 0; - } - return len; - } -}; From 5c9c5852cf2aa5b2dd1e35a723f8e317a114821f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Feb 2016 17:26:23 +0800 Subject: [PATCH 1769/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88a5af612..55b350a29 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [C++](./C++/implement-strstr.cpp) [Python](./Python/implement-strstr.py) | _O(n + k)_ | _O(k)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [C++](./C++/count-and-say.cpp) [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [C++](./C++/multiply-strings.cpp) [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || -58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || +58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [C++](./C++/length-of-last-word.cpp) [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || From 0a1d3b911c4c9e914047c98391bde1521ff8e59a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Feb 2016 17:31:03 +0800 Subject: [PATCH 1770/1939] Update length-of-last-word.cpp --- C++/length-of-last-word.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/length-of-last-word.cpp b/C++/length-of-last-word.cpp index 7806368cb..05684d6ca 100644 --- a/C++/length-of-last-word.cpp +++ b/C++/length-of-last-word.cpp @@ -4,7 +4,7 @@ class Solution { public: int lengthOfLastWord(string s) { - const auto is_space = [](const char c) { return c == ' '; }; + const auto is_space = [](const char c) { return isspace(c); }; const auto it = find_if_not(s.rbegin(), s.rend(), is_space); const auto jt = find_if(it, s.rend(), is_space); return distance(it, jt); From 74dd7293733a5be8ae1107d5451b1be65ff62f27 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 12:01:03 +0800 Subject: [PATCH 1771/1939] Create increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 44 ++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/increasing-triplet-subsequence.py diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py new file mode 100644 index 000000000..a0f4ba5fc --- /dev/null +++ b/Python/increasing-triplet-subsequence.py @@ -0,0 +1,44 @@ +# Time: O(n) +# Space: O(n) + +# 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(object): + def increasingTriplet(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + n = len(nums) + + exist_smaller = set() + min_num = 0 + for i in xrange(1, n): + if (nums[i] <= nums[min_num]): + min_num = i + else: + exist_smaller.add(i) + + max_num = n - 1 + for i in reversed(xrange(n-1)): + if (nums[i] >= nums[max_num]): + max_num = i + else: + if i in exist_smaller: + return True + + return False From 8ec1a4ea248e345ef9b7cd2a979e2cde7efc9c14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 12:16:32 +0800 Subject: [PATCH 1772/1939] Update increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index a0f4ba5fc..2de30e91e 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(n) +# Space: O(1) # Given an unsorted array return whether an increasing # subsequence of length 3 exists or not in the array. @@ -18,6 +18,22 @@ # return false. class Solution(object): + def increasingTriplet(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + first_min, second_min = None, None + for i in xrange(len(nums)): + if first_min is None or first_min >= nums[i]: + first_min = nums[i] + elif second_min is None or second_min >= nums[i]: + second_min = nums[i] + else: + return True + return False + +class Solution2(object): def increasingTriplet(self, nums): """ :type nums: List[int] From 8249c54cecbe2fabc184b68aec629a2b5212e5e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 12:18:44 +0800 Subject: [PATCH 1773/1939] Update increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index 2de30e91e..468cae61b 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -24,11 +24,11 @@ def increasingTriplet(self, nums): :rtype: bool """ first_min, second_min = None, None - for i in xrange(len(nums)): - if first_min is None or first_min >= nums[i]: - first_min = nums[i] - elif second_min is None or second_min >= nums[i]: - second_min = nums[i] + for i in nums: + if first_min is None or first_min >= i: + first_min = i + elif second_min is None or second_min >= i: + second_min = i else: return True return False From 81ea5e43bfc9beb8e43bff7e2bb65ddc26a97376 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 12:21:52 +0800 Subject: [PATCH 1774/1939] Create increasing-triplet-subsequence.cpp --- C++/increasing-triplet-subsequence.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/increasing-triplet-subsequence.cpp diff --git a/C++/increasing-triplet-subsequence.cpp b/C++/increasing-triplet-subsequence.cpp new file mode 100644 index 000000000..332f8776d --- /dev/null +++ b/C++/increasing-triplet-subsequence.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool increasingTriplet(vector& nums) { + int first_min = numeric_limits::max(), second_min = numeric_limits::max(); + for (const auto& i : nums) { + if (first_min >= i) { + first_min = i; + } else if (second_min >= i) { + second_min = i; + } else { + return true; + } + } + return false; + } +}; From efc75e9c23714bff719171a7ba2adba3ee158901 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 12:24:57 +0800 Subject: [PATCH 1775/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 55b350a29..89b004c9f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-333%20%2F%20333-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-334%20%2F%20334-ff69b4.svg) -Up to date (2016-02-12), there are `316` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-02-16), there are `317` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `333` questions. +Here is the classification of all `334` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -93,6 +93,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(n * (c+1))_ | _O(1)_ | Easy |📖|| 296| [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) | [C++](./C++/best-meeting-point.cpp) [Python](./Python/best-meeting-point.py) | _O(m * n)_ | _O(m + n)_ | Medium |📖|| 311| [Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/) | [C++](./C++/sparse-matrix-multiplication.cpp) [Python](./Python/sparse-matrix-multiplication.py) | _O(m * n * l)_ | _O(m * l)_ | Medium |📖|| +334| [Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./C++/increasing-triplet-subsequence.cpp) [Python](./Python/increasing-triplet-subsequence.py) | _O(n)_ | _O(1)_ | Medium ||| ## String # | Title | Solution | Time | Space | Difficulty | Tag | Note From 84cd3c023829507d2bdbcd9d56f8e251b017c2f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 12:25:26 +0800 Subject: [PATCH 1776/1939] Update increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index 468cae61b..e983c411f 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -33,6 +33,8 @@ def increasingTriplet(self, nums): return True return False +# Time: O(n) +# Space: O(n) class Solution2(object): def increasingTriplet(self, nums): """ From 329ce3903c9c4927e1df0949b8eefff23feec4bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 12:26:49 +0800 Subject: [PATCH 1777/1939] Update increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index e983c411f..63341bf7c 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -23,11 +23,11 @@ def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool """ - first_min, second_min = None, None + first_min, second_min = float("inf"), float("inf") for i in nums: - if first_min is None or first_min >= i: + if first_min >= i: first_min = i - elif second_min is None or second_min >= i: + elif second_min >= i: second_min = i else: return True From ebb3992f139418f98b32319bd674a828473c01e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 12:54:17 +0800 Subject: [PATCH 1778/1939] Update increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index 63341bf7c..511f4f315 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -26,7 +26,7 @@ def increasingTriplet(self, nums): first_min, second_min = float("inf"), float("inf") for i in nums: if first_min >= i: - first_min = i + first_min, second_min = i, float("inf") elif second_min >= i: second_min = i else: From a25403797412fe3229657f9fba44f78c71b89abf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 12:54:58 +0800 Subject: [PATCH 1779/1939] Update increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index 511f4f315..63341bf7c 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -26,7 +26,7 @@ def increasingTriplet(self, nums): first_min, second_min = float("inf"), float("inf") for i in nums: if first_min >= i: - first_min, second_min = i, float("inf") + first_min = i elif second_min >= i: second_min = i else: From deb32070f8ae4f3561d669860dd4ebf7a85cc0fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 13:14:11 +0800 Subject: [PATCH 1780/1939] Update increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index 63341bf7c..57856790c 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -23,12 +23,12 @@ def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool """ - first_min, second_min = float("inf"), float("inf") - for i in nums: - if first_min >= i: - first_min = i - elif second_min >= i: - second_min = i + min_num, a, b = float("inf"), float("inf"), float("inf") + for c in nums: + if min_num >= c: + min_num = c + elif b >= c: + a, b = min_num, c else: return True return False From c679efde385012332ed67303cd554d04a48af326 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 13:17:27 +0800 Subject: [PATCH 1781/1939] Update increasing-triplet-subsequence.cpp --- C++/increasing-triplet-subsequence.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/increasing-triplet-subsequence.cpp b/C++/increasing-triplet-subsequence.cpp index 332f8776d..6fe31aacf 100644 --- a/C++/increasing-triplet-subsequence.cpp +++ b/C++/increasing-triplet-subsequence.cpp @@ -4,12 +4,12 @@ class Solution { public: bool increasingTriplet(vector& nums) { - int first_min = numeric_limits::max(), second_min = numeric_limits::max(); + int min = numeric_limits::max(), a = numeric_limits::max(), b = numeric_limits::max(); for (const auto& i : nums) { - if (first_min >= i) { - first_min = i; - } else if (second_min >= i) { - second_min = i; + if (min >= i) { + min = i; + } else if (b >= i) { + a = min, b = i; } else { return true; } From ea04f55e3476a7e10d5bc65aca0803d60b4f6ffd Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 13:35:31 +0800 Subject: [PATCH 1782/1939] Update increasing-triplet-subsequence.cpp --- C++/increasing-triplet-subsequence.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/increasing-triplet-subsequence.cpp b/C++/increasing-triplet-subsequence.cpp index 6fe31aacf..b86afd4c7 100644 --- a/C++/increasing-triplet-subsequence.cpp +++ b/C++/increasing-triplet-subsequence.cpp @@ -5,12 +5,12 @@ class Solution { public: bool increasingTriplet(vector& nums) { int min = numeric_limits::max(), a = numeric_limits::max(), b = numeric_limits::max(); - for (const auto& i : nums) { - if (min >= i) { - min = i; - } else if (b >= i) { - a = min, b = i; - } else { + for (const auto& c : nums) { + if (min >= c) { + min = c; + } else if (b >= c) { + a = min, b = c; + } else { // a < b < c return true; } } From 265499078b5ed52731bd8843140809ad181017de Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Feb 2016 13:36:04 +0800 Subject: [PATCH 1783/1939] Update increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index 57856790c..4c31d4cab 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -29,7 +29,7 @@ def increasingTriplet(self, nums): min_num = c elif b >= c: a, b = min_num, c - else: + else: # a < b < c return True return False From 0a440dbc30e9e7b07bc5b9b7bf8fb8051d1db0ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 17 Feb 2016 11:48:37 +0800 Subject: [PATCH 1784/1939] Update increasing-triplet-subsequence.py --- Python/increasing-triplet-subsequence.py | 32 +++++++++--------------- 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index 4c31d4cab..a9e76c280 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -33,30 +33,22 @@ def increasingTriplet(self, nums): return True return False -# Time: O(n) -# Space: O(n) -class Solution2(object): +# Time: O(n * logk) +# Space: O(k) +# Generalization of k-uplet. +class Solution_Generalization(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ - n = len(nums) - - exist_smaller = set() - min_num = 0 - for i in xrange(1, n): - if (nums[i] <= nums[min_num]): - min_num = i - else: - exist_smaller.add(i) - - max_num = n - 1 - for i in reversed(xrange(n-1)): - if (nums[i] >= nums[max_num]): - max_num = i - else: - if i in exist_smaller: + def increasingKUplet(nums, k): + inc = [float('inf')] * (k - 1) + for num in nums: + i = bisect.bisect_left(inc, num) + if i >= k - 1: return True + inc[i] = num + return k == 0 - return False + return increasingKUplet(nums, 3) From 4a9a77024b9023ade7317e7bcb69430d874f9eee Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 17 Feb 2016 11:57:40 +0800 Subject: [PATCH 1785/1939] Update increasing-triplet-subsequence.cpp --- C++/increasing-triplet-subsequence.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/C++/increasing-triplet-subsequence.cpp b/C++/increasing-triplet-subsequence.cpp index b86afd4c7..44eed9fc1 100644 --- a/C++/increasing-triplet-subsequence.cpp +++ b/C++/increasing-triplet-subsequence.cpp @@ -17,3 +17,25 @@ class Solution { return false; } }; + +// Time: O(n * logk) +// Space: O(k) +// Generalization of k-uplet. +class Solution_Generalization { +public: + bool increasingTriplet(vector& nums) { + return increasingKUplet(nums, 3); + } + + bool increasingKUplet(const vector& nums, const int k) { + vector inc(k - 1, numeric_limits::max()); + for (const auto& num : nums) { + auto it = lower_bound(inc.begin(), inc.end(), num); + if (distance(inc.begin(), it) >= k - 1) { + return true; + } + *it = num; + } + return k == 0; + } +}; From 31225390cafdac944f1b5b67b81342f403cfa0f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 17 Feb 2016 11:59:06 +0800 Subject: [PATCH 1786/1939] Update increasing-triplet-subsequence.cpp --- C++/increasing-triplet-subsequence.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/increasing-triplet-subsequence.cpp b/C++/increasing-triplet-subsequence.cpp index 44eed9fc1..8b6066111 100644 --- a/C++/increasing-triplet-subsequence.cpp +++ b/C++/increasing-triplet-subsequence.cpp @@ -27,7 +27,8 @@ class Solution_Generalization { return increasingKUplet(nums, 3); } - bool increasingKUplet(const vector& nums, const int k) { +private: + bool increasingKUplet(const vector& nums, const size_t k) { vector inc(k - 1, numeric_limits::max()); for (const auto& num : nums) { auto it = lower_bound(inc.begin(), inc.end(), num); From 42151a23c7d6134a79329f9aae002da2e1ac6f15 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 18 Feb 2016 01:50:20 +0800 Subject: [PATCH 1787/1939] Update letter-combinations-of-a-phone-number.py --- Python/letter-combinations-of-a-phone-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/letter-combinations-of-a-phone-number.py b/Python/letter-combinations-of-a-phone-number.py index f25d8bcc8..c876137ca 100644 --- a/Python/letter-combinations-of-a-phone-number.py +++ b/Python/letter-combinations-of-a-phone-number.py @@ -26,7 +26,7 @@ def letterCombinations(self, digits): for digit in reversed(digits): choices = lookup[int(digit)] m, n = len(choices), len(result) - result.extend([result[i % n] for i in xrange(n, m * n)]) + result += [result[i % n] for i in xrange(n, m * n)] for i in xrange(m * n): result[i] = choices[i / n] + result[i] From 229cd40922d1af5cd0cde5f86c00de7650aec24b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 18 Feb 2016 01:50:26 +0800 Subject: [PATCH 1788/1939] Update maximum-product-of-word-lengths.py --- Python/maximum-product-of-word-lengths.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximum-product-of-word-lengths.py b/Python/maximum-product-of-word-lengths.py index d189fdf9d..ddc03bd4b 100644 --- a/Python/maximum-product-of-word-lengths.py +++ b/Python/maximum-product-of-word-lengths.py @@ -40,7 +40,7 @@ def counting_sort(words): res = [] for i in reversed(xrange(k)): if buckets[i]: - res.extend(buckets[i]) + res += buckets[i] return res words = counting_sort(words) From 58229de67bceac377747cda8f48877807102f79d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Feb 2016 17:54:40 +0800 Subject: [PATCH 1789/1939] Create add-binary.cpp --- C++/add-binary.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/add-binary.cpp diff --git a/C++/add-binary.cpp b/C++/add-binary.cpp new file mode 100644 index 000000000..eaac45a64 --- /dev/null +++ b/C++/add-binary.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string addBinary(string a, string b) { + string result; + int result_length = max(a.length(), b.length()) ; + + int carry = 0; + for (int i = 0; i < result_length; ++i) { + int a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0; + int b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0; + int sum = carry + a_bit_i + b_bit_i; + carry = sum / 2; + sum %= 2; + result.push_back('0' + sum); + } + if (carry) { + result.push_back('0' + carry); + } + reverse(result.begin(), result.end()); + + return result; + } +}; From 54fa6f79e6270e469362ec63d84eb612e621adcc Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Feb 2016 17:55:17 +0800 Subject: [PATCH 1790/1939] Delete addBinary.cpp --- C++/addBinary.cpp | 29 ----------------------------- 1 file changed, 29 deletions(-) delete mode 100644 C++/addBinary.cpp diff --git a/C++/addBinary.cpp b/C++/addBinary.cpp deleted file mode 100644 index 585618ce6..000000000 --- a/C++/addBinary.cpp +++ /dev/null @@ -1,29 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - string addBinary(string a, string b) { - size_t carry = 0; - string ans; - - for(auto ai = a.rbegin(), bi = b.rbegin(); ai != a.rend() || bi != b.rend();) { - const size_t av = (ai != a.rend())? *ai - '0' : 0; - const size_t bv = (bi != b.rend())? *bi - '0' : 0; - const size_t val = (av + bv + carry) % 2; - carry = (av + bv + carry) / 2; - ans.push_back( val + '0' ); - - if(ai != a.rend()) - ++ai; - if(bi != b.rend()) - ++bi; - } - if(carry) - ans.push_back('1'); - - reverse(ans.begin(), ans.end()); - - return ans; - } -}; From 9ed65d18f3a7f34572777d6d069705e91183898d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Feb 2016 17:56:17 +0800 Subject: [PATCH 1791/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 89b004c9f..a178f5297 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [C++](./C++/count-and-say.cpp) [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [C++](./C++/multiply-strings.cpp) [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [C++](./C++/length-of-last-word.cpp) [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || -67| [Add Binary](https://leetcode.com/problems/add-binary/) | [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || +67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./Python/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || From f2ad6af1fba7fc0ec8eed50cdf2190ef8d8aae1f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Feb 2016 17:56:56 +0800 Subject: [PATCH 1792/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a178f5297..1b733a16f 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [C++](./C++/count-and-say.cpp) [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [C++](./C++/multiply-strings.cpp) [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [C++](./C++/length-of-last-word.cpp) [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || -67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./Python/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || +67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./C++/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || From 9c38ca4d0ca97dffcebe3f1dc044e93ffc125398 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Feb 2016 21:32:17 +0800 Subject: [PATCH 1793/1939] Update add-binary.cpp --- C++/add-binary.cpp | 52 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/C++/add-binary.cpp b/C++/add-binary.cpp index eaac45a64..1c3591b60 100644 --- a/C++/add-binary.cpp +++ b/C++/add-binary.cpp @@ -4,23 +4,53 @@ class Solution { public: string addBinary(string a, string b) { - string result; - int result_length = max(a.length(), b.length()) ; + string res; + size_t res_len = max(a.length(), b.length()) ; - int carry = 0; - for (int i = 0; i < result_length; ++i) { - int a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0; - int b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0; - int sum = carry + a_bit_i + b_bit_i; + size_t carry = 0; + for (int i = 0; i < res_len; ++i) { + const size_t a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0; + const size_t b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0; + size_t sum = carry + a_bit_i + b_bit_i; carry = sum / 2; sum %= 2; - result.push_back('0' + sum); + res.push_back('0' + sum); } if (carry) { - result.push_back('0' + carry); + res.push_back('0' + carry); } - reverse(result.begin(), result.end()); + reverse(res.begin(), res.end()); - return result; + return res; + } +}; + +class Solution2 { +public: + string addBinary(string a, string b) { + size_t carry = 0; + string res; + + for (auto a_it = a.rbegin(), b_it = b.rbegin(); a_it != a.rend() || b_it != b.rend();) { + const size_t a_bit_i = (a_it != a.rend()) ? *a_it - '0' : 0; + const size_t b_bit_i = (b_it != b.rend()) ? *b_it - '0' : 0; + size_t sum = a_bit_i + b_bit_i + carry; + carry = sum / 2; + sum %= 2; + res.push_back('0' + sum); + + if (a_it != a.rend()) { + ++a_it; + } + if (b_it != b.rend()) { + ++b_it; + } + } + if (carry) { + res.push_back('0' + carry); + } + reverse(res.begin(), res.end()); + + return res; } }; From a408df73391a5dcd97f9ba19f8a1be580c695f95 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Feb 2016 21:32:46 +0800 Subject: [PATCH 1794/1939] Update add-binary.cpp --- C++/add-binary.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/add-binary.cpp b/C++/add-binary.cpp index 1c3591b60..7a273e67d 100644 --- a/C++/add-binary.cpp +++ b/C++/add-binary.cpp @@ -25,6 +25,7 @@ class Solution { } }; +// Iterator solution. class Solution2 { public: string addBinary(string a, string b) { From 577758052b5fcae7ad7e1c337df9dd08c47e85d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Feb 2016 16:25:58 +0800 Subject: [PATCH 1795/1939] Update and rename textJustification.cpp to text-justification.cpp --- C++/text-justification.cpp | 48 ++++++++++++++++++++++++++++++++++++++ C++/textJustification.cpp | 46 ------------------------------------ 2 files changed, 48 insertions(+), 46 deletions(-) create mode 100644 C++/text-justification.cpp delete mode 100644 C++/textJustification.cpp diff --git a/C++/text-justification.cpp b/C++/text-justification.cpp new file mode 100644 index 000000000..f286a7d29 --- /dev/null +++ b/C++/text-justification.cpp @@ -0,0 +1,48 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector fullJustify(vector& words, int maxWidth) { + vector res; + const int n = words.size(); + int begin = 0, len = 0; + for (int i = 0; i < n; ++i) { + if (len + words[i].size() + (i - begin) > maxWidth) { + res.emplace_back(connect(words, maxWidth, begin, i, len, false)); + begin = i; + len = 0; + } + len += words[i].size(); + } + // Last line. + res.emplace_back(connect(words, maxWidth, begin, n, len, true)); + return res; + } + +private: + string connect(const vector &words, int maxWidth, + int begin, int end, int len, + bool is_last) { + string s; + int n = end - begin; + for (int i = 0; i < n; ++i) { + s += words[begin + i]; + addSpaces(i, n - 1, maxWidth - len, is_last, &s); + } + // For only one word in a line. + if (s.size() < maxWidth) { + s.append(maxWidth - s.size(), ' '); + } + return s; + } + + void addSpaces(int i, int spaceCnt, int maxWidth, bool is_last, string *s) { + if (i < spaceCnt) { + // For the last line of text, it should be left justified, + // and no extra space is inserted between words. + int spaces = is_last ? 1 : maxWidth / spaceCnt + (i < maxWidth % spaceCnt); + s->append(spaces, ' '); + } + } +}; diff --git a/C++/textJustification.cpp b/C++/textJustification.cpp deleted file mode 100644 index 8187d104f..000000000 --- a/C++/textJustification.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// LeetCode, Text Justification -// Complexity: -// O(n) time -// O(1) space - -class Solution { -public: - vector fullJustify(vector &words, int L) { - vector result; - const int n = words.size(); - int begin = 0, len = 0; - for (int i = 0; i < n; ++i) { - if (len + words[i].size() + (i - begin) > L) { - result.push_back(connect(words, begin, i - 1, len, L, false)); - begin = i; - len = 0; - } - - len += words[i].size(); - } - // last line - result.push_back(connect(words, begin, n - 1, len, L, true)); - return result; - } - - string connect(vector &words, int begin, int end, - int len, int L, bool is_last) { - string s; - int n = end - begin + 1; - for (int i = 0; i < n; ++i) { - s += words[begin + i]; - addSpaces(s, i, n - 1, L - len, is_last); - } - // for only one word in a line - if (s.size() < L) s.append(L - s.size(), ' '); - return s; - } - - void addSpaces(string &s, int i, int n, int L, bool is_last) { - if (n < 1 || i > n - 1) return; - // for the last line of text, it should be left justified, - // and no extra space is inserted between words. - int spaces = is_last ? 1 : (L / n + (i < (L % n) ? 1 : 0)); - s.append(spaces, ' '); - } -}; \ No newline at end of file From ef96d99d261a718dd5472b0f35f388463629a481 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Feb 2016 16:27:47 +0800 Subject: [PATCH 1796/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1b733a16f..6a175e971 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [C++](./C++/multiply-strings.cpp) [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [C++](./C++/length-of-last-word.cpp) [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./C++/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || -68| [Text Justification](https://leetcode.com/problems/text-justification/) | [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || +68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| From 5cba46ede541667040578c0a63dd9715d3b6d427 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Feb 2016 16:48:35 +0800 Subject: [PATCH 1797/1939] Update text-justification.cpp --- C++/text-justification.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/text-justification.cpp b/C++/text-justification.cpp index f286a7d29..98db06b75 100644 --- a/C++/text-justification.cpp +++ b/C++/text-justification.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(1) +// Space: O(k), k is maxWidth. class Solution { public: From 6eea64a3ed8ee11a87e0d71ceead3ed48978f888 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Feb 2016 16:54:20 +0800 Subject: [PATCH 1798/1939] Update text-justification.py --- Python/text-justification.py | 96 +++++++++++++++++------------------- 1 file changed, 46 insertions(+), 50 deletions(-) diff --git a/Python/text-justification.py b/Python/text-justification.py index 5ccab0e51..bb060f2c4 100644 --- a/Python/text-justification.py +++ b/Python/text-justification.py @@ -1,15 +1,19 @@ # Time: O(n) -# Space: O(1) +# Space: O(k), k is maxWidth. # -# Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. +# Given an array of words and a length L, format the text such that +# each line has exactly L characters and is fully (left and right) justified. # -# You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' +# You should pack your words in a greedy approach; that is, pack +# as many words as you can in each line. Pad extra spaces ' ' # when necessary so that each line has exactly L characters. # # Extra spaces between words should be distributed as evenly as possible. -# If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. +# If the number of spaces on a line do not divide evenly between words, +# the empty slots on the left will be assigned more spaces than the slots on the right. # -# For the last line of text, it should be left justified and no extra space is inserted between words. +# For the last line of text, it should be left justified and no extra space +# is inserted between words. # # For example, # words: ["This", "is", "an", "example", "of", "text", "justification."] @@ -23,52 +27,44 @@ # ] # Note: Each word is guaranteed not to exceed L in length. -class Solution: - # @param words, a list of strings - # @param L, an integer - # @return a list of strings - def fullJustify(self, words, L): - result = [] - - i = 0 - while i < len(words): - # count words in one line - size, begin = 0, i - while i < len(words): - if size == 0: - newsize = len(words[i]) - else: - newsize = size + len(words[i]) + 1 - if newsize <= L: - size = newsize - else: - break - i += 1 - - # count space number - spaceCount = L - size - if i - begin - 1 > 0 and i < len(words): - everyCount = spaceCount / (i - begin - 1) + 1 - spaceCount %= i - begin - 1 - else: - everyCount = 1 +class Solution(object): + def fullJustify(self, words, maxWidth): + """ + :type words: List[str] + :type maxWidth: int + :rtype: List[str] + """ + def addSpaces(i, spaceCnt, maxWidth, is_last): + if i < spaceCnt: + # For the last line of text, it should be left justified, + # and no extra space is inserted between words. + return 1 if is_last else (maxWidth // spaceCnt) + int(i < maxWidth % spaceCnt) + return 0 + + def connect(words, maxWidth, begin, end, length, is_last): + s = [] + n = end - begin + for i in xrange(n): + s += words[begin + i], + s += ' ' * addSpaces(i, n - 1, maxWidth - length, is_last), + # For only one word in a line. + line = "".join(s) + if len(line) < maxWidth: + line += ' ' * (maxWidth - len(line)) + return line + + res = [] + begin, length = 0, 0 + for i in xrange(len(words)): + if length + len(words[i]) + (i - begin) > maxWidth: + res += connect(words, maxWidth, begin, i, length, False), + begin, length = i, 0 + length += len(words[i]) + + # Last line. + res += connect(words, maxWidth, begin, len(words), length, True), + return res - # add space - j = begin - while j < i: - if j == begin: - s = words[j] - else: - s += ' ' * everyCount - if spaceCount > 0 and i < len(words): - s += ' ' - spaceCount -= 1 - s += words[j] - j += 1 - s += ' ' * spaceCount - result.append(s) - - return result if __name__ == "__main__": print Solution().fullJustify(["This", "is", "an", "example", "of", "text", "justification."], 16) From 670bd3073451aac9e34ac9e568669e10c034d3bf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Feb 2016 16:55:22 +0800 Subject: [PATCH 1799/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6a175e971..dc8da7a6d 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [C++](./C++/multiply-strings.cpp) [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [C++](./C++/length-of-last-word.cpp) [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./C++/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || -68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || +68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(k)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| From 8d92c942217da8ccdaf08f07c5cb63b9ab49e3ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Feb 2016 16:57:00 +0800 Subject: [PATCH 1800/1939] Update text-justification.cpp --- C++/text-justification.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/text-justification.cpp b/C++/text-justification.cpp index 98db06b75..f286a7d29 100644 --- a/C++/text-justification.cpp +++ b/C++/text-justification.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(k), k is maxWidth. +// Space: O(1) class Solution { public: From eafd5d6a293d2faed29a6b732bc8424fac2a3ecc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Feb 2016 16:57:23 +0800 Subject: [PATCH 1801/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dc8da7a6d..6a175e971 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [C++](./C++/multiply-strings.cpp) [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [C++](./C++/length-of-last-word.cpp) [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./C++/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || -68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(k)_ | Hard || +68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| From 0e7dfe8529eba89d2d0d13f08a857ce669590a39 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Feb 2016 16:58:42 +0800 Subject: [PATCH 1802/1939] Update text-justification.py --- Python/text-justification.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/text-justification.py b/Python/text-justification.py index bb060f2c4..b292c30f7 100644 --- a/Python/text-justification.py +++ b/Python/text-justification.py @@ -42,7 +42,7 @@ def addSpaces(i, spaceCnt, maxWidth, is_last): return 0 def connect(words, maxWidth, begin, end, length, is_last): - s = [] + s = [] # The extra space O(k) is spent here. n = end - begin for i in xrange(n): s += words[begin + i], From 4c6667258ed9951adc497028a7e18b6e27a60db5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Feb 2016 17:13:54 +0800 Subject: [PATCH 1803/1939] Update text-justification.cpp --- C++/text-justification.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/text-justification.cpp b/C++/text-justification.cpp index f286a7d29..601be856e 100644 --- a/C++/text-justification.cpp +++ b/C++/text-justification.cpp @@ -21,7 +21,7 @@ class Solution { } private: - string connect(const vector &words, int maxWidth, + string connect(const vector& words, int maxWidth, int begin, int end, int len, bool is_last) { string s; From 9ae64848556994b4ac3a042a07269c20a3b752d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Feb 2016 20:04:59 +0800 Subject: [PATCH 1804/1939] Update and rename isPalindromeII.cpp to valid-palindrome.cpp --- C++/isPalindromeII.cpp | 24 ----------------------- C++/valid-palindrome.cpp | 42 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 24 deletions(-) delete mode 100644 C++/isPalindromeII.cpp create mode 100644 C++/valid-palindrome.cpp diff --git a/C++/isPalindromeII.cpp b/C++/isPalindromeII.cpp deleted file mode 100644 index 557697794..000000000 --- a/C++/isPalindromeII.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - bool isPalindrome(string s) { - transform(s.begin(), s.end(), s.begin(), ::tolower); - auto left = s.begin(); - auto right = prev(s.end()); - for(; left < right;) { - if(!isalnum(*left)) - ++left; - else if(!isalnum(*right)) - --right; - else if(*left != *right) - return false; - else { - ++left; - --right; - } - } - return true; - } -}; diff --git a/C++/valid-palindrome.cpp b/C++/valid-palindrome.cpp new file mode 100644 index 000000000..be15bef7a --- /dev/null +++ b/C++/valid-palindrome.cpp @@ -0,0 +1,42 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool isPalindrome(string s) { + int i = 0, j = s.length() - 1; + while (i < j) { + if (!isalnum(s[i])) { + ++i; + } else if (!isalnum(s[j])) { + --j; + } else if (tolower(s[i]) != ::tolower(s[j])) { + return false; + } else { + ++i, --j; + } + } + return true; + } +}; + +// Iterator solution. +class Solution2 { +public: + bool isPalindrome(string s) { + auto left = s.begin(); + auto right = prev(s.end()); + for(; left < right;) { + if(!isalnum(*left)) { + ++left; + } else if(!isalnum(*right)) { + --right; + } else if(::tolower(*left) != ::tolower(*right)) { + return false; + } else { + ++left, --right; + } + } + return true; + } +}; From 62f45d4d74bffd7822f1e877340a6165c1fbd01c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Feb 2016 20:05:27 +0800 Subject: [PATCH 1805/1939] Update valid-palindrome.cpp --- C++/valid-palindrome.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/C++/valid-palindrome.cpp b/C++/valid-palindrome.cpp index be15bef7a..c416b16db 100644 --- a/C++/valid-palindrome.cpp +++ b/C++/valid-palindrome.cpp @@ -10,7 +10,7 @@ class Solution { ++i; } else if (!isalnum(s[j])) { --j; - } else if (tolower(s[i]) != ::tolower(s[j])) { + } else if (::tolower(s[i]) != ::tolower(s[j])) { return false; } else { ++i, --j; @@ -20,6 +20,8 @@ class Solution { } }; +// Time: O(n) +// Space: O(1) // Iterator solution. class Solution2 { public: From f6b12824a96eba1441142e3acc44d7b6c98047a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Feb 2016 20:05:49 +0800 Subject: [PATCH 1806/1939] Update valid-palindrome.cpp --- C++/valid-palindrome.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/valid-palindrome.cpp b/C++/valid-palindrome.cpp index c416b16db..c7d0b0478 100644 --- a/C++/valid-palindrome.cpp +++ b/C++/valid-palindrome.cpp @@ -10,7 +10,7 @@ class Solution { ++i; } else if (!isalnum(s[j])) { --j; - } else if (::tolower(s[i]) != ::tolower(s[j])) { + } else if (tolower(s[i]) != tolower(s[j])) { return false; } else { ++i, --j; @@ -33,7 +33,7 @@ class Solution2 { ++left; } else if(!isalnum(*right)) { --right; - } else if(::tolower(*left) != ::tolower(*right)) { + } else if(tolower(*left) != tolower(*right)) { return false; } else { ++left, --right; From 809a5b1df49444b67d3da5b4ddfc9633c8284eba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Feb 2016 20:06:51 +0800 Subject: [PATCH 1807/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6a175e971..87039955c 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [C++](./C++/length-of-last-word.cpp) [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./C++/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || -125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || +125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [C++](./C++/valid-palindrome.cpp) [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| 165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || From e63a6ee15bf5028b7235c1ebc5b226b9b9a821dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Feb 2016 20:07:37 +0800 Subject: [PATCH 1808/1939] Update valid-palindrome.cpp --- C++/valid-palindrome.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/valid-palindrome.cpp b/C++/valid-palindrome.cpp index c7d0b0478..3e81b0275 100644 --- a/C++/valid-palindrome.cpp +++ b/C++/valid-palindrome.cpp @@ -28,12 +28,12 @@ class Solution2 { bool isPalindrome(string s) { auto left = s.begin(); auto right = prev(s.end()); - for(; left < right;) { - if(!isalnum(*left)) { + while (left < right) { + if (!isalnum(*left)) { ++left; - } else if(!isalnum(*right)) { + } else if (!isalnum(*right)) { --right; - } else if(tolower(*left) != tolower(*right)) { + } else if (tolower(*left) != tolower(*right)) { return false; } else { ++left, --right; From c44a447ae39883221b50d97cebb7edde70eec86b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Feb 2016 20:15:16 +0800 Subject: [PATCH 1809/1939] Update and rename reverseWords.cpp to reverse-words.cpp --- C++/reverse-words.cpp | 31 +++++++++++++++++++++++++++++++ C++/reverseWords.cpp | 22 ---------------------- 2 files changed, 31 insertions(+), 22 deletions(-) create mode 100644 C++/reverse-words.cpp delete mode 100644 C++/reverseWords.cpp diff --git a/C++/reverse-words.cpp b/C++/reverse-words.cpp new file mode 100644 index 000000000..26755a535 --- /dev/null +++ b/C++/reverse-words.cpp @@ -0,0 +1,31 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + void reverseWords(string &s) { + // Reverse the whole string first. + reverse(s.begin(), s.end()); + + size_t start = 0, end; + while ((end = s.find(" ", start)) != string::npos) { + // Reverse each word in the string. + reverse(s.begin() + start, s.begin() + end); + start = end + 1; + } + // Reverse the last word. + reverse(s.begin() + start, s.end()); + + // Remove beginning and trailing spaces. + int new_len = 0; + for (int i = 0; i < s.length(); ++i) { + if (s[i] != ' ') { + s[new_len++] = s[i]; + if (s[i + 1] == ' ' || i == s.length() - 1) { + s[new_len++] = ' '; + } + } + } + s.resize(new_len == 0 ? 0 : new_len - 1); + } +}; diff --git a/C++/reverseWords.cpp b/C++/reverseWords.cpp deleted file mode 100644 index c481c96b0..000000000 --- a/C++/reverseWords.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// Complexity: -// O(n) time -// O(n) space - -class Solution { -public: - void reverseWords(string &s) - { - string rs; - for (int i = s.length()-1; i >= 0; ) - { - while (i >= 0 && s[i] == ' ') i--; - if (i < 0) break; - if (!rs.empty()) rs.push_back(' '); - string t; - while (i >= 0 && s[i] != ' ') t.push_back(s[i--]); - reverse(t.begin(), t.end()); - rs.append(t); - } - s = rs; - } -}; \ No newline at end of file From 8f05a9ef90f3b0fa5e5176036d39bb39c8c4410b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Feb 2016 20:17:54 +0800 Subject: [PATCH 1810/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 87039955c..0b03d9ca1 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./C++/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [C++](./C++/valid-palindrome.cpp) [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || -151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(n)_ | Medium || +151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [C++](./C++/reverse-words-in-a-string.cpp) [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(1)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| 165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | From 9ecba3351bfae1a17db3ed645fbba5ec8fdf80c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Feb 2016 20:18:33 +0800 Subject: [PATCH 1811/1939] Rename reverse-words.cpp to reverse-words-in-a-string.cpp --- C++/{reverse-words.cpp => reverse-words-in-a-string.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{reverse-words.cpp => reverse-words-in-a-string.cpp} (100%) diff --git a/C++/reverse-words.cpp b/C++/reverse-words-in-a-string.cpp similarity index 100% rename from C++/reverse-words.cpp rename to C++/reverse-words-in-a-string.cpp From 7d4b4a79efb9ffea0d5101e415cd8c0420c3cd3c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Feb 2016 22:10:34 +0800 Subject: [PATCH 1812/1939] Update reverse-words-in-a-string.cpp --- C++/reverse-words-in-a-string.cpp | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/C++/reverse-words-in-a-string.cpp b/C++/reverse-words-in-a-string.cpp index 26755a535..52579434d 100644 --- a/C++/reverse-words-in-a-string.cpp +++ b/C++/reverse-words-in-a-string.cpp @@ -7,25 +7,20 @@ class Solution { // Reverse the whole string first. reverse(s.begin(), s.end()); - size_t start = 0, end; - while ((end = s.find(" ", start)) != string::npos) { + size_t start = 0, end = 0; + size_t len = 0; + while ((start = s.find_first_not_of(" ", end)) != string::npos) { + if ((end = s.find(" ", start)) == string::npos) { + end = s.length(); + } // Reverse each word in the string. reverse(s.begin() + start, s.begin() + end); - start = end + 1; - } - // Reverse the last word. - reverse(s.begin() + start, s.end()); - // Remove beginning and trailing spaces. - int new_len = 0; - for (int i = 0; i < s.length(); ++i) { - if (s[i] != ' ') { - s[new_len++] = s[i]; - if (s[i + 1] == ' ' || i == s.length() - 1) { - s[new_len++] = ' '; - } - } + // Shift the word to avoid extra space. + move(s.begin() + start, s.begin() + end, s.begin() + len); + len += end - start; + s[len++] = ' '; } - s.resize(new_len == 0 ? 0 : new_len - 1); + s.resize(len ? len - 1 : 0); } }; From 7ad6b7ba99e0454072480cae0f49f4d28d8b4be3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Feb 2016 22:11:19 +0800 Subject: [PATCH 1813/1939] Update reverse-words-in-a-string.cpp --- C++/reverse-words-in-a-string.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/reverse-words-in-a-string.cpp b/C++/reverse-words-in-a-string.cpp index 52579434d..9b4a047bd 100644 --- a/C++/reverse-words-in-a-string.cpp +++ b/C++/reverse-words-in-a-string.cpp @@ -7,8 +7,7 @@ class Solution { // Reverse the whole string first. reverse(s.begin(), s.end()); - size_t start = 0, end = 0; - size_t len = 0; + size_t start = 0, end = 0, len = 0; while ((start = s.find_first_not_of(" ", end)) != string::npos) { if ((end = s.find(" ", start)) == string::npos) { end = s.length(); From 32eb88d0367d5905e4d2304d1c0ccb081839e57a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Feb 2016 22:12:20 +0800 Subject: [PATCH 1814/1939] Update reverse-words-in-a-string.cpp --- C++/reverse-words-in-a-string.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/reverse-words-in-a-string.cpp b/C++/reverse-words-in-a-string.cpp index 9b4a047bd..5621252ec 100644 --- a/C++/reverse-words-in-a-string.cpp +++ b/C++/reverse-words-in-a-string.cpp @@ -7,17 +7,17 @@ class Solution { // Reverse the whole string first. reverse(s.begin(), s.end()); - size_t start = 0, end = 0, len = 0; - while ((start = s.find_first_not_of(" ", end)) != string::npos) { - if ((end = s.find(" ", start)) == string::npos) { + size_t begin = 0, end = 0, len = 0; + while ((begin = s.find_first_not_of(" ", end)) != string::npos) { + if ((end = s.find(" ", begin)) == string::npos) { end = s.length(); } // Reverse each word in the string. - reverse(s.begin() + start, s.begin() + end); + reverse(s.begin() + begin, s.begin() + end); // Shift the word to avoid extra space. - move(s.begin() + start, s.begin() + end, s.begin() + len); - len += end - start; + move(s.begin() + begin, s.begin() + end, s.begin() + len); + len += end - begin; s[len++] = ' '; } s.resize(len ? len - 1 : 0); From dda53c4e1da0c7601e99545a2e7f9e3390d52a0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 19:36:05 +0800 Subject: [PATCH 1815/1939] Create self-crossing.cpp --- C++/self-crossing.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/self-crossing.cpp diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp new file mode 100644 index 000000000..7b4a2375b --- /dev/null +++ b/C++/self-crossing.cpp @@ -0,0 +1,33 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool isSelfCrossing(vector& x) { + for (int i = 3; i < x.size(); ++i) { + if (x[i] >= x[i - 2] && x[i - 1] <= x[i - 3]) { +// i-2 +// case 1 : i-1┌─┐ +// └─┼─>i +// i-3 + return true; + } else if (i >= 4 && x[i - 1] == x[i - 3] && x[i] + x[i - 4] >= x[i - 2]) { +// i-2 +// case 2 : i-1 ┌────┐ +// └─══>┘i-3 +// i i-4 (overlapped) + return true; + } else if (i >= 5 && x[i - 2] >= x[i - 4] && x[i] + x[i - 4] >= x[i - 2] && + x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) { +// i-4 +// ┌──┐ +// case 3 : │i<┼─┐ +// i-3│ i-5│i-1 +// └────┘ +// i-2 + return true; + } + } + return false; + } +}; From 95a4e9a82342249ef03a2743fafdf208d741a786 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 19:42:05 +0800 Subject: [PATCH 1816/1939] Update self-crossing.cpp --- C++/self-crossing.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp index 7b4a2375b..cce4f0b01 100644 --- a/C++/self-crossing.cpp +++ b/C++/self-crossing.cpp @@ -28,6 +28,6 @@ class Solution { return true; } } - return false; + return false; } }; From 633dd602112ccbef13c79186385621ad63bdad97 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 19:48:45 +0800 Subject: [PATCH 1817/1939] Create self-crossing.py --- Python/self-crossing.py | 51 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/self-crossing.py diff --git a/Python/self-crossing.py b/Python/self-crossing.py new file mode 100644 index 000000000..7d96d2206 --- /dev/null +++ b/Python/self-crossing.py @@ -0,0 +1,51 @@ +# Time: O(n) +# Space: O(1) + +# You are given an array x of n positive numbers. +# You start at point (0,0) and moves x[0] metres to +# the north, then x[1] metres to the west, x[2] metres +# to the south, x[3] metres to the east and so on. +# In other words, after each move your direction changes counter-clockwise. +# +# Write a one-pass algorithm with O(1) extra space to determine, +# if your path crosses itself, or not. +# +# Example 1: +# Given x = [2, 1, 1, 2] +# Return true (self crossing) +# Example 2: +# Given x = [1, 2, 3, 4] +# Return false (not self crossing) +# Example 3: +# Given x = [1, 1, 1, 1] +# Return true (self crossing) + +class Solution(object): + def isSelfCrossing(self, x): + """ + :type x: List[int] + :rtype: bool + """ + for i in xrange(3, len(x)): + if x[i] >= x[i - 2] and x[i - 3] >= x[i - 1]: +# i-2 +# case 1 : i-1┌─┐ +# └─┼─>i +# i-3 + return True + elif i >= 4 and x[i - 1] == x[i - 3] and x[i] + x[i - 4] >= x[i - 2]: +# i-2 +# case 2 : i-1 ┌────┐ +# └─══>┘i-3 +# i i-4 (overlapped) + return True + elif i >= 5 and x[i - 4] <= x[i - 2] and x[i] + x[i - 4] >= x[i - 2] and \ + x[i - 1] <= x[i - 3] and x[i - 5] + x[i - 1] >= x[i - 3]: +# i-4 +# ┌──┐ +# case 3 : │i<┼─┐ +# i-3│ i-5│i-1 +# └────┘ +# i-2 + return True + return False From bedaa2d9c0ccdc2ea88472228b03760007476be7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 19:51:07 +0800 Subject: [PATCH 1818/1939] Update self-crossing.cpp --- C++/self-crossing.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp index cce4f0b01..61f355be7 100644 --- a/C++/self-crossing.cpp +++ b/C++/self-crossing.cpp @@ -5,7 +5,7 @@ class Solution { public: bool isSelfCrossing(vector& x) { for (int i = 3; i < x.size(); ++i) { - if (x[i] >= x[i - 2] && x[i - 1] <= x[i - 3]) { + if (x[i] >= x[i - 2] && x[i - 3] >= x[i - 1]) { // i-2 // case 1 : i-1┌─┐ // └─┼─>i @@ -17,7 +17,7 @@ class Solution { // └─══>┘i-3 // i i-4 (overlapped) return true; - } else if (i >= 5 && x[i - 2] >= x[i - 4] && x[i] + x[i - 4] >= x[i - 2] && + } else if (i >= 5 && x[i - 4] <= x[i - 2] && x[i] + x[i - 4] >= x[i - 2] && x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) { // i-4 // ┌──┐ From 80aca665d0b1de215c57132b352b7954d0896e39 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 19:53:05 +0800 Subject: [PATCH 1819/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0b03d9ca1..70b293dff 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-334%20%2F%20334-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-335%20%2F%20335-ff69b4.svg) -Up to date (2016-02-16), there are `317` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-02-16), there are `318` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `334` questions. +Here is the classification of all `335` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -243,6 +243,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 292| [Nim Game](https://leetcode.com/problems/nim-game/) | [C++](./C++/nim-game.cpp) [Python](./Python/nim-game.py) | _O(1)_ | _O(1)_ | Easy | LintCode || 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./C++/bulb-switcher.cpp) [Python](./Python/bulb-switcher.py) | _O(1)_ | _O(1)_ | Medium ||| 326 | [Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./C++/power-of-three.cpp) [Python](./Python/power-of-three.py) | _O(1)_ | _O(1)_ | Easy ||| +335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | [C++](./C++/self-crossing.cpp) [Python](./Python/self-crossing.py) | _O(n)_ | _O(1)_ | Medium ||| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From 6248d37db8965b4941403da903da2fce6fe925fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 19:55:00 +0800 Subject: [PATCH 1820/1939] Update self-crossing.cpp --- C++/self-crossing.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp index 61f355be7..33e1fbd6c 100644 --- a/C++/self-crossing.cpp +++ b/C++/self-crossing.cpp @@ -19,12 +19,12 @@ class Solution { return true; } else if (i >= 5 && x[i - 4] <= x[i - 2] && x[i] + x[i - 4] >= x[i - 2] && x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) { -// i-4 -// ┌──┐ -// case 3 : │i<┼─┐ -// i-3│ i-5│i-1 -// └────┘ -// i-2 +// i-4 +// ┌──┐ +// case 3 : │i<┼─┐ +// i-3│ i-5│i-1 +// └────┘ +// i-2 return true; } } From 0d00ec15a87862e52be658c8b1a1afd4890834bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 19:55:51 +0800 Subject: [PATCH 1821/1939] Update self-crossing.cpp --- C++/self-crossing.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp index 33e1fbd6c..eae6e4043 100644 --- a/C++/self-crossing.cpp +++ b/C++/self-crossing.cpp @@ -12,18 +12,18 @@ class Solution { // i-3 return true; } else if (i >= 4 && x[i - 1] == x[i - 3] && x[i] + x[i - 4] >= x[i - 2]) { -// i-2 -// case 2 : i-1 ┌────┐ -// └─══>┘i-3 -// i i-4 (overlapped) +// i-2 +// case 2 : i-1┌────┐ +// └─══>┘i-3 +// i i-4 (overlapped) return true; } else if (i >= 5 && x[i - 4] <= x[i - 2] && x[i] + x[i - 4] >= x[i - 2] && x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) { -// i-4 -// ┌──┐ -// case 3 : │i<┼─┐ -// i-3│ i-5│i-1 -// └────┘ +// i-4 +// ┌──┐ +// case 3 : │i<┼─┐ +// i-3│ i-5│i-1 +// └────┘ // i-2 return true; } From 62ef04d60cd3e71573b92f493f8414220df4dcd1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 19:57:33 +0800 Subject: [PATCH 1822/1939] Update self-crossing.py --- Python/self-crossing.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Python/self-crossing.py b/Python/self-crossing.py index 7d96d2206..a0f85c630 100644 --- a/Python/self-crossing.py +++ b/Python/self-crossing.py @@ -28,16 +28,16 @@ def isSelfCrossing(self, x): """ for i in xrange(3, len(x)): if x[i] >= x[i - 2] and x[i - 3] >= x[i - 1]: -# i-2 -# case 1 : i-1┌─┐ -# └─┼─>i -# i-3 +# i-2 +# case 1 : i-1┌─┐ +# └─┼─>i +# i-3 return True elif i >= 4 and x[i - 1] == x[i - 3] and x[i] + x[i - 4] >= x[i - 2]: -# i-2 -# case 2 : i-1 ┌────┐ +# i-2 +# case 2 : i-1┌────┐ # └─══>┘i-3 -# i i-4 (overlapped) +# i i-4 (overlapped) return True elif i >= 5 and x[i - 4] <= x[i - 2] and x[i] + x[i - 4] >= x[i - 2] and \ x[i - 1] <= x[i - 3] and x[i - 5] + x[i - 1] >= x[i - 3]: @@ -46,6 +46,6 @@ def isSelfCrossing(self, x): # case 3 : │i<┼─┐ # i-3│ i-5│i-1 # └────┘ -# i-2 +# i-2 return True return False From eb88f8d46ad7c0bfcd7648242843e8afdcb3119b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 19:58:24 +0800 Subject: [PATCH 1823/1939] Update self-crossing.cpp --- C++/self-crossing.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp index eae6e4043..fb170d8ab 100644 --- a/C++/self-crossing.cpp +++ b/C++/self-crossing.cpp @@ -6,25 +6,25 @@ class Solution { bool isSelfCrossing(vector& x) { for (int i = 3; i < x.size(); ++i) { if (x[i] >= x[i - 2] && x[i - 3] >= x[i - 1]) { -// i-2 -// case 1 : i-1┌─┐ -// └─┼─>i -// i-3 +// i-2 +// case 1 : i-1┌─┐ +// └─┼─>i +// i-3 return true; } else if (i >= 4 && x[i - 1] == x[i - 3] && x[i] + x[i - 4] >= x[i - 2]) { -// i-2 -// case 2 : i-1┌────┐ -// └─══>┘i-3 -// i i-4 (overlapped) +// i-2 +// case 2 : i-1┌────┐ +// └─══>┘i-3 +// i i-4 (overlapped) return true; } else if (i >= 5 && x[i - 4] <= x[i - 2] && x[i] + x[i - 4] >= x[i - 2] && x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) { -// i-4 -// ┌──┐ -// case 3 : │i<┼─┐ -// i-3│ i-5│i-1 -// └────┘ -// i-2 +// i-4 +// ┌──┐ +// case 3 : │i<┼─┐ +// i-3│ i-5│i-1 +// └────┘ +// i-2 return true; } } From 1b8a42520feda720c6926846b972d260ae5c95e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Feb 2016 20:17:31 +0800 Subject: [PATCH 1824/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 70b293dff..95f58705c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-335%20%2F%20335-ff69b4.svg) -Up to date (2016-02-16), there are `318` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-02-23), there are `318` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `335` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From da6563070da3f00ddd7997353cdacbc838afa361 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 00:11:43 +0800 Subject: [PATCH 1825/1939] Update self-crossing.cpp --- C++/self-crossing.cpp | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp index fb170d8ab..9ef6304d6 100644 --- a/C++/self-crossing.cpp +++ b/C++/self-crossing.cpp @@ -4,27 +4,32 @@ class Solution { public: bool isSelfCrossing(vector& x) { + if (x.size() >= 5 && x[3] == x[1] && x[4] + x[0] >= x[2]) { + // Crossing in a loop: + // i-2 + // i-1┌────┐ + // └─══>┘i-3 + // i i-4 (overlapped) + return true; + } + for (int i = 3; i < x.size(); ++i) { if (x[i] >= x[i - 2] && x[i - 3] >= x[i - 1]) { -// i-2 -// case 1 : i-1┌─┐ -// └─┼─>i -// i-3 - return true; - } else if (i >= 4 && x[i - 1] == x[i - 3] && x[i] + x[i - 4] >= x[i - 2]) { -// i-2 -// case 2 : i-1┌────┐ -// └─══>┘i-3 -// i i-4 (overlapped) + // Crossing in a shrinking spiral: + // i-2 + // i-1┌─┐ + // └─┼─>i + // i-3 return true; } else if (i >= 5 && x[i - 4] <= x[i - 2] && x[i] + x[i - 4] >= x[i - 2] && x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) { -// i-4 -// ┌──┐ -// case 3 : │i<┼─┐ -// i-3│ i-5│i-1 -// └────┘ -// i-2 + // Crossing in a growing spiral: + // i-4 + // ┌──┐ + // │i<┼─┐ + // i-3│ i-5│i-1 + // └────┘ + // i-2 return true; } } From 22eb26965ff96bcffbcf1de5950b2e4fa64b4b39 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 00:13:10 +0800 Subject: [PATCH 1826/1939] Update self-crossing.cpp --- C++/self-crossing.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp index 9ef6304d6..164fa8a52 100644 --- a/C++/self-crossing.cpp +++ b/C++/self-crossing.cpp @@ -15,7 +15,7 @@ class Solution { for (int i = 3; i < x.size(); ++i) { if (x[i] >= x[i - 2] && x[i - 3] >= x[i - 1]) { - // Crossing in a shrinking spiral: + // Case 1: // i-2 // i-1┌─┐ // └─┼─>i @@ -23,7 +23,7 @@ class Solution { return true; } else if (i >= 5 && x[i - 4] <= x[i - 2] && x[i] + x[i - 4] >= x[i - 2] && x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) { - // Crossing in a growing spiral: + // Case 2: // i-4 // ┌──┐ // │i<┼─┐ From 8b9e326bf6b490c0ebc1916d811c0c621bbeaac3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 00:16:00 +0800 Subject: [PATCH 1827/1939] Update self-crossing.cpp --- C++/self-crossing.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp index 164fa8a52..a6869a171 100644 --- a/C++/self-crossing.cpp +++ b/C++/self-crossing.cpp @@ -6,10 +6,10 @@ class Solution { bool isSelfCrossing(vector& x) { if (x.size() >= 5 && x[3] == x[1] && x[4] + x[0] >= x[2]) { // Crossing in a loop: - // i-2 - // i-1┌────┐ - // └─══>┘i-3 - // i i-4 (overlapped) + // 2 + // 3 ┌────┐ + // └─══>┘1 + // 4 0 (overlapped) return true; } From bfb45768f572b26a6dba7d86c29412a202eedd39 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 00:18:52 +0800 Subject: [PATCH 1828/1939] Update self-crossing.cpp --- C++/self-crossing.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/self-crossing.cpp b/C++/self-crossing.cpp index a6869a171..2db45b704 100644 --- a/C++/self-crossing.cpp +++ b/C++/self-crossing.cpp @@ -29,7 +29,7 @@ class Solution { // │i<┼─┐ // i-3│ i-5│i-1 // └────┘ - // i-2 + // i-2 return true; } } From 008f3144c72a9f2657c5e9cbb0a7631f8c99f3c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 00:19:35 +0800 Subject: [PATCH 1829/1939] Update self-crossing.py --- Python/self-crossing.py | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/Python/self-crossing.py b/Python/self-crossing.py index a0f85c630..3d2b5c986 100644 --- a/Python/self-crossing.py +++ b/Python/self-crossing.py @@ -26,26 +26,30 @@ def isSelfCrossing(self, x): :type x: List[int] :rtype: bool """ + if len(x) >= 5 and x[3] == x[1] and x[4] + x[0] >= x[2]: + # Crossing in a loop: + # 2 + # 3 ┌────┐ + # └─══>┘1 + # 4 0 (overlapped) + return True + for i in xrange(3, len(x)): if x[i] >= x[i - 2] and x[i - 3] >= x[i - 1]: -# i-2 -# case 1 : i-1┌─┐ -# └─┼─>i -# i-3 - return True - elif i >= 4 and x[i - 1] == x[i - 3] and x[i] + x[i - 4] >= x[i - 2]: -# i-2 -# case 2 : i-1┌────┐ -# └─══>┘i-3 -# i i-4 (overlapped) + # Case 1: + # i-2 + # i-1┌─┐ + # └─┼─>i + # i-3 return True elif i >= 5 and x[i - 4] <= x[i - 2] and x[i] + x[i - 4] >= x[i - 2] and \ x[i - 1] <= x[i - 3] and x[i - 5] + x[i - 1] >= x[i - 3]: -# i-4 -# ┌──┐ -# case 3 : │i<┼─┐ -# i-3│ i-5│i-1 -# └────┘ -# i-2 + # Case 2: + # i-4 + # ┌──┐ + # │i<┼─┐ + # i-3│ i-5│i-1 + # └────┘ + # i-2 return True return False From 64a798cc3c9571205bb61cc8b40ba4d226344e8a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 00:20:42 +0800 Subject: [PATCH 1830/1939] Update self-crossing.py --- Python/self-crossing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/self-crossing.py b/Python/self-crossing.py index 3d2b5c986..1cb2f8f22 100644 --- a/Python/self-crossing.py +++ b/Python/self-crossing.py @@ -32,7 +32,7 @@ def isSelfCrossing(self, x): # 3 ┌────┐ # └─══>┘1 # 4 0 (overlapped) - return True + return True for i in xrange(3, len(x)): if x[i] >= x[i - 2] and x[i - 3] >= x[i - 1]: From 98896c222c2686dbab96b58819c08131d31dc1b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 00:21:42 +0800 Subject: [PATCH 1831/1939] Update self-crossing.py --- Python/self-crossing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/self-crossing.py b/Python/self-crossing.py index 1cb2f8f22..5fab7c4e8 100644 --- a/Python/self-crossing.py +++ b/Python/self-crossing.py @@ -43,7 +43,7 @@ def isSelfCrossing(self, x): # i-3 return True elif i >= 5 and x[i - 4] <= x[i - 2] and x[i] + x[i - 4] >= x[i - 2] and \ - x[i - 1] <= x[i - 3] and x[i - 5] + x[i - 1] >= x[i - 3]: + x[i - 1] <= x[i - 3] and x[i - 5] + x[i - 1] >= x[i - 3]: # Case 2: # i-4 # ┌──┐ From 8ab534ab1e64e483bf5138511eec8d5e3c5cf7ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 20:50:01 +0800 Subject: [PATCH 1832/1939] Update one-edit-distance.py --- Python/one-edit-distance.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Python/one-edit-distance.py b/Python/one-edit-distance.py index 8a5dd426b..480e0c26c 100644 --- a/Python/one-edit-distance.py +++ b/Python/one-edit-distance.py @@ -4,11 +4,13 @@ # Given two strings S and T, determine if they are both one edit distance apart. # -class Solution: - # @param s, a string - # @param t, a string - # @return a boolean +class Solution(object): def isOneEditDistance(self, s, t): + """ + :type s: str + :type t: str + :rtype: bool + """ m, n = len(s), len(t) if m > n: return self.isOneEditDistance(t, s) @@ -26,4 +28,4 @@ def isOneEditDistance(self, s, t): return i == m if __name__ == "__main__": - print Solution().isOneEditDistance("teacher", "acher") \ No newline at end of file + print Solution().isOneEditDistance("teacher", "acher") From f03348dfbe1a95490ce2f28a65dc3e5ceee4fafe Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 20:50:20 +0800 Subject: [PATCH 1833/1939] Update one-edit-distance.py --- Python/one-edit-distance.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/one-edit-distance.py b/Python/one-edit-distance.py index 480e0c26c..4e11cfe29 100644 --- a/Python/one-edit-distance.py +++ b/Python/one-edit-distance.py @@ -26,6 +26,7 @@ def isOneEditDistance(self, s, t): i += 1 return i == m - + + if __name__ == "__main__": print Solution().isOneEditDistance("teacher", "acher") From 34b6fe61a1828a79c688e6c4ee6e97d3ff48c301 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 21:05:11 +0800 Subject: [PATCH 1834/1939] Create one-edit-distance.cpp --- C++/one-edit-distance.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/one-edit-distance.cpp diff --git a/C++/one-edit-distance.cpp b/C++/one-edit-distance.cpp new file mode 100644 index 000000000..586fc8200 --- /dev/null +++ b/C++/one-edit-distance.cpp @@ -0,0 +1,28 @@ +// Time: O(m + n) +// Space: O(1) + +class Solution { +public: + bool isOneEditDistance(string s, string t) { + const int m = s.length(), n = t.length(); + if (m > n) { + return isOneEditDistance(t, s); + } + if (n - m > 1) { + return false; + } + + int i = 0, shift = n - m; + while (i < m && s[i] == t[i]) { + ++i; + } + if (shift == 0) { + ++i; + } + while (i < m && s[i] == t[i + shift]) { + ++i; + } + + return i == m; + } +}; From 49e8dd3e52b1146d03412ec28dcaaf4ce5cfc9a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Feb 2016 21:06:26 +0800 Subject: [PATCH 1835/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 95f58705c..c9b53e387 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [C++](./C++/valid-palindrome.cpp) [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [C++](./C++/reverse-words-in-a-string.cpp) [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(1)_ | Medium || -161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| +161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [C++](./C++/one-edit-distance.cpp) [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| 165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` From 0b7bc3c77e28d0ef12e656867c92fc8683084bf5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 25 Feb 2016 00:02:08 +0800 Subject: [PATCH 1836/1939] Update self-crossing.py --- Python/self-crossing.py | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/Python/self-crossing.py b/Python/self-crossing.py index 5fab7c4e8..cdb4439ab 100644 --- a/Python/self-crossing.py +++ b/Python/self-crossing.py @@ -2,22 +2,37 @@ # Space: O(1) # You are given an array x of n positive numbers. -# You start at point (0,0) and moves x[0] metres to -# the north, then x[1] metres to the west, x[2] metres -# to the south, x[3] metres to the east and so on. -# In other words, after each move your direction changes counter-clockwise. +# You start at point (0,0) and moves x[0] metres to the north, +# then x[1] metres to the west, x[2] metres to the south, +# x[3] metres to the east and so on. In other words, +# after each move your direction changes counter-clockwise. # -# Write a one-pass algorithm with O(1) extra space to determine, +# Write a one-pass algorithm with O(1) extra space to determine, # if your path crosses itself, or not. # # Example 1: -# Given x = [2, 1, 1, 2] +# Given x = [2, 1, 1, 2], +# ┌───┐ +# │ │ +# └───┼──> +# │ +# # Return true (self crossing) # Example 2: -# Given x = [1, 2, 3, 4] +# Given x = [1, 2, 3, 4], +# ┌──────┐ +# │ │ +# │ +# │ +# └────────────> +# # Return false (not self crossing) # Example 3: -# Given x = [1, 1, 1, 1] +# Given x = [1, 1, 1, 1], +# ┌───┐ +# │ │ +# └───┼> +# # Return true (self crossing) class Solution(object): From 60c46e58895e409f573ac649e5a7d003d0480263 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 25 Feb 2016 22:41:29 +0800 Subject: [PATCH 1837/1939] Create compare-version-numbers.cpp --- C++/compare-version-numbers.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/compare-version-numbers.cpp diff --git a/C++/compare-version-numbers.cpp b/C++/compare-version-numbers.cpp new file mode 100644 index 000000000..e15efbc72 --- /dev/null +++ b/C++/compare-version-numbers.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int compareVersion(string version1, string version2) { + const int n1 = version1.length(), n2 = version2.length(); + for (int i = 0, j = 0; i < n1 || j < n2; ++i, ++j) { + int v1 = 0, v2 = 0; + while (i < n1 && version1[i] != '.') { + v1 = v1 * 10 + version1[i++] - '0'; + } + while (j < n2 && version2[j] != '.') { + v2 = v2 * 10 + version2[j++] - '0'; + } + if (v1 != v2) { + return v1 > v2 ? 1 : -1; + } + } + return 0; + } +}; From d3b325b0a2f2a461f67f6af0a49f237c5098fee5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 25 Feb 2016 22:43:35 +0800 Subject: [PATCH 1838/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c9b53e387..807094615 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [C++](./C++/valid-palindrome.cpp) [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [C++](./C++/reverse-words-in-a-string.cpp) [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(1)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [C++](./C++/one-edit-distance.cpp) [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| -165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || +165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [C++](./C++/compare-version-numbers.cpp) [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` 271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [C++](./C++/encode-and-decode-strings.cpp) [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 📖 | From e73aa4d0dd91d89c35ff01dc633f032f4faa6faf Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 25 Feb 2016 22:50:19 +0800 Subject: [PATCH 1839/1939] Update compare-version-numbers.py --- Python/compare-version-numbers.py | 40 +++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/Python/compare-version-numbers.py b/Python/compare-version-numbers.py index a59d88c29..78056296c 100644 --- a/Python/compare-version-numbers.py +++ b/Python/compare-version-numbers.py @@ -1,6 +1,6 @@ # Time: O(n) # Space: O(1) -# + # Compare two version numbers version1 and version1. # If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. # @@ -13,13 +13,39 @@ # 0.1 < 1.1 < 1.2 < 13.37 # +class Solution(object): + def compareVersion(self, version1, version2): + """ + :type version1: str + :type version2: str + :rtype: int + """ + n1, n2 = len(version1), len(version2) + i, j = 0, 0 + while i < n1 or j < n2: + v1, v2 = 0, 0 + while i < n1 and version1[i] != '.': + v1 = v1 * 10 + int(version1[i]) + i += 1 + while j < n2 and version2[j] != '.': + v2 = v2 * 10 + int(version2[j]) + j += 1 + if v1 != v2: + return 1 if v1 > v2 else -1 + i += 1 + j += 1 + + return 0 + # Time: O(n) -# Space: O(n), this could be enhanced to O(1) by better but trivial string parsing -class Solution: - # @param a, a string - # @param b, a string - # @return a boolean +# Space: O(n) +class Solution2(object): def compareVersion(self, version1, version2): + """ + :type version1: str + :type version2: str + :rtype: int + """ v1, v2 = version1.split("."), version2.split(".") if len(v1) > len(v2): @@ -41,4 +67,4 @@ def compareVersion(self, version1, version2): if __name__ == "__main__": print Solution().compareVersion("21.0", "121.1.0") print Solution().compareVersion("01", "1") - print Solution().compareVersion("1", "1.0") \ No newline at end of file + print Solution().compareVersion("1", "1.0") From 67d33d0a346eeda02f210287a09ce320888fb5e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 25 Feb 2016 22:51:02 +0800 Subject: [PATCH 1840/1939] Update compare-version-numbers.py --- Python/compare-version-numbers.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Python/compare-version-numbers.py b/Python/compare-version-numbers.py index 78056296c..bc4f909ef 100644 --- a/Python/compare-version-numbers.py +++ b/Python/compare-version-numbers.py @@ -2,11 +2,16 @@ # Space: O(1) # Compare two version numbers version1 and version1. -# If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. +# If version1 > version2 return 1, if version1 < version2 +# return -1, otherwise return 0. # -# You may assume that the version strings are non-empty and contain only digits and the . character. -# The . character does not represent a decimal point and is used to separate number sequences. -# For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. +# You may assume that the version strings are non-empty and +# contain only digits and the . character. +# The . character does not represent a decimal point and +# is used to separate number sequences. +# For instance, 2.5 is not "two and a half" or "half way to +# version three", it is the fifth second-level revision of +# the second first-level revision. # # Here is an example of version numbers ordering: # From 16b2e8ffe232f7b2793285c241afcfdb733711f8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Feb 2016 09:52:07 +0800 Subject: [PATCH 1841/1939] Update reverse-words-in-a-string-ii.py --- Python/reverse-words-in-a-string-ii.py | 30 +++++++++++++++----------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/Python/reverse-words-in-a-string-ii.py b/Python/reverse-words-in-a-string-ii.py index 09bd7f87b..6656ae327 100644 --- a/Python/reverse-words-in-a-string-ii.py +++ b/Python/reverse-words-in-a-string-ii.py @@ -1,9 +1,11 @@ # Time: O(n) # Space:O(1) # -# Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. +# Given an input string, reverse the string word by word. +# A word is defined as a sequence of non-space characters. # -# The input string does not contain leading or trailing spaces and the words are always separated by a single space. +# The input string does not contain leading or trailing spaces +# and the words are always separated by a single space. # # For example, # Given s = "the sky is blue", @@ -12,23 +14,25 @@ # Could you do it in-place without allocating extra space? # -class Solution: - # @param s, a list of 1 length strings, e.g., s = ['h','e','l','l','o'] - # @return nothing +class Solution(object): def reverseWords(self, s): - self.reverse(s, 0, len(s)) - + """ + :type s: a list of 1 length strings (List[str]) + :rtype: nothing + """ + def reverse(s, begin, end): + for i in xrange((end - begin) / 2): + s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i] + + reverse(s, 0, len(s)) i = 0 for j in xrange(len(s) + 1): if j == len(s) or s[j] == ' ': - self.reverse(s, i, j) + reverse(s, i, j) i = j + 1 - - def reverse(self, s, begin, end): - for i in xrange((end - begin) / 2): - s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i] + if __name__ == '__main__': s = ['h','e','l','l','o', ' ', 'w', 'o', 'r', 'l', 'd'] Solution().reverseWords(s) - print s \ No newline at end of file + print s From 068e1c7da917356c54f9a578b847b66f65a1664f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Feb 2016 09:58:53 +0800 Subject: [PATCH 1842/1939] Create reverse-words-in-a-string-ii.cpp --- C++/reverse-words-in-a-string-ii.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/reverse-words-in-a-string-ii.cpp diff --git a/C++/reverse-words-in-a-string-ii.cpp b/C++/reverse-words-in-a-string-ii.cpp new file mode 100644 index 000000000..88babb196 --- /dev/null +++ b/C++/reverse-words-in-a-string-ii.cpp @@ -0,0 +1,15 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + void reverseWords(string &s) { + reverse(s.begin(), s.end()); + for (int i = 0, j = 0; j <= s.length(); ++j) { + if (j == s.length() || s[j] == ' ') { + reverse(s.begin() + i, s.begin() + j); + i = j + 1; + } + } + } +}; From b7779db1a8b1e8a634f235168c989cbfabbea766 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Feb 2016 09:59:39 +0800 Subject: [PATCH 1843/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 807094615..32363c669 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [C++](./C++/reverse-words-in-a-string.cpp) [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(1)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [C++](./C++/one-edit-distance.cpp) [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖| 165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [C++](./C++/compare-version-numbers.cpp) [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || -186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) | [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) |[C++](./C++/reverse-words-in-a-string-ii.cpp) [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` 271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [C++](./C++/encode-and-decode-strings.cpp) [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 📖 | 273| [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [C++](./C++/integer-to-english-words.cpp) [Python](./Python/integer-to-english-words.py) | _O(logn)_ | _O(1)_ | Medium | | From 8b84e4304ca804c4b515d4fc1710a51f271b87a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Feb 2016 20:17:47 +0800 Subject: [PATCH 1844/1939] Update and rename addTwoNumbers.cpp to add-two-numbers.cpp --- C++/add-two-numbers.cpp | 37 +++++++++++++++++++++++++++++++++++++ C++/addTwoNumbers.cpp | 33 --------------------------------- 2 files changed, 37 insertions(+), 33 deletions(-) create mode 100644 C++/add-two-numbers.cpp delete mode 100644 C++/addTwoNumbers.cpp diff --git a/C++/add-two-numbers.cpp b/C++/add-two-numbers.cpp new file mode 100644 index 000000000..800431821 --- /dev/null +++ b/C++/add-two-numbers.cpp @@ -0,0 +1,37 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode dummy = ListNode(0); + ListNode *cur = &dummy; + int carry = 0; + while (l1 || l2) { + int val {carry}; + if (l1) { + val += l1->val; + l1 = l1->next; + } + if (l2) { + val += l2->val; + l2 = l2->next; + } + carry = val / 10; + cur->next = new ListNode(val % 10); + cur = cur->next; + } + if (carry) { + cur->next = new ListNode(carry); + } + return dummy.next; + } +}; diff --git a/C++/addTwoNumbers.cpp b/C++/addTwoNumbers.cpp deleted file mode 100644 index b921dc8b8..000000000 --- a/C++/addTwoNumbers.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - public: - ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { - ListNode dummy(INT_MIN); - ListNode *p = &dummy; - int carry = 0; - - for(; l1 || l2; p = p->next) { - const int v1 = (l1)? l1->val : 0; - const int v2 = (l2)? l2->val : 0; - p->next = new ListNode((v1 + v2 + carry) % 10); - carry = (v1 + v2 + carry) / 10; - if(l1) l1 = l1->next; - if(l2) l2 = l2->next; - } - - if(carry) - p->next = new ListNode(carry); - - return dummy.next; - } -}; From 91043655b5394b34077a58871e87a97c48f1200b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Feb 2016 20:18:46 +0800 Subject: [PATCH 1845/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 32363c669..bc788c9d5 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || +2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [C++](./C++/add-two-numbers.cpp) [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || 24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || 25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || 61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || From 37e6fa2d43c4c5d3cd83a3758ac50dc865d112ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Mar 2016 21:54:35 +0800 Subject: [PATCH 1846/1939] Create swap-nodes-in-pairs.cpp --- C++/swap-nodes-in-pairs.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/swap-nodes-in-pairs.cpp diff --git a/C++/swap-nodes-in-pairs.cpp b/C++/swap-nodes-in-pairs.cpp new file mode 100644 index 000000000..05fe77e0b --- /dev/null +++ b/C++/swap-nodes-in-pairs.cpp @@ -0,0 +1,29 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + ListNode dummy = ListNode(0); + dummy.next = head; + ListNode *cur = &dummy; + while (cur->next && cur->next->next) { + ListNode *next_one = cur->next; + ListNode *next_two = next_one->next; + ListNode *next_three = next_two->next; + cur->next = next_two; + next_two->next = next_one; + next_one->next = next_three; + cur = next_one; + } + return dummy.next; + } +}; From c6fbfc87ab3b6ba7b275f7e496350784a81577d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Mar 2016 21:55:25 +0800 Subject: [PATCH 1847/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc788c9d5..c2078cca1 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [C++](./C++/add-two-numbers.cpp) [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || -24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || +24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [C++](./C++/swap-nodes-in-pairs.cpp) [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || 25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || 61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || 82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || From 133754bbd89ce9eca01eb99a3923b0eaca61907a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Mar 2016 20:49:35 +0800 Subject: [PATCH 1848/1939] Update and rename reverseKGroup.cpp to reverse-nodes-in-k-group.cpp --- C++/reverse-nodes-in-k-group.cpp | 45 ++++++++++++++++++++++++++++++ C++/reverseKGroup.cpp | 47 -------------------------------- 2 files changed, 45 insertions(+), 47 deletions(-) create mode 100644 C++/reverse-nodes-in-k-group.cpp delete mode 100644 C++/reverseKGroup.cpp diff --git a/C++/reverse-nodes-in-k-group.cpp b/C++/reverse-nodes-in-k-group.cpp new file mode 100644 index 000000000..a3d16c385 --- /dev/null +++ b/C++/reverse-nodes-in-k-group.cpp @@ -0,0 +1,45 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + ListNode dummy = ListNode(0); + dummy.next = head; + ListNode *cur = head, *cur_dummy = &dummy; + int len = 0; + + while (cur) { + ListNode *next_cur = cur->next; + len = (len + 1) % k; + + if (len == 0) { + ListNode *next_dummy = cur_dummy->next; + reverse(&cur_dummy, cur->next); + cur_dummy = next_dummy; + } + cur = next_cur; + } + return dummy.next; + } + + void reverse(ListNode **begin, const ListNode *end) { + ListNode *first = (*begin)->next; + ListNode *cur = first->next; + + while (cur != end) { + first->next = cur->next; + cur->next = (*begin)->next; + (*begin)->next = cur; + cur = first->next; + } + } +}; diff --git a/C++/reverseKGroup.cpp b/C++/reverseKGroup.cpp deleted file mode 100644 index a384ed97a..000000000 --- a/C++/reverseKGroup.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - public: - ListNode *reverseKGroup(ListNode *head, int k) { - ListNode dummy(INT_MIN); - dummy.next = head; - - ListNode *cur = head; - ListNode *cur_dummy = &dummy; - int len = 0; - - while(cur) { - ListNode *next = cur->next; - len = (len + 1) % k; - if(len == 0) { - ListNode *next_dummy = cur_dummy->next; - reverseKGroup(cur_dummy, cur->next); - cur_dummy = next_dummy; - } - cur = next; - } - - return dummy.next; - } - - void reverseKGroup(ListNode *pre, ListNode *end) { - ListNode *first = pre->next; - ListNode *cur = first->next; - while(cur != end) { - ListNode *next = cur->next; - first->next = cur->next; // connect first node to the one next to current node - cur->next = pre->next; // remove current node from list and add the current node to the head - pre->next = cur; // connect previous node to the current node - cur = next; // set next node as current node - } - } -}; From 77a6a476aeffb22a4dc50bbc1f0c45c8cf2664f7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Mar 2016 20:51:51 +0800 Subject: [PATCH 1849/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c2078cca1..020e4d376 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [C++](./C++/add-two-numbers.cpp) [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || 24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [C++](./C++/swap-nodes-in-pairs.cpp) [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || -25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || +25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [C++](./C++/reverse-nodes-in-k-group.cpp) [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || 61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || 82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || From 225cc19164fa9504630211e26f1c3c444d2076f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Mar 2016 20:30:03 +0800 Subject: [PATCH 1850/1939] Update and rename rotateRight.cpp to rotate-list.cpp --- C++/rotate-list.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++++ C++/rotateRight.cpp | 35 ------------------------------ 2 files changed, 52 insertions(+), 35 deletions(-) create mode 100644 C++/rotate-list.cpp delete mode 100644 C++/rotateRight.cpp diff --git a/C++/rotate-list.cpp b/C++/rotate-list.cpp new file mode 100644 index 000000000..1abb67537 --- /dev/null +++ b/C++/rotate-list.cpp @@ -0,0 +1,52 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* rotateRight(ListNode* head, int k) { + ListNode dummy(0); + dummy.next = head; + + // Get the length of the list. + ListNode *cur = &dummy; + int len = 0; + while (cur->next) { + ++len; + cur = cur->next; + } + if (len == 0) { + return nullptr; + } + + k %= len; + if (k == 0) { + return head; + } + + // Find the position to split. + ListNode *slow = &dummy; + ListNode *fast = &dummy; + while (k) { + fast = fast->next; + --k; + } + while (fast && fast->next) { + fast = fast->next; + slow = slow->next; + } + + dummy.next = slow->next; // New head. + slow->next = nullptr; // Split. + fast->next = head; // Link. + + return dummy.next; + } +}; diff --git a/C++/rotateRight.cpp b/C++/rotateRight.cpp deleted file mode 100644 index 9e5ffbd42..000000000 --- a/C++/rotateRight.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - public: - ListNode *rotateRight(ListNode *head, int k) { - ListNode dummy(INT_MIN); - dummy.next = head; - ListNode *p = &dummy; - for(int i = 0; p && i < k; ++i) { - p = p->next; - if(!p) - p = dummy.next; - } - - if(!p || !p->next) - return dummy.next; - - ListNode *cur = &dummy; - for(; p->next; cur = cur->next, p = p->next); // find new head - p->next = dummy.next; // connect tail to the head - dummy.next = cur->next; // update new head - cur->next = NULL; // update new tail - - return dummy.next; - } -}; From 39852bacc07d271f7361fd7ec91db5aa01b7d3b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Mar 2016 20:57:03 +0800 Subject: [PATCH 1851/1939] Update rotate-list.cpp --- C++/rotate-list.cpp | 52 +++++++++++++++++++-------------------------- 1 file changed, 22 insertions(+), 30 deletions(-) diff --git a/C++/rotate-list.cpp b/C++/rotate-list.cpp index 1abb67537..c4dac2a4e 100644 --- a/C++/rotate-list.cpp +++ b/C++/rotate-list.cpp @@ -1,6 +1,14 @@ // Time: O(n) // Space: O(1) +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ /** * Definition for singly-linked list. * struct ListNode { @@ -12,41 +20,25 @@ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { - ListNode dummy(0); - dummy.next = head; - - // Get the length of the list. - ListNode *cur = &dummy; - int len = 0; - while (cur->next) { - ++len; - cur = cur->next; - } - if (len == 0) { - return nullptr; - } - - k %= len; - if (k == 0) { + if (head == nullptr || head->next == nullptr) { return head; } - // Find the position to split. - ListNode *slow = &dummy; - ListNode *fast = &dummy; - while (k) { - fast = fast->next; - --k; - } - while (fast && fast->next) { - fast = fast->next; - slow = slow->next; + int n = 1; + ListNode *cur = head; + for (; cur->next; cur = cur->next) { + ++n; } + cur->next = head; - dummy.next = slow->next; // New head. - slow->next = nullptr; // Split. - fast->next = head; // Link. + ListNode *tail = cur; + k = n - k % n; + cur = head; + for (int i = 0; i < k; cur = cur->next, ++i) { + tail = cur; + } - return dummy.next; + tail->next = nullptr; + return cur; } }; From 6985d18c4c87c2de4d911754964533a7995388f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Mar 2016 21:02:09 +0800 Subject: [PATCH 1852/1939] Update rotate-list.py --- Python/rotate-list.py | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/Python/rotate-list.py b/Python/rotate-list.py index 14b7b2591..ca6721cfa 100644 --- a/Python/rotate-list.py +++ b/Python/rotate-list.py @@ -18,30 +18,30 @@ def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) -class Solution: - # @param head, a ListNode - # @param k, an integer - # @return a ListNode +class Solution(object): def rotateRight(self, head, k): - if head is None: - return head - - cur, len = head, 1 + """ + :type head: ListNode + :type k: int + :rtype: ListNode + """ + if not head or not head.next: + return head; + + n, cur = 1, head while cur.next: cur = cur.next - len += 1 + n += 1 cur.next = head - - cur = head - shift = len - k%len - 1 - while shift > 0: + + cur, tail = head, cur + for _ in xrange(n - k % n): + tail = cur cur = cur.next - shift -= 1 - - result = cur.next - cur.next = None - - return result + tail.next = None + + return cur + if __name__ == "__main__": head = ListNode(1) From c90cef496f40bbe5115d0305201354bb20e0fe94 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Mar 2016 21:02:29 +0800 Subject: [PATCH 1853/1939] Update rotate-list.py --- Python/rotate-list.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/rotate-list.py b/Python/rotate-list.py index ca6721cfa..6a536da17 100644 --- a/Python/rotate-list.py +++ b/Python/rotate-list.py @@ -26,7 +26,7 @@ def rotateRight(self, head, k): :rtype: ListNode """ if not head or not head.next: - return head; + return head n, cur = 1, head while cur.next: From f05a902849d9d49cdbc3c0e7b4141f92e8db0b11 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Mar 2016 21:12:05 +0800 Subject: [PATCH 1854/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 020e4d376..6ee23d049 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [C++](./C++/add-two-numbers.cpp) [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || 24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [C++](./C++/swap-nodes-in-pairs.cpp) [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || 25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [C++](./C++/reverse-nodes-in-k-group.cpp) [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || -61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || +61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [C++](./C++/rotate-list.cpp) [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || 82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || 92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || From a36c29d2eb55b29ee3c936e21bbaa848993fdd9a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Mar 2016 21:45:39 +0800 Subject: [PATCH 1855/1939] Update and rename deleteDuplicatesII.cpp to remove-duplicates-from-sorted-list-ii.cpp --- C++/deleteDuplicatesII.cpp | 45 ------------------- C++/remove-duplicates-from-sorted-list-ii.cpp | 32 +++++++++++++ 2 files changed, 32 insertions(+), 45 deletions(-) delete mode 100644 C++/deleteDuplicatesII.cpp create mode 100644 C++/remove-duplicates-from-sorted-list-ii.cpp diff --git a/C++/deleteDuplicatesII.cpp b/C++/deleteDuplicatesII.cpp deleted file mode 100644 index f1e228b71..000000000 --- a/C++/deleteDuplicatesII.cpp +++ /dev/null @@ -1,45 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - public: - ListNode *deleteDuplicates(ListNode *head) { - if(!head) - return NULL; - ListNode dummy(INT_MIN); - dummy.next = head; - ListNode *pre2nd = &dummy; - ListNode *pre1st = head; - ListNode *cur = pre1st->next; - bool isDup = false; - - while(pre1st) { - if(cur && pre1st->val == cur->val) { - pre2nd->next = cur; // remove previous first node - delete pre1st; - pre1st = NULL; - isDup = true; - } - else if(isDup){ - pre2nd->next = cur; // remove previous first node - delete pre1st; - pre1st = NULL; - isDup = false; - } - - if(pre1st) pre2nd = pre1st; - pre1st = cur; - if(cur) cur = cur->next; - } - - return dummy.next; - } -}; diff --git a/C++/remove-duplicates-from-sorted-list-ii.cpp b/C++/remove-duplicates-from-sorted-list-ii.cpp new file mode 100644 index 000000000..f7e70a2a6 --- /dev/null +++ b/C++/remove-duplicates-from-sorted-list-ii.cpp @@ -0,0 +1,32 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode dummy = ListNode(0); + ListNode *pre = &dummy; + while (head) { + if (head->next && head->next->val == head->val) { + auto val = head->val; + while (head && head->val == val) { + head = head->next; + } + pre->next = head; + } else { + pre->next = head; + pre = head; + head = head->next; + } + } + return dummy.next; + } +}; From d73a1a646e5619f6fe8a712558192cb3bd3ff413 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Mar 2016 21:46:36 +0800 Subject: [PATCH 1856/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6ee23d049..ea0ae851b 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [C++](./C++/swap-nodes-in-pairs.cpp) [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Medium || 25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [C++](./C++/reverse-nodes-in-k-group.cpp) [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || 61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [C++](./C++/rotate-list.cpp) [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || -82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [C++](./C++/remove-duplicates-from-sorted-list-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || 92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || From f59589c179dbc553e8fffdb964728316fbad0b1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Mar 2016 22:01:56 +0800 Subject: [PATCH 1857/1939] Update remove-duplicates-from-sorted-list-ii.py --- .../remove-duplicates-from-sorted-list-ii.py | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/Python/remove-duplicates-from-sorted-list-ii.py b/Python/remove-duplicates-from-sorted-list-ii.py index 5c8f44e14..e1b71703c 100644 --- a/Python/remove-duplicates-from-sorted-list-ii.py +++ b/Python/remove-duplicates-from-sorted-list-ii.py @@ -21,21 +21,25 @@ def __repr__(self): else: return "{} -> {}".format(self.val, repr(self.next)) -class Solution: - # @param head, a ListNode - # @return a ListNode +class Solution(object): def deleteDuplicates(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ dummy = ListNode(0) dummy.next = head - current = dummy - while current.next: - next = current.next - while next.next and next.next.val == next.val: - next = next.next - if current.next is not next: - current.next = next.next + pre, cur = dummy, head + while cur: + if cur.next and cur.next.val == cur.val: + val = cur.val; + while cur and cur.val == val: + cur = cur.next + pre.next = cur else: - current = current.next + pre.next = cur + pre = cur + cur = cur.next return dummy.next if __name__ == "__main__": @@ -43,4 +47,4 @@ def deleteDuplicates(self, head): head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(4) head.next.next.next.next.next, head.next.next.next.next.next.next = ListNode(4), ListNode(5) print Solution().deleteDuplicates(head) - \ No newline at end of file + From d754464ff40232a583801ac85ff750857edb0cbc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 16:31:09 +0800 Subject: [PATCH 1858/1939] Create house-robber-iii.cpp --- C++/house-robber-iii.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/house-robber-iii.cpp diff --git a/C++/house-robber-iii.cpp b/C++/house-robber-iii.cpp new file mode 100644 index 000000000..fc55edcb4 --- /dev/null +++ b/C++/house-robber-iii.cpp @@ -0,0 +1,30 @@ +// Time: O(n) +// Space: O(h) + +/** + * 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: + int rob(TreeNode* root) { + pair res = robHelper(root); + return max(res.first, res.second); + } + +private: + pair robHelper(TreeNode* root) { + if (!root) { + return {0, 0}; + } + auto left = robHelper(root->left); + auto right = robHelper(root->right); + return {root->val + left.second + right.second, + max(left.first, left.second) + max(right.first, right.second)}; + } +}; From a9c265ab91335ad993218a7feac0df0b607d09e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 16:32:10 +0800 Subject: [PATCH 1859/1939] Update house-robber-iii.cpp --- C++/house-robber-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/house-robber-iii.cpp b/C++/house-robber-iii.cpp index fc55edcb4..2e4746f21 100644 --- a/C++/house-robber-iii.cpp +++ b/C++/house-robber-iii.cpp @@ -13,7 +13,7 @@ class Solution { public: int rob(TreeNode* root) { - pair res = robHelper(root); + auto res = robHelper(root); return max(res.first, res.second); } From f8523e1fa9908b28bb9a30f640f313ed4354cf27 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 16:38:34 +0800 Subject: [PATCH 1860/1939] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ea0ae851b..5b66fb846 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-335%20%2F%20335-ff69b4.svg) -Up to date (2016-02-23), there are `318` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-03-05), there are `318` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). Besides, there are `2` exclusive interview questions on [Mock Interview](https://leetcode.com/mockinterview/). The number of questions is increasing recently. Here is the classification of all `335` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. @@ -426,6 +426,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 309| [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-cooldown.py) | _O(n)_ | _O(1)_ | Medium || 312| [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./C++/burst-balloons.cpp) [Python](./Python/burst-balloons.py) | _O(n^3)_ | _O(n^2)_ | Medium || 322| [Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./C++/coin-change.cpp) [Python](./Python/coin-change.py) | _O(n * k)_ | _O(k)_ | Medium || +Mock Interview| [House Robber III](https://leetcode.com/problems/house-robber-iii/)| [C++](./C++/house-robber-iii.cpp) [Python](./Python/house-robber-iii.py) | _O(n)_ | _O(h)_ | Medium || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 779a3310bc4d9a53c805cb712f98a984c6eda009 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 18:13:23 +0800 Subject: [PATCH 1861/1939] Create palindrome-pairs.py --- Python/palindrome-pairs.py | 65 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Python/palindrome-pairs.py diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py new file mode 100644 index 000000000..06327d747 --- /dev/null +++ b/Python/palindrome-pairs.py @@ -0,0 +1,65 @@ +# Time: O(n * l), n is the number of words, l is the max length of the words +# Space: O(n * l) + +# Given a list of unique words. Find all pairs of indices (i, j) +# in the given list, so that the concatenation of the two words, +# i.e. words[i] + words[j] is a palindrome. +# +# Example 1: +# Given words = ["bat", "tab", "cat"] +# Return [[0, 1], [1, 0]] +# The palindromes are ["battab", "tabbat"] +# Example 2: +# Given words = ["abcd", "dcba", "lls", "s", "sssll"] +# Return [[0, 1], [1, 0], [3, 2], [2, 4]] +# The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"] + +class TrieNode: + def __init__(self): + self.word_idx = -1 + self.leaves = {} + + def insert(self, word, i): + cur = self + for c in word: + if not c in cur.leaves: + cur.leaves[c] = TrieNode() + cur = cur.leaves[c] + cur.word_idx = i + + def find(self, s, idx, res): + cur = self + for i in reversed(xrange(len(s))): + if s[i] in cur.leaves: + cur = cur.leaves[s[i]] + if cur.word_idx != -1: + if self.is_palindrome(s, i - 1) and idx != cur.word_idx: + res.append([cur.word_idx, idx]) + else: + break + + def is_palindrome(self, s, j): + i = 0 + while i <= j: + if s[i] != s[j]: + return False + i += 1 + j -= 1 + return True + + +class Solution_MLE(object): + def palindromePairs(self, words): + """ + :type words: List[str] + :rtype: List[List[int]] + """ + res = [] + trie = TrieNode() + for i in xrange(len(words)): + trie.insert(words[i], i) + + for i in xrange(len(words)): + trie.find(words[i], i, res) + + return res From f8050fc95040371a60adb5bbce73810720203344 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 18:14:05 +0800 Subject: [PATCH 1862/1939] Create palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 68 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 C++/palindrome-pairs.cpp diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp new file mode 100644 index 000000000..a564bbb6d --- /dev/null +++ b/C++/palindrome-pairs.cpp @@ -0,0 +1,68 @@ +// Time: O(n * l), n is the number of the words, l is the max length of the words. +// Space: O(n * l) + +class Solution_MLE { +public: + vector> palindromePairs(vector& words) { + vector> res; + TrieNode trie; + for (int i = 0; i < words.size(); ++i) { + trie.insert(words[i], i); + } + for (int i = 0; i < words.size(); ++i) { + trie.find(words[i], i, &res); + } + return res; + } + +private: + struct TrieNode { + int word_idx = -1; + unordered_map leaves; + + void insert(const string& s, int i) { + auto* p = this; + for (const auto& c : s) { + if (p->leaves.find(c) == p->leaves.cend()) { + p->leaves[c] = new TrieNode; + } + p = p->leaves[c]; + } + p->word_idx = i; + } + + void find(const string& s, int idx, vector> *res) { + auto* p = this; + for (int i = s.length() - 1; i >= 0; --i) { + if (p->leaves.find(s[i]) != p->leaves.cend()) { + p = p->leaves[s[i]]; + if (p->word_idx != -1) { + if (is_palindrome(s, i - 1) && idx != p->word_idx) { + res->push_back({p->word_idx, idx}); + } + } + } else { + break; + } + } + } + + bool is_palindrome(const string& s, int j) { + int i = 0; + while (i <= j) { + if (s[i++] != s[j--]) { + return false; + } + } + return true; + } + + ~TrieNode() { + for (auto& kv : leaves) { + if (kv.second) { + kv.second->~TrieNode(); + } + } + } + }; +}; From 8edfc92e5a5801e423dcbe3df08defbc8b1dea46 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 18:14:33 +0800 Subject: [PATCH 1863/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index 06327d747..9b5d57f54 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -1,4 +1,4 @@ -# Time: O(n * l), n is the number of words, l is the max length of the words +# Time: O(n * l), n is the number of the words, l is the max length of the words # Space: O(n * l) # Given a list of unique words. Find all pairs of indices (i, j) From 7290ba08d65b729151ba310ebc4b1eac6e171ab5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 18:19:30 +0800 Subject: [PATCH 1864/1939] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5b66fb846..7d9dcd3c5 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | +Mock Interview| Palindrome Pairs | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * l)_ | _O(n * l)_ | Medium | Trie | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -426,7 +427,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 309| [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-cooldown.py) | _O(n)_ | _O(1)_ | Medium || 312| [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./C++/burst-balloons.cpp) [Python](./Python/burst-balloons.py) | _O(n^3)_ | _O(n^2)_ | Medium || 322| [Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./C++/coin-change.cpp) [Python](./Python/coin-change.py) | _O(n * k)_ | _O(k)_ | Medium || -Mock Interview| [House Robber III](https://leetcode.com/problems/house-robber-iii/)| [C++](./C++/house-robber-iii.cpp) [Python](./Python/house-robber-iii.py) | _O(n)_ | _O(h)_ | Medium || +Mock Interview| House Robber III | [C++](./C++/house-robber-iii.cpp) [Python](./Python/house-robber-iii.py) | _O(n)_ | _O(h)_ | Medium || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From c4285fe4da672a7b40f943f8497ccec2acda8f47 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 18:20:42 +0800 Subject: [PATCH 1865/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7d9dcd3c5..0153b7929 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -Mock Interview| Palindrome Pairs | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * l)_ | _O(n * l)_ | Medium | Trie | +Mock Interview| Palindrome Pairs | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * l)_ | _O(n * l)_ | Medium | | Trie | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note From 8df3f6b29c097ddacac02a6c3888d8dfd47bc437 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 18:30:09 +0800 Subject: [PATCH 1866/1939] Create house-robber-iii.py --- Python/house-robber-iii.py | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/house-robber-iii.py diff --git a/Python/house-robber-iii.py b/Python/house-robber-iii.py new file mode 100644 index 000000000..06d4ea317 --- /dev/null +++ b/Python/house-robber-iii.py @@ -0,0 +1,49 @@ +# Time: O(n) +# Space: O(h) + +# 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. +# +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def rob(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def robHelper(root): + if not root: + return (0, 0) + left, right = robHelper(root.left), robHelper(root.right) + return (root.val + left[1] + right[1], max(left) + max(right)) + + return max(robHelper(root)) From accbbab07b9a359c2ec3d953aec4e684607cbcf5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 18:34:15 +0800 Subject: [PATCH 1867/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index a564bbb6d..778c5f46e 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -1,4 +1,4 @@ -// Time: O(n * l), n is the number of the words, l is the max length of the words. +// Time: O(n * l), n is the number of the words, l is the max length of the words. // Space: O(n * l) class Solution_MLE { From 5218996842a3ac846c42e4e4921bbe3c56d0989b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 18:34:31 +0800 Subject: [PATCH 1868/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index 9b5d57f54..1a4eabbe7 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -1,4 +1,4 @@ -# Time: O(n * l), n is the number of the words, l is the max length of the words +# Time: O(n * l), n is the number of the words, l is the max length of the words. # Space: O(n * l) # Given a list of unique words. Find all pairs of indices (i, j) From f1ff06c3284a84fe2ad6329f8fc1991f38b0c3a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 21:11:07 +0800 Subject: [PATCH 1869/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0153b7929..5b48bf306 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,7 @@ Mock Interview| Palindrome Pairs | [C++](./C++/palindrome-pairs.cpp) [Python](./ 253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |📖| | 274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Medium || Counting Sort | 280| [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) | [C++](./C++/wiggle-sort.cpp) [Python](./Python/wiggle-sort.py) | _O(n)_ | _O(1)_ | Medium |📖| | -324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | +324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | ## Two Pointers # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -300,6 +300,7 @@ Mock Interview| Palindrome Pairs | [C++](./C++/palindrome-pairs.cpp) [Python](./ 298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) | [C++](./C++/binary-tree-longest-consecutive-sequence.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence.py) | _O(n)_ | _O(h)_ | Medium |📖| 327| [Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./C++/count-of-range-sum.cpp) [Python](./Python/count-of-range-sum.py) | _O(nlogn)_ | _O(n)_ | Hard || 333 | [Largest BST Subtree](https://leetcode.com/problems/largest-bst-subtree/) | [C++](./C++/largest-bst-subtree.cpp) [Python](./Python/largest-bst-subtree.py) | _O(n)_ | _O(h)_ | Medium |📖| +Mock Interview| House Robber III | [C++](./C++/house-robber-iii.cpp) [Python](./Python/house-robber-iii.py) | _O(n)_ | _O(h)_ | Medium || ## Binary Search # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -427,7 +428,6 @@ Mock Interview| Palindrome Pairs | [C++](./C++/palindrome-pairs.cpp) [Python](./ 309| [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-cooldown.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-cooldown.py) | _O(n)_ | _O(1)_ | Medium || 312| [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./C++/burst-balloons.cpp) [Python](./Python/burst-balloons.py) | _O(n^3)_ | _O(n^2)_ | Medium || 322| [Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./C++/coin-change.cpp) [Python](./Python/coin-change.py) | _O(n * k)_ | _O(k)_ | Medium || -Mock Interview| House Robber III | [C++](./C++/house-robber-iii.cpp) [Python](./Python/house-robber-iii.py) | _O(n)_ | _O(h)_ | Medium || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 50358ae9df37d7221510e4882bb12df986d9bb95 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 21:11:28 +0800 Subject: [PATCH 1870/1939] Update wiggle-sort-ii.cpp --- C++/wiggle-sort-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/wiggle-sort-ii.cpp b/C++/wiggle-sort-ii.cpp index 53e7aa47d..76d6835db 100644 --- a/C++/wiggle-sort-ii.cpp +++ b/C++/wiggle-sort-ii.cpp @@ -1,4 +1,4 @@ -// Time: O(n) ~ O(n^2) +// Time: O(n) ~ O(n^2), O(n) on average. // Space: O(1) // Tri Partition (aka Dutch National Flag Problem) with virtual index solution. (44ms) From a5d4afc5038a183e2a97a8f5a316d6e0be6a1bba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 23:32:10 +0800 Subject: [PATCH 1871/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index 778c5f46e..e321d7096 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -36,10 +36,9 @@ class Solution_MLE { for (int i = s.length() - 1; i >= 0; --i) { if (p->leaves.find(s[i]) != p->leaves.cend()) { p = p->leaves[s[i]]; - if (p->word_idx != -1) { - if (is_palindrome(s, i - 1) && idx != p->word_idx) { - res->push_back({p->word_idx, idx}); - } + if (p->word_idx != -1 && p->word_idx != idx && + is_palindrome(s, i - 1)) { + res->push_back({p->word_idx, idx}); } } else { break; From fa01b7c19a01ca857829f3b8f3ec5ee22ba37c75 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Mar 2016 23:33:58 +0800 Subject: [PATCH 1872/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index 1a4eabbe7..ae9e42848 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -32,9 +32,9 @@ def find(self, s, idx, res): for i in reversed(xrange(len(s))): if s[i] in cur.leaves: cur = cur.leaves[s[i]] - if cur.word_idx != -1: - if self.is_palindrome(s, i - 1) and idx != cur.word_idx: - res.append([cur.word_idx, idx]) + if cur.word_idx not in (-1, idx) and \ + self.is_palindrome(s, i - 1): + res.append([cur.word_idx, idx]) else: break From 6b3676daa46c37471662d1665d88da2af12d7a02 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Mar 2016 20:25:30 +0800 Subject: [PATCH 1873/1939] Create remove-duplicates-from-sorted-list.cpp --- C++/remove-duplicates-from-sorted-list.cpp | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/remove-duplicates-from-sorted-list.cpp diff --git a/C++/remove-duplicates-from-sorted-list.cpp b/C++/remove-duplicates-from-sorted-list.cpp new file mode 100644 index 000000000..0a0795c91 --- /dev/null +++ b/C++/remove-duplicates-from-sorted-list.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + auto iter = head; + while (iter) { + auto runner = iter->next; + while (runner && runner->val == iter->val) { + runner = runner->next; + } + iter->next = runner; + iter = runner; + } + return head; + } +}; From 4eaf9e7e97ae2006c0b14031752188c8d093fd95 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Mar 2016 20:26:39 +0800 Subject: [PATCH 1874/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5b48bf306..33cdd7fbd 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [C++](./C++/reverse-nodes-in-k-group.cpp) [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || 61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [C++](./C++/rotate-list.cpp) [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || 82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [C++](./C++/remove-duplicates-from-sorted-list-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || -83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || +83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [C++](./C++/remove-duplicates-from-sorted-list.cpp) [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || 92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || 160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || From 9e446e6e71fc627bf09903e99994b224918821a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Mar 2016 20:41:51 +0800 Subject: [PATCH 1875/1939] Update remove-duplicates-from-sorted-list.py --- Python/remove-duplicates-from-sorted-list.py | 32 +++++++++----------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/Python/remove-duplicates-from-sorted-list.py b/Python/remove-duplicates-from-sorted-list.py index 88e0fd370..cb3f9fb59 100644 --- a/Python/remove-duplicates-from-sorted-list.py +++ b/Python/remove-duplicates-from-sorted-list.py @@ -9,32 +9,28 @@ # # Definition for singly-linked list. -class ListNode: +class ListNode(object): def __init__(self, x): self.val = x self.next = None - - def __repr__(self): - if self is None: - return "Nil" - else: - return "{} -> {}".format(self.val, repr(self.next)) -class Solution: - # @param head, a ListNode - # @return a ListNode +class Solution(object): def deleteDuplicates(self, head): - current = head - while current and current.next: - next = current.next - if current.val == next.val: - current.next = current.next.next - else: - current = next + """ + :type head: ListNode + :rtype: ListNode + """ + cur = head + while cur: + runner = cur.next + while runner and runner.val == cur.val: + runner = runner.next + cur.next = runner + cur = runner return head if __name__ == "__main__": head, head.next, head.next.next = ListNode(1), ListNode(1), ListNode(2) head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(3) print Solution().deleteDuplicates(head) - \ No newline at end of file + From b0e641fd62f1051bf6734d3f696e12eb2f4d51e4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Mar 2016 21:22:44 +0800 Subject: [PATCH 1876/1939] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 33cdd7fbd..ea287b214 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-335%20%2F%20335-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-336%20%2F%20336-ff69b4.svg) -Up to date (2016-03-05), there are `318` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). Besides, there are `2` exclusive interview questions on [Mock Interview](https://leetcode.com/mockinterview/). +Up to date (2016-03-09), there are `319` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `335` questions. +Here is the classification of all `336` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -Mock Interview| Palindrome Pairs | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * l)_ | _O(n * l)_ | Medium | | Trie | +336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * l)_ | _O(n * l)_ | Medium | | Trie | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note From 2e8e5e1b56d6f16eb93e7d65fb970dc1d650491b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Mar 2016 23:21:09 +0800 Subject: [PATCH 1877/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index e321d7096..b52af21cd 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -59,7 +59,7 @@ class Solution_MLE { ~TrieNode() { for (auto& kv : leaves) { if (kv.second) { - kv.second->~TrieNode(); + delete kv.second; } } } From d520a13bf2670ddf1926d69992f7d8cf4c19068e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Mar 2016 23:27:18 +0800 Subject: [PATCH 1878/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ea287b214..896c568d7 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * l)_ | _O(n * l)_ | Medium | | Trie | +336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * l)_ | _O(n * l)_ | Hard | | Trie | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note From f8dd70b42735a727a59ddbbc8a8bfd48a74cdbed Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Mar 2016 23:28:37 +0800 Subject: [PATCH 1879/1939] Update word-search-ii.cpp --- C++/word-search-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/word-search-ii.cpp b/C++/word-search-ii.cpp index 6a6c761cd..7fc8d6e13 100644 --- a/C++/word-search-ii.cpp +++ b/C++/word-search-ii.cpp @@ -28,7 +28,7 @@ class Solution { ~TrieNode() { for (auto& kv : leaves) { if (kv.second) { - kv.second->~TrieNode(); + delete kv.second; } } } From cabfe0473c35ebb2060e4db5b68265a263613164 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Mar 2016 23:30:58 +0800 Subject: [PATCH 1880/1939] Update word-search-ii.cpp --- C++/word-search-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/word-search-ii.cpp b/C++/word-search-ii.cpp index 7fc8d6e13..731c4e73a 100644 --- a/C++/word-search-ii.cpp +++ b/C++/word-search-ii.cpp @@ -90,8 +90,8 @@ class Solution { visited[i][j] = true; // Try each direction. - const vector> direction{{0, -1}, {0, 1}, - {-1, 0}, {1, 0}}; + const vector> directions{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; for (const auto& d : directions) { findWordsDFS(grid, visited, nextNode, i + d.first, j + d.second, cur, ret); From ef7bd99b5e657cd11a7dae31d6587362a1484416 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 01:55:32 +0800 Subject: [PATCH 1881/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 65 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 63 insertions(+), 2 deletions(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index b52af21cd..73eba17c4 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -1,6 +1,67 @@ -// Time: O(n * l), n is the number of the words, l is the max length of the words. -// Space: O(n * l) +// Time: O(n * k^2), n is the number of the words, k is the max length of the words. +// Space: O(n * k + n^2) +class Solution { +public: + struct hashPair { + public: + template + std::size_t operator()(const std::pair &x) const { + return std::hash()(x.first) ^ std::hash()(x.second); + } + }; + + vector> palindromePairs(vector& words) { + vector> res; + unordered_map lookup; + unordered_set, hashPair> visited; + for (int i = 0; i < words.size(); ++i) { + lookup[words[i]] = i; + } + + for (int i = 0; i < words.size(); ++i) { + const int k = words[i].size(); + for (int l = 0; l <= k; ++l) { + if (is_palindrome(words[i], 0, l - 1)) { + string tmp = words[i].substr(l); + reverse(tmp.begin(), tmp.end()); + if (lookup.find(tmp) != lookup.end()) { + if ((lookup[tmp] != i) && + (visited.find(make_pair(lookup[tmp], i)) == visited.end())) { + res.push_back({lookup[tmp], i}); + visited.emplace(make_pair(lookup[tmp], i)); + } + } + } + if (is_palindrome(words[i], l, k - 1)) { + string tmp = words[i].substr(0, l); + reverse(tmp.begin(), tmp.end()); + if (lookup.find(tmp) != lookup.end()) { + if ((i != lookup[tmp]) && + (visited.find(make_pair(i, lookup[tmp])) == visited.end())) { + res.push_back({i, lookup[tmp]}); + visited.emplace(make_pair(i, lookup[tmp])); + } + } + } + } + } + return res; + } + +private: + bool is_palindrome(string& s, int start, int end) { + while (start < end) { + if (s[start++] != s[end--]) { + return false; + } + } + return true; + } +}; + +// Time: O(n * k), n is the number of the words, k is the max length of the words. +// Space: O(n * k) class Solution_MLE { public: vector> palindromePairs(vector& words) { From 0969947b2cffea9d29de54a96380cef718d854b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 01:57:20 +0800 Subject: [PATCH 1882/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 896c568d7..d18d8bdb5 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * l)_ | _O(n * l)_ | Hard | | Trie | +336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k)_ | _O(n * k)_ | Hard | | Trie | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note From d65dec56f2512c6695eeafd8b30b9ea533376ce7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 02:01:48 +0800 Subject: [PATCH 1883/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index ae9e42848..e9e0a71a4 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -1,5 +1,5 @@ -# Time: O(n * l), n is the number of the words, l is the max length of the words. -# Space: O(n * l) +# Time: O(n * k), n is the number of the words, k is the max length of the words. +# Space: O(n * k) # Given a list of unique words. Find all pairs of indices (i, j) # in the given list, so that the concatenation of the two words, From 668f826e8b73ffc87c111c985ff7f272f8450586 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 21:16:07 +0800 Subject: [PATCH 1884/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 78 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 2 deletions(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index 73eba17c4..9981f2815 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -1,5 +1,7 @@ -// Time: O(n * k^2), n is the number of the words, k is the max length of the words. -// Space: O(n * k + n^2) +// Time: O(n * k^2 + r), n is the number of the words, +// k is the max length of the words, +// r is the number of the result. +// Space: O(n * k + r) class Solution { public: @@ -60,6 +62,78 @@ class Solution { } }; +// Time: O(n * k + r), n is the number of the words, +// k is the max length of the words, +// r is the number of the result. +// Space: O(n * k^2) +// Manacher solution. +class Solution2 { +public: + vector> palindromePairs(vector& words) { + unordered_multimap prefix, suffix; + for (int i = 0; i < words.size(); ++i) { + vector P; + manacher(words[i], &P); + for (int j = 0; j < P.size(); ++j) { + if (j - P[j] == 1) { + prefix.emplace(words[i].substr((j + P[j]) / 2), i); + } + if (j + P[j] == P.size() - 2) { + suffix.emplace(words[i].substr(0, (j - P[j]) / 2), i); + } + } + } + + vector> res; + for (int i = 0; i < words.size(); ++i) { + string reversed_word(words[i].rbegin(), words[i].rend()); + auto its = prefix.equal_range(reversed_word); + for (auto it = its.first; it != its.second; ++it) { + if (it->second != i) { + res.push_back({i, it->second}); + } + } + its = suffix.equal_range(reversed_word); + for (auto it = its.first; it != its.second; ++it) { + if (words[i].size() != words[it->second].size()) { + res.push_back({it->second, i}); + } + } + } + return res; + } + + void manacher(const string& s, vector *P) { + string T = preProcess(s); + const int n = T.length(); + P->resize(n); + int C = 0, R = 0; + for (int i = 1; i < n - 1; ++i) { + int i_mirror = 2 * C - i; + (*P)[i] = (R > i) ? min(R - i, (*P)[i_mirror]) : 0; + while (T[i + 1 + (*P)[i]] == T[i - 1 - (*P)[i]]) { + ++(*P)[i]; + } + if (i + (*P)[i] > R) { + C = i; + R = i + (*P)[i]; + } + } + } + + string preProcess(const string& s) { + if (s.empty()) { + return "^$"; + } + string ret = "^"; + for (int i = 0; i < s.length(); ++i) { + ret += "#" + s.substr(i, 1); + } + ret += "#$"; + return ret; + } +}; + // Time: O(n * k), n is the number of the words, k is the max length of the words. // Space: O(n * k) class Solution_MLE { From 629d516d29f7c83c2e0fb63b1b1462a27e11abb0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 21:23:03 +0800 Subject: [PATCH 1885/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index 9981f2815..d3f06b3e7 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -134,7 +134,9 @@ class Solution2 { } }; -// Time: O(n * k), n is the number of the words, k is the max length of the words. +// Time: O(n * k^2 + r), n is the number of the words, k is the max length of the words. +// k is the max length of the words, +// r is the number of the result. // Space: O(n * k) class Solution_MLE { public: @@ -168,11 +170,11 @@ class Solution_MLE { void find(const string& s, int idx, vector> *res) { auto* p = this; - for (int i = s.length() - 1; i >= 0; --i) { + for (int i = s.length() - 1; i >= 0; --i) { // O(k) if (p->leaves.find(s[i]) != p->leaves.cend()) { p = p->leaves[s[i]]; if (p->word_idx != -1 && p->word_idx != idx && - is_palindrome(s, i - 1)) { + is_palindrome(s, i - 1)) { // O(k) res->push_back({p->word_idx, idx}); } } else { From 7409cc3917ae3cfad502e55d04b2b818ec6af5de Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 21:25:23 +0800 Subject: [PATCH 1886/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d18d8bdb5..18127d7dc 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k)_ | _O(n * k)_ | Hard | | Trie | +336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k + r)_ | _O(n * k^2)_ | Hard | | Trie | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note From bf2aa2a575d28cceb68b434d2b1a38467733c25c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 21:30:56 +0800 Subject: [PATCH 1887/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index d3f06b3e7..c273afbb6 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -16,9 +16,9 @@ class Solution { vector> palindromePairs(vector& words) { vector> res; unordered_map lookup; - unordered_set, hashPair> visited; + unordered_set, hashPair> visited; // At most O(r) space. for (int i = 0; i < words.size(); ++i) { - lookup[words[i]] = i; + lookup[words[i]] = i; // Total O(n * k) space. } for (int i = 0; i < words.size(); ++i) { @@ -62,21 +62,21 @@ class Solution { } }; -// Time: O(n * k + r), n is the number of the words, -// k is the max length of the words, -// r is the number of the result. +// Time: O(n * k^2 + r), n is the number of the words, +// k is the max length of the words, +// r is the number of the result. // Space: O(n * k^2) // Manacher solution. class Solution2 { public: vector> palindromePairs(vector& words) { unordered_multimap prefix, suffix; - for (int i = 0; i < words.size(); ++i) { + for (int i = 0; i < words.size(); ++i) { // O(n) vector P; manacher(words[i], &P); - for (int j = 0; j < P.size(); ++j) { + for (int j = 0; j < P.size(); ++j) { // O(k) if (j - P[j] == 1) { - prefix.emplace(words[i].substr((j + P[j]) / 2), i); + prefix.emplace(words[i].substr((j + P[j]) / 2), i); // O(k) } if (j + P[j] == P.size() - 2) { suffix.emplace(words[i].substr(0, (j - P[j]) / 2), i); @@ -85,8 +85,8 @@ class Solution2 { } vector> res; - for (int i = 0; i < words.size(); ++i) { - string reversed_word(words[i].rbegin(), words[i].rend()); + for (int i = 0; i < words.size(); ++i) { // O(n) + string reversed_word(words[i].rbegin(), words[i].rend()); // O(k) auto its = prefix.equal_range(reversed_word); for (auto it = its.first; it != its.second; ++it) { if (it->second != i) { From 88786193db2e3b4cab45bed1472682a57a6ea05a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 21:31:30 +0800 Subject: [PATCH 1888/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index c273afbb6..8df38f040 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -138,6 +138,7 @@ class Solution2 { // k is the max length of the words, // r is the number of the result. // Space: O(n * k) +// Trie solution. class Solution_MLE { public: vector> palindromePairs(vector& words) { From 60a117fe608d130f1e354874698cfad1135def41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 21:32:29 +0800 Subject: [PATCH 1889/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 18127d7dc..be81822c1 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k + r)_ | _O(n * k^2)_ | Hard | | Trie | +336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2 + r)_ | _O(n * k + r)_ | Hard | | Trie | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note From 87b17e389501d2e5f3d5f74151b73c2fc87f0ccc Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 21:33:31 +0800 Subject: [PATCH 1890/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index be81822c1..253adda6c 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2 + r)_ | _O(n * k + r)_ | Hard | | Trie | +336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2 + r)_ | _O(n * k + r)_ | Hard | | Trie, `Manacher's Algorithm` | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note From eaeae3beb45ee154120cfd3da31a80f3c983b7f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 22:17:31 +0800 Subject: [PATCH 1891/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 50 +++++++++++++--------------------------- 1 file changed, 16 insertions(+), 34 deletions(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index 8df38f040..a959249dc 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -1,49 +1,31 @@ -// Time: O(n * k^2 + r), n is the number of the words, -// k is the max length of the words, -// r is the number of the result. -// Space: O(n * k + r) +// Time: O(n * k^2), n is the number of the words, +// k is the max length of the words, +// r is the number of the result. +// Space: O(n * k) class Solution { public: - struct hashPair { - public: - template - std::size_t operator()(const std::pair &x) const { - return std::hash()(x.first) ^ std::hash()(x.second); - } - }; - vector> palindromePairs(vector& words) { vector> res; unordered_map lookup; - unordered_set, hashPair> visited; // At most O(r) space. for (int i = 0; i < words.size(); ++i) { - lookup[words[i]] = i; // Total O(n * k) space. + lookup[words[i]] = i; } for (int i = 0; i < words.size(); ++i) { - const int k = words[i].size(); - for (int l = 0; l <= k; ++l) { - if (is_palindrome(words[i], 0, l - 1)) { - string tmp = words[i].substr(l); - reverse(tmp.begin(), tmp.end()); - if (lookup.find(tmp) != lookup.end()) { - if ((lookup[tmp] != i) && - (visited.find(make_pair(lookup[tmp], i)) == visited.end())) { - res.push_back({lookup[tmp], i}); - visited.emplace(make_pair(lookup[tmp], i)); - } + for (int j = 0; j <= words[i].length(); ++j) { + if (is_palindrome(words[i], j, words[i].length() - 1)) { + string suffix = words[i].substr(0, j); + reverse(suffix.begin(), suffix.end()); + if (lookup.find(suffix) != lookup.end() && i != lookup[suffix]) { + res.push_back({i, lookup[suffix]}); } } - if (is_palindrome(words[i], l, k - 1)) { - string tmp = words[i].substr(0, l); - reverse(tmp.begin(), tmp.end()); - if (lookup.find(tmp) != lookup.end()) { - if ((i != lookup[tmp]) && - (visited.find(make_pair(i, lookup[tmp])) == visited.end())) { - res.push_back({i, lookup[tmp]}); - visited.emplace(make_pair(i, lookup[tmp])); - } + if (j > 0 && is_palindrome(words[i], 0, j - 1)) { + string prefix = words[i].substr(j); + reverse(prefix.begin(), prefix.end()); + if (lookup.find(prefix) != lookup.end() && lookup[prefix] != i) { + res.push_back({lookup[prefix], i}); } } } From 5a401ec8f3601d8c760a30a7e809578a25ed2c6b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 22:18:46 +0800 Subject: [PATCH 1892/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 253adda6c..a1ed44d5c 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2 + r)_ | _O(n * k + r)_ | Hard | | Trie, `Manacher's Algorithm` | +336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2)_ | _O(n * k)_ | Hard | | Trie, `Manacher's Algorithm` | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note From f0b22d03e488f45fc7f80bf95a0c9d80741c58cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 22:19:24 +0800 Subject: [PATCH 1893/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index a959249dc..a294f76ce 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -1,6 +1,5 @@ // Time: O(n * k^2), n is the number of the words, -// k is the max length of the words, -// r is the number of the result. +// k is the max length of the words. // Space: O(n * k) class Solution { From 11001335da60eafc522de62057accead2957d6d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 22:28:44 +0800 Subject: [PATCH 1894/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 42 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index e9e0a71a4..36c327f56 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -1,4 +1,5 @@ -# Time: O(n * k), n is the number of the words, k is the max length of the words. +# Time: O(n * k^2), n is the number of the words, +# k is the max length of the words. # Space: O(n * k) # Given a list of unique words. Find all pairs of indices (i, j) @@ -14,6 +15,39 @@ # Return [[0, 1], [1, 0], [3, 2], [2, 4]] # The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"] + +class Solution(object): + def palindromePairs(self, words): + """ + :type words: List[str] + :rtype: List[List[int]] + """ + def is_palindrome(s, start, end): + while start <= end: + if s[start] != s[end]: + return False + start += 1 + end -= 1 + return True + + res = [] + lookup = {} + for i, word in enumerate(words): + lookup[word] = i + + for i in xrange(len(words)): + for j in xrange(len(words[i]) + 1): + if is_palindrome(words[i], j, len(words[i]) - 1): + suffix = words[i][:j][::-1] + if suffix in lookup and lookup[suffix] != i: + res.append([i, lookup[suffix]]) + if j > 0 and is_palindrome(words[i], 0, j - 1): + prefix = words[i][j:][::-1] + if prefix in lookup and lookup[prefix] != i: + res.append([lookup[prefix], i]) + return res + +# Trie solution. class TrieNode: def __init__(self): self.word_idx = -1 @@ -47,7 +81,11 @@ def is_palindrome(self, s, j): j -= 1 return True - +# Time: O(n * k^2 + r), n is the number of the words, k is the max length of the words. +# k is the max length of the words, +# r is the number of the result. +# Space: O(n * k) +# Trie solution. class Solution_MLE(object): def palindromePairs(self, words): """ From 7e65abd1528eed193d4414c35966154dfecaa228 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 22:45:24 +0800 Subject: [PATCH 1895/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index 36c327f56..a90b3c98a 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -22,14 +22,6 @@ def palindromePairs(self, words): :type words: List[str] :rtype: List[List[int]] """ - def is_palindrome(s, start, end): - while start <= end: - if s[start] != s[end]: - return False - start += 1 - end -= 1 - return True - res = [] lookup = {} for i, word in enumerate(words): @@ -37,14 +29,14 @@ def is_palindrome(s, start, end): for i in xrange(len(words)): for j in xrange(len(words[i]) + 1): - if is_palindrome(words[i], j, len(words[i]) - 1): - suffix = words[i][:j][::-1] - if suffix in lookup and lookup[suffix] != i: - res.append([i, lookup[suffix]]) - if j > 0 and is_palindrome(words[i], 0, j - 1): - prefix = words[i][j:][::-1] - if prefix in lookup and lookup[prefix] != i: - res.append([lookup[prefix], i]) + prefix = words[i][j:] + suffix = words[i][:j] + if prefix == prefix[::-1] and \ + suffix[::-1] in lookup and lookup[suffix[::-1]] != i: + res.append([i, lookup[suffix[::-1]]]) + if j > 0 and suffix == suffix[::-1] and \ + prefix[::-1] in lookup and lookup[prefix[::-1]] != i: + res.append([lookup[prefix[::-1]], i]) return res # Trie solution. From a5b6b028394ef091098628ae3b9d075fa8ce16c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 22:47:29 +0800 Subject: [PATCH 1896/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a1ed44d5c..beb96ef77 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2)_ | _O(n * k)_ | Hard | | Trie, `Manacher's Algorithm` | +336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2)_ | _O(n * k)_ | Hard | | | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note From dde25ee7a0948de84af5b68534ca930fcb6c82d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 23:02:08 +0800 Subject: [PATCH 1897/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index a294f76ce..af52e2670 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -43,9 +43,8 @@ class Solution { } }; -// Time: O(n * k^2 + r), n is the number of the words, -// k is the max length of the words, -// r is the number of the result. +// Time: O(n * k^2), n is the number of the words, +// k is the max length of the words. // Space: O(n * k^2) // Manacher solution. class Solution2 { @@ -115,9 +114,8 @@ class Solution2 { } }; -// Time: O(n * k^2 + r), n is the number of the words, k is the max length of the words. -// k is the max length of the words, -// r is the number of the result. +// Time: O(n * k^2), n is the number of the words, k is the max length of the words. +// k is the max length of the words. // Space: O(n * k) // Trie solution. class Solution_MLE { From f39e8f142d5f8e1180cbd0a4a93763d50f594a35 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 23:09:11 +0800 Subject: [PATCH 1898/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index a90b3c98a..991409e08 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -73,9 +73,8 @@ def is_palindrome(self, s, j): j -= 1 return True -# Time: O(n * k^2 + r), n is the number of the words, k is the max length of the words. -# k is the max length of the words, -# r is the number of the result. +# Time: O(n * k^2), n is the number of the words, k is the max length of the words. +# k is the max length of the words. # Space: O(n * k) # Trie solution. class Solution_MLE(object): From ceb4422ad07b51b015f4eb6c47f097d86e6b6b63 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 23:09:50 +0800 Subject: [PATCH 1899/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index 991409e08..d0d829400 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -39,6 +39,10 @@ def palindromePairs(self, words): res.append([lookup[prefix[::-1]], i]) return res + +# Time: O(n * k^2), n is the number of the words, k is the max length of the words. +# k is the max length of the words. +# Space: O(n * k) # Trie solution. class TrieNode: def __init__(self): @@ -73,10 +77,6 @@ def is_palindrome(self, s, j): j -= 1 return True -# Time: O(n * k^2), n is the number of the words, k is the max length of the words. -# k is the max length of the words. -# Space: O(n * k) -# Trie solution. class Solution_MLE(object): def palindromePairs(self, words): """ From 93510376861037acf4c67ac7edfa7dae182e928d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 23:10:38 +0800 Subject: [PATCH 1900/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index d0d829400..b7c2e9d7d 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -40,7 +40,7 @@ def palindromePairs(self, words): return res -# Time: O(n * k^2), n is the number of the words, k is the max length of the words. +# Time: O(n * k^2), n is the number of the words, # k is the max length of the words. # Space: O(n * k) # Trie solution. From 2b21eec918ec1cd133c48f5267e2b2e82042b107 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Mar 2016 23:33:07 +0800 Subject: [PATCH 1901/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index beb96ef77..eb466933d 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 📖 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | -336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2)_ | _O(n * k)_ | Hard | | | ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -214,6 +213,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 314| [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) | [C++](./C++/binary-tree-vertical-order-traversal.cpp) [Python](./Python/binary-tree-vertical-order-traversal.py) | _O(n)_ | _O(n)_| Medium | 📖 | BFS 323| [Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) | [C++](./C++/number-of-connected-components-in-an-undirected-graph.cpp) [Python](./Python/number-of-connected-components-in-an-undirected-graph.py) | _O(n)_ | _O(n)_| Medium | 📖 | Union Find 325| [Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/) | [C++](./C++/maximum-size-subarray-sum-equals-k.cpp) [Python](./Python/maximum-size-subarray-sum-equals-k.py) | _O(n)_ | _O(n)_| Easy | 📖 | +336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2)_ | _O(n * k)_ | Hard | | | ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note From b94e1fcbb45b9127439cbc4a63568ed4ac41c983 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Mar 2016 00:45:09 +0800 Subject: [PATCH 1902/1939] Update longest-palindromic-substring.cpp --- C++/longest-palindromic-substring.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/C++/longest-palindromic-substring.cpp b/C++/longest-palindromic-substring.cpp index 0a441016c..bd3851f2b 100644 --- a/C++/longest-palindromic-substring.cpp +++ b/C++/longest-palindromic-substring.cpp @@ -28,15 +28,14 @@ class Solution { } // Find the maximum element in P. - int max_len = 0, center_index = 0; + int max_i = 0; for (int i = 1; i < n - 1; ++i) { - if (P[i] > max_len) { - max_len = P[i]; - center_index = i; + if (P[i] > P[max_i]) { + max_i = i; } } - return s.substr((center_index - 1 - max_len) / 2, max_len); + return s.substr((max_i - P[max_i]) / 2, P[max_i]); } private: From d02a7758cfb4ae17d08da3e8b2178e6954efb46c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Mar 2016 00:54:17 +0800 Subject: [PATCH 1903/1939] Update longest-palindromic-substring.py --- Python/longest-palindromic-substring.py | 57 ++++++++++++++----------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/Python/longest-palindromic-substring.py b/Python/longest-palindromic-substring.py index 79abaf5af..be85bf7de 100644 --- a/Python/longest-palindromic-substring.py +++ b/Python/longest-palindromic-substring.py @@ -8,40 +8,45 @@ # Manacher's Algorithm # http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html -class Solution: + +class Solution(object): def longestPalindrome(self, s): - string = self.preProcess(s) - palindrome = [0] * len(string) + """ + :type s: str + :rtype: str + """ + def preProcess(s): + if not s: + return "^$" + T = "^" + for i in s: + T += "#" + i + T += "#$" + return T + + T = preProcess(s) + P = [0] * len(T) center, right = 0, 0 - for i in xrange(1, len(string) - 1): + for i in xrange(1, len(T) - 1): i_mirror = 2 * center - i if right > i: - palindrome[i] = min(right - i, palindrome[i_mirror]) + P[i] = min(right - i, P[i_mirror]) else: - palindrome[i] = 0 + P[i] = 0 - while string[i + 1 + palindrome[i]] == string[i - 1 - palindrome[i]]: - palindrome[i] += 1 + while T[i + 1 + P[i]] == T[i - 1 - P[i]]: + P[i] += 1 - if i + palindrome[i] > right: - center, right = i, i + palindrome[i] + if i + P[i] > right: + center, right = i, i + P[i] - max_len, max_center = 0, 0 - for i in xrange(1, len(string) - 1): - if palindrome[i] > max_len: - max_len = palindrome[i] - max_center = i - start = (max_center - 1 - max_len) / 2 - return s[start : start + max_len] - - def preProcess(self, s): - if not s: - return "^$" - string = "^" - for i in s: - string += "#" + i - string += "#$" - return string + max_i = 0 + for i in xrange(1, len(T) - 1): + if P[i] > P[max_i]: + max_i = i + start = (max_i - 1 - P[max_i]) / 2 + return s[start : start + P[max_i]] + if __name__ == "__main__": print Solution().longestPalindrome("abb") From 77d4c5ee4238a064d3363798d4db9965ca9b6e90 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Mar 2016 00:55:22 +0800 Subject: [PATCH 1904/1939] Update longest-palindromic-substring.py --- Python/longest-palindromic-substring.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/longest-palindromic-substring.py b/Python/longest-palindromic-substring.py index be85bf7de..82a43ccab 100644 --- a/Python/longest-palindromic-substring.py +++ b/Python/longest-palindromic-substring.py @@ -8,7 +8,6 @@ # Manacher's Algorithm # http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html - class Solution(object): def longestPalindrome(self, s): """ From 5aa21e145fe7ed30e4ed9dc97b402b780d1b4ee2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Mar 2016 02:11:12 +0800 Subject: [PATCH 1905/1939] Update and rename maximalRectangle.cpp to maximal-rectangle.cpp --- C++/maximal-rectangle.cpp | 46 +++++++++++++++++++++++++++++++++++++++ C++/maximalRectangle.cpp | 46 --------------------------------------- 2 files changed, 46 insertions(+), 46 deletions(-) create mode 100644 C++/maximal-rectangle.cpp delete mode 100644 C++/maximalRectangle.cpp diff --git a/C++/maximal-rectangle.cpp b/C++/maximal-rectangle.cpp new file mode 100644 index 000000000..81729530b --- /dev/null +++ b/C++/maximal-rectangle.cpp @@ -0,0 +1,46 @@ +// Time: O(m * n) +// Space: O(n) + +class Solution { +public: + int maximalRectangle(vector > &matrix) { + if(matrix.empty()) + return 0; + + const int m = matrix.size(); + const int n = matrix.front().size(); + + int ans = 0; + + vector H(n, 0); // height of all ones rectangle include matrix[i][j] + vector L(n, 0); // left closed bound of all ones rectangle include matrix[i][j] + vector R(n, n); // right open bound of all onces rectangle include matrix[i][j] + + for(int i = 0; i < m; ++i) { + int left = 0, right = n; + for(int j = 0; j < n; ++j) { + if(matrix[i][j] == '1') { + ++H[j]; // update height + L[j] = max(L[j], left); // update left bound + } + else { + left = j + 1; + H[j] = L[j] = 0; + R[j] = n; + } + } + + for(int j = n - 1; j >= 0; --j) { + if(matrix[i][j] == '1') { + R[j] = min(R[j], right); // update right bound + ans = max(ans, H[j] * (R[j] - L[j])); + } + else { + right = j; + } + } + } + + return ans; + } +}; diff --git a/C++/maximalRectangle.cpp b/C++/maximalRectangle.cpp deleted file mode 100644 index 829905865..000000000 --- a/C++/maximalRectangle.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// Time Complexity: O(m * n) -// Space Complexity: O(n) - -class Solution { - public: - int maximalRectangle(vector > &matrix) { - if(matrix.empty()) - return 0; - - const int m = matrix.size(); - const int n = matrix.front().size(); - - int ans = 0; - - vector H(n, 0); // height of all ones rectangle include matrix[i][j] - vector L(n, 0); // left closed bound of all ones rectangle include matrix[i][j] - vector R(n, n); // right open bound of all onces rectangle include matrix[i][j] - - for(int i = 0; i < m; ++i) { - int left = 0, right = n; - for(int j = 0; j < n; ++j) { - if(matrix[i][j] == '1') { - ++H[j]; // update height - L[j] = max(L[j], left); // update left bound - } - else { - left = j + 1; - H[j] = L[j] = 0; - R[j] = n; - } - } - - for(int j = n - 1; j >= 0; --j) { - if(matrix[i][j] == '1') { - R[j] = min(R[j], right); // update right bound - ans = max(ans, H[j] * (R[j] - L[j])); - } - else { - right = j; - } - } - } - - return ans; - } -}; From 895e117a5f635d34f42bc81a56640c674da87de6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Mar 2016 02:11:38 +0800 Subject: [PATCH 1906/1939] Update maximal-rectangle.cpp --- C++/maximal-rectangle.cpp | 39 ++++++++++++++++++--------------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/C++/maximal-rectangle.cpp b/C++/maximal-rectangle.cpp index 81729530b..240cd6f70 100644 --- a/C++/maximal-rectangle.cpp +++ b/C++/maximal-rectangle.cpp @@ -4,43 +4,40 @@ class Solution { public: int maximalRectangle(vector > &matrix) { - if(matrix.empty()) + if (matrix.empty()) { return 0; + } const int m = matrix.size(); const int n = matrix.front().size(); + int res = 0; + vector H(n, 0); // Height of all ones rectangle include matrix[i][j]. + vector L(n, 0); // Left closed bound of all ones rectangle include matrix[i][j]. + vector R(n, n); // Right open bound of all onces rectangle include matrix[i][j]. - int ans = 0; - - vector H(n, 0); // height of all ones rectangle include matrix[i][j] - vector L(n, 0); // left closed bound of all ones rectangle include matrix[i][j] - vector R(n, n); // right open bound of all onces rectangle include matrix[i][j] - - for(int i = 0; i < m; ++i) { + for (int i = 0; i < m; ++i) { int left = 0, right = n; - for(int j = 0; j < n; ++j) { - if(matrix[i][j] == '1') { - ++H[j]; // update height - L[j] = max(L[j], left); // update left bound - } - else { + for (int j = 0; j < n; ++j) { + if (matrix[i][j] == '1') { + ++H[j]; // Update height. + L[j] = max(L[j], left); // Update left bound. + } else { left = j + 1; H[j] = L[j] = 0; R[j] = n; } } - for(int j = n - 1; j >= 0; --j) { - if(matrix[i][j] == '1') { - R[j] = min(R[j], right); // update right bound - ans = max(ans, H[j] * (R[j] - L[j])); - } - else { + for (int j = n - 1; j >= 0; --j) { + if (matrix[i][j] == '1') { + R[j] = min(R[j], right); // Update right bound. + res = max(res, H[j] * (R[j] - L[j])); + } else { right = j; } } } - return ans; + return res; } }; From fd8490c94822bed33bdc0e64723e5702a1ad92f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Mar 2016 02:13:02 +0800 Subject: [PATCH 1907/1939] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index eb466933d..c47d995c9 100644 --- a/README.md +++ b/README.md @@ -400,10 +400,10 @@ Mock Interview| House Robber III | [C++](./C++/house-robber-iii.cpp) [Python](./ 53| [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || 62| [Unique Paths](https://leetcode.com/problems/unique-paths/) | [Python](./Python/unique-paths.py)| _O(m * n)_ | _O(m + n)_ | Medium || 63| [Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) | [Python](./Python/unique-paths-ii.py) | _O(m * n)_ | _O(m + n)_ | Medium || -64| [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/)|[Python](./Python/minimum-path-sum.py)| _O(m * n)_ | _O(m + n)_ | Medium || +64| [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/)| [Python](./Python/minimum-path-sum.py)| _O(m * n)_ | _O(m + n)_ | Medium || 70| [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)| [Python](./Python/climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || 72| [Edit Distance](https://leetcode.com/problems/edit-distance/)|[Python](./Python/edit-distance.py)| _O(m * n)_ | _O(m + n)_ | Hard || -85| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)|[Python](./Python/maximal-rectangle.py)| _O(n^2)_ | _O(n)_ | Hard || +85| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)| [C++](./C++/maximal-rectangle.cpp) [Python](./Python/maximal-rectangle.py)| _O(m * n)_ | _O(n)_ | Hard || 87| [Scramble String](https://leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || 91| [Decode Ways](https://leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || 96| [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n)_ | _O(1)_ | Medium || Math From 4edd88dacd6ff7d1712e12c2655aaa31cb868a4c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Mar 2016 10:26:26 +0800 Subject: [PATCH 1908/1939] Update palindrome-pairs.cpp --- C++/palindrome-pairs.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/C++/palindrome-pairs.cpp b/C++/palindrome-pairs.cpp index af52e2670..8b108b478 100644 --- a/C++/palindrome-pairs.cpp +++ b/C++/palindrome-pairs.cpp @@ -1,5 +1,4 @@ -// Time: O(n * k^2), n is the number of the words, -// k is the max length of the words. +// Time: O(n * k^2), n is the number of the words, k is the max length of the words. // Space: O(n * k) class Solution { @@ -43,8 +42,7 @@ class Solution { } }; -// Time: O(n * k^2), n is the number of the words, -// k is the max length of the words. +// Time: O(n * k^2), n is the number of the words, k is the max length of the words. // Space: O(n * k^2) // Manacher solution. class Solution2 { @@ -115,7 +113,6 @@ class Solution2 { }; // Time: O(n * k^2), n is the number of the words, k is the max length of the words. -// k is the max length of the words. // Space: O(n * k) // Trie solution. class Solution_MLE { From ebb9cd7830520199049f2cdecdc0ce6602b51b89 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Mar 2016 10:26:58 +0800 Subject: [PATCH 1909/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index b7c2e9d7d..2285b1f72 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -1,5 +1,4 @@ -# Time: O(n * k^2), n is the number of the words, -# k is the max length of the words. +# Time: O(n * k^2), n is the number of the words, k is the max length of the words. # Space: O(n * k) # Given a list of unique words. Find all pairs of indices (i, j) @@ -40,8 +39,7 @@ def palindromePairs(self, words): return res -# Time: O(n * k^2), n is the number of the words, -# k is the max length of the words. +# Time: O(n * k^2), n is the number of the words, k is the max length of the words. # Space: O(n * k) # Trie solution. class TrieNode: From 0e2e6adb85459174b908815d55ec30796ed78471 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 12 Mar 2016 12:48:35 +0800 Subject: [PATCH 1910/1939] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index c47d995c9..df1be04e9 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-336%20%2F%20336-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-337%20%2F%20337-ff69b4.svg) -Up to date (2016-03-09), there are `319` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-03-12), there are `320` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `336` questions. +Here is the classification of all `337` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -300,7 +300,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) | [C++](./C++/binary-tree-longest-consecutive-sequence.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence.py) | _O(n)_ | _O(h)_ | Medium |📖| 327| [Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./C++/count-of-range-sum.cpp) [Python](./Python/count-of-range-sum.py) | _O(nlogn)_ | _O(n)_ | Hard || 333 | [Largest BST Subtree](https://leetcode.com/problems/largest-bst-subtree/) | [C++](./C++/largest-bst-subtree.cpp) [Python](./Python/largest-bst-subtree.py) | _O(n)_ | _O(h)_ | Medium |📖| -Mock Interview| House Robber III | [C++](./C++/house-robber-iii.cpp) [Python](./Python/house-robber-iii.py) | _O(n)_ | _O(h)_ | Medium || +337| [House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./C++/house-robber-iii.cpp) [Python](./Python/house-robber-iii.py) | _O(n)_ | _O(h)_ | Medium || ## Binary Search # | Title | Solution | Time | Space | Difficulty | Tag | Note From 177f3b753a89aab4f4a3096e53d9dffcb6248b10 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 Mar 2016 11:17:27 +0800 Subject: [PATCH 1911/1939] Update longest-palindromic-substring.py --- Python/longest-palindromic-substring.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/longest-palindromic-substring.py b/Python/longest-palindromic-substring.py index 82a43ccab..2c0f238d9 100644 --- a/Python/longest-palindromic-substring.py +++ b/Python/longest-palindromic-substring.py @@ -16,11 +16,11 @@ def longestPalindrome(self, s): """ def preProcess(s): if not s: - return "^$" - T = "^" - for i in s: - T += "#" + i - T += "#$" + return ['^', '$'] + T = ['^'] + for c in s: + T += ['#', c] + T += ['#', '$'] return T T = preProcess(s) From 0bfe81983410a9de6cbe37ec816b59aac1e68707 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 Mar 2016 11:23:17 +0800 Subject: [PATCH 1912/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index 2285b1f72..ae2fb2758 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -38,6 +38,57 @@ def palindromePairs(self, words): res.append([lookup[prefix[::-1]], i]) return res +# Time: O(n * k^2), n is the number of the words, k is the max length of the words. +# Space: O(n * k^2) +# Manacher solution. +class Solution_TLE(object): + def palindromePairs(self, words): + """ + :type words: List[str] + :rtype: List[List[int]] + """ + def manacher(s, P): + def preProcess(s): + if not s: + return ['^', '$'] + T = ['^'] + for c in s: + T += ["#", c] + T += ['#', '$'] + return T + + T = preProcess(s) + center, right = 0, 0 + for i in xrange(1, len(T) - 1): + i_mirror = 2 * center - i + if right > i: + P[i] = min(right - i, P[i_mirror]) + else: + P[i] = 0 + while T[i + 1 + P[i]] == T[i - 1 - P[i]]: + P[i] += 1 + if i + P[i] > right: + center, right = i, i + P[i] + + prefix, suffix = collections.defaultdict(list), collections.defaultdict(list) + for i, word in enumerate(words): + P = [0] * (2 * len(word) + 3) + manacher(word, P) + for j in xrange(len(P)): + if j - P[j] == 1: + prefix[word[(j + P[j]) / 2:]].append(i) + if j + P[j] == len(P) - 2: + suffix[word[:(j - P[j]) / 2]].append(i) + res = [] + for i, word in enumerate(words): + for j in prefix[word[::-1]]: + if j != i: + res.append([i, j]) + for j in suffix[word[::-1]]: + if len(word) != len(words[j]): + res.append([j, i]) + return res + # Time: O(n * k^2), n is the number of the words, k is the max length of the words. # Space: O(n * k) From bd765470a082b801d173c7ba8360b4412c0d911f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 Mar 2016 11:24:45 +0800 Subject: [PATCH 1913/1939] Update palindrome-pairs.py --- Python/palindrome-pairs.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index ae2fb2758..bf823ce55 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -14,7 +14,6 @@ # Return [[0, 1], [1, 0], [3, 2], [2, 4]] # The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"] - class Solution(object): def palindromePairs(self, words): """ From 4c09e525abf9337e328a6a4f5cba4495677ed77b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 Mar 2016 11:28:55 +0800 Subject: [PATCH 1914/1939] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 39 ++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index 45639926a..a4a4927cb 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -13,10 +13,12 @@ # # KMP Algorithm -class Solution: - # @param {string} s - # @return {string} +class Solution(object): def shortestPalindrome(self, s): + """ + :type s: str + :rtype: str + """ if not s: return s @@ -39,12 +41,25 @@ def getPrefix(self, pattern): return prefix +# Time: O(n) +# Space: O(n) # Manacher's Algorithm -class Solution_TLE: - # @param {string} s - # @return {string} +class Solution2(object): def shortestPalindrome(self, s): - string = self.preProcess(s) + """ + :type s: str + :rtype: str + """ + def preProcess(s): + if not s: + return ['^', '$'] + string = ['^'] + for c in s: + string += ['#', c] + string += ['#', '$'] + return string + + string = preProcess(s) palindrome = [0] * len(string) center, right = 0, 0 for i in xrange(1, len(string) - 1): @@ -65,13 +80,3 @@ def shortestPalindrome(self, s): if i - palindrome[i] == 1: max_len = palindrome[i] return s[len(s)-1:max_len-1:-1] + s - - def preProcess(self, s): - if not s: - return "^$" - string = "^" - for i in s: - string += "#" + i - string += "#$" - return string - From 66c36c8d7a6620eb6c583459a9d36c17bf5bb87c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 Mar 2016 11:31:25 +0800 Subject: [PATCH 1915/1939] Update shortest-palindrome.py --- Python/shortest-palindrome.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index a4a4927cb..f092ca4bf 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -19,26 +19,26 @@ def shortestPalindrome(self, s): :type s: str :rtype: str """ + def getPrefix(pattern): + prefix = [-1] * len(pattern) + j = -1 + for i in xrange(1, len(pattern)): + while j > -1 and pattern[j+1] != pattern[i]: + j = prefix[j] + if pattern[j+1] == pattern[i]: + j += 1 + prefix[i] = j + return prefix + if not s: return s A = s + s[::-1] - prefix = self.getPrefix(A) + prefix = getPrefix(A) i = prefix[-1] while i >= len(s): i = prefix[i] return s[i+1:][::-1] + s - - def getPrefix(self, pattern): - prefix = [-1] * len(pattern) - j = -1 - for i in xrange(1, len(pattern)): - while j > -1 and pattern[j+1] != pattern[i]: - j = prefix[j] - if pattern[j+1] == pattern[i]: - j += 1 - prefix[i] = j - return prefix # Time: O(n) From 0938e19f15c0192ba2051cba665408207dec32df Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Mar 2016 21:40:07 +0800 Subject: [PATCH 1916/1939] Update decode-ways.py --- Python/decode-ways.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/decode-ways.py b/Python/decode-ways.py index 6b84185bc..8d0940f4c 100644 --- a/Python/decode-ways.py +++ b/Python/decode-ways.py @@ -22,7 +22,7 @@ def numDecodings(self, s): if len(s) == 0 or s[0] == '0': return 0 prev, prev_prev = 1, 0 - for i in range(len(s)): + for i in xrange(len(s)): current = 0 if s[i] != '0': current = prev @@ -33,4 +33,4 @@ def numDecodings(self, s): if __name__ == "__main__": for i in ["0", "10", "10", "103", "1032", "10323"]: - print Solution().numDecodings(i) \ No newline at end of file + print Solution().numDecodings(i) From feeb561abc865f5a7fdb77cbf008a182021a09b4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Mar 2016 21:41:17 +0800 Subject: [PATCH 1917/1939] Update decode-ways.py --- Python/decode-ways.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/Python/decode-ways.py b/Python/decode-ways.py index 8d0940f4c..2f474480b 100644 --- a/Python/decode-ways.py +++ b/Python/decode-ways.py @@ -15,22 +15,25 @@ # The number of ways decoding "12" is 2. # -class Solution: - # @param s, a string - # @return an integer +class Solution(object): def numDecodings(self, s): + """ + :type s: str + :rtype: int + """ if len(s) == 0 or s[0] == '0': return 0 prev, prev_prev = 1, 0 for i in xrange(len(s)): - current = 0 + cur = 0 if s[i] != '0': - current = prev + cur = prev if i > 0 and (s[i - 1] == '1' or (s[i - 1] == '2' and s[i] <= '6')): - current += prev_prev - prev, prev_prev = current, prev + cur += prev_prev + prev, prev_prev = cur, prev return prev - + + if __name__ == "__main__": for i in ["0", "10", "10", "103", "1032", "10323"]: print Solution().numDecodings(i) From 5f420db85fcbdd9247527bf548b2332d4340d9a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Mar 2016 21:42:13 +0800 Subject: [PATCH 1918/1939] Update and rename numDecodings.cpp to decode-ways.cpp --- C++/decode-ways.cpp | 30 ++++++++++++++++++++++++++++++ C++/numDecodings.cpp | 25 ------------------------- 2 files changed, 30 insertions(+), 25 deletions(-) create mode 100644 C++/decode-ways.cpp delete mode 100644 C++/numDecodings.cpp diff --git a/C++/decode-ways.cpp b/C++/decode-ways.cpp new file mode 100644 index 000000000..38f4d9368 --- /dev/null +++ b/C++/decode-ways.cpp @@ -0,0 +1,30 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int numDecodings(string s) { + if (s.empty()) { + return 0; + } + + int prev = 0; // f[n - 2] + int cur = 1; // f[n - 1] + + for (int i = 0; i < s.length(); ++i) { + if (s[i] == '0') { + cur = 0; // f[n - 1] = 0 + } + if (i == 0 || + !(s[i - 1] == '1' || (s[i - 1] == '2' && s[i] <= '6'))) { + prev = 0; // f[n - 2] = 0 + } + + int tmp = cur; + cur += prev; // f[n] = f[n - 1] + f[n - 2] + prev = tmp; + } + + return cur; + } +}; diff --git a/C++/numDecodings.cpp b/C++/numDecodings.cpp deleted file mode 100644 index 1f77e5d0a..000000000 --- a/C++/numDecodings.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - int numDecodings(string s) { - if(s.empty()) return 0; - - int prev = 0; // f[n - 2] - int cur = 1; // f[n - 1] - - for(int i = 1; i <= s.length(); ++i) { - if(s[i - 1] == '0') - cur = 0; // f[n - 1] = 0 - if(i < 2 || !(s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) - prev = 0; // f[n - 2] = 0; - - int tmp = cur; - cur += prev; // f[n] = f[n - 1] + f[n - 2] - prev = tmp; - } - - return cur; - } -}; From 152bf5b2d79bffb513bac040f7c16ea688b682ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Mar 2016 21:42:49 +0800 Subject: [PATCH 1919/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index df1be04e9..897d95c6f 100644 --- a/README.md +++ b/README.md @@ -405,7 +405,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 72| [Edit Distance](https://leetcode.com/problems/edit-distance/)|[Python](./Python/edit-distance.py)| _O(m * n)_ | _O(m + n)_ | Hard || 85| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)| [C++](./C++/maximal-rectangle.cpp) [Python](./Python/maximal-rectangle.py)| _O(m * n)_ | _O(n)_ | Hard || 87| [Scramble String](https://leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || -91| [Decode Ways](https://leetcode.com/problems/decode-ways/) | [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || +91| [Decode Ways](https://leetcode.com/problems/decode-ways/) | [C++](./Python/decode-ways.cpp) [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || 96| [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | [Python](./Python/unique-binary-search-trees.py) | _O(n)_ | _O(1)_ | Medium || Math 97| [Interleaving String](https://leetcode.com/problems/interleaving-string/)|[Python](./Python/interleaving-string.py)| _O(m * n)_ | _O(m + n)_ | Hard || 115| [Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/)|[Python](./Python/distinct-subsequences.py)| _O(n^2)_ | _O(n)_ | Hard || From f359b400d1b39aacf31a70283a1d013f8938ab40 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 15 Mar 2016 19:41:53 +0800 Subject: [PATCH 1920/1939] Update and rename reverseBetween.cpp to reverse-linked-list-ii.cpp --- C++/{reverseBetween.cpp => reverse-linked-list-ii.cpp} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename C++/{reverseBetween.cpp => reverse-linked-list-ii.cpp} (94%) diff --git a/C++/reverseBetween.cpp b/C++/reverse-linked-list-ii.cpp similarity index 94% rename from C++/reverseBetween.cpp rename to C++/reverse-linked-list-ii.cpp index 0936b787e..85caade49 100644 --- a/C++/reverseBetween.cpp +++ b/C++/reverse-linked-list-ii.cpp @@ -1,5 +1,5 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) +// Time: O(n) +// Space: O(1) /** * Definition for singly-linked list. From e031bf10397cd4bc5b78bbf072d04fb7e8cd9385 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 15 Mar 2016 19:43:00 +0800 Subject: [PATCH 1921/1939] Update reverse-linked-list-ii.cpp --- C++/reverse-linked-list-ii.cpp | 38 +++++++++++++++++----------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/C++/reverse-linked-list-ii.cpp b/C++/reverse-linked-list-ii.cpp index 85caade49..a3152d3d3 100644 --- a/C++/reverse-linked-list-ii.cpp +++ b/C++/reverse-linked-list-ii.cpp @@ -10,29 +10,29 @@ * }; */ class Solution { - public: - ListNode *reverseBetween(ListNode *head, int m, int n) { - ListNode dummy(-1); - dummy.next = head; +public: + ListNode* reverseBetween(ListNode* head, int m, int n) { + ListNode dummy{0}; + dummy.next = head; - ListNode *prev = &dummy; - - for(int i = 0; i < m - 1; ++i) { - prev = prev->next; - } - - ListNode *const head2 = prev; + auto *prev = &dummy; + for (int i = 0; i < m - 1; ++i) { prev = prev->next; - ListNode *cur = prev->next; + } - for(int i = m; i < n; ++i) { - prev->next = cur->next; // remove cur from the list - cur->next = head2->next; // add cur to the head - head2->next = cur; // add cur to the head - cur = prev->next; // get next cur - } + auto *head2 = prev; - return dummy.next; + prev = prev->next; + auto *cur = prev->next; + + for (int i = m; i < n; ++i) { + prev->next = cur->next; // Remove cur from the list. + cur->next = head2->next; // Add cur to the head. + head2->next = cur; // Add cur to the head. + cur = prev->next; // Get next cur. } + + return dummy.next; + } }; From 1dde0565de6cd1db4d6f9aa870189a82e9de94ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 15 Mar 2016 19:44:59 +0800 Subject: [PATCH 1922/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 897d95c6f..3ae504cb5 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [C++](./C++/rotate-list.cpp) [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || 82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [C++](./C++/remove-duplicates-from-sorted-list-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [C++](./C++/remove-duplicates-from-sorted-list.cpp) [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || -92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || +92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [C++](./C++/reverse-linked-list-ii.cpp) [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || 160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || 203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || From aace860c4656aac51dcfba30972c5550b78fedd1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Mar 2016 20:47:44 +0800 Subject: [PATCH 1923/1939] Update and rename copyRandomList.cpp to copy-list-with-random-pointer.cpp --- C++/copy-list-with-random-pointer.cpp | 40 +++++++++++++++++++++++++++ C++/copyRandomList.cpp | 40 --------------------------- 2 files changed, 40 insertions(+), 40 deletions(-) create mode 100644 C++/copy-list-with-random-pointer.cpp delete mode 100644 C++/copyRandomList.cpp diff --git a/C++/copy-list-with-random-pointer.cpp b/C++/copy-list-with-random-pointer.cpp new file mode 100644 index 000000000..c730b93a2 --- /dev/null +++ b/C++/copy-list-with-random-pointer.cpp @@ -0,0 +1,40 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list with a random pointer. + * struct RandomListNode { + * int label; + * RandomListNode *next, *random; + * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} + * }; + */ +class Solution { +public: + RandomListNode *copyRandomList(RandomListNode *head) { + // Insert the copied node after the original one. + for (auto *cur = head; cur; cur = cur->next->next) { + auto *node = new RandomListNode(cur->label); + node->next = cur->next; + cur->next = node; + } + + // Update random node. + for (auto *cur = head; cur; cur = cur->next->next) { + if (cur->random) { + cur->next->random = cur->random->next; + } + } + + // Seperate the copied nodes from original ones. + RandomListNode dummy(INT_MIN); + for (auto *cur = head, *copy_cur = &dummy; + cur; + copy_cur = copy_cur->next, cur = cur->next) { + copy_cur->next = cur->next; + cur->next = cur->next->next; + } + + return dummy.next; + } +}; diff --git a/C++/copyRandomList.cpp b/C++/copyRandomList.cpp deleted file mode 100644 index ae69f7482..000000000 --- a/C++/copyRandomList.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -/** - * Definition for singly-linked list with a random pointer. - * struct RandomListNode { - * int label; - * RandomListNode *next, *random; - * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} - * }; - */ -class Solution { - public: - RandomListNode *copyRandomList(RandomListNode *head) { - // insert the copied node after the original one - for(RandomListNode *cur = head; cur; cur = cur->next->next) { - RandomListNode *node = new RandomListNode(cur->label); - node->next = cur->next; - cur->next = node; - } - - // update random node - for(RandomListNode *cur = head; cur; cur = cur->next->next) { - if(cur->random) { - cur->next->random = cur->random->next; - } - } - - // seperate the copied nodes from original ones - RandomListNode dummy(INT_MIN); - for( RandomListNode *cur = head, *copy_cur = &dummy; - cur; - copy_cur = copy_cur->next, cur = cur->next) { - copy_cur->next = cur->next; - cur->next = cur->next->next; - } - - return dummy.next; - } -}; From fe057ecadbfd10828906598c4467fef4c7a1d658 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Mar 2016 20:48:29 +0800 Subject: [PATCH 1924/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3ae504cb5..293b2ae67 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [C++](./C++/remove-duplicates-from-sorted-list-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [C++](./C++/remove-duplicates-from-sorted-list.cpp) [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || 92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [C++](./C++/reverse-linked-list-ii.cpp) [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || -138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || +138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [C++](./C++/copy-list-with-random-pointer.cpp) [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || 160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || 203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || 206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || From 6fcf35b38eac8f8b1745e4dcd2e445b573882214 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 17 Mar 2016 21:37:38 +0800 Subject: [PATCH 1925/1939] Create intersection-of-two-linked-lists.cpp --- C++/intersection-of-two-linked-lists.cpp | 44 ++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/intersection-of-two-linked-lists.cpp diff --git a/C++/intersection-of-two-linked-lists.cpp b/C++/intersection-of-two-linked-lists.cpp new file mode 100644 index 000000000..d5dda7208 --- /dev/null +++ b/C++/intersection-of-two-linked-lists.cpp @@ -0,0 +1,44 @@ +// Time: O(m + n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + ListNode *curA = headA, *curB = headB; + ListNode *begin = nullptr, *tailA = nullptr, *tailB = nullptr; + while (curA && curB) { + if (curA == curB) { + begin = curA; + break; + } + + if (curA->next) { + curA = curA->next; + } else if (!tailA) { + tailA = curA; + curA = headB; + } else { + break; + } + + if (curB->next) { + curB = curB->next; + } else if (!tailB) { + tailB = curB; + curB = headA; + } else { + break; + } + } + + return begin; + } +}; From 74157d41c37b2a23e0008c22fec94f6995b21526 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 17 Mar 2016 21:38:17 +0800 Subject: [PATCH 1926/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 293b2ae67..0726fda17 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [C++](./C++/remove-duplicates-from-sorted-list.cpp) [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || 92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [C++](./C++/reverse-linked-list-ii.cpp) [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [C++](./C++/copy-list-with-random-pointer.cpp) [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || -160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || +160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [C++](./C++/intersection-of-two-linked-lists.cpp) [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || 203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || 206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || From f5d5a2d121b28abb8c38c180d5b44d6c163be759 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 18 Mar 2016 00:14:20 +0800 Subject: [PATCH 1927/1939] Create counting-bits.cpp --- C++/counting-bits.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/counting-bits.cpp diff --git a/C++/counting-bits.cpp b/C++/counting-bits.cpp new file mode 100644 index 000000000..075424289 --- /dev/null +++ b/C++/counting-bits.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector countBits(int num) { + vector res{0}; + for (int i = 0, cnt = res.size(); + res.size() <= num; + i = (i + 1) % cnt) { + if (i == 0) { + cnt = res.size(); + } + res.emplace_back(res[i] + 1); + } + return res; + } +}; From 0581a4f8703bd7063b3f582b6e6d18a83d667af8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 18 Mar 2016 00:21:01 +0800 Subject: [PATCH 1928/1939] Update counting-bits.cpp --- C++/counting-bits.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/C++/counting-bits.cpp b/C++/counting-bits.cpp index 075424289..46157cf92 100644 --- a/C++/counting-bits.cpp +++ b/C++/counting-bits.cpp @@ -2,6 +2,19 @@ // Space: O(n) class Solution { +public: + vector countBits(int num) { + vector res{0}; + for (int i = 1; i <= num; ++i) { + res.emplace_back(res[i >> 1] + (i & 1)); + } + return res; + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { public: vector countBits(int num) { vector res{0}; From 6c76687a8829ca3efdbdb813b430325207d0a72f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 18 Mar 2016 00:24:52 +0800 Subject: [PATCH 1929/1939] Create counting-bits.py --- Python/counting-bits.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/counting-bits.py diff --git a/Python/counting-bits.py b/Python/counting-bits.py new file mode 100644 index 000000000..3aeb1f8cb --- /dev/null +++ b/Python/counting-bits.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(1) + +# 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. +# Hint: +# +# 1. You should make use of what you have produced already. +# 2. Divide the numbers in ranges like [2-3], [4-7], [8-15] +# and so on. And try to generate new range from previous. +# 3. Or does the odd/even status of the number help you in +# calculating the number of 1s? + +class Solution(object): + def countBits(self, num): + """ + :type num: int + :rtype: List[int] + """ + res = [0] + for i in xrange(1, num + 1): + res.append(res[i >> 1] + (i & 1)) + return res From 6b18254cf4b80e31f58eecd6bf0913166cde80d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 18 Mar 2016 00:26:37 +0800 Subject: [PATCH 1930/1939] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0726fda17..8abdcd2e8 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-337%20%2F%20337-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-338%20%2F%20338-ff69b4.svg) -Up to date (2016-03-12), there are `320` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-03-17), there are `321` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `337` questions. +Here is the classification of all `338` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions. ) @@ -245,6 +245,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./C++/bulb-switcher.cpp) [Python](./Python/bulb-switcher.py) | _O(1)_ | _O(1)_ | Medium ||| 326 | [Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./C++/power-of-three.cpp) [Python](./Python/power-of-three.py) | _O(1)_ | _O(1)_ | Easy ||| 335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | [C++](./C++/self-crossing.cpp) [Python](./Python/self-crossing.py) | _O(n)_ | _O(1)_ | Medium ||| +338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./C++/counting-bits.cpp) [Python](./Python/counting-bits.py) | _O(n)_ | _O(n)_ | Medium ||| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From 6e7eb27f86c0ec665db800909af26de3f7823207 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 18 Mar 2016 00:37:17 +0800 Subject: [PATCH 1931/1939] Update counting-bits.cpp --- C++/counting-bits.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/counting-bits.cpp b/C++/counting-bits.cpp index 46157cf92..bdc3f7c71 100644 --- a/C++/counting-bits.cpp +++ b/C++/counting-bits.cpp @@ -6,7 +6,7 @@ class Solution { vector countBits(int num) { vector res{0}; for (int i = 1; i <= num; ++i) { - res.emplace_back(res[i >> 1] + (i & 1)); + res.emplace_back((i & 1) + res[i >> 1]); } return res; } From a4103a63d2969e8819447685f42423cd22fed2ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 18 Mar 2016 00:39:58 +0800 Subject: [PATCH 1932/1939] Update counting-bits.py --- Python/counting-bits.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/counting-bits.py b/Python/counting-bits.py index 3aeb1f8cb..27a762944 100644 --- a/Python/counting-bits.py +++ b/Python/counting-bits.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(1) +# Space: O(n) # Given a non negative integer number num. For every numbers i # in the range 0 <= i <= num calculate the number @@ -33,5 +33,6 @@ def countBits(self, num): """ res = [0] for i in xrange(1, num + 1): - res.append(res[i >> 1] + (i & 1)) + # Number of 1's in i = (i & 1) + number of 1's in (i / 2). + res.append((i & 1) + res[i >> 1]) return res From b36d4511695efc34ba56263125c68ef5cb4aca7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Mar 2016 11:49:53 +0800 Subject: [PATCH 1933/1939] Update paint-house-ii.cpp --- C++/paint-house-ii.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/paint-house-ii.cpp b/C++/paint-house-ii.cpp index e19f4a573..7a4fc3851 100644 --- a/C++/paint-house-ii.cpp +++ b/C++/paint-house-ii.cpp @@ -54,6 +54,5 @@ class Solution2{ }; vector min_cost = accumulate(costs.cbegin(), costs.cend(), vector(costs[0].size(), 0), combine); return *min_element(min_cost.cbegin(), min_cost.cend()); - } }; From c29c4e49928958c6782c473bd7672eb0403990c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 19 Mar 2016 12:09:04 +0800 Subject: [PATCH 1934/1939] Update perfect-squares.cpp --- C++/perfect-squares.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/C++/perfect-squares.cpp b/C++/perfect-squares.cpp index 22d9e33ac..15188df34 100644 --- a/C++/perfect-squares.cpp +++ b/C++/perfect-squares.cpp @@ -16,6 +16,8 @@ class Solution { } }; +// Time: O(n * sqrt(n)) +// Space: O(n) class Solution2 { public: int numSquares(int n) { From d4e96b814c054497c1ee6cde951da1b2b19b6bc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 20 Mar 2016 13:42:19 +0800 Subject: [PATCH 1935/1939] Create remove-linked-list-elements.cpp --- C++/remove-linked-list-elements.cpp | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/remove-linked-list-elements.cpp diff --git a/C++/remove-linked-list-elements.cpp b/C++/remove-linked-list-elements.cpp new file mode 100644 index 000000000..cbfc500f1 --- /dev/null +++ b/C++/remove-linked-list-elements.cpp @@ -0,0 +1,30 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + auto dummy = ListNode(0); + dummy.next = head; + auto *prev = &dummy, *cur = dummy.next; + + while (cur) { + if (cur->val == val) { + prev->next = cur->next; + delete cur; + } else { + prev = cur; + } + cur = cur->next; + } + return dummy.next; + } +}; From dfc0894540ba1c0adfbbacdc95acccce71612d5d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 20 Mar 2016 13:43:52 +0800 Subject: [PATCH 1936/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8abdcd2e8..a438d98b8 100644 --- a/README.md +++ b/README.md @@ -130,7 +130,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [C++](./C++/reverse-linked-list-ii.cpp) [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [C++](./C++/copy-list-with-random-pointer.cpp) [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || 160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [C++](./C++/intersection-of-two-linked-lists.cpp) [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || -203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || +203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [C++](./C++/remove-linked-list-elements.cpp) [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || 206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 237| [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./C++/delete-node-in-a-linked-list.cpp) [Python](./Python/delete-node-in-a-linked-list.py) | _O(1)_ | _O(1)_ | Easy | LintCode | From a99f76aed47affe8f89691fc5ef888d3ea54a5fb Mon Sep 17 00:00:00 2001 From: Sarvesh Sadhoo Date: Mon, 21 Mar 2016 23:06:39 -0700 Subject: [PATCH 1937/1939] Update longest-common-prefix.py You don't have to loop over the first string since we consider it as our base case. Tested on leetcode --- Python/longest-common-prefix.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/longest-common-prefix.py b/Python/longest-common-prefix.py index 970d4a11b..f5a918469 100644 --- a/Python/longest-common-prefix.py +++ b/Python/longest-common-prefix.py @@ -14,7 +14,7 @@ def longestCommonPrefix(self, strs): return "" for i in xrange(len(strs[0])): - for string in strs: + for string in strs[1:]: if i >= len(string) or string[i] != strs[0][i]: return strs[0][:i] return strs[0] From 8c2185dc89c72994d4b214d80ec7632d570807e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Mar 2016 15:27:36 +0800 Subject: [PATCH 1938/1939] Create reverse-linked-list.cpp --- C++/reverse-linked-list.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/reverse-linked-list.cpp diff --git a/C++/reverse-linked-list.cpp b/C++/reverse-linked-list.cpp new file mode 100644 index 000000000..edf8ecd92 --- /dev/null +++ b/C++/reverse-linked-list.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + auto *dummy_head = new ListNode(0); + + while (head) { + auto *tmp = head->next; + head->next = dummy_head->next; + dummy_head->next = head; + head = tmp; + } + + return dummy_head->next; + } +}; From 3aaa158dd9ffb74a128cbf1b5e0c9443ecd2b928 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Mar 2016 15:30:55 +0800 Subject: [PATCH 1939/1939] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a438d98b8..5c1e3341c 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [C++](./C++/copy-list-with-random-pointer.cpp) [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || 160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [C++](./C++/intersection-of-two-linked-lists.cpp) [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || 203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [C++](./C++/remove-linked-list-elements.cpp) [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || -206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || +206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [C++](./C++/reverse-linked-list.cpp) [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 237| [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./C++/delete-node-in-a-linked-list.cpp) [Python](./Python/delete-node-in-a-linked-list.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 242| [Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./C++/valid-anagram.cpp) [Python](./Python/valid-anagram.py) | _O(n)_ | _O(1)_ | Easy | LintCode |